2 # Author: Michael H. Hohn (mhhohn@lbl.gov)
4 # Copyright (c) 2006, The Regents of the University of California
6 # See legal.txt and license.txt
12 from l3lang
.ast
import *
13 from l3lang
.interp
import *
14 from l3lang
.repl
import *
15 from l3gui
.main
import *
16 from l3gui
.cruft
.pylab
import *
17 from l3gui
.widgets
import *
18 from l3gui
.l3canvas
import *
19 from l3gui
.misc
import *
20 from l3gui
.misc
import _get_props
, _set_props
, _safed
21 from l3lang
.globals import *
23 from pickle
import dumps
26 from pprint
import pprint
30 def enter_debug(type, value
, traceback
):
31 pdb
.post_mortem(traceback
)
34 sys
.excepthook
= enter_debug
38 sys
.excepthook
= sys
.__excepthook
__
43 # NO: gtk.threads_init()
44 gobject
.threads_init()
48 import profile
, pstats
49 prof
= profile
.Profile()
50 prof
.run('gtk.main()')
52 ps
= pstats
.Stats(prof
)
54 ps
.sort_stats('cumulative').print_stats(40)
55 ps
.sort_stats('time', 'stdname').print_stats(40)
57 # Function ... was called by
66 in running gnome
-terminal inside the phenix setup
:
68 (gnome
-terminal
:979): Pango
-WARNING
**: No builtin
or dynamically
69 loaded modules were found
. Pango will
not work correctly
. This
70 probably means there was an error
in the creation of
:
71 '/net/ribbon/scratch1/phenix/phenix-1.22a/build/intel-linux-2.4/python/etc/pango/pango.modules'
72 You may be able to recreate this
file by running
78 # Automatically generated file, do not edit
80 # ModulesPath = /net/ribbon/scratch1/phenix/phenix-1.22a/build/intel-linux-2.4/python/lib/pango/1.4.0/modules
83 which
is a nonexistent
file..
88 foo
= save_state(w_
, '/tmp/foo.state')
92 # VERY useful for debugging: tree structure, plain text!
93 pprint(utils
.as_list(get_current_state(w_
)))
97 bar
= load_state(w_
, '/tmp/foo.state')
100 pprint(utils
.file_unpickle('/tmp/bar.1'))
105 #** find all instances of l3If
106 lc
= w_
.lib_canvas
.view
108 print filter(lambda x
: isinstance(x
, l3If
), lc
._nodes
)
110 t_if
= filter(lambda x
: isinstance(x
, l3If
), lc
._nodes
)[0]
111 print t_if
._d
_cond
_marker
.get_property("points")
113 t_set
= filter(lambda x
: isinstance(x
, l3Set
), lc
._nodes
)
115 print set._d
_lhs
_marker
.get_property("points")
122 utils
.file_pickle(tree
)
130 fn
= utils
.file_pickle(itr
)
134 w_
.node_tree
.view
.widget
.expand_to_path( w_
.node_tree
.view
.start
) # yes
135 w_
.node_tree
.view
.widget
.row_activated(w_
.node_tree
.view
.start
, label_col
)
136 # the cursor must be released somehow...
137 w_
.node_tree
.view
.widget
.set_cursor( w_
.node_tree
.view
.start
) # no
138 w_
.node_tree
.view
.widget
.scroll_to_cell( w_
.node_tree
.view
.start
) # no
142 #* canvas-embedded text, running program
143 raw
= list(w_
.canvas
.view
._nodes
)[1]
145 print raw
._textview
.get_events()
148 print raw
._textview
.get_property("sensitive")
149 raw
._textview
.set_property("sensitive", False)
152 print raw
._ltext
.get_bounds()
153 buff
= raw
._textview
.get_buffer()
154 print buff
.get_text(*buff
.get_bounds())
160 #* canvas-embedded text widget
162 view
= w_
.canvas
.view
163 ra
= w_
.canvas
.view
.root().add
165 c_root
= ra(canvas
.CanvasGroup
)
166 c_text
= gtk
.TextView()
167 c_text
.get_buffer().set_text("short text")
170 c_label
= ra(canvas
.CanvasWidget
,
171 anchor
= gtk
.ANCHOR_NORTH_WEST
,
172 # size_pixels = False,
185 c_label
= c_root
.add(canvas
.CanvasWidget
,
186 anchor
= gtk
.ANCHOR_NORTH_WEST
,
187 # size_pixels = False,
206 print c_label
.get_bounds()
210 buff
= c_text
.get_buffer()
211 print [ii
.get_offset() for ii
in buff
.get_bounds()]
213 tag_call
= buff
.create_tag()
214 tag_size
= buff
.create_tag( family
= "Monospace")
216 buff
.apply_tag(tag_size
, *buff
.get_bounds() )
217 buff
.apply_tag(tag_call
, *buff
.get_bounds() )
219 print tag_call
.get_priority()
220 print tag_size
.get_priority()
224 def tag_event(texttag
, widget
, event
, iter):
226 if event
.type == gtk
.gdk
.BUTTON_PRESS
:
227 if event
.button
== 1:
228 print "at: ", iter.get_offset()
229 texttag
.set_property("weight", pango
.WEIGHT_HEAVY
)
231 elif event
.type == gtk
.gdk
.BUTTON_RELEASE
:
232 if event
.button
== 1:
233 texttag
.set_property("weight", pango
.WEIGHT_NORMAL
)
237 tag_call
.connect("event", lambda *a
: tag_event(*a
))
240 #*** dynamic property adjust
241 print tag_size
.get_property("size-points")
242 tag_size
.set_property("size-points", 12)
246 def re_tag_inserted_text(buffer, iter, text
, length
):
247 iter_to
= iter.copy()
248 if not iter.backward_chars(length
):
251 if iter.has_tag(tag_size
):
252 print "no tagging needed"
255 buff
.apply_tag(tag_size
, iter, iter_to
)
258 buff
.connect_after("insert-text", lambda *a
: re_tag_inserted_text(*a
))
262 #** pango font adjust -- whole widget
263 # font_desc = c_text.get_pango_context().get_font_description()
264 # print font_desc.get_size() # 10240 -- 10 pt font
265 # font_desc.set_size(fs_default / 10)
270 nds
= w_
.canvas
.view
._nodes
278 view
= w_
.canvas
.view
279 ra
= w_
.canvas
.view
.root().add
280 c_label
= ra(canvas
.CanvasText
,
282 size_points
= 12 * 1,
287 # c_label.set_property("scale", 0.5)
288 print c_label
.get_property("size-set")
292 # The item only moves; no font size change.
293 def affine_scale(sx
, sy
):
294 return (sx
, 0.0, 0.0, sy
, 0.0, 0.0)
296 c_label
.affine_relative(affine_scale(0.2, 0.2))
302 view
= w_
.canvas
.view
303 ra
= w_
.canvas
.view
.root().add
304 c_label
= ra(canvas
.CanvasText
,
306 size
= 10 * pango
.SCALE
,
314 c_label
.set_property("size", 15 * pango
.SCALE
) # Resize. Good.
317 # c_label.affine_relative( (0.5, 0.0, 0.0, 0.5, 0.0, 0.0) ) # Only moves...
321 #*** Moving item test.
322 # Drag region is the bounding box. Easy to select.
328 def drag_event(item
, event
):
329 if event
.type == gtk
.gdk
.BUTTON_PRESS
:
330 if event
.button
== 1:
331 # sm: move group start
332 self
.remember_x
= event
.x
333 self
.remember_y
= event
.y
336 elif event
.type == gtk
.gdk
.MOTION_NOTIFY
:
337 if event
.state
& gtk
.gdk
.BUTTON1_MASK
:
339 # Get the new position and move by the difference.
344 dx
= new_x
- self
.remember_x
345 dy
= new_y
- self
.remember_y
347 self
.remember_x
= new_x
348 self
.remember_y
= new_y
352 print c_label
.connect("event", drag_event
)
355 #*** Font change test.
356 c_label
.set_property("font", "monospace") # Font style name
357 c_label
.set_property("size", 12 * pango
.SCALE
) #
361 #*** Color change test.
362 c_label
.set_property("fill-color", "red")
367 #** CanvasText speed test
369 view
= w_
.canvas
.view
370 rg
= w_
.canvas
.view
.root().add(canvas
.CanvasGroup
)
373 c_label
= ra(canvas
.CanvasText
,
374 x
= 2 + (ii
% 10) * 7,
376 size
= 10 * pango
.SCALE
,
378 scale
= 1.8, # ignored...
384 text_l
= [add(ii
) for ii
in xrange(0,1000)]
388 # Zoom does change position, but not size.
391 #*** change font and size
394 ii
.set_property("font", "monospace")
395 ii
.set_property("size", 12 * pango
.SCALE
)
400 ii
.set_property("font", "monospace")
401 ii
.set_property("size", 8 * pango
.SCALE
)
405 # "scale" is ignored (maybe try cairo backend?)
407 ii
.set_property("scale", 1.8)
408 ii
.set_property("scale_set", True)
418 view
= w_
.canvas
.view
420 raw
= l3Rawtext(view
.w_
, view
)
423 buff
= raw
._ltext
.get_buffer()
424 tag_call
= buff
.create_tag()
425 print tag_call
.get_priority()
426 tag_call
.set_priority(0)
428 def tag_event(texttag
, widget
, event
, iter):
430 # useless: iter.get_offset() is always 0 for mouse buttons
431 # never signalled: gtk.gdk.ENTER_NOTIFY, LEAVE_NOTIFY
432 if event
.type == gtk
.gdk
.BUTTON_PRESS
:
433 if event
.button
== 1:
434 print "at: ", iter.get_offset()
435 texttag
.set_property("weight", pango
.WEIGHT_HEAVY
)
437 elif event
.type == gtk
.gdk
.BUTTON_RELEASE
:
438 if event
.button
== 1:
439 texttag
.set_property("weight", pango
.WEIGHT_NORMAL
)
443 print tag_call
.get_property("size-set")
444 tag_call
.set_property("size", view
._pixpu
_base
* 10)
445 # tag_call.set_property("size-set", False)
447 tag_call
.connect("event", lambda *a
: tag_event(*a
))
450 # Text reverts to old size after apply_tag...
451 # buff.apply_tag(raw._tag_size, *buff.get_bounds() )
452 # The sequence create, edit, esc, apply_tag works...
454 raw
._focus
_dummy
.grab_focus()
456 # raw._text_orig = buff.get_text(*buff.get_bounds())
457 buff
.set_text( raw
._text
_orig
)
459 buff
.apply_tag(tag_call
, *buff
.get_bounds() )
460 # beg, _ = buff.get_bounds()
462 # end.forward_chars(4)
463 # beg.forward_chars(1)
464 # buff.apply_tag(tag_call, beg, end )
466 buff
.apply_tag(raw
._tag
_size
, *buff
.get_bounds() )
468 # buff.get_tag_table().foreach(lambda tag, _: pprint(tag))
471 #** text handling, raw
476 #** pango font adjustments
478 view
= w_
.canvas
.view
479 ra
= w_
.canvas
.view
.root().add
481 font_desc
= view
.get_pango_context().get_font_description()
482 font_desc
.set_stretch(pango
.STRETCH_NORMAL
)
483 fs_default
= font_desc
.get_size() # 10240 -- 10 pt font
484 font_desc
.set_size(fs_default
/ 10)
486 print font_desc
.get_size()
489 c_label
= ra(canvas
.CanvasRichText
,
494 text
= "NEW SAMPLE TEXT",
504 pprint(w_
.canvas
.view
._nodes
)
505 pprint(w_
.canvas
.view
._edges
)
507 pprint(w_
.canvas
.view
._pgraph
._nodes
)
508 pprint(w_
.canvas
.view
._pgraph
._edges
)
510 (w_
.canvas
.view
._edges
[0]).lower_to_bottom()
513 w_
.canvas
.view
._nodes
[(2, 'root')].get_bounds()
516 #** canvas anti-aliasing
517 view
= w_
.canvas
.view
518 view
.get_property('aa')
519 view
.set_property('aa', True) # only at init time.
522 view
= canvas
.Canvas(aa
= True)
523 view
.modify_bg(gtk
.STATE_NORMAL
, gtk
.gdk
.color_parse("grey5") )
526 #** canvas item zoom, affine
527 view
= w_
.canvas
.view
528 rt
= list(view
._nodes
)[0]._ltext
533 view
= w_
.canvas
.view
536 # view.set_center_scroll_region(True)
537 view
.set_pixels_per_unit(view
._pixpu
* 1.6)
541 print view
.get_scroll_offsets() # pixels
542 print view
.get_scroll_region() # world
544 view
.set_scroll_region
547 wc
= view
.get_allocation().width
# pixels
548 hc
= view
.get_allocation().height
550 # Get the display size.
551 cxw
, cyw
= view
.c2w(wc
/2, hc
/2)
553 view
.world_to_window(0, 0)
554 view
.window_to_world(400, 400)
558 view
.get_size_request()
560 view
.parent
.children()
561 view
.parent
.get_child_visible
565 # <gtk.HBox object (GtkHBox) at 0x40d6e8c4>
566 # >>> view.parent.get_parent_window().get_size()
575 # GnomeCanvas-ERROR **: file gnome-canvas-rich-text.c: line 1596
576 # (blink_cb): assertion failed: (text->_priv->layout)
579 c_label
= ra(canvas
.CanvasRichText
,
581 width
= 10 * cp_
.font_size
, height
= 1 * cp_
.font_size
,
582 text
= "sample text",
587 ra
= w_
.canvas
.view
.root().add
590 fill_color
= 'black',
593 line_style
= gtk
.gdk
.LINE_SOLID
,
594 width_pixels
= cp_
.outline_width_normal
,
595 points
= [ 0,0, 20,20 ], # scaled units.
598 point_l
= (edge
).get_property('points') # by value..
601 #** motion via properties:
602 (edge
).set_property('points', [ 0, 0, 20, 10])
604 (edge
).set_property('points', [ 0, 0, 20, 5])
609 canv
= w_
.canvas
.view
613 focus_dummy
= w_
.canvas
.view
.root().add(canvas
.CanvasItem
)
615 focus_dummy
.grab_focus()
619 label_root
= w_
.canvas
.view
.root().add(canvas
.CanvasGroup
)
623 label_text
= label_root
.add(canvas
.CanvasRichText
,
629 ### grow_height = True,
631 cursor_visible
= False,
632 cursor_blink
= False,
637 print label_text
.get_bounds()
638 x1
, y1
, x2
, y2
= label_text
.get_bounds()
639 x1
, y1
= canv
.c2w(int(x1
), int(y1
))
640 x2
, y2
= canv
.c2w(int(x2
), int(y2
))
642 label_rect
= label_root
.add(canvas
.CanvasRect
,
645 fill_color
= 'green',
646 outline_color
= 'blue',
647 width_pixels
= cp_
.outline_width_normal
,
655 def tag_event_1(texttag
, widget
, event
, iter):
656 if event
.type == gtk
.gdk
.BUTTON_PRESS
:
657 if event
.button
== 1:
658 print "tag_event_1: ", texttag
661 def tag_event(texttag
, widget
, event
, iter):
662 # useless: iter.get_offset() is always 0 for mouse buttons
663 # never signalled: gtk.gdk.ENTER_NOTIFY, LEAVE_NOTIFY
664 if event
.type == gtk
.gdk
.BUTTON_PRESS
:
665 if event
.button
== 1:
666 print "at: ", iter.get_offset()
667 texttag
.set_property("weight", pango
.WEIGHT_HEAVY
)
669 elif event
.type == gtk
.gdk
.BUTTON_RELEASE
:
670 if event
.button
== 1:
671 texttag
.set_property("weight", pango
.WEIGHT_NORMAL
)
675 def select_event(item
, event
, data
= None):
676 if event
.type == gtk
.gdk
.BUTTON_PRESS
:
678 ### item.grab_focus()
679 if event
.button
== 3:
686 # Creation order has no effect on size override.
688 buff
= label_text
.get_buffer()
689 buff_text
= "sample text"
690 buff
.set_text(buff_text
)
693 gi
= buff
.get_iter_at_offset
694 ct
= lambda color
: buff
.create_tag( background
= color
,
695 size
= int(10 * canv
._pixpu
_base
),
696 family
= "Monospace",
698 tag_call
= map(ct
, ["blue", "grey90"])
700 ii
= buff_text
.find(" ", 0)
703 tag_size
= buff
.create_tag( size
= int(10 * canv
._pixpu
_base
),
704 family
= "Monospace",
706 ### No text, serious delays:
707 ### tag_size = buff.create_tag( size = 10 * pango.SCALE,
708 ### family = "Monospace")
711 # Application order has no effect on override.
712 ### buff.apply_tag(tag_size, *buff.get_bounds() )
713 ### buff.apply_tag(tag_call[0], gi(2), gi(ii))
715 ### # The overlapping region has NO tag's text size.
716 ### buff.apply_tag(tag_size, gi(0), gi(4) )
717 ### buff.apply_tag(tag_call[0], gi(2), buff.get_bounds()[1])
719 buff
.apply_tag(tag_size
, gi(0), gi(4) )
720 buff
.apply_tag(tag_call
[0], gi(4), gi(7))
721 buff
.apply_tag(tag_call
[1], gi(7), buff
.get_bounds()[1])
724 # jj = buff_text.find(" ", ii + 1)
726 # jj = len(buff_text)
728 # buff.apply_tag(tag_call[1],
731 print tag_size
.get_priority()
732 print tag_call
[0].get_priority()
734 # no effect on size...
735 # tag_size.set_priority(buff.get_tag_table().get_size() - 1)
738 tag_size
.set_property("size", canv
._pixpu
_base
* 1.2)
741 #** Event connection.
742 tag_size
.connect("event", lambda *a
: tag_event(*a
))
743 tag_call
[0].connect("event", lambda *a
: tag_event_1(*a
))
744 tag_call
[1].connect("event", lambda *a
: tag_event_1(*a
))
746 label_root
.connect("event", select_event
)
752 ### canv.set_pixels_per_unit(canv._pixpu)
754 canv
._pixpu
= (1.00001 * canv
._pixpu
)
755 canv
.set_pixels_per_unit(canv
._pixpu
)
758 #** affine adjustment
759 # The affine transform changes the box bounds, but not the font size...
760 # label_text.affine_relative( (0.1, 0.0,
764 # print label_text.get_bounds()
765 # print label_text.i2c_affine(tuple(range(0,6)))
766 # print label_text.i2w_affine(tuple(range(0,6)))
768 # label_text = label_root.add(canvas.CanvasRichText,
770 # width = 10 * cp_.font_size, height = 1 * cp_.font_size,
771 # text = "sample text",
774 #** tried and discarded
776 ### No effect (events not received?):
777 ### label_root.connect("event", select_event)
778 ### label_root.connect("event", focus_event)
781 ### massive delays when zooming:
782 ### tag_size = buff.create_tag(# size = 12 * w_.canvas.view._pixpu,
783 ### size_points = 12,
786 ### core dump after zoom:
787 ### tag_size = buff.create_tag(# size = 12 * w_.canvas.view._pixpu,
794 #* minimal window sample
795 def zoom_spin_button():
796 spinner_adj
= gtk
.Adjustment(2.500,
801 spinner
= gtk
.SpinButton(spinner_adj
, 0.001, 3)
804 l_window
= gtk
.Window()
805 l_window
.connect("delete-event", lambda *args
: l_window
.destroy())
806 l_window
.set_border_width(0)
807 l_window
.add(spinner
)
821 aa
.source_string() # no_source...
823 aa
= reader
.parse("""
829 print aa
.source_string() # no_source...
834 #* program formation from gui; evaluation test.
837 view
.print_info(storage
, prog
, show_macros
= True)
839 pgraph
= w_
.canvas
.view
._pgraph
840 chains
, free_nodes
= pgraph
.identify_programs()
841 print "Free nodes found: ", free_nodes
# modeline / popup?
843 print "Chains found: ",
846 print "============================================"
848 [info(storage
.load(foo
)) for foo
in chains
[0] ]
851 programs
= [pgraph
.chain_to_program(ch
,
855 print "============================================"
860 print "============================================"
862 value
= programs
[0].interpret(def_env
, storage
)
866 cnvs
= w_
.canvas
.view
867 from canvas
import MOVETO_OPEN
, MOVETO
, LINETO
, CURVETO
, END
869 ls_path
= canvas
.path_def_new([(MOVETO
, 10, 10),
875 ls_item
= cnvs
.root().add(canvas
.CanvasBpath
,
877 outline_color
= "black",
878 fill_color
= "green",
880 ls_item
.set_bpath(ls_path
)
885 def affine_scale(sx
, sy
):
886 return (sx
, 0.0, 0.0, sy
, 0.0, 0.0)
888 ls_item
.affine_relative(affine_scale(0.7, 0.3))
891 ls_item
.affine_relative(affine_scale(1/0.7, 1/0.3))
900 cnvs
= w_
.canvas
.view
901 from canvas
import MOVETO_OPEN
, MOVETO
, LINETO
, CURVETO
, END
904 ls_path
= canvas
.path_def_new(path
)
905 ls_item
= cnvs
.root().add(canvas
.CanvasBpath
,
906 width_units
= 1.0/w_
.cp_
.font_size
* 2,
907 outline_color
= "black",
908 fill_color
= "green",
909 cap_style
= gtk
.gdk
.CAP_ROUND
,
910 join_style
= gtk
.gdk
.JOIN_ROUND
,
912 ls_item
.set_bpath(ls_path
)
914 ll
, tt
, rr
, bb
= canvas_item_get_bounds_world(ls_item
)
915 ls_item
.move( 10 + w_
.cp_
.off_x
- ll
,
916 10 + w_
.cp_
.off_y
- tt
,
925 # Rounded corner, leaving the bezier control points on the tangent lines.
935 path
= [(MOVETO
, 0, 0), # p1
946 #*** rounded corner rectangle
947 # rectangle w/ rounded corners, leaving the bezier control points on
949 # Note: using one definition, say on [0,1]x[0,1] and scaling will also
950 # scale the rounded edges, but these must have absolute size. [ie. the
951 # rounding size must be independent of the rectangle size.]
954 def path_rectangle_rounded(el
, er
,
955 et
, eb
, # edge positions
956 cv
, ch
, # corner point indentation
957 sv
, sh
, # spline control point indentation
962 assert ((er
- el
) > 2*ch
)
963 assert ((eb
- et
) > 2*cv
)
965 path
= [(MOVETO
, el
, et
+ cv
),
967 (LINETO
, el
, eb
- cv
),
968 (CURVETO
, # bottom left
974 (LINETO
, er
- ch
, eb
), # bottom right
981 (LINETO
, er
, et
+ cv
),
982 (CURVETO
, # top right
988 (LINETO
, el
+ ch
, et
),
989 (CURVETO
, # top left
1008 test_path(path_rectangle_rounded(el
, er
, et
, eb
,
1011 test_path(path_rectangle_rounded(5, 10, 5, 20,
1017 cnvs
= w_
.canvas
.view
1018 from canvas
import MOVETO_OPEN
, MOVETO
, LINETO
, CURVETO
, END
1021 def __init__(self
, dct
):
1022 self
.__dict
__.update(dct
)
1026 # Scaling is expected to widen or heighten the object, retaining the
1027 # left upper corner. For this to happen with a simple call to
1028 # affine_relative(), the upper left of the original must be at 0,0,
1029 # and the drawing must be in the positive x and y directions.
1031 # The problem here is insufficient use of CanvasGroups.
1033 def draw_path(path
, width_w
, **props
):
1034 # This drawing order shows nothing.
1037 ls_path
= canvas
.path_def_new(path
)
1038 ls_rg
= cnvs
.root().add(canvas
.CanvasGroup
)
1039 ls_item
= ls_rg
.add(canvas
.CanvasBpath
, **props
)
1040 ls_item
.set_bpath(ls_path
)
1044 ll
, tt
, rr
, bb
= canvas_item_get_bounds_world(ls_item
)
1045 ls_item
.move( -ll
, -tt
)
1050 sx
= sy
= width_w
/ (rr
- ll
)
1051 print "scale: ", sx
,sy
1052 ## ls_item.affine_relative( (sx, 0.0, 0.0, sy, 0.0, 0.0) )
1055 ll
, tt
, rr
, bb
= canvas_item_get_bounds_world(ls_item
)
1056 ls_item
.move( 20 + w_
.cp_
.off_x
- ll
,
1057 10 + w_
.cp_
.off_y
- tt
,
1059 return AttrDict(locals())
1062 def draw_path(path
, width_w
, **props
):
1064 ls_path
= canvas
.path_def_new(path
)
1065 ls_rg
= cnvs
.root().add(canvas
.CanvasGroup
)
1066 ls_item
= ls_rg
.add(canvas
.CanvasBpath
, **props
)
1067 ls_item
.set_bpath(ls_path
)
1071 ll
, tt
, rr
, bb
= canvas_item_get_bounds_world(ls_item
)
1072 ls_item
.move( 20 + w_
.cp_
.off_x
- ll
,
1073 10 + w_
.cp_
.off_y
- tt
,
1076 # Scale using the local coordinates (the group is unchanged).
1077 sx
= sy
= width_w
/ (rr
- ll
)
1078 ls_item
.affine_relative( (sx
, 0.0, 0.0, sy
, 0.0, 0.0) )
1080 return AttrDict(locals())
1083 #*** good: proper affine nesting.
1085 # @@ name the groups.
1086 # distinct nested groups for group, center, scale and
1089 def draw_path(path
, width_w
, **props
):
1091 grp_trans
= cnvs
.root().add(canvas
.CanvasGroup
)
1092 grp_scale
= grp_trans
.add(canvas
.CanvasGroup
)
1093 grp_obj
= grp_scale
.add(canvas
.CanvasGroup
)
1096 ls_path
= canvas
.path_def_new(path
)
1097 ls_item
= grp_obj
.add(canvas
.CanvasBpath
, **props
)
1098 ls_item
.set_bpath(ls_path
)
1100 # Reposition for scaling around center.
1102 ll
, tt
, rr
, bb
= canvas_item_get_bounds_world(grp_obj
)
1103 grp_obj
.move( -(ll
+ rr
)/2, -(tt
+ bb
)/2 )
1107 ll
, tt
, rr
, bb
= canvas_item_get_bounds_world(grp_scale
)
1108 sx
= sy
= width_w
/ (rr
- ll
)
1109 grp_scale
.affine_relative( (sx
, 0.0, 0.0, sy
, 0.0, 0.0) )
1111 # Translate for visibility.
1113 ll
, tt
, rr
, bb
= canvas_item_get_bounds_world(grp_trans
)
1114 grp_trans
.move( 20 + w_
.cp_
.off_x
- ll
,
1115 10 + w_
.cp_
.off_y
- tt
,
1118 return AttrDict(locals())
1136 # (LINETO, 0,0), # use end to close (avoid irregularities)
1141 dct
= draw_path(path
,
1143 width_units
= 1.0/w_
.cp_
.font_size
* 2,
1144 outline_color
= "black",
1145 fill_color
= "black",
1146 cap_style
= gtk
.gdk
.CAP_ROUND
,
1147 join_style
= gtk
.gdk
.JOIN_ROUND
,
1154 print w_
.dct
.ls_item
.i2w_affine(tuple(range(0,6)))
1155 print w_
.dct
.grp_trans
.i2w_affine(tuple(range(0,6)))
1158 w_
.dct
.grp_scale
.affine_relative( (3, 0.0, 0.0, 3, 0.0, 0.0) ) # scale
1159 w_
.dct
.grp_trans
.move(2,2)
1161 w_
.dct
.grp_trans
.destroy()
1165 cnvs
= w_
.canvas
.view
1166 list_
= l3List(w_
, cnvs
)
1168 cnvs
.display_bounding_box( list_
._head
.get_bounds())
1171 # list_._root_group.connect("event", lambda *a: list_.drag_event(*a))
1172 # list_._head._root_group.connect("event", lambda *a: list_.drag_event(*a))
1173 # list_._alist._root_group.connect("event", lambda *a: list_.drag_event(*a))
1175 #* bounding box testing
1176 def bounds_world(item
):
1177 x
, y
, u
, v
= item
.get_bounds()
1178 return item
.i2w(x
,y
) + item
.i2w(u
,v
)
1180 # Outline bounds != outline corners. Why?
1182 print rawt
._loutline
.get_bounds()
1183 print [rawt
._loutline
.get_property(prop
) for prop
in ['x1', 'y1', 'x2', 'y2']]
1186 self__lgroup
= cnvs
.root().add(canvas
.CanvasGroup
)
1188 self__textview
= gtk
.TextView()
1189 self__ltext
= self__lgroup
.add(canvas
.CanvasWidget
,
1190 size_pixels
= False,
1191 height
= 1.5, ### params
1194 widget
= self__textview
,
1198 x1
, y1
, x2
, y2
= self__ltext
.get_bounds() # world units
1199 x1
-= 5 / cnvs
._pixpu
1200 y1
-= 5 / cnvs
._pixpu
1201 x2
+= 5 / cnvs
._pixpu
1202 y2
+= 5 / cnvs
._pixpu
1204 self__loutline
= self__lgroup
.add(
1208 fill_color
= 'white',
1209 outline_color
= 'black',
1210 width_pixels
= cp_
.outline_width_normal
,
1213 st
.__dict
__.update( locals())
1218 print st
.self__loutline
.get_bounds()
1219 print [st
.self__loutline
.get_property(prop
)
1220 for prop
in ['x1', 'y1', 'x2', 'y2']]
1223 #################################
1225 self__lgroup
= cnvs
.root().add(canvas
.CanvasGroup
)
1227 self__loutline
= self__lgroup
.add(
1231 fill_color
= 'white',
1232 outline_color
= 'black',
1233 width_pixels
= cp_
.outline_width_normal
,
1236 st
.__dict
__.update( locals())
1241 print st
.self__loutline
.get_bounds()
1242 print [st
.self__loutline
.get_property(prop
)
1243 for prop
in ['x1', 'y1', 'x2', 'y2']]
1246 #################################
1248 self__lgroup
= cnvs
.root().add(canvas
.CanvasGroup
)
1250 self__loutline
= self__lgroup
.add(
1254 fill_color
= 'white',
1255 outline_color
= 'black',
1258 return utils
.Shared(**locals())
1262 print st
.self__loutline
.get_bounds()
1263 print [st
.self__loutline
.get_property(prop
)
1264 for prop
in ['x1', 'y1', 'x2', 'y2']]
1267 print st
.self__ltext
.get_bounds()
1269 #################################
1271 x
, y
, u
, v
= bounds_world(rawt
._loutline
)
1274 print "group bounds"
1275 print rawt
._root
_group
.get_bounds()
1276 x
, y
, u
, v
= bounds_world(rawt
._root
_group
)
1278 print bounds_world(rawt
._root
_group
)
1281 print rawt
._ltext
.get_bounds()
1282 x
, y
, u
, v
= bounds_world(rawt
._ltext
)
1284 print bounds_world(rawt
._ltext
)
1287 print rawt
._loutline
.i2w_affine(tuple(range(0,6)))
1288 print rawt
._root
_group
.i2w_affine(tuple(range(0,6)))
1291 print rawt
._loutline
.i2c_affine(tuple(range(0,6)))
1292 print rawt
._root
_group
.i2c_affine(tuple(range(0,6)))
1296 cnvs
= w_
.canvas
.view
1297 l_line
= cnvs
.root().add(canvas
.CanvasLine
,
1298 fill_color
= "black",
1305 line_style
= gtk
.gdk
.SOLID
,
1306 cap_style
= gtk
.gdk
.CAP_ROUND
,
1307 join_style
= gtk
.gdk
.JOIN_ROUND
,
1312 l_line
= cnvs
.root().add(canvas
.CanvasLine
,
1313 fill_color
= "blue",
1320 line_style
= gtk
.gdk
.SOLID
,
1321 cap_style
= gtk
.gdk
.CAP_ROUND
,
1322 join_style
= gtk
.gdk
.JOIN_ROUND
,
1326 print l_line
.get_property('points')
1330 cnvs
= w_
.canvas
.view
1331 l_line
= cnvs
.root().add(canvas
.CanvasPolygon
,
1332 fill_color
= "black",
1339 cap_style
= gtk
.gdk
.CAP_ROUND
,
1340 join_style
= gtk
.gdk
.JOIN_ROUND
,
1343 l_line
= cnvs
.root().add(canvas
.CanvasPolygon
,
1344 fill_color
= "black",
1352 cap_style
= gtk
.gdk
.CAP_ROUND
,
1353 join_style
= gtk
.gdk
.JOIN_ROUND
,
1356 print l_line
.get_bounds()
1358 print l_line
.get_property('points')
1362 #* canvas ast insertion / display
1363 tree
= reader
.parse("[d,e]")
1364 tree
= reader
.parse("function = { |x,y| x - y }")
1366 tree
= reader
.parse("""
1367 [ function = not_yet({ |x,y| x - y }),
1368 macro = not_yet([ |x,y| z = x - y ]),
1369 raw_expression = a - b,
1372 from operator import *
1373 from l3lang.test.functions import axpy
1378 tree
.setup(empty_parent(), def_env
, storage
)
1379 view
.print_info(storage
, tree
)
1380 w_
.lib_canvas
.view
.start_add_l3tree(tree
)
1384 pcon
= w_
.lib_canvas
.view
.get_pango_context()
1385 pcon
.list_families()
1386 pcon
.list_families()[0].get_name()
1387 pcon
.get_font_description()
1388 print pcon
.get_font_description().get_size() / pango
.SCALE
1393 font_desc
= pcon
.get_font_description().copy()
1394 font_desc
.set_family("monospace")
1395 font_desc
.set_size(sz_orig
* pango
.SCALE
)
1397 # Set new canvas default.
1398 pcon
.set_font_description(font_desc
)
1402 font
= pcon
.load_font(font_desc
)
1403 metrics
= font
.get_metrics()
1404 # Font sizes are in pango_units.
1405 # 1 point == PANGO_SCALE pango_units
1406 # 1 pango_point = 1/72 inch
1407 fheight
= (metrics
.get_ascent() + metrics
.get_descent())
1408 fwidth
= metrics
.get_approximate_digit_width()
1409 # print fwidth / pango.SCALE
1410 # print fheight / pango.SCALE
1411 return fwidth
, fheight
1412 ## logi, ink = font.get_glyph_extents("m")
1417 # No content in last line.
1424 return reduce(max, [len(line
) for line
in st
.split('\n')], 0)
1427 #** Sizing using test string.
1428 view
= w_
.canvas
.view
1429 ra
= w_
.canvas
.view
.root().add
1430 c_string
= "01234\n" * 8
1431 c_label
= ra(canvas
.CanvasText
,
1434 font_desc
= font_desc
,
1436 ## c_label.destroy()
1441 l1
, t1
, r1
, b1
= c_label
.get_bounds()
1442 print "x: cu / char", (r1
- l1
) / width(c_string
)
1443 print "y: cu / char", (b1
- t1
) / lines(c_string
)
1444 print view
._pixpu
_base
1446 cu_p_char
= (r1
- l1
) / width(c_string
)
1447 view
._pixpu
= view
._pixpu
* cu_p_char
1448 view
.set_pixels_per_unit(view
._pixpu
)
1454 #*** Draw long string.
1455 lng_str
= "the test string,\nusing two lines"
1456 lng_label
= ra(canvas
.CanvasText
,
1458 anchor
= gtk
.ANCHOR_NORTH_WEST
,
1460 font_desc
= font_desc
,
1462 ## lng_label.destroy()
1463 # Verify canvas size ratio...
1464 l1
, t1
, r1
, b1
= lng_label
.get_bounds()
1465 print "x: cu / char", (r1
- l1
) / width(lng_str
)
1466 print "y: cu / char", (b1
- t1
) / lines(lng_str
)
1468 # Compare to font metric ratio...
1469 wid
, hei
= dump_metrics()
1470 print "metric h / w", 1.0*hei
/wid
1473 #*** Draw substring at proper position.
1475 # sub_start = lng_str.find(sub_str)
1478 sub_str
= lng_str
.split('\n')[sub_top
][sub_lef
:]
1479 sub_label
= ra(canvas
.CanvasText
,
1480 anchor
= gtk
.ANCHOR_NORTH_WEST
,
1481 fill_color
= "blue",
1484 font_desc
= font_desc
,
1486 sub_label
.move(sub_lef
, 1.0 * sub_top
/ wid
* hei
)
1487 ## sub_label.destroy()
1488 # Verify size ratio...
1489 l1
, t1
, r1
, b1
= sub_label
.get_bounds()
1490 print "x: cu / char", (r1
- l1
) / width(sub_str
)
1491 print "y: cu / char", (b1
- t1
) / lines(sub_str
)
1493 # Compare to font metric ratio...
1494 wid
, hei
= dump_metrics()
1495 print "metric h / w", 1.0*hei
/wid
1500 #*** Set new font sizes.
1501 fsize
= sz
* pango
.SCALE
1502 font_desc
.set_size(fsize
)
1503 c_label
.set_property('size', fsize
)
1504 lng_label
.set_property('size', fsize
)
1505 sub_label
.set_property('size', fsize
)
1507 #*** Set 1 cu = 1 ex (horizontal)
1508 l1
, t1
, r1
, b1
= c_label
.get_bounds()
1509 print "x: cu / char", (r1
- l1
) / width(c_string
)
1510 print "y: cu / char", (b1
- t1
) / lines(c_string
)
1512 cu_p_char
= (r1
- l1
) / width(c_string
)
1513 view
._pixpu
= view
._pixpu
* cu_p_char
1514 view
.set_pixels_per_unit(view
._pixpu
)
1516 #*** Check vertical [cu]
1517 l1
, t1
, r1
, b1
= c_label
.get_bounds()
1518 print "x: cu / char", (r1
- l1
) / width(c_string
)
1519 print "y: cu / char", (b1
- t1
) / lines(c_string
)
1520 #*** Compare font metrics (points) at new sizes
1521 wid
, hei
= dump_metrics()
1522 print "metric h / w", 1.0*hei
/wid
1525 #** Find matching font metric.
1526 wid
, hei
= dump_metrics()
1527 h_o_w
= 1.0 * hei
/ wid
1528 print "metric h / w", h_o_w
1530 sz_bnds
= range(4, 41)
1531 print "pt. height/ "
1532 print "size widtht "
1533 print "-------------------"
1535 fsize
= sz
* pango
.SCALE
1536 font_desc
.set_size(fsize
)
1537 wid
, hei
= dump_metrics()
1538 sz_hw
= 1.0 * hei
/ wid
1539 print "%-6d %.5f" % (sz
, sz_hw
)
1543 #* tree & clone structure
1544 tw
= TreeWork(storage
)
1545 loads
= storage
.load
1546 printi
= lambda xx
: print_info(storage
, xx
)
1547 printai
= lambda xx
: print_all_info(storage
, xx
)
1549 # id from first Symbol('abserr') inside If
1552 printai(tw
.find_root(loads(mid
)))
1555 # add header, run program, compare again
1557 printai(tw
.find_root(loads(mid
)))
1560 # change `if abserrr...` to `if prints(abserrr...`
1561 # run again, compare
1562 # no longer connected:
1563 # printai(loads(mid))
1564 # printai(tw.find_root(loads(mid)))
1565 printai(loads(30150)) # main program
1567 # search for prints...
1568 # The subtree was replaced and is re-run, including abserr()
1571 # stats for printing all info:
1574 wrt return 1.0 / 2 * (xk + x / xk)
1575 single clone prefix dump, 20 lines
1580 prefix dump, no clones, 135 lines
1581 prefix dump, all clones, 770 lines
1582 infix, 30 lines - 10 comment = 20 lines
1583 ratio (/ 135.0 20) 6.75
1591 show only clone starting points: Function, Program
1596 def print_dot(storage
, tree
):
1597 # Print every expression and its clones.
1598 # This is far too much detail; only l3 Function clones are needed.
1600 iter = tree
.prefix_grpd(storage
)
1602 nd
, clone_lev
, indent
= iter.next()
1603 print nd
.source_string()
1607 nd
, clone_lev
, indent
= iter.next()
1608 if clone_lev
== '(':
1610 nd
, clone_lev
, indent
= iter.next()
1611 print nd
._id
, nd
.source_string()
1612 if clone_lev
== ')':
1615 except StopIteration:
1620 def print_dot(storage
, tree
):
1621 # Print expressions once, including clones.
1622 # For every expression, include the id and link to clone
1626 # The if expressions are missing their lead indent.
1627 # The clone sources may not appear explicitly (with id); e.g., in
1630 # if abserr(x, xn) > 0.0001:
1631 # return loop(x, xkp1(x, xn))
1635 # 30254 -> 30920 /* clone of */
1636 # 30867 -> 30920 /* cloned by */
1638 # the Function 30254 is referenced, but only shows up inside other
1642 iter = tree
.prefix_grpd(storage
)
1643 gaa
= lambda id: storage
.get_attributes(
1644 id, ["clone_of", "cloned_by", "interp_env"])
1648 nd
, clone_lev
, indent
= iter.next()
1649 if isinstance(nd
, Program
):
1651 print clone_lev
, nid
1652 print nd
.source_string()
1654 of
, by
, env
= gaa(nid
)
1656 print "%(of)d -> %(nid)d /* clone of */" % locals()
1658 print "%(by)d -> %(nid)d /* cloned by */" % locals()
1660 except StopIteration:
1665 def print_dot(storage
, tree
):
1666 # Print expressions once, including clones.
1667 # For every expression, include the id and link to clone
1671 # - The if expressions are missing their lead indent.
1672 # - The clone sources may not appear explicitly (with id);
1673 # - Displaying ALL clones takes too much room;
1675 iter = tree
.prefix_grpd(storage
)
1676 gaa
= lambda id: storage
.get_attributes(
1677 id, ["clone_of", "cloned_by", "interp_env"])
1681 nd
, clone_lev
, indent
= iter.next()
1682 if isinstance(nd
, Program
):
1684 print nid
, '[label="%s"]; /* clone level %d */' % \
1685 (repr(nd
.source_string())[1:-1].replace(r
"\n",
1689 of
, by
, env
= gaa(nid
)
1691 print "%(of)d -> %(nid)d [color=green]; /* clone of */" % locals()
1693 print "%(by)d -> %(nid)d [color=blue]; /* cloned by */" % locals()
1695 except StopIteration:
1701 page = "8.5,11.0"; /* size of single physical page */
1702 size="7.5,10.0"; /* graph size */
1706 node [shape=plaintext];
1708 print_dot(storage
, t_tree
)
1711 # Program P is a clone of a Function F
1712 # cloned by a Call C
1716 sload
= storage
.load
1720 t_string
= open('../l3lang/test/sqrt.l3').readlines()
1721 t_tree
= reader
.parse("".join(t_string
))
1722 t_tree
.setup(empty_parent(), def_env
, storage
)[0].set_outl_edges(self
.w_
, None)
1723 # print_info(storage, t_tree)
1724 print_all_info(storage
, t_tree
)
1725 w_
.canvas
.view
.clear_state( )
1726 w_
.canvas
.view
.start_add_l3tree(t_tree
)
1732 # put tree on canvas.
1735 import linecache
, sys
1736 def traceit(frame
, event
, arg
):
1738 file = frame
.f_code
.co_filename
1740 if "usr/tmp/python-" in file:
1741 lineno
= frame
.f_lineno
1742 line
= linecache
.getline(file, lineno
)
1743 print "line %d: %s" % (lineno
, line
.rstrip())
1748 sys
.settrace(traceit
)
1750 import linecache
, sys
1751 def traceit(frame
, event
, arg
):
1753 file = frame
.f_code
.co_filename
1756 ## if "usr/tmp/python-" in file:
1757 lineno
= frame
.f_lineno
1758 line
= linecache
.getline(file, lineno
)
1759 print "%s:%d: %s" % (file, lineno
, line
.rstrip())
1764 sys
.settrace(traceit
)
1767 pdb
.run('w_.canvas.view.centered_zoom(0.1)')
1769 # The warning is printed through
1772 # intel-linux-2.4/python/lib/python2.4/warnings.py
1777 self
._canvas
.display_bounding_box(canvas_item_get_bounds_world(self
._blank
))
1778 self
._canvas
.display_bounding_box(self
.get_bounds_world())
1779 self
._canvas
.display_bounding_box(canvas_item_get_bounds_world(self
._d
_lhs
_marker
))
1780 self
._canvas
.display_bounding_box(canvas_item_get_bounds_world(self
._root
_group
))
1781 self
._canvas
.display_bounding_box(canvas_item_get_bounds_world(self
._blank
))
1784 # self._canvas.display_bounding_box(self.get_bounds_world())
1785 self
._canvas
.display_bounding_box(canvas_item_get_bounds_world(self
._root
_group
))
1787 self
._canvas
.display_bounding_box(self
._expander
.get_bounds_world())
1789 #* phenix refine display
1791 t_tree
= reader
.parse_file(
1792 os
.path
.expandvars('$SPXROOT/l3lang/test/refine.l3'))
1793 t_tree
.setup(empty_parent(), def_env
, storage
).set_outl_edges(self
.w_
, None)
1794 ## print_info(storage, t_tree)
1795 ## view.print_all_info(storage, t_tree)
1796 w_
.canvas
.view
.clear_state()
1797 # SLOW! But interesting to watch.
1798 w_
.canvas
.view
.start_add_l3tree(t_tree
)
1801 #** program, limited depth
1802 t_tree
= reader
.parse_file(
1803 os
.path
.expandvars('$SPXROOT/l3lang/test/refine.l3'))
1804 t_tree
.setup(empty_parent(), def_env
, storage
).set_outl_edges(self
.w_
, None)
1806 # hide nodes at level N
1807 vista
= w_
.canvas
.view
._vis
_tab
= VisibilityTable() # Reset.
1809 vista
.hide_at(t_tree
, N
)
1812 # ld = w_.state_.storage.load
1813 # for id in vista.keys():
1817 w_
.canvas
.view
.clear_state()
1818 w_
.canvas
.view
.start_add_l3tree(t_tree
)
1822 t_tree
= reader
.parse("""
1825 file_name = 'None',},
1832 test_flag_value = 'None',
1833 disable_suitability_test = 'False',},
1834 experimental_phases = {
1838 file_name = 'None',},}
1840 t_tree
.setup(empty_parent(), def_env
, storage
).set_outl_edges(self
.w_
, None)
1841 ## print_info(storage, t_tree)
1842 ## view.print_all_info(storage, t_tree)
1843 w_
.canvas
.view
.clear_state()
1844 w_
.canvas
.view
.start_add_l3tree(t_tree
)
1847 #** various file's layout
1848 def layout_file(name
, level
= 7):
1850 t_tree
= reader
.parse_file(os
.path
.expandvars(name
))
1851 t_tree
.setup(empty_parent(), def_env
, storage
).set_outl_edges(self
.w_
, None)
1853 # hide nodes at LEVEL.
1854 vista
= w_
.canvas
.view
._vis
_tab
= VisibilityTable() # Reset.
1855 vista
.hide_at(t_tree
, level
)
1858 w_
.canvas
.view
.clear_state()
1859 w_
.canvas
.view
.start_add_l3tree(t_tree
)
1863 layout_file('$SPXROOT/l3lang/test/refine.l3')
1864 layout_file('$SPXROOT/l3lang/test/ctf.l3')
1865 layout_file('$SPXROOT/l3lang/test/golem_1.l3')
1867 #* legible data dumping via PyYAML (yaml)
1874 print yaml
.dump(['foo', 'bar', 'baz'])
1878 # 2. yaml.representer.RepresenterError: recursive objects are not
1879 # allowed: Env(30288, Env-30269-skel.blck, [Program at 0x40d79a8c, id
1881 yaml
.dump(get_current_state(w_
), stream
= sys
.stdout
)
1882 ## yaml.dump(py_obj, stream = None)
1886 #* legible data dumping via syck (yaml)
1894 print syck
.dump(['foo', 'bar', 'baz'])
1899 # [Mon Apr 30 10:28:42 2007]
1900 # Fails on <weakproxy> instances
1902 # AttributeError: viewList instance has no attribute '__reduce__'
1903 # and there is no customization hook.
1904 syck
.dump(get_current_state(w_
), sys
.stdout
)
1907 # [Mon Apr 30 10:35:19 2007]
1908 # Try a detour via pickle. This fails too:
1909 # (.:16125): GLib-GObject-WARNING **: cannot retrieve class for
1910 # invalid (unclassed) type `<invalid>' ** ERROR **: file pygenum.c:
1911 # line 60 (pyg_enum_repr): assertion failed:
1912 # (G_IS_ENUM_CLASS(enum_class)) aborting...
1913 # /net/hooknose/scratch1/hohn/t2/sparx-bin/bin/sparx.wrap: line 36:
1914 # 16125 Aborted python -i
1915 # Process Python exited abnormally with code 134
1917 # Works after removing some more unnecessary gtk information.
1919 n_tree
= pickle
.loads( pickle
.dumps(get_current_state(w_
), protocol
=2))
1920 syck
.dump(n_tree
, sys
.stdout
)
1923 # l3 graphical node (local eval)
1925 print syck
.dump(self
)
1927 # l3 tree (local eval)
1928 print syck
.dump(self
._l3tree
)
1939 [horizontal layout, requires, >
1940 display choice display choice display choice
1941 display choice display choice display choice
1946 requires: display choice (direction)
1950 2d layout -- requires -- comment parsing
1954 #** Compare state files via their yaml representations.
1956 from l3lang
.utils
import *
1958 n_tree_1
= file_unpickle('st.1')
1959 syck
.dump(n_tree_1
, open('st.1.syck', 'w'))
1961 n_tree_2
= file_unpickle('st.2')
1962 syck
.dump(n_tree_2
, open('st.2.syck', 'w'))
1969 ==== local console
; exit with end
-of
-file (ctrl
-d
) ====
1971 import l3lang
.view
as view
1972 view
.print_all_info(self
.w_
.state_
.storage
, self
._l3tree
)
1977 lcan
= w_
.lib_canvas
.view
1978 pprint(lcan
.root().item_list
)
1980 pprint(self
._root
_group
.item_list
)
1982 #*visibility tables testing.
1983 lcan
= w_
.lib_canvas
.view
1985 pprint(lcan
._vis
_tab
)
1987 # Assuming constant tree and node offset:
1988 manually_chosen
= {30098: 'vis_hide',
1995 lcan
._vis
_tab
.replace_table( manually_chosen
)
1996 # use "apply mark" on topmost element.
1999 /tmp
/st
.lib
- compacted library only
.
2000 /tmp
/st
.for-pre
-run
- loop sample
2003 #* l3 loop templates
2004 #** range iteration, function version.
2005 # for i in range(n,m):
2007 def _for(_n
, _m
, body
):
2010 return _for(_n
+ 1, _m
, body
)
2014 _for(1, 7, {|i|
print_(i
) })
2015 _for(30, 31, {|i| foo
})
2016 # _for(1, 5, lambda i: print_(i) )
2017 # Nesting is no problem:
2020 {|j|
print_("%d %d" % (i
,j
)) })})
2021 #** range, macro version
2022 # [Thu Feb 9 16:29:39 2006]
2023 # Better not to use this one...
2025 # for i in range(n,m):
2031 return _form(_n
+ 1, _m
)
2037 # Paste, insert body, change "i" to new name, run.
2038 # Nesting requires unique _for names; the following has a problem::
2048 print_("%d %d" % (ii
, jj
))
2050 return _for(_n
+ 1, _m
)
2055 return _for(_n
+ 1, _m
) # wrong _for
2061 #* context for values
2063 # Given multiple values from a single expression and its clones, find
2064 # the dynamic context -- the changed arguments to
2065 # enclosing Functions, or (sigh) the changed values of the stacked
2066 # bindings. Complicated.
2069 st
= w_
.state_
.storage
2070 load
= w_
.state_
.storage
.load
2071 tw
= ast
.TreeWork(w_
.state_
.storage
)
2077 # LOADING RESETS THE STORAGE TABLE AND OTHERS!
2079 # U s e t h e w _ a c c e s s p a t h !
2082 st
= w_
.state_
.storage
2083 load
= w_
.state_
.storage
.load
2084 tw
= ast
.TreeWork(w_
.state_
.storage
)
2086 # Toplevel id (static).
2087 l3nd
= w_
.selector
.get_selection()
2088 c_id
= l3nd
._l3tree
._id
2090 print load(c_id
).source_string()
2093 clone_l
= st
.get_attribute(c_id
, "interp_clone")
2096 # If no values: is the correct storage instance used?
2098 print id, st
.get_attribute(id, 'interp_result')
2100 # For deeper nesting, follow the clone trail.
2101 st
.get_attribute(id, "interp_clone")
2104 cctxt
= tw
.get_call_ctxt(c_id
)
2108 tw
.print_call_ctxt(cctxt
)
2110 # If clones were cloned, these may be non-empty?
2111 # for id in clone_l:
2112 # print tw.get_call_ctxt(id)
2114 # symbol('i') evaluated, has time stamp, but no value, no env? --
2115 # Use correct storage!
2117 print id, st
.get_attribute(id, 'interp_result')
2118 print id, st
.get_attribute(id, 'interp_env')
2119 pprint( [id, st
.get_attribute_table(id)])
2122 parent
= tw
.find_first_parent(load(id), (ast
.Function
, ast
.Program
))
2123 view
.print_info(st
, parent
)
2124 print parent
._eval
_env
.all_bindings() # empty
2125 print parent
._eval
_env
.lookup('i') # value, at last...
2128 print parent
._eval
_env
.ie_lookup('i')
2131 #* environment viewing
2132 # local eval for program
2133 (self
._l3tree
)._block
_env
.all_bindings()
2134 (self
._l3tree
)._eval
_env
.all_bindings()
2135 (self
._l3tree
)._eval
_env
.ls()
2136 # has print_'s time stamp, but no print.
2137 # [after loading /tmp/st.post-loop ]
2139 #* state examination
2140 # Failed to complete:
2141 print syck
.dump(get_current_state(w_
))
2143 import pickle
, pickletools
2144 st
= get_current_state(w_
)
2145 pickletools
.dis(pickle
.dumps(st
, protocol
=2))
2151 print (self
._l3tree
)._eval
_env
.lookup('print_')
2152 # <function print_ at 0x40402ed4>
2154 n_tree
= pickle
.loads( pickle
.dumps(self
._l3tree
, protocol
=2))
2155 print (n_tree
)._eval
_env
.lookup('print_')
2157 #* voea etc. sample problem
2158 #** python support functions
2159 from l3lang
.external
.golem
import \
2160 create_write_gridprojections
, \
2168 # caption = 'Delta theta (degrees)',
2171 anglist
= Golem
.voea(deltheta
)
2178 # caption = 'Filename of volume to project',
2179 volfile
= "volext.spi"
2181 # caption = 'Kaiser-Bessel K parameter',
2184 # caption = 'Kaiser-Bessel alpha parameter',
2187 # caption = 'Projection file pattern',
2188 filepattern
= 'proj{****}.tst'
2190 # print vol.get_xsize()
2191 create_write_gridprojections(
2192 Golem
.getImage(volfile
),
2193 anglist
, K
, alpha
, filepattern
)
2198 # caption = 'Spider doc filename',
2200 docfname
= 'foo-doc.tst'
2201 anglist2doc(anglist
, docfname
)
2208 # caption = 'Projection file pattern',
2209 filepattern
= 'proj{****}.tst' # above!
2211 # caption = 'Projection start index',
2214 # caption = 'Projection stop index',
2217 # caption = 'Name of angle Spider doc file',
2218 angdocfile
= docfname
# above!
2220 # caption = 'Name of reconstructed volume',
2221 newvolname
= 'newvol.spi'
2222 spidbprg(filepattern
,
2231 # comparison in v4 shows newvolname to be poor...
2233 #* voea/bp as single program
2235 tree
= reader
.parse("""
2237 from l3lang.external.golem import \
2238 create_write_gridprojections, \
2244 def _for(_n, _m, body):
2247 return _for(_n + 1, _m, body)
2253 anglist = Golem.voea(deltheta)
2260 # caption = 'Filename of volume to project',
2261 volfile = "volext.spi"
2263 # caption = 'Kaiser-Bessel K parameter',
2266 # caption = 'Kaiser-Bessel alpha parameter',
2269 # caption = 'Projection file pattern',
2270 filepattern = 'proj{****}.tst'
2272 # print vol.get_xsize()
2273 create_write_gridprojections(
2274 Golem.getImage(volfile),
2275 anglist, K, alpha, filepattern)
2280 # caption = 'Spider doc filename',
2282 docfname = 'foo-doc.tst'
2283 anglist2doc(anglist, docfname)
2290 # caption = 'Projection file pattern',
2291 filepattern = 'proj{****}.tst' # above!
2293 # caption = 'Projection start index',
2296 # caption = 'Projection stop index',
2299 # caption = 'Name of angle Spider doc file',
2300 angdocfile = docfname # above!
2302 # caption = 'Name of reconstructed volume',
2303 newvolname = 'newvol.spi'
2304 spidbprg(filepattern,
2316 #** Directory setup.
2318 ev
= os
.path
.expandvars
2319 os
.chdir(ev('$SPXROOT/l3lang/test'))
2321 shutil
.rmtree('bp-test')
2323 os
.chdir(ev('$SPXROOT/l3lang/test/bp-test'))
2325 shutil
.copyfile(ev('$SPXROOT/l3lang/test/volext.spi'), 'volext.spi')
2328 #** setup and execute
2330 tree
.setup(empty_parent(), def_env
, w_
.state_
.storage
).set_outl_edges(self
.w_
, None)
2331 # view.print_info(storage, tree)
2332 w_
.canvas
.view
.start_add_l3tree(tree
)
2336 from l3lang
import utils
, reader
, ast
, view
, interp
2337 play_env
= interp
.get_child_env(def_env
, storage
)
2338 tree
.setup(empty_parent(), def_env
, storage
).set_outl_edges(self
.w_
, None)
2339 tree
.interpret(def_env
, storage
)
2340 pprint(os
.listdir(os
.getcwd()))
2344 #* voea/bp using docstrings
2345 # /net/cci/hohn/w/tmp/eman2/libpyEM/Golem
2347 tree
= reader
.parse("""
2349 from l3lang.external.golemwrap import *
2352 def _for(_n, _m, body):
2355 return _for(_n + 1, _m, body)
2360 anglist = voea(deltheta)
2365 filepattern = 'proj{****}.tst'
2370 gridproj(getImage("volext.spi"), # nesting...
2374 {filepattern = filepattern})
2377 docfname = 'foo-doc.tst'
2381 anglist2doc(anglist, docfname)
2386 spidbprg(filepattern,
2396 #** Directory setup.
2398 ev
= os
.path
.expandvars
2399 os
.chdir(ev('$SPXROOT/l3lang/test'))
2401 shutil
.rmtree('bp-test')
2403 os
.chdir(ev('$SPXROOT/l3lang/test/bp-test'))
2405 shutil
.copyfile(ev('$SPXROOT/l3lang/test/volext.spi'), 'volext.spi')
2408 #** setup and execute
2410 tree
.setup(empty_parent(), def_env
, w_
.state_
.storage
).set_outl_edges(self
.w_
, None)
2411 # view.print_info(storage, tree)
2412 w_
.canvas
.view
.start_add_l3tree(tree
)
2416 from l3lang
.external
import golemwrap
2417 from l3lang
import utils
, reader
, ast
, view
, interp
2418 play_env
= interp
.get_child_env(def_env
, storage
)
2419 tree
.setup(empty_parent(), play_env
, storage
)
2420 tree
.interpret(play_env
, storage
)
2421 pprint(os
.listdir(os
.getcwd()))
2423 #* voea/bp w/o spider
2425 tree
= reader
.parse("""
2428 #** Directory setup.
2430 ev
= os
.path
.expandvars
2431 os
.chdir(ev('$SPXROOT/l3lang/test'))
2433 shutil
.rmtree('bp-test')
2435 os
.chdir(ev('$SPXROOT/l3lang/test/bp-test'))
2437 shutil
.copyfile(ev('$SPXROOT/l3lang/test/volext.spi'), 'volext.spi')
2440 #** setup and execute
2442 tree
.setup(empty_parent(), def_env
, w_
.state_
.storage
)
2443 # view.print_info(storage, tree)
2444 w_
.canvas
.view
.start_add_l3tree(tree
)
2448 from l3lang
import utils
, reader
, ast
, view
, interp
2449 play_env
= interp
.get_child_env(def_env
, storage
)
2450 tree
.setup(empty_parent(), def_env
, storage
)
2451 tree
.interpret(def_env
, storage
)
2452 pprint(os
.listdir(os
.getcwd()))
2457 view
.print_info(storage
, tree
)
2459 pri( reader
.parse("aa = ff(xx)"))
2460 pri( reader
.parse("aa = ff(xx, yy)"))
2461 pri( reader
.parse("! aa = ! ff( !xx)"))
2463 pri( reader
.parse("aa = ff(xx)"))
2464 pri( reader
.parse("(aa, bb) = ff(xx)"))
2466 reader
.parse("!! aa symbol")
2469 # ---------------------------------
2470 from l3lang
.ast
import *
2471 l3tree
= reader
.parse("a = f(x)")[0][0]
2472 l3tree
= reader
.parse("(a,b) = f(x)")[0][0]
2473 l3tree
= reader
.parse("(a,b) = f(x,y)")[0][0]
2474 l3tree
= reader
.parse("a = f(x,y)")[0][0]
2476 # ---------------------------------
2477 # Test for the special case `a = f(x)` and its
2480 # def add_l3tree_set_tuple()
2484 Call(Marker('ff'), Marker('xx')))):
2485 # Convert to a list of args and list of return values.
2486 _function
= ma
['ff'] # Symbol or expr.
2487 _in
= ma
['xx'] # aList of args.
2489 if ma
.match(out
, # a,b,... =
2490 Tuple(Marker('aa'))):
2491 _out
= ma
['aa'] # aList
2492 elif ma
.match(out
, # a =
2493 MarkerTyped(String('aa'), Symbol('symbol'))):
2494 _out
= aList([ma
['aa']]) # aList
2498 # Get documentation for _in, _out, and _function.
2499 print _out
, _function
, _in
2501 # Get paths for editables.
2502 # Using the unique id.
2508 # The initial try at an expression marker. This version is too buggy;
2509 # the new one is in widgets.py, based on a merge of l3If and
2516 def __init__(self
, w_
, cnvs
, l3_parent
, l3_pidx
, d_expr
):
2519 - `l3_parent` The raw l3 ast parent of d_expr._l3tree.
2520 Without propagation of events from the l3 ast to its
2521 display (the current case), l3_parent should not be
2523 - `l3_pidx` The index of d_expr._l3tree in l3_parent.
2524 - `d_expr` The displayed expression to be handled here.
2526 assert isinstance(d_expr
, (wdgt
.l3aList
, wdgt
.l3Base
))
2527 assert isinstance(l3_parent
, (ast
.astType
,))
2532 self
._l3_parent
= l3_parent
2533 self
._l3_pidx
= l3_pidx
2534 self
._d
_expr
= d_expr
2537 self
._root
_group
= cnvs
.root().add(canvas
.CanvasGroup
)
2538 self
._d
_parent
= None
2539 self
._destroy
_hook
= [] # (func -> None) list
2540 self
._vis
_indic
= None # visibility status indicator
2543 self
._marker
_points
= {}
2544 self
._d
_marker
= self
.draw_marker()
2545 self
._d
_marker
.lower_to_bottom()
2547 # Inform obj of marker.
2548 # This directs physical detachment of d_expr from daExprMarker to
2549 # daExprMarker.detach, which forwards the tree detachment.
2550 d_expr
.setup_marker(self
._d
_marker
, self
)
2553 # Align with respect to d_expr.
2556 ## _, y, x, _ = d_if.get_bounds()
2557 ## u, v, _, _ = d_cond.get_bounds()
2558 ## d_cond.move(x - u, y - v)
2562 self
._d
_marker
.connect("event", lambda *a
: self
.insert_event(*a
))
2563 # Forwarding to parent is implicit.
2564 # # self._root_group.connect("event", lambda *a:
2565 # # self.drag_event(*a))
2566 daExprMarker
.__init
__ = __init__
2569 #** destroy subtree and display
2573 self
._root
_group
.destroy()
2574 daExprMarker
.destroy
= destroy
2576 l3Base
.add_destroy_hook
= add_destroy_hook
2577 l3Base
._run
_destroy
_hook
= _run_destroy_hook
2581 l3Nested
.drag_event
= drag_event
2584 def detach(self
, d_expr
):
2585 if d_expr
!= self
._d
_expr
:
2586 raise DisplayError("Detaching invalid child.")
2588 # Reparent graphical parts.
2589 d_expr
.reparent_to_root()
2597 # Refresh decoration.
2600 # Move following items in parent.
2602 self
._d
_parent
.new_size_for(self
)
2605 if self
.w_
.fluid_ref(detach_l3_tree
= True):
2607 self
._l3_parent
.detach_child(self
.d_expr
._l3tree
._id
,
2608 self
.w_
.state_
.storage
)
2609 # Insert a placeholder, to keep indices valid.
2610 dummy
= ast
.placeholder(self
._l3_parent
, self
.w_
.state_
.storage
)
2611 self
._l3_parent
.insert_child(self
._l3_pidx
, dummy
)
2612 daExprMarker
.detach
= detach
2614 def draw_marker(self
):
2617 cp
.exp_marker_width
, 0,
2618 cp
.exp_marker_width
, cp
.exp_marker_height
,
2619 0 , cp
.exp_marker_height
,
2622 _marker
= self
._root
_group
.add(
2623 canvas
.CanvasPolygon
,
2624 fill_color
= "black",
2627 cap_style
= gtk
.gdk
.CAP_ROUND
,
2628 join_style
= gtk
.gdk
.JOIN_ROUND
,
2630 self
._marker
_points
[_marker
] = points
2632 daExprMarker
.draw_marker
= draw_marker
2634 def insert_event(self
, item
, event
):
2635 if event
.type == gtk
.gdk
.BUTTON_PRESS
:
2636 if event
.button
== 2:
2637 print "insert_event"
2638 if not self
.w_
.selector
.have_selection():
2639 ten_second_message("No node selected.")
2642 self
.insert(item
, self
.w_
.selector
.get_selection())
2644 daExprMarker
.insert_event
= insert_event
2646 def insert(self
, marker
, newobj
):
2647 assert isinstance(newobj
, l3Base
)
2649 if marker
!= self
._d
_marker
:
2650 raise DisplayError("Insertion from wrong marker.")
2652 # Avoid special cases:
2653 if newobj
.contains_recursive(self
._d
_expr
):
2654 ten_second_message("Cannot insert object into itself.")
2657 if newobj
._canvas
!= self
._canvas
:
2658 ten_second_message("Cannot move objects across displays. "
2659 "Use copy instead.")
2663 old_entry
= self
._l3_parent
[self
._l3_pidx
]
2664 slot_available(self
.w_
, old_entry
)
2667 self
._d
_expr
= d_expr
= newobj
2669 # Reparent object display.
2670 newobj
.reparent(self
)
2672 # Position new child.
2674 l1
, t1
, _
, _
= self
._d
_marker
.get_bounds()
2675 l2
, t2
, _
, _
= self
._d
_expr
.get_bounds()
2676 d_expr
.move(l1
- l2
, t1
- t2
)
2680 # Refresh decoration.
2682 # Move following items in parent.
2684 self
._d
_parent
.new_size_for(self
)
2687 if self
.w_
.fluid_ref(insert_l3_tree
= True):
2688 self
._l3_parent
.replace_child(old_entry
._id
, newobj
._l3tree
)
2690 # Inform obj of marker.
2691 newobj
.setup_marker(self
._d
_marker
, self
)
2693 daExprMarker
.insert
= insert
2696 def get_bounds(self
):
2697 """ Marker interface used in Nested.drag_event.
2699 return marker_get_bounds(self
.w_
, self
._d
_marker
)
2700 daExprMarker
.get_bounds
= get_bounds
2705 l3_parent
= reader
.parse("a = f(x,y)")[0][0]
2706 play_env
= interp
.get_child_env(def_env
, storage
)
2707 l3_parent
.setup(empty_parent(), play_env
, storage
)
2710 d_expr
= w_
.canvas
.view
.start_add_l3tree(l3_parent
[l3_pidx
])
2711 d_expr
.move(100, 100)
2713 the_marker
= daExprMarker(w_
, w_
.canvas
.view
, l3_parent
, l3_pidx
, d_expr
)
2719 [ future(operation
, i
, other
) for i
in list]
2721 # operation is a pure function, no envs. Future need not provide
2727 def compute(_n
, _m
):
2729 print_( (_n
+ 1) * _m
)
2730 return compute(_n
+ 1, _m
)
2736 tree
= reader
.parse("""
2738 from l3lang.l3_utils import print_, pprint
2740 def compute(_n, _m):
2742 print_( (_n + 1) * _m)
2743 return compute(_n + 1, _m)
2747 tree
.setup(empty_parent(), def_env
, w_
.state_
.storage
)
2748 w_
.canvas
.view
.start_add_l3tree(tree
)
2754 for i
in range(0,10):
2759 from pprint
import pprint
2761 import atexit
, pdb
, sys
, os
2762 from EMAN2
import EMData
2765 ev
= os
.path
.expandvars
2767 os
.chdir(ev('$SPXROOT/l3lang/test'))
2768 def load( file_name
):
2770 img
.read_image( file_name
)
2772 #** List available functionality.
2773 pprint(EMAN2
.Processors
.get_list())
2774 pprint(EMAN2
.Projectors
.get_list())
2775 pprint(EMAN2
.Reconstructors
.get_list())
2776 pprint(EMAN2
.Cmps
.get_list())
2777 #** Dump ALL get_list containing members.
2778 for nm
in dir(EMAN2
):
2780 memb
= eval("EMAN2.%s.get_list" % nm
)
2781 except AttributeError:
2783 print ("EMAN2.%s.get_list" % nm
)
2785 #** simple mirror test
2789 e
.set_value_at(0,1, 1.0)
2790 print "original at start"
2793 # Use the processors listed by .get_list() above.
2794 f1
= e
.process("mirror",{"axis":'x'})
2795 print "new mirrored image"
2798 print "original after mirror (unchanged)"
2801 e
.process_inplace("mirror",{"axis":'x'})
2802 print "original after in-place mirror"
2805 # Another possibility:
2808 e
.set_value_at(0,0, 1.0)
2809 print "original at start"
2812 e
= e
.process("mirror",{"axis":'x'})
2813 print "new mirrored image"
2817 #* sample from andres' paper
2822 from EMAN2 import EMNumPy
2823 def img_sphere(size, radius, axis, center, fill):
2824 from EMAN2 import EMData
2826 e.set_size(size, size, size)
2827 e.process_inplace('testimage.circlesphere',
2828 {'radius':radius, 'axis':axis,
2829 'c':center, 'fill':fill})
2834 sphere
= img_sphere(32, 20, 'z', 15, 1)
2836 # sphere.print_image()
2838 # No slicing on emdata, use numpy array.
2839 t1
= EMNumPy
.em2numpy(sphere
)
2841 # View all 2d slices
2842 for ix
in range(0,32):
2843 t1
[ix
, 0:None, 0:None]
2849 from EMAN2 import EMNumPy
2850 def img_circle(size, radius, center, fill):
2851 from EMAN2 import EMData
2853 e.set_size(size, size)
2854 e.process_inplace('testimage.circlesphere',
2855 {'radius':radius, 'c':center, 'fill':fill})
2858 circle
= img_circle(32, 20, 15, 1)
2859 t1
= EMNumPy
.em2numpy(circle
)
2863 #** dither / diffuse
2864 #** form projections
2868 #** and much more...
2869 # See "http://www.sciencedirect.com/science?_ob=ArticleURL&_udi=B6WM5-4HVMFBS-1&_user=635986&_coverDate=03%2F31%2F2006&_fmt=full&_orig=search&_cdi=6925&view=c&_acct=C000059612&_version=1&_urlVersion=0&_userid=635986&md5=0e4b1d3ea658eb6330884fef78c4b035&ref=full#SECX2"
2870 # 2D alignment and classification. Particles were normalized, low- and
2871 #high-pass filtered, soft-masked, and then centered. The low- and
2872 #high-pass filters were centered at 1/5 pixels1
2875 #* large list display
2877 # Insert as list list returns but keeps using 100% cpu
2881 # RuntimeError: maximum recursion depth exceeded in cmp
2883 # The number of bounds calculations (marker_get_bounds() and others)
2884 # is ~ N, and bounds calculations are VERY slow...
2887 volume
= load( "model.tcp" )
2889 proj
= volume
.project("pawel",
2890 {"angletype" : "SPIDER",
2891 "anglelist" : [10, 20, 30], # phi, theta, psi
2896 #* visual program representation
2898 # Very convoluted example, heavily using higher-order functions.
2899 # Ugly in graphical view.
2900 t_tree
= reader
.parse_file(
2901 os
.path
.expandvars('$SPXROOT/l3lang/test/calc.l3'))
2902 t_tree
.setup(empty_parent(), def_env
, w_
.state_
.storage
)
2903 w_
.canvas
.view
.clear_state()
2904 w_
.canvas
.view
.start_add_l3tree(t_tree
)
2910 # Very clean top-to-bottom script. Graphical view is still tedious.
2911 # Good reference for prototyping 'nice' graphical view w/o loops.
2912 tm_tree
= reader
.parse_file(
2913 os
.path
.expandvars('$SPXROOT/l3lang/test/ctf.l3'))
2914 tm_tree
.setup(empty_parent(), def_env
, w_
.state_
.storage
)
2915 w_
.canvas
.view
.clear_state()
2916 tm_tree_l3pic
= w_
.canvas
.view
.start_add_l3tree(tm_tree
)
2920 #*** concise view, program level, static
2922 # no program editing (static)
2923 t0_tree
= reader
.parse("""
2924 "project from volume"
2925 "convolve image and ctf"
2926 "produce noisy image"
2927 "apply ctf correction"
2930 t0_tree
.setup(empty_parent(), def_env
, w_
.state_
.storage
)
2931 t0_tree_pic
= w_
.canvas
.view
.start_add_l3tree(t0_tree
)
2933 t0_tree_pic
.move(+8, +5.5) # Relative movement.
2936 #*** concise view, program + calls, static
2938 # no program editing (static)
2939 t1_tree
= reader
.parse("""
2940 project_from_volume(spi.pj3)
2942 convolve_image_and_ctf(spi.ft, spi.tfc, spi.mu, spi.ft)
2944 produce_noisy_image(spi.mo, spi.adf)
2946 apply_ctf_correction(spi.tfcts)
2950 t1_tree
.setup(empty_parent(), def_env
, w_
.state_
.storage
)
2951 t1_tree_pic
= w_
.canvas
.view
.start_add_l3tree(t1_tree
)
2953 t1_tree_pic
.move(+35, +7.5) # Relative movement.
2957 #*** concise view, program + manually selected details
2959 # For ctf.l3, selected full subtrees are the desirable level of detail, so
2960 # no reordered node display is needed.
2961 # To keep the connection to the (function name based) outline view,
2962 # the function names can appear explicitly around the expansion.
2963 # For the present sample, this is redundant. Maybe not for others?
2964 t3_tree
= reader
.parse("""
2965 project_from_volume(
2967 testimg = spi.pj3("/home/hohn/w/phenix/l3lang/test/volext.spi",
2969 [45.5, 27.2, -30.0])))
2971 convolve_image_and_ctf(
2974 ctf = spi.tfc((2), # cs[mm]
2975 (10000, 0.025), # defocus(a), lambda(a)
2976 (64, 64), # dimension of the 2d array
2977 (0.17), # maximum spatial frequency
2978 (0.005, 0), # source size[a-1], defocus spread[a]
2979 (0, 0), # astigmatism[a], azimuth[deg]
2980 (0.1, 10000), # amplitude contrast ratio, gaussian envelope halfwidth
2981 (-1), # sign (+1 or -1)
2986 produce_noisy_image(
2988 noise = call_kwd_func(spi.mo, [64, 64], "random",
2989 { use_gaussian = 'y', mean = 1,
2990 std_deviation = 200} )),
2993 apply_ctf_correction(
2995 restored_img = spi.tfcts(spi.img_to_stack(noisyimg),
2997 spi.img_to_stack(ctf),
3003 t3_tree
.setup(empty_parent(), def_env
, w_
.state_
.storage
)
3004 t3_tree_pic
= w_
.canvas
.view
.start_add_l3tree(t3_tree
)
3006 t3_tree_pic
.move(+70, +7.5) # Relative movement.
3009 #*** concise view, program + some full details
3011 # full program editing in the details
3012 # This version is disjoint from the others; it's missing the
3014 t2_tree
= reader
.parse("""
3015 project_from_volume(
3016 testimg = spi.pj3("/home/hohn/w/phenix/l3lang/test/volext.spi",[64, 64],
3017 [45.5, 27.2, -30.0]))
3019 convolve_image_and_ctf(spi.ft,
3022 (10000, 0.025), # defocus(a), lambda(a)
3023 (64, 64), # dimension of the 2d array
3024 (0.17), # maximum spatial frequency
3025 (0.005, 0), # source size[a-1], defocus spread[a]
3026 (0, 0), # astigmatism[a], azimuth[deg]
3027 (0.1, 10000), # amplitude contrast ratio, gaussian envelope halfwidth
3028 (-1), # sign (+1 or -1)
3031 produce_noisy_image(
3032 noise = call_kwd_func(spi.mo, [64, 64], "random",
3033 { use_gaussian = 'y', mean = 1,
3034 std_deviation = 200} ),
3037 apply_ctf_correction(restored_img = spi.tfcts(spi.img_to_stack(noisyimg),
3039 spi.img_to_stack(ctf),
3045 t2_tree
.setup(empty_parent(), def_env
, w_
.state_
.storage
)
3046 t2_tree_pic
= w_
.canvas
.view
.start_add_l3tree(t2_tree
)
3048 t2_tree_pic
.move(+135, +7.5) # Relative movement.
3051 #* LOOP language addition.
3054 from l3lang
import utils
, reader
, ast
, view
, interp
3056 t2_tree
= reader
.parse("""
3057 inline "from pprint import pprint"
3058 loop dtheta(iteration, deltheta) from (1, 40):
3060 pprint([iteration, deltheta])
3061 return dtheta(iteration + 1, deltheta / 2.0)
3063 return deltheta / 2.0
3066 play_env
= interp
.get_child_env(def_env
, w_
.state_
.storage
)
3069 t2_tree
.setup(empty_parent(), play_env
, w_
.state_
.storage
)
3070 t2_tree
.interpret(play_env
, w_
.state_
.storage
)
3073 t2_tree
.setup(empty_parent(), play_env
, w_
.state_
.storage
)
3074 # view.print_info(storage, tree)
3075 # pdb.run('w_.canvas.view.start_add_l3tree(t2_tree)')
3078 ##l3gui.misc.DisplayError: internal _container / _parent inconsistency.
3079 ##w_.canvas.view.clear_state()
3080 w_
.canvas
.view
.start_add_l3tree(t2_tree
)
3085 #* LIST language addition.
3088 from l3lang
import utils
, reader
, ast
, view
, interp
3091 t2_tree
= reader
.parse("""
3092 inline "from pprint import pprint"
3099 pprint((iteration, "small"))
3104 t2_tree
= reader
.parse("""
3105 inline "from pprint import pprint"
3106 list "A short block":
3109 if (iteration <= 10):
3112 pprint((iteration, "small"))
3116 play_env
= interp
.get_child_env(def_env
, w_
.state_
.storage
)
3119 t2_tree
.setup(empty_parent(), play_env
, w_
.state_
.storage
)
3120 w_
.canvas
.view
.start_add_l3tree(t2_tree
)
3125 t2_tree
.setup(empty_parent(), play_env
, w_
.state_
.storage
)
3126 t2_tree
.interpret(play_env
, w_
.state_
.storage
)
3134 The reference files for these fragments are now
3136 l3lang/test/voea-bp.py, v1.7 and beyond
3138 voea-bp-var.l3, v1.5 and beyond
3140 #** utils (evaluate this!)
3141 def canvas_add_program(text
, xx
= 0, yy
= 0):
3142 t0_tree
= reader
.parse(text
)
3143 t0_play_env
= interp
.get_child_env(def_env
, w_
.state_
.storage
)
3144 t0_tree
.setup(empty_parent(), t0_play_env
, w_
.state_
.storage
)
3145 t0_tree_l3pic
= w_
.canvas
.view
.start_add_l3tree(t0_tree
)
3146 t0_tree_l3pic
.move(xx
, yy
) # Relative movement.
3148 def canvas_add_1st_expr(text
, xx
= 0, yy
= 0):
3149 t0_tree
= reader
.parse(text
)[0][0]
3150 t0_tree
.setup(empty_parent(), def_env
, w_
.state_
.storage
)
3151 t0_tree_l3pic
= w_
.canvas
.view
.start_add_l3tree(t0_tree
)
3152 t0_tree_l3pic
.move(xx
, yy
) # Relative movement.
3154 def canvas_add_ast(self
, t0_tree
, xx
= 0, yy
= 0):
3155 from l3lang
import utils
, reader
, ast
, view
, interp
3157 t0_play_env
= interp
.get_child_env(st
.def_env
, st
.storage
)
3158 t0_tree
.setup(ast
.empty_parent(), t0_play_env
, st
.storage
)
3159 t0_tree_l3pic
= self
.start_add_l3tree(t0_tree
)
3160 t0_tree_l3pic
.move(xx
, yy
) # Relative movement.
3161 return t0_tree_l3pic
3162 l3Canvas
.canvas_add_ast
= canvas_add_ast
3165 # print "\n".join(map(lambda (x,y): "%g %g" % (x,y),
3166 # (zip([1,2], [3,4]))))
3171 data
= "\n".join(map(lambda (x
,y
): "%g %g" % (x
,y
),
3174 gnuplot -persist <<EOF
3177 set out "/tmp/foo.ps"
3181 ## set title "comparison"
3183 plot '-' w lines lw 6
3187 ps2epsi /tmp/foo.ps /tmp/foo.eps
3192 ## plot([1,2], [3,4])
3195 #*** directory of program run
3196 # See Program.directory
3200 # #*** concise view, program level, static
3201 # # manually written
3202 # # no program editing (static)
3203 # t0_tree = reader.parse("""
3204 # "get reference volume"
3205 # "iterate delta theta"(
3206 # "calculate angles",
3209 # "compare volumes",
3210 # "repeat if necessary")
3212 # t0_play_env = interp.get_child_env(def_env, w_.state_.storage)
3213 # t0_tree.setup(empty_parent(), t0_play_env, w_.state_.storage)
3214 # ## w_.canvas.view.clear_state()
3215 # t0_tree_l3pic = w_.canvas.view.start_add_l3tree(t0_tree)
3216 # t0_tree_l3pic.move(+8.5, +7.5) # Relative movement.
3220 # #*** concise view, program + calls, static
3221 # # manually written
3222 # # no program editing (static)
3223 # t1_tree = reader.parse("""
3224 # "get reference volume"
3225 # "iterate delta theta"(
3226 # "calculate angles"(anglist = voea(deltheta)),
3227 # "projections"(proj_list = gridproj(ref_vol,
3231 # "backproject"(back_projection = backproj(proj_list,
3235 # "compare volumes"(ccc = EMAN2.Cmps.get("ccc").cmp(back_projection,
3237 # "repeat if necessary"(if_branch))
3239 # t1_play_env = interp.get_child_env(def_env, w_.state_.storage)
3240 # t1_tree.setup(empty_parent(), t1_play_env, w_.state_.storage)
3241 # ## w_.canvas.view.clear_state()
3242 # t1_tree_l3pic = w_.canvas.view.start_add_l3tree(t1_tree)
3243 # t1_tree_l3pic.move(+42, +7.5) # Relative movement.
3248 # Very clean top-to-bottom script
3249 tm_tree
= reader
.parse_file(
3250 os
.path
.expandvars('$SPXROOT/l3lang/test/voea-bp.l3'))
3251 tm_play_env
= interp
.get_child_env(def_env
, w_
.state_
.storage
)
3252 tm_tree
.setup(empty_parent(), tm_play_env
, w_
.state_
.storage
)
3253 # w_.canvas.view.clear_state()
3254 tm_tree_l3pic
= w_
.canvas
.view
.start_add_l3tree(tm_tree
)
3255 # tm_tree_l3pic.move(+77, +7.5) # Relative movement.
3259 #** Add text tree to canvas
3262 # [12L, 13L, 27L, 59L, 195L]
3264 canvas_add_1st_expr("""
3274 canvas_add_1st_expr("""
3285 canvas_add_program("""
3286 from l3lang.test.voea_bp_support import *
3307 # Figure from gnuplot
3310 #** get the diretory structure
3312 ## use program -> eval locally
3314 (self
._l3tree
)._block
_env
.print_tree()
3317 (self
._l3tree
)._eval
_env
.print_tree()
3319 # As lists of names.
3321 from pprint
import pprint
3322 pprint((self
._l3tree
)._block
_env
.get_tree())
3323 pprint((self
._l3tree
)._eval
_env
.get_tree())
3327 ## use program -> eval locally
3328 from pprint
import pprint
3329 listing
= (self
._l3tree
)._eval
_env
.get_dynamic_subtrees()
3332 dir_struct
= self
._l3tree
.directory(listing
)
3333 dir_view
= self
._canvas
.canvas_add_ast(dir_struct
)
3334 dir_view
.move(10, 10)
3337 #*** More^2 filtered.
3338 ## use program -> eval locally
3339 dir_struct
= self
._l3tree
.directory_l3()
3340 dir_view
= self
._canvas
.canvas_add_ast(dir_struct
)
3341 dir_view
.move(20, 20)
3344 dir_struct
= List(aList([List(aList([List(aList([Symbol('volume'), Symbol('projections'), Symbol('errs'), Symbol('anglist'), Symbol('proj_list'), Symbol('back_projection'), Symbol('cross_corr'), Symbol('volfile'), Symbol('freqs'), Symbol('num_angles'), Symbol('angle_file'), Symbol('fsc_vals')])), Symbol('iteration'), Symbol('deltheta')])), List(aList([List(aList([Symbol('volume'), Symbol('projections'), Symbol('errs'), Symbol('anglist'), Symbol('proj_list'), Symbol('back_projection'), Symbol('cross_corr'), Symbol('volfile'), Symbol('freqs'), Symbol('num_angles'), Symbol('angle_file'), Symbol('fsc_vals')])), Symbol('iteration'), Symbol('deltheta')])), List(aList([List(aList([Symbol('volume'), Symbol('projections'), Symbol('errs'), Symbol('anglist'), Symbol('proj_list'), Symbol('back_projection'), Symbol('cross_corr'), Symbol('volfile'), Symbol('freqs'), Symbol('num_angles'), Symbol('angle_file'), Symbol('fsc_vals')])), Symbol('iteration'), Symbol('deltheta')])), List(aList([List(aList([Symbol('volume'), Symbol('projections'), Symbol('errs'), Symbol('anglist'), Symbol('proj_list'), Symbol('back_projection'), Symbol('cross_corr'), Symbol('volfile'), Symbol('freqs'), Symbol('num_angles'), Symbol('angle_file'), Symbol('fsc_vals')])), Symbol('iteration'), Symbol('deltheta')])), List(aList([List(aList([Symbol('volume'), Symbol('projections'), Symbol('errs'), Symbol('anglist'), Symbol('proj_list'), Symbol('back_projection'), Symbol('cross_corr'), Symbol('volfile'), Symbol('freqs'), Symbol('num_angles'), Symbol('angle_file'), Symbol('fsc_vals')])), Symbol('iteration'), Symbol('deltheta')])), Symbol('dtheta'), Symbol('spi'), Symbol('ref_vol')]))
3346 dir_view
= w_
.canvas
.view
.canvas_add_ast(dir_struct
)
3347 dir_view
.move(20, 20)
3351 gtk
.main() # use menu->exit
3353 #* presentation-may-2006
3355 # xterm reference size 120x50
3357 # convert /tmp/foo.ps -rotate 90 -resize 400x400 /tmp/foo.png
3359 tm_tree
= reader
.parse("""
3371 list "eman2 members":
3374 list "spider members":
3397 inline "from l3lang.test.voea_bp_support import *"
3399 loop name(arg) from (start_val):
3403 tm_play_env
= interp
.get_child_env(def_env
, w_
.state_
.storage
)
3404 tm_tree
.setup(empty_parent(), tm_play_env
, w_
.state_
.storage
)
3406 tm_tree_l3pic
= w_
.canvas
.view
.start_add_l3tree(tm_tree
)
3411 #** value insertion preview
3413 canvas_add_1st_expr("""
3423 canvas_add_1st_expr("""
3434 canvas_add_program("""
3435 inline "from l3lang.test.voea_bp_support import *"
3457 #* sparx functions as of [Jun-13-2006]
3459 #** Changed sparx imports to fix this.
3460 #** Trying to get an overview of the sparx functions
3461 # as of [Jun-13-2006]
3465 # For this, the module structure SHOULD be useful. But it isn't
3466 # available interactively.
3468 # The following doesn't do much good. There are no comments, and
3469 # e.g. do_alignment (visible via dir(sparx)) is not shown at all.
3473 from sparx
import libpy
3474 # with ImportError: cannot import name libpy.
3477 # is <module 'sparx' from '/net/hooknose/scratch1/hohn/rh9/ia32/installer-0.5/sparx-bin/opt/sparx/libpy/sparx.pyc'>
3479 # All because of the
3480 # from utilities import *
3481 # from filter import *
3482 # from projection import *
3483 # from fundamentals import *
3484 # from statistics import *
3485 # from alignment import *
3486 # from morphology import *
3487 # from reconstruction import *
3488 # in libpy/sparx.py!
3489 help(sparx
.do_alignment
)
3491 # So, I manually get the structure.
3502 # For nested modules, this should give information
3503 prfx
, lst
= ("sparx",
3514 [help("%s.%s" % (prfx
, itm
)) for itm
in lst
]
3516 # But here it fails with
3517 # no Python documentation found for 'sparx.utilities'
3518 # no Python documentation found for 'sparx.filter'
3519 # no Python documentation found for 'sparx.projection'
3521 # again because of the import *
3523 #** Overview of the sparx functions as of [Tue Jun 13 13:05:25 2006]
3524 import sparx
.libpy
as spx
3527 # module/function listing
3528 for mod
in dir(spx
):
3529 if not is_module(mod
): continue
3530 for func
in dir(mod
):
3531 if not is_function(func
): continue
3532 print "module: %s\t\tfunction: %s" % (mod
, func
)
3536 #** sparx.gui console use:
3538 tm_tree
= reader
.parse_file(
3539 os
.path
.expandvars('$SPXROOT/l3gui/test/iref01.py'))
3540 tm_play_env
= interp
.get_child_env(def_env
, w_
.state_
.storage
)
3541 tm_tree
.setup(empty_parent(), tm_play_env
, w_
.state_
.storage
)
3542 tm_tree_l3pic
= w_
.canvas
.view
.start_add_l3tree(tm_tree
)
3545 #* sparx persistence
3546 #** eman 'native' I/O
3548 volume
= sx
.getImage( "model.tcp" )
3550 raw
= sx
.project(volume
, [10.0, 20.0, 30.0, 0.0, 0.0], 35)
3553 print raw
.get_attr_dict()
3555 # Looks like spider format doesn't keep the attributes:
3556 sx
.dropImage(raw
, "raw.spi", itype
= 's')
3557 raw_s
= sx
.getImage("raw.spi")
3559 print raw_s
.get_attr_dict()
3563 sx
.dropImage(raw
, "raw.hdf")
3564 raw_s
= sx
.getImage("raw.hdf")
3566 print raw_s
.get_attr_dict()
3570 # Make sure there is no EMData.__getattr__ to avoid '__getinitargs__':
3571 # 'Not exist' caught crap.
3572 import l3lang
.utils
as ut
3574 raw_p
= ut
.file_unpickle("/tmp/foo")
3577 print raw
.get_attr_dict()
3578 print raw_p
.get_attr_dict()
3581 #** l3 state table pickling
3583 import l3lang
.utils
as ut
3584 ut
.file_pickle(w_
.state_
.storage
, "st.post-run-table")
3585 # takes forever; remove
3587 #* comment attachment
3588 # Similar to reader.raw_lexer(code_s)
3590 import sys
, token
, tokenize
3591 code_s
= open(os
.path
.expandvars('$SPXROOT/l3gui/test/iref01.py')).read()
3595 # Comment type identifier.
3596 COMMENT
, _
= filter(lambda (k
,v
): v
== 'COMMENT', token
.tok_name
.items())[0]
3597 NEWLINE
, _
= filter(lambda (k
,v
): v
== 'NEWLINE', token
.tok_name
.items())[0]
3598 NL
, _
= filter(lambda (k
,v
): v
== 'NL', token
.tok_name
.items())[0]
3602 #*** Cluster connected successive comment lines.
3603 # When connecting to the parse tree, this style of clustering has a
3613 # `comment 1` will attach to `code 1`, leaving `comment 2` to attach to
3614 # `code 2`, which is not good.
3617 # - drop one of the comments, attach other to `code 1`
3618 # - combine comments and attach to `code 1`
3620 gen
= tokenize
.generate_tokens(reader
.string_readline(code_s
))
3622 va_cluster
= [] # (string, begin, end) list
3623 va_accum
= [] # va_cluster list
3625 (type, string
, begin
, end
, line
) = ii
3627 # Dump every comment.
3629 print "(%r, %s, %s)" % (string
, begin
, end
)
3631 # Cluster comment lines.
3632 if type in [COMMENT
]:
3634 va_cluster
.append( (string
, begin
, end
) )
3638 va_accum
.append(va_cluster
)
3643 pprint(va_accum
, sys
.stdout
, 4, 2)
3646 #*** Cluster successive (incl.separated) comment lines
3647 # Combine blank-separated comment blocks.
3648 gen
= tokenize
.generate_tokens(reader
.string_readline(code_s
))
3650 va_cluster
= [] # (string, begin, end) list
3651 va_accum
= [] # va_cluster list
3653 (type, string
, begin
, end
, line
) = ii
3655 # # Dump every comment.
3656 # if type == COMMENT:
3657 # print "(%r, %s, %s)" % (string, begin, end)
3659 # Cluster successive comment lines, even those separated by blanks.
3660 if type in [COMMENT
]:
3662 va_cluster
.append( (string
, begin
, end
) )
3664 elif type in [NEWLINE
, NL
]:
3666 va_cluster
.append( (string
, begin
, end
) )
3669 # Remove trailing empty newlines.
3671 while tl
[0] == '\n':
3672 tl
= va_cluster
.pop()
3673 va_cluster
.append(tl
)
3675 va_accum
.append(va_cluster
)
3682 for clus
in va_accum
:
3683 print clus
[0][1] # begin
3685 print line
[0], # body
3686 print clus
[-1][2] # end
3690 #*** Simplify comment structure
3691 # Adjust lexeme row indexing, compact clusters, and remove unused data.
3692 va_comments
= [] # ((last_row, first_col), string) list
3694 ( (clus
[-1][2][0] - 1, clus
[0][1][1]), # (last_row, first_col)
3695 "".join([line
[0] for line
in clus
]))
3696 for clus
in va_accum
]
3701 tree
= reader
.parse(code_s
)
3704 #*** extract a list of leading subnodes from the parse tree
3706 tr_lines
= [] # [(start_row, col), node] list
3707 for nd
in tree
.subtrees():
3708 (row
, col
), _
= nd
.get_char_range()
3709 # Prune all but first expression on a line.
3711 tr_lines
.append( [(row
,col
), nd
] )
3712 ## tr_lines.append( [(row,col), nd] )
3718 #** Find expression to attach to.
3719 # Consider only the first expression in given line.
3720 # Find the first expression following a comment end.
3722 def align_and_show():
3723 com_it
= iter(va_comments
)
3724 node_it
= iter(tr_lines
)
3725 com_row
= lambda com
: com
[0][0]
3727 try: com
= com_it
.next()
3728 except StopIteration: break
3729 try: nd
= node_it
.next()
3730 except StopIteration: break
3731 com_line
= com
[0][0]
3732 # Find first line after current comment.
3733 while nd
[0][0] <= com_line
:
3735 if com
[0][1] != nd
[0][1]:
3736 print "==== column mismatch"
3738 print nd
[1].source_string()
3741 ## import pdb; pdb.set_trace()
3744 #* selection handling
3745 # See pygtk-2.4.1/examples/ide/edit.py as example.
3749 warnings
.filterwarnings("error", "assertion") # , GtkWarning
3751 # But the C code just continues on.
3753 # ... the bigger problem is that a fair amount of C code doesn't
3754 # handle the case where the assertion fails ...
3759 view
= w_
.canvas
.view
3760 ra
= w_
.canvas
.view
.root().add
3761 c_label
= ra(canvas
.CanvasText
,
3763 size_points
= 12 * 1,
3769 print c_label
.get_bounds()
3770 print c_label
.__grefcount
__
3774 view
= w_
.canvas
.view
3775 ra
= GtkObjProxy(w_
.canvas
.view
.root())
3776 c_label
= GtkObjProxy(ra
.add(canvas
.CanvasText
,
3778 size_points
= 12 * 1,
3784 print c_label
.get_bounds()
3787 print c_label
.get_bounds()
3790 #* python compile tests
3791 # Accepted as complete input...
3800 ''', '<string>', 'single')
3828 #* gtk object pickling
3829 # local eval of l3Rawtext
3830 import l3lang
.utils
as ut
3831 # Runs (works? Protocol 1 fails.).
3832 ut
.file_pickle( self
._ltext
.get_property("anchor"))
3833 val
= ut
.file_unpickle("/tmp/foo")
3836 # (.:19911): GLib-GObject-WARNING **: cannot retrieve class for
3837 # invalid (unclassed) type `<invalid>'
3839 # ** ERROR **: file pygenum.c: line 60 (pyg_enum_repr): assertion
3840 # failed: (G_IS_ENUM_CLASS(enum_class))
3844 #* l3IfLoop addition
3845 #** test single loop
3858 # calc 3d reconstruction
3864 # calc 3d reconstruction
3867 # repeat from gen. proj
3869 return _lname(2 - foo)
3874 # repeat from gen. proj
3876 return _loop(bar + 1)
3879 l3tree
= reader
.parse(test_s
)
3883 #** l3ifloopbreak pattern 1
3888 template
= reader
.parse(code_s
)
3891 #** l3ifloopbreak pattern 2
3896 template
= reader
.parse(code_s
)
3900 #** test single loop w/ break
3912 #** test single loop w/ continue
3918 return lname(new_args)
3924 #** l3ifloop pattern
3931 template
= reader
.parse(code_s
)
3936 # From template.body().
3938 body
= l3tree
.body()
3941 aList([Set(MarkerTyped(Symbol('LNAME'), Symbol('symbol')),
3942 Function(MarkerTyped(Symbol('LARGS'), aList([])),
3943 MarkerTyped(Symbol('LBODY'), aList([])))),
3944 Call(MarkerTyped(Symbol('LNAME2'), Symbol('symbol')),
3945 MarkerTyped(Symbol('CARGS'), aList([])))]),
3947 if ma
['LNAME'] != ma
['LNAME2']:
3948 warn_("loop name mismatch; no special display")
3949 elif len(ma
['LARGS']) != len(ma
['CARGS']):
3950 warn_("arguments mismatched between loop definition and call")
3960 from l3lang
.l3
import *
3962 #** interpretation order
3974 print "hello", "world"
3977 inline
"from math import *"
3978 def f(a
,b
, c
= cos(22), d
= 10):
3985 f(1,2, e
= 1) # unknown keyword
3989 p
= f(1,2, c
= cos(22), d
= 1)
3990 p
= f(1,2, c
= 22, d
= 1)
4012 # old errors (pre-r460)
4013 print parse('a = b')
4014 print parse('a == b')
4016 print parse('(a == b)')
4017 print parse('(a <= b)')
4019 print parse('(a = b)')
4020 print parse('(av1*(int(nima/2)+(nima%2)) + av2*int(nima/2))/nima')
4023 #* l3 tests, in gui (repeated interpretation checks)
4025 filter(lambda x
: x
> 2, [1,2,3,4])
4028 inline
"from l3lang.l3 import *"
4029 def f(a
,b
, c
= cos(22), d
= 10):
4034 if ("prog", "filter test"):
4035 filter(lambda x
: x
> 2, [1,2,3,4])
4044 # using > "eval locally"
4046 # Program(aList([Call(Symbol('*'), aList([Int(6L), Call(Symbol('-'), aList([Int(3L), Int(2L)]))]))]))
4047 # >>> self._l3tree._first_char
4049 # >>> self._l3tree._last_char
4054 #* statement additions
4055 #** is, is not, not in
4059 print hello, "world"
4061 reader
.raw_lexer(code_s
)
4064 #* l3 internals tests (from python)
4066 tree
= reader
.parse('f(1,2, c = sin(22), d = 10)')
4068 play_env
= interp
.get_child_env(def_env
, storage
)
4069 tree
.setup(empty_parent(), play_env
, storage
)
4070 view
.print_info(storage
, tree
, show_macros
= True)
4073 print tree
.body().positional_args()
4074 print tree
.body().nargs()
4075 print tree
.body().named_args()
4077 tree
.interpret(def_env
, storage
)
4079 tree
= reader
.parse('''
4080 def f(a,b, c = cos(22), d = 10):
4084 play_env
= interp
.get_child_env(def_env
, storage
)
4085 tree
.setup(empty_parent(), play_env
, storage
)
4086 view
.print_info(storage
, tree
, show_macros
= True)
4088 func_
= tree
.body()[1]
4089 print func_
.positional_block_args()
4090 print func_
.named_block_args()
4094 tree
.interpret(def_env
, storage
)
4098 from l3lang
.view
import print_ast
4100 print_ast(reader
.parse(str))
4106 tree
= reader
.parse('''
4114 play_env
= interp
.get_child_env(def_env
, storage
)
4115 tree
.setup(empty_parent(), play_env
, storage
)
4116 view
.print_info(storage
, tree
, show_macros
= True)
4119 tree
.interpret(def_env
, storage
)
4120 view
.print_info(storage
, tree
)
4121 view
.print_all_info(storage
, tree
)
4122 # ok: repeated .interpret() reuses first clone.
4130 reader
.py_lexer(code_s
)
4131 print reader
.parse(code_s
)
4133 #*** eval 3 - single call
4141 # reader.raw_lexer(code_s)
4142 # reader.py_lexer(code_s)
4143 tree
= reader
.parse(code_s
)
4146 play_env
= interp
.get_child_env(def_env
, storage
)
4147 tree
.setup(empty_parent(), play_env
, storage
)
4148 view
.print_info(storage
, tree
, show_macros
= True)
4151 tree
.interpret(play_env
, storage
)
4152 view
.print_info(storage
, tree
)
4153 view
.print_all_info(storage
, tree
)
4154 # repeated .interpret() reuses first clone ?
4157 #*** eval 4 - variable value change
4166 # reader.raw_lexer(code_s)
4167 # reader.py_lexer(code_s)
4168 tree
= reader
.parse(code_s
)
4171 play_env
= interp
.get_child_env(def_env
, storage
)
4172 tree
.setup(empty_parent(), play_env
, storage
)
4173 view
.print_info(storage
, tree
, show_macros
= True)
4176 tree
.interpret(play_env
, storage
)
4177 view
.print_env(play_env
)
4178 view
.print_info(storage
, tree
)
4179 view
.print_all_info(storage
, tree
)
4180 # repeated .interpret() reuses first clone ???
4193 # reader.raw_lexer(code_s)
4194 # reader.py_lexer(code_s)
4195 tree
= reader
.parse(code_s
)
4198 play_env
= interp
.get_child_env(def_env
, storage
)
4199 tree
.setup(empty_parent(), play_env
, storage
)
4200 view
.print_info(storage
, tree
, show_macros
= True)
4203 tree
.interpret(play_env
, storage
)
4204 view
.print_all_info(storage
, tree
)
4205 tree
.interpret(play_env
, storage
)
4206 view
.print_all_info(storage
, tree
)
4208 view
.print_info(storage
, tree
)
4209 view
.print_env(play_env
)
4210 # repeated .interpret() reuses first clone ???
4216 #** eval 6 -- `while` expansion
4243 tree
= reader
.parse(code_s
)
4246 play_env
= interp
.get_child_env(def_env
, storage
)
4247 tree
.setup(empty_parent(), play_env
, storage
)
4250 tree
.interpret(play_env
, storage
)
4251 view
.print_all_info(storage
, tree
)
4253 tree
.interpret(play_env
, storage
)
4254 view
.print_all_info(storage
, tree
)
4256 view
.print_env(play_env
)
4259 #** eval 7 -- `while` template
4275 tree
= reader
.parse(code_s
)
4278 play_env
= interp
.get_child_env(def_env
, storage
)
4279 tree
.setup(empty_parent(), play_env
, storage
)
4280 view
.print_all_info(storage
, tree
)
4284 #** eval 8 -- `while` tests
4293 tree
= reader
.parse(code_s
)
4296 play_env
= interp
.get_child_env(def_env
, storage
)
4297 tree
.setup(empty_parent(), play_env
, storage
)
4298 view
.print_info(storage
, tree
)
4301 tree
.interpret(play_env
, storage
)
4302 view
.print_all_info(storage
, tree
)
4304 tree
.interpret(play_env
, storage
)
4305 view
.print_all_info(storage
, tree
)
4307 view
.print_env(play_env
)
4309 #*** reference comparison
4310 # Remove id / timestamp columns, then compare per-character.
4326 ref_t
= reader
.parse(ref_s
)
4328 ref_env
= interp
.get_child_env(def_env
, storage
)
4329 ref_t
.setup(empty_parent(), ref_env
, storage
)
4330 view
.print_info(storage
, ref_t
)
4333 #** eval 9 -- `while` pattern
4346 tree
= reader
.parse(code_s
)
4356 # Nesting, check identifiers.
4371 #* for loop language addition
4372 # for loop using while
4374 #** iterator wrapper
4376 def __init__(self
, seq
):
4377 self
._iter
= iter(seq
)
4379 self
._next
_ready
= False
4382 if self
._next
_ready
:
4385 self
._next
= self
._iter
.next()
4386 self
._next
_ready
= True
4388 except StopIteration:
4389 self
._next
_ready
= False
4394 self
._next
_ready
= False
4396 raise InterpreterError("Request for elements from finished iterator.")
4404 for (x
,y
) in [(1,2), (3,4)]:
4410 I
= l3iter([(1,2), (3,4)])
4415 # To avoid pickling [(1,2), (3,4)] or I, use
4417 # inline 'I = l3iter([(1,2), (3,4)])'
4420 inline
'from l3lang.interp import l3iter; I = l3iter([(1,2), (3,4)])'
4427 #** embed l3 'tail call' form for while:
4432 # def "_while_ID"():
4433 # if not C: # force boolean evaluation via not
4437 # return _while_ID()
4442 inline
'from l3lang.interp import l3iter; I = l3iter([(1,2), (3,4)])'
4454 #** iterator problems
4456 # 1. The sequence cannot be edited (it's a string)
4457 # 2. The indirection
4458 # - (value list VL) -> external (l3iter) -> (value sequence VS)
4459 # loses the time stamps between VL and VS, so that updates to VL
4460 # re-evaluate everything.
4462 # Thus, iterators are USELESS in l3: no persistence and no
4463 # incremental evaluation.
4465 # 3. Are I.more and I.next called again on repeated interpretation?
4467 # 4. External iterator assignments will cause failure:
4481 # Repeat execution of UNORDERED iterators will always fail.
4482 # l3 execution imparts unique ids, IN ORDER of execution.
4484 # Retrieving all iterator values and storing them is not an option
4485 # because iterators need not be finite.
4487 # A prime example: a true rand() MUST NOT be used in l3. Unless it's
4488 # a pseudo-random, FIXED sequence.
4491 # [Thu Jul 12 11:57:28 2007]
4492 # A possible adjustment is to let Call.interpret return all iterators
4493 # as externals, and evaluating every time as done for Inline(). If
4494 # done that way, the for loop also simplifies.
4498 I
= l3iter([(1,2), (3,4)])
4510 #** iterator problems, part 2
4511 # ---------------------------------
4512 # Re-examining iterators in l3 is slow and makes interpretation yet
4513 # more complicated. Instead,
4515 # 1. make sure that l3iter instances pickle,
4517 # 2. assume (and test that) the iterator given to l3iter produces a
4518 # constant sequence, and
4520 # 3. let l3iter re-run the iterators (after unpickling, or better at
4521 # the first call to I.more) to get to the correct position in the
4523 # If the iterator itself performs a lot of work, nothing is gained
4526 # Retrieving the iterator is a problem.
4527 # It cannot be saved with the l3iter instance, but re-running
4528 # l3iter(iterator) will create a new instance (losing the
4529 # timestamp/position info).
4530 # This requires some internal magic...
4533 #** simplify to sequences
4534 # ----------------------
4535 # Backtrack to Python < 2.2, without the __iterator__ mess. There,
4537 # The for statement is used to iterate over the elements of a
4538 # sequence (string, tuple or list):
4541 # sequence types support the len() and [] operators (__len__ and
4542 # __getitem__). Restricting to known-size sequences is a minor
4543 # restriction for tracked, DISPLAYED items.
4545 # For general iterators and simple uses, use Python directly. The
4548 for k
in edsummary
.iterkeys():
4549 print k
+ ": %.3f" % edsummary
[k
]
4551 # uses an unordered iterator, so it cannot work in l3. It also performs
4552 # a trivial task not worth tracking, so it could be in python.
4554 # For this example, using
4555 for k
in edsummary
.keys():
4556 print k
+ ": %.3f" % edsummary
[k
]
4557 # in l3 would be better.
4559 # For sequences providing len() and getitem(), there are two choices:
4560 # 1. another wrapper ( l3traverse() ) can be added, and the
4561 # following should work:
4564 I
= l3traverse([(1,2), (3,4)])
4574 # However, this wrapper would require access to l3 internals, so an
4575 # l3 version is preferable:
4577 # 2. Use a tail call form to handle indexing
4582 # In the following, ITEMS, IDX, LEN and LOOP are leaf nodes, to be
4583 # replaced UNIQUELY in if.setup().
4585 # See also ref[Wed Jul 18 11:38:10 2007]
4589 ITEMS
= [(1,2), (3,4)]
4597 (x
,y
) = ITEMS
[ IDX
- 1 ]
4606 # List as text (no insertions)
4611 # List as structure.
4618 for (i
, x
) in [(1, 1), (2, 4), (3,9)]:
4621 # Nesting, check identifiers.
4630 #* scitbx flex array
4631 from scitbx
.array_family
import flex
4632 data
= flex
.random_double(size
= 4)
4635 # Traceback (most recent call last):
4636 # File "<console>", line 1, in ?
4637 # ArgumentError: Python argument types in
4638 # double.reshape(double, int, int)
4639 # did not match C++ signature:
4640 # reshape(scitbx::af::versa<double, scitbx::af::flex_grid<scitbx::af::small<long, 10u> > > {lvalue}, scitbx::af::flex_grid<scitbx::af::small<long, 10u> >)
4643 #* slice and getitem
4647 na
= N
.arange(28).reshape((7,4))
4651 print na
.__getitem
__( [1,2] )
4652 print na
.__getitem
__( (1,2) ) # correct
4655 print na
.__getitem
__( (slice(1,4), 2) )
4658 print na
.__getitem
__( (slice(1,4), ) )
4659 print na
.__getitem
__( [slice(1,4)] )
4662 print na
.__getitem
__( (slice(1,3), slice(3,6)) )
4663 print operator
.getitem(na
, [slice(1,3), slice(3,6)] )
4664 print operator
.getitem(na
, (slice(1,3), slice(3,6)) )
4666 # Python reference values:
4673 # Compare with # Python reference values:
4677 na
= N
.arange(28).reshape((7,4))
4687 #* gtk images, numeric, eman
4690 from EMAN2
import EMNumPy
4695 ema_arr
= EMAN2
.EMData()
4696 EMNumPy
.numpy2em(num_arr
, ema_arr
)
4700 num_arr
= EMNumPy
.em2numpy(foo
)
4702 EMNumPy
.em2numpy(None)
4705 #*** 1. get numeric array
4706 num_arr
= M
.rand(4,4)
4708 #*** 2.b. numeric -> gtk
4709 # Convert float array to 8-bit array.
4710 rows
, cols
= num_arr
.shape
4711 bottom
= M
.min(M
.min(num_arr
))
4712 top
= M
.max(M
.max(num_arr
))
4713 scale
= (top
- bottom
)
4714 norm_arr
= ((num_arr
- bottom
) / scale
* 255).astype('b')
4716 #*** Use 3 8-bit arrays as (rgb) values.
4717 t3
= N
.outerproduct(norm_arr
, N
.array([1,1,1], 'b'))
4718 t4
= N
.reshape(t3
, (rows
, cols
, 3))
4719 pix_arr
= N
.array(t4
, 'b')
4721 #*** Get the pixbuf.
4722 # array input indexing is row, pixel, [r,g,b {,a} ]
4723 pixbuf
= gtk
.gdk
.pixbuf_new_from_array(pix_arr
,
4724 gtk
.gdk
.COLORSPACE_RGB
, 8)
4726 #*** 3. display pixbuf as item
4727 d_canv
= w_
.canvas
.view
4728 d_rt
= d_canv
.root().add(canvas
.CanvasGroup
)
4729 d_rt
.add(canvas
.CanvasPixbuf
,
4730 x
= 20, # world units
4734 width
= 15, # world units
4740 # Image orientation is consistent with `norm_arr` printed form.
4741 # Indexing is (row, col) from upper left.
4742 # Storage is row-major?
4744 # This is the first view of a VALUE -- the others are astTypes.
4745 # Useful value information is the program source.
4748 # "anchor" GtkAnchorType : Read / Write
4749 # "height" gdouble : Read / Write
4750 # "height-in-pixels" gboolean : Read / Write
4751 # "height-set" gboolean : Read / Write
4752 # "pixbuf" GdkPixbuf : Read / Write
4753 # "width" gdouble : Read / Write
4754 # "width-in-pixels" gboolean : Read / Write
4755 # "width-set" gboolean : Read / Write
4756 # "x" gdouble : Read / Write
4757 # "x-in-pixels" gboolean : Read / Write
4758 # "y" gdouble : Read / Write
4759 # "y-in-pixels" gboolean : Read / Write
4762 # # Other pixmap sources:
4763 # image = gtk.Image()
4764 # # use the current directory for the file
4766 # pixbuf = gtk.gdk.pixbuf_new_from_file(GTKLOGO_IMAGE)
4767 # image.set_from_pixbuf(pixbuf)
4769 # image = gtk.Image()
4770 # image.set_from_file(BUDDY_IMAGE);
4772 # image.get_pixbuf()
4773 # # pixbuf -> canvas
4775 # gtk.gdk.pixbuf_new_from_array
4776 # gtk.gdk.Pixbuf.get_pixels_array
4777 # gtk.gdk.Pixbuf.save
4778 # call gtk.Image.queue_draw() after you change the Numeric array.
4781 # # from EMAN2.EMNumPy import numpy2em, em2numpy
4784 #* gtk images, numpy, eman
4787 from EMAN2
import EMNumPy
4791 ema_arr
= em
.EMData()
4792 EMNumPy
.numpy2em(num_arr
, ema_arr
)
4797 ti
= EMAN2
.test_image(type = 1, size
= (128,64))
4798 num_arr
= EMNumPy
.em2numpy(ti
)
4800 # [Fri Mar 16 16:25:40 2007]: transposed: (64, 128)
4801 # [Mon Mar 19 11:23:08 2007]: eman2 fix by Grant Tang.
4802 # [Thu Mar 22 10:36:14 2007]: order confusion between eman2/hdf/numpy...
4806 #*** 1. get numpy array
4807 num_arr
= N
.random
.ranf( (5,4) )
4809 #*** 2.b. numpy -> gtk
4810 # Convert float array to 8-bit array.
4811 rows
, cols
= num_arr
.shape
4812 bottom
= N
.min(num_arr
)
4813 top
= N
.max(num_arr
)
4814 scale
= (top
- bottom
)
4815 norm_arr
= ((num_arr
- bottom
) / scale
* 255).astype(N
.uint8
).reshape(rows
*cols
)
4818 #*** Use 3 8-bit arrays as (rgb) values.
4819 t3
= N
.outer(norm_arr
, N
.array([1,1,1], 'b'))
4820 t4
= N
.reshape(t3
, (rows
, cols
, 3))
4821 pix_arr
= N
.array(t4
, dtype
=N
.uint8
)
4823 #*** Get the pixbuf.
4824 # array input indexing is row, pixel, [r,g,b {,a} ]
4825 # TypeError: pixbuf_new_from_array() argument 1 must be array, not
4827 # pixbuf = gtk.gdk.pixbuf_new_from_array(pix_arr,
4828 # gtk.gdk.COLORSPACE_RGB, 8)
4829 pixbuf
= gtk
.gdk
.pixbuf_new_from_data(
4830 pix_arr
.tostring(order
='a'),
4831 gtk
.gdk
.COLORSPACE_RGB
,
4838 #*** compare to input
4839 pixbuf
.get_pixels_array()
4840 print pixbuf
.get_pixels_array().shape
4841 print pixbuf
.get_height()
4842 print pixbuf
.get_width()
4845 #*** 3. display pixbuf as item
4846 d_canv
= w_
.canvas
.view
4847 d_rt
= d_canv
.root().add(canvas
.CanvasGroup
)
4848 d_rt
.add(canvas
.CanvasPixbuf
,
4849 x
= 20, # world units
4853 width
= 15, # world units
4859 #* minimal EMData display test
4863 inline("import EMAN2 ")
4864 ti
= EMAN2
.test_image(type = 1, size
= (128,64))
4865 # program > menu > run code
4866 # ti > menu > insert values
4870 tm_tree
= reader
.parse('''
4871 inline("import EMAN2 ")
4872 ti = EMAN2.test_image(type = 0, size = (64,64))
4874 tm_play_env
= interp
.get_child_env(def_env
, w_
.state_
.storage
)
4875 tm_tree
.setup(empty_parent(), tm_play_env
, w_
.state_
.storage
)
4876 tm_l3pic
= w_
.canvas
.view
.start_add_l3tree(tm_tree
)
4879 tm_l3pic
._l3tree
.interpret(w_
.state_
.def_env
, w_
.state_
.storage
)
4881 val
, val_id
= ast
.val2ast(tm_l3pic
.get_values_list())\
4882 .setup(empty_parent(),
4883 Env('dummy_env', None, None, storage
),
4885 w_
.canvas
.view
.add_l3tree(val
, RenderTable())
4889 #* l3IfOutline addition
4890 # High-level interface via outlining.
4891 #** original tree (simple)
4892 # Body from demo/proj-align/s1a.py, truncated for simplicity.
4893 ref_t
= reader
.parse_file("./demo/proj-align/s1a-in.py")
4894 ref_env
= interp
.get_child_env(def_env
, storage
)
4895 ref_t
.setup(empty_parent(), ref_env
, storage
)
4896 view
.print_info(storage
, ref_t
)
4899 # (set-variable (quote outline-regexp) "[ ]*\\#+\\*+")
4900 # (set-variable (quote outline-regexp) "\\W+\" +" nil)
4902 #** OR: original tree (full)
4903 ref_t
= reader
.parse_file("./demo/proj-align/s1a.py")
4904 ref_env
= interp
.get_child_env(def_env
, storage
)
4905 ref_t
.setup(empty_parent(), ref_env
, storage
)
4906 # view.print_info(storage, ref_t)
4907 #** add outline cross-refs
4908 ref_t
.set_outl_edges(w_
, None)
4909 #** examine embedded outline (text)
4910 view
.print_info(storage
, ref_t
, custom
= "nd._outl_parent._id")
4912 ref_pic
= w_
.canvas
.view
.start_add_l3tree(ref_t
)
4917 #*** outline tree, flat
4918 ref_o
= ref_t
.get_outline(w_
)
4921 ref_prun
= ref_o
.prune(w_
)
4923 view
.print_info(storage
, ref_prun
, custom
= "nd._real_tree._id")
4926 #*** OR: outline tree, nested
4927 ref_o
= ref_t
.get_outline(w_
, outl_type
= 'nested')
4929 view
.print_info(storage
, ref_o
)
4931 ref_prun
= ref_o
.prune(w_
)
4933 view
.print_info(storage
, ref_prun
)
4935 #*** OR: outline tree, subtree
4936 # (nested outline to level N, then content)
4937 # Pick a nested outline manually.
4938 # here, 'Compute proj...'
4939 storage
.load(40886).set_outline('subtree')
4941 ref_o
= ref_t
.get_outline(w_
, outl_type
= 'nested')
4943 # view.print_info(storage, ref_o)
4945 ref_prun
= ref_o
.prune(w_
)
4947 # view.print_info(storage, ref_prun)
4951 ref_t_pic
= w_
.canvas
.view
.start_add_l3tree(ref_t
)
4954 #*** display outline
4955 ref_pic
= w_
.canvas
.view
.start_add_l3tree(ref_prun
)
4959 tm_tree
= reader
.parse('''
4960 if ("outline", !! TITLE "sample"):
4964 #** single expression
4967 l3tree
= reader
.parse(ref_s
)
4971 #** single nesting level
4974 template
= reader
.parse(code_s
)
4980 template
= reader
.parse(code_s
)
4985 vl
, _
= viewList(aList([])).setup(empty_parent(), def_env
, storage
)
4986 sl
, _
= List(aList([])).setup(empty_parent(), def_env
, storage
)
4988 vls
= viewList().setup_viewlist(w_
, ref_t
)
4992 #* list display tests
5018 #* viewlist display tests
5021 # things are to be done...
5022 if ("outline", "Load volume."):
5023 vol
= getImage(ev("$SPXROOT/sparx/test/model001.tcp"))
5024 # See http://www.macro-em.org/sparxwiki/prep_vol
5025 (volft
, kb
) = prep_vol(vol
)
5027 # Like these wonderful ones...
5028 if ("outline", "Compute projection angles"):
5029 angles
= even_angles(10.0, 90.0, 90.1, 0.0, 179.9,'P')
5030 nangles
= len(angles
)
5035 #* system identification
5040 #* l3-system interface
5044 sc
.system('echo', ['a'], [])
5045 sc
.system_wrap('echo', 'a', n
='')
5047 from l3lang
.l3
import *
5056 #* system interface via shell wrapper
5057 #** prepare sample data directory, python
5059 ev
= os
.path
.expandvars
5060 def ignore(cmd
, *args
, **kwd
):
5066 ignore(os
.mkdir
, 'foo-sh-wrap')
5067 os
.chdir('foo-sh-wrap')
5069 ev('$HOME/w/sparx/xmipp/Basic_Demo/walkthrough/taguA.tot'),
5072 ev('$HOME/w/sparx/xmipp/Basic_Demo/walkthrough/taguA.tot.inf'),
5075 ev('$HOME/w/sparx/xmipp/Basic_Demo/walkthrough/tagtA.tot'),
5078 ev('$HOME/w/sparx/xmipp/Basic_Demo/walkthrough/tagtA.tot.inf'),
5082 #** call using assumed return value structure
5083 # This is completely impractical; see ref[Mon Apr 16 14:35:34 2007]
5085 os
.system('pwd; ls')
5086 (angles
, coords
, images
, sel_tilt
, sel_untilt
) = xmipp_mark("taguA.tot")
5089 #** call in directory
5090 # This is a minimalistic approach, letting the user select directory
5091 # entries after execution.
5093 #*** using xmipp_mark found on system path
5094 os
.system('pwd; ls -l')
5095 xmipp_mark(w_
, "taguA.tot", tilted
= "tagtA.tot")
5097 # menu -> save coords > tag.pos
5098 # menu -> save angles > tag.ang
5099 # menu -> generate images > images.xmp
5103 os
.system('pwd; ls -l')
5106 #*** using l3lang.external module
5107 from l3lang
.external
import xmipp_wrap
5108 xmipp_wrap
.xmipp_mark("/net/cci/hohn/w/sparx/xmipp/Basic_Demo/walkthrough/taguA.tot",
5110 "/net/cci/hohn/w/sparx/xmipp/Basic_Demo/walkthrough/tagtA.tot")
5112 #** with l3lang.external module
5113 #*** using subdirectory, l3
5114 # For batch programs, the toplevel should suffice:
5115 from l3lang
.l3
import *
5119 # l3 input, using manually specified full paths.
5121 inline
"from l3lang.external.xmipp_wrap import *"
5125 (status
, log
) = xmipp_mark(
5126 "/net/cci/hohn/w/sparx/xmipp/Basic_Demo/walkthrough/taguA.tot",
5127 tilted
= "/net/cci/hohn/w/sparx/xmipp/Basic_Demo/walkthrough/tagtA.tot")
5131 # Next, try commands using the file(s).
5133 cp(sd
.foobar
, "foobar_copy")
5136 # value inspection, via local eval:
5137 # self.w_.state_.storage.load(self._l3tree._id)
5140 #*** directory only tests, l3
5141 # [Fri Apr 20 16:23:21 2007]
5143 inline
"from l3lang.external.xmipp_wrap import *"
5150 # Next, try commands using the file(s).
5152 cp(sd
.foobar
, "foobar_copy")
5154 print sd1
.foobar_copy
5156 # [Thu Apr 19 15:32:15 2007]
5157 # state save sequence
5159 # (save state st.no-exec.1)
5168 inline
'from rpy import *'
5170 d
= r
.capabilities()
5172 device
= r
.png
# Robj, won't pickle
5175 device
= r
.postscript
5178 faithful_data
= r
.faithful
# short form:
5179 ed
= faithful_data
["eruptions"]
5184 inline
"import Numeric as N; import MLab as M"
5186 num_arr
= M
.rand(4,4) # Get numeric array.
5188 num_arr
= M
.rand(4,4)
5189 (rows
, cols
) = num_arr
.shape
5190 bottom
= M
.min(M
.min(num_arr
))
5191 top
= M
.max(M
.max(num_arr
))
5192 scale
= (top
- bottom
)
5193 norm_arr
= ((num_arr
- bottom
) / scale
* 255).astype('b') # Convert float array to 8-bit array.
5195 t3
= N
.outerproduct(norm_arr
, N
.array([1,1,1], 'b'))
5196 t4
= N
.reshape(t3
, (rows
, cols
, 3))
5197 pix_arr
= N
.array(t4
, 'b') # Use 3 8-bit arrays as (rgb) values.
5200 #* external test collection
5204 e
.set_value_at(0,1, 1.0)
5205 print "original at start"
5208 f1
= e
.process("mirror",{"axis":'x'})
5209 print "new mirrored image"
5213 #** image display test
5214 # [Fri Apr 20 16:48:25 2007]
5216 inline("import EMAN2 ")
5217 ti
= EMAN2
.test_image(type = 1, size
= (128,64))
5218 # program > menu > run code
5219 # ti > menu > insert list of values l3
5222 #** Micrograph and particle selection
5223 # Using the xmipp demo and data.
5225 inline
'''from l3lang.external.xmipp_wrap import \
5226 xmipp_mark, xmipp_do_selfile'''
5228 cp('$HOME/w/sparx/xmipp/Basic_Demo/walkthrough/taguA.tot',
5230 cp('$HOME/w/sparx/xmipp/Basic_Demo/walkthrough/taguA.tot.Common.pos',
5231 'taguA.tot.Common.pos')
5232 cp('$HOME/w/sparx/xmipp/Basic_Demo/walkthrough/taguA.tot.inf',
5234 cp('$HOME/w/sparx/xmipp/Basic_Demo/walkthrough/tagtA.tot',
5236 cp('$HOME/w/sparx/xmipp/Basic_Demo/walkthrough/tagtA.tot.Common.pos',
5237 'tagtA.tot.Common.pos')
5238 cp('$HOME/w/sparx/xmipp/Basic_Demo/walkthrough/tagtA.tot.inf',
5242 # Do the following in xmipp_mark:
5244 # file -> load coords
5245 # The file paths must be retrieved from l3, via
5246 # orig subdir > menu > pwd
5248 # file -> save angles
5250 # file -> generate images
5255 # 1551:SelFile::read: File
5256 # ..../Subdir-30214/taguA.tot.tot.Common.sel
5259 (status
, log
) = xmipp_mark( orig
.taguA_tot
,
5260 tilted
= orig
.tagtA_tot
)
5262 # Selection file listing images in current directory.
5263 xmipp_do_selfile("img_t*.xmp", "tilted.sel")
5264 xmipp_do_selfile("img_u*.xmp", "untilted.sel")
5266 # Selection file listing images relative to main directory.
5267 # A full xmipp wrapper would hide selection files completely.
5268 print (mark
.l3_dirname() + "/" + "img_t*.xmp", "tilted.sel")
5269 xmipp_do_selfile(mark
.l3_dirname() + "/" + "img_t*.xmp", "tilted.sel")
5270 xmipp_do_selfile(mark
.l3_dirname() + "/" + "img_u*.xmp", "untilted.sel")
5273 # Even without any matching input files,
5274 # xmipp_do_selfile("img_u*.xmp", "untilted.sel")
5275 # returns status zero ...
5283 >> Need xmipp_show to
view (intermediate
) images
.
5286 #** generate phantom
5287 inline
"import l3lang.external.xmipp_wrap as xw"
5288 vol
, fourpr
= xw
.pdbphantom("input-data/1P30.pdb",
5289 sampling_rate
= 1.6,
5290 high_sampling_rate
= 0.8,
5295 #** data alignment and classification
5299 produce
.doc
file -- view
as plain text
.
5308 #** nested loop data selection
5309 # [Wed May 16 12:01:45 2007]
5323 from l3lang
.pretty
import *
5325 #** manual construct / convert
5326 doc
= DocText("hello") |
DocBreak(" ") |
DocText("world")
5332 #** construct / convert
5333 B
= lambda : DocBreak(" ")
5334 T
= lambda t
: DocText(t
)
5335 G
= lambda x
: DocGroupAuto(x
)
5336 doc
= G(T("begin") |
B() |
5337 G(T("stmt1;") |
B() |
5339 T("stmt3;")) |
B() |
5342 print doc
.toString(40)
5343 print doc
.toString(8)
5344 print doc
.toString(4)
5347 #** manual construct / convert
5348 B
= lambda : DocBreak(" ")
5349 T
= lambda t
: DocText(t
)
5350 G
= lambda x
: DocGroupAuto(x
)
5351 GB
= lambda x
: DocGroupBreak(x
)
5352 GF
= lambda x
: DocGroupFill(x
)
5353 doc
= G(T("begin") |
B() |
5354 G(T("stmt1;") |
B() |
5359 print doc
.toString(40) # no breaks
5360 print doc
.toString(20) # break outer group
5361 print doc
.toString(4) # break all
5364 #** manual construct w/ indentation
5365 B
= lambda : DocBreak(" ")
5366 C
= lambda x
,y
: DocCons(x
, y
)
5367 T
= lambda t
: DocText(t
)
5368 G
= lambda x
: DocGroupAuto(x
)
5369 GB
= lambda x
: DocGroupBreak(x
)
5370 GF
= lambda x
: DocGroupFill(x
)
5371 I
= lambda r
, x
: DocNest(r
, x
)
5372 doc
= G(T("begin") |
5375 G( C(C(T("stmt1;"), B()), T("stmt3;"))))
5379 print doc
.toString(40) # no breaks
5380 print doc
.toString(20) # break outer group
5381 print doc
.toString(4) # break all
5383 #* full-tree pretty printing
5384 #** manual comparison
5393 tree
= reader
.parse(code_s
)
5396 play_env
= interp
.get_child_env(def_env
, storage
)
5397 tree
.setup(empty_parent(), play_env
, storage
)
5398 # # view.print_info(storage, tree)
5399 print tree
.get_infix_string(40)
5400 print tree
.get_infix_string(10)
5403 #** print-parse-compare cycle function
5404 def comp_trees(otree
, otree_tbl
, pptree
, pptree_tbl
):
5405 # Compare trees and associated comments
5409 print "Check for differences..."
5410 print "--------------------------------------------"
5411 o_it
= otree
.top_down()
5412 pp_it
= pptree
.top_down()
5414 try: o_nd
= o_it
.next()
5415 except StopIteration: break
5416 pp_nd
= pp_it
.next()
5419 if o_nd
.eql_1(pp_nd
):
5420 if otree_tbl
.has_key(o_nd
._id
):
5421 if otree_tbl
[o_nd
._id
].eql_1(pptree_tbl
[pp_nd
._id
]):
5424 print ("Comment difference from line %d, col %d\n"
5425 " to line %d, col %d\n"
5426 % (o_nd
._first
_char
[0], o_nd
._first
_char
[1],
5427 pp_nd
._first
_char
[0], pp_nd
._first
_char
[1]))
5428 print otree_tbl
[o_nd
._id
]
5429 print pptree_tbl
[pp_nd
._id
]
5433 print ("Tree difference: line %d, col %d\n original:\n%s\n"
5436 (pp_nd
._first
_char
[0],
5437 pp_nd
._first
_char
[1],
5442 def ppc(code_s
, width
):
5444 tree
= reader
.parse(code_s
).single_program()
5445 tree_env
= interp
.get_child_env(def_env
, storage
)
5446 tree
.setup(empty_parent(), tree_env
, storage
)
5447 associate_comments(w_
, tree
, code_s
)
5449 # Tree from printed output.
5450 pp_string
= tree
.get_infix_string(width
, w_
.deco_table_
)
5452 print "Pretty-printed string, width %d: " % width
5453 print "--------------------------------------------"
5456 pp_tree
= reader
.parse(pp_string
).single_program()
5457 pp_env
= interp
.get_child_env(def_env
, storage
)
5458 pp_tree
.setup(empty_parent(), pp_env
, storage
)
5459 associate_comments(w_
, pp_tree
, pp_string
)
5461 comp_trees(tree
, w_
.deco_table_
, pp_tree
, w_
.deco_table_
)
5463 def ppcm(code_s
, width_list
):
5464 for width
in width_list
:
5473 #** string special case
5474 #*** repr / str behavior
5477 aa
= reader
.parse('"""a\nb"""')
5478 chars(aa
.body()._primary
[0])
5480 aa
= reader
.parse('"""Outer radius : %i\n"""')
5481 chars(aa
.body()._primary
[0])
5484 str(aa
.body()._primary
[0])
5485 # str(aa) converts unprintables into ascii
5486 # repr(aa) converts unprintables into ascii and escapes when needed
5499 d = r.capabilities()
5501 device = r.png # Robj, won't pickle
5504 device = r.postscript
5512 #** def special case
5524 #** loop (set, function, operators)
5526 # Now for something else...
5527 # ... like a comment
5539 #** program (program, subdir, tuple, comment)
5551 cp('$HOME/w/sparx/xmipp/Basic_Demo/walkthrough/taguA.tot',
5555 inline "from l3lang.external.xmipp_wrap import xmipp_mark"
5556 # file -> load coords
5557 # The file paths must be retrieved from l3, via an Env
5558 # listing from the original subdir.
5560 (status, log) = xmipp_mark( orig.taguA_tot,
5561 tilted = orig.tagtA_tot )
5566 #** comment in expression
5581 if ("outline", "outer 1"):
5582 if ("outline", "tools"):
5587 if ("outline", "inner 2"):
5592 #* Local node examination.
5593 # From a widget with _l3tree
5594 st
= self
.w_
.state_
.storage
5595 st
.load(self
._l3tree
._id
)
5596 res
= st
.get_attribute(self
._l3tree
._id
, "interp_result")
5598 #* ctf, emdata and numpy
5600 from EMAN2
import EMNumPy
5602 from numpy
import flipud
, fliplr
5605 #** conversion check (indep.)
5608 e1
.process_inplace('testimage.noise.uniform.rand')
5609 e1
.get_data_pickle() # emdata -> std::vector -> python list
5614 #** conversion check (indep.)
5616 from EMAN2
import EMNumPy
5619 n1
= N
.random
.ranf( (5,4) )
5620 e1
= EMData(); EMNumPy
.numpy2em(n1
, e1
)
5621 n2
= EMNumPy
.em2numpy(e1
)
5622 assert N
.max(N
.max(n2
- n1
)) == 0, \
5623 "Array conversion failed (error = %g)." % N
.max(N
.max(n2
- n1
))
5625 #** Get spider format image.
5626 image
= getImage('foo.spi')
5628 #** Flip it to get correct layout.
5629 img_num
= flipud(fliplr(EMNumPy
.em2numpy(image
)))
5631 EMNumPy
.numpy2em(img_num
, img_em
)
5633 #*** Verify the conversion.
5634 num_2
= EMNumPy
.em2numpy(img_em
)
5635 assert N
.max(N
.max(num_2
- img_num
)) == 0, "Array conversion failed."
5637 # Check a single element
5639 N
.where( (img_num
- img_em
.get_value_at(0,0)) < 1e-14)
5640 # No matches. This means that the (0,1) element must be wrong,
5641 # not merely misplaced.
5642 N
.where( (img_num
- img_em
.get_value_at(0,1)) < 1e-14)
5646 ctf_img
= filt_ctf(image
, 2000, 2.0, 200,
5649 #** Save the image with ctf applied.
5650 dropImage(ctf_img
, "ctf.spi", itype
= 's')
5653 import numpy
as N
, pickle
, types
5655 print N
.version
.version
5658 aa
= N
.array([ 1, 2, 3, 4 ]);
5660 print type(aa1
) == types
.BuiltinFunctionType
5664 pickle
.dumps(N
.reshape
)
5667 #* Numeric and pickle
5668 import Numeric
as N
, pickle
5672 aa
= N
.array([ 1, 2, 3, 4 ]);
5674 print type(aa1
) == types
.BuiltinFunctionType
5678 pickle
.dumps(N
.reshape
)
5680 #* outline traversal
5682 for (nd
, level
) in w_
.lib_tree
.body().outl_top_down():
5683 print " " * level
, level
, nd
.l_label
5686 def time_func(fun
, *args
, **kwd
):
5687 from time
import time
5690 print time() - start
5692 #* eman2 pickle tests
5693 # - Works when run in one session.
5694 # - Works across sessions.
5695 import sparx
as sx
, l3lang
.utils
as ut
5696 volume
= sx
.getImage( "model.tcp" )
5697 print volume
.get_xsize() * volume
.get_ysize() * volume
.get_zsize()
5699 image
= sx
.project(volume
, [10.0, 20.0, 30.0, 0.0, 0.0], 35)
5700 print image
.get_xsize()
5703 time_func(cPickle
.dumps
, image
, protocol
= 2)
5705 ut
.file_pickle(image
, 'st.1')
5706 image_ld
= ut
.file_unpickle('st.1')
5711 # st = cPickle.dumps(volume, protocol=2)
5712 time_func(cPickle
.dumps
, volume
, protocol
=2)
5714 time_func(sx
.dropImage
, volume
, "st.spi", itype
= 's')
5716 ut
.file_pickle(volume
, 'st.2')
5717 # Load in separate session.
5718 import sparx
as sx
, l3lang
.utils
as ut
5719 volume_ld
= ut
.file_unpickle('st.2')
5721 vol_st
= volume_ld
.__getstate
__()
5723 #* Set() special form: aa[ii] = rhs
5724 #** single-index pattern derivation
5725 aa
= reader
.parse("aa[i] = foo").body()
5727 # Set(Call(Member(Symbol('operator'),
5728 # Symbol('getitem')),
5729 # aList([Symbol('a'),
5733 aa
= reader
.parse("! AA[ ! II ] = ! RHS").body()
5735 Set(Call(Member(Symbol('operator'),
5737 aList([Marker('AA'),
5741 #** transform to `operator.setitem(aa, ii, rhs)`
5742 print reader
.parse('operator.setitem(!AA, !II, !RHS)').body()
5744 Call(Member(Symbol('operator'),
5746 aList([Marker('AA'),
5751 #** numeric: single-bracket, multi-index
5753 aa
= N
.reshape(N
.array([ 1, 2, 3, 4 ]), (2,2))
5757 print reader
.parse("aa[0,1]").body()
5760 print reader
.parse("aa[(0,1)]").body()
5762 print operator
.getitem(aa
, (0,1))
5764 # Call(Member(Symbol('operator'),
5765 # Symbol('getitem')),
5766 # aList([Symbol('aa'),
5767 # Tuple(aList([Int(0),
5770 # So the single-index pattern will work.
5773 print reader
.parse("aa[ii] = foo").body()
5775 # Circumvents l3 value tracking.
5781 #* Set() special form: aa[ii][jj] = rhs
5783 aa
= reader
.parse("! AA[ ! II ] [ !JJ ] = ! RHS").body()
5785 Set(Call(Member(Symbol('operator'),
5787 aList([Call(Member(Symbol('operator'),
5789 aList([Marker('AA'),
5795 #** Transformed out.
5796 print reader
.parse('''
5798 operator.getitem(!AA, !II),
5801 Call(Member(Symbol('operator'),
5803 aList([Call(Member(Symbol('operator'),
5805 aList([Marker('AA'),
5811 print reader
.parse("aa[ii][jj] = foo").body()
5813 # Circumvents l3 value tracking.
5820 #* Set special form: a.foo = 2
5821 # Still uses setitem.
5824 operator
.setitem(aa
, 'foo', 2)
5828 #** n behavior, manual eval
5829 # This lets python convert the \n to an escape:
5830 aa
= reader
.parse('"""Outer radius : %i\n""" % 123')
5831 chars(aa
.body()._primary
[1][0]._primary
[0])
5834 play_env
= interp
.get_child_env(def_env
, storage
)
5835 aa
.setup(empty_parent(), play_env
, storage
)
5836 view
.print_info(storage
, aa
)
5839 news
= aa
.interpret(play_env
, storage
)
5840 chars(news
[0]) # has actual newline
5841 #** n behavior, pasting
5842 """Outer radius : %i\n""" % 123
5843 # run code => ('Outer radius : 123\\n', 5496)
5846 45065 -22 45065 String('Outer radius : %i\n')
5849 >>> print """Outer radius : %i\n""" % 123
5850 Outer radius
: 123\n
5853 45072 5494 45072 String('Outer radius : %i\\n')
5855 #** difference, commit c2c6cff9496972d40011002de24d20abca1a6bab and before
5857 # This lets python convert the \n to an escape:
5858 aa
= reader
.parse('"""Outer radius : %i\n""" % 123')
5860 # This won't, and that's the behavior observed from the gui / toplevel.
5861 aa
= reader
.parse(r
'"""Outer radius : %i\n""" % 123')
5863 # This also contains \\n instead of the control code.
5864 pprint
.pprint([ii
for ii
in tokenize
.generate_tokens(string_readline(r
'"Outer radius : %i\n"'))])
5867 #** difference removed
5868 # both contain \n control code.
5869 print reader
.parse('"""Outer radius : %i\n""" % 123')
5871 # This won't, and that's the behavior observed from the gui / toplevel.
5872 print reader
.parse(r
'"""Outer radius : %i\n""" % 123')
5875 #* pytables for reading hdf
5878 # File is available after ali2d.l3 run
5879 fi
= tables
.openFile("_K-8-133679/average.hdf")
5880 # method listNodes in module tables.file:
5881 fi
.listNodes
# show all
5882 [li
for li
in fi
.listNodes('/MDF/images')]
5884 # RootGroup in module tables.group object:
5887 fi
.root
== fi
.getNode('/') # true
5889 for node
in fi
.root
:
5892 list(fi
.root
) # list from iterator
5893 list(fi
.root
)[0] # first child
5894 list(list(fi
.root
)[0]) # first child's children
5898 fi
.listNodes('/') # get list
5899 (fi
.listNodes('/')[0])._v
_name
5901 for sub
in fi
.listNodes('/'):
5905 # >>> fi.getNode('/')
5907 # children := ['MDF' (Group)]
5908 # >>> fi.getNode('/').getNode('MDF')
5909 # Segmentation fault
5911 fi
.getNode('/MDF/images')
5912 fi
.getNode('/MDF/images')._v
_attrs
# print
5913 fi
.getNode('/MDF/images')._v
_attrs
._g
_listAttr
() # get list
5915 fi
.getNode('/MDF/images')._f
_getChild
('1')
5917 fi
.getNode('/MDF/images/1')
5918 # tables.attributeset.AttributeSet'>
5919 fi
.getNode('/MDF/images/1')._v
_attrs
# print info
5920 fi
.getNode('/MDF/images/1')._v
_attrs
._g
_listAttr
() # get list
5921 (fi
.getNode('/MDF/images/1')._v
_attrs
)._f
_list
() # get list (better)
5922 fi
.getNode('/MDF/images/1')._v
_attrs
._g
_getAttr
('EMAN.Class_average')
5923 fi
.getNode('/MDF/images/1')._v
_attrs
._g
_getAttr
('EMAN.nobjects')
5924 fi
.getNode('/MDF/images/1')._v
_attrs
._g
_getAttr
('EMAN.members')
5927 # Array in module tables.array
5928 arr
= fi
.getNode('/MDF/images')._f
_getChild
('1')._f
_getChild
('image')
5929 arr
= fi
.getNode('/MDF/images/1/image')
5931 a00
= arr
[0,0] # Returns a 0-D array
5932 a00
= arr
[0:1,0:1] # Returns a slice copy.
5935 #** relevant for eman2 use
5937 # 1. The pytable classes:
5939 # / <class 'tables.group.RootGroup'>
5940 # MDF <class 'tables.group.Group'>
5941 # images <class 'tables.group.Group'>
5942 # 0 <class 'tables.group.Group'>
5943 # image <class 'tables.array.Array'>
5944 # 1 <class 'tables.group.Group'>
5945 # image <class 'tables.array.Array'>
5947 # 2. The attributes of a Group
5948 # ... members in a Group start with some reserved prefix, like _f_
5949 # (for public methods), _g_ (for private ones), _v_ (for instance
5950 # variables) or _c_ (for class variables).
5952 # tables.attributeset.AttributeSet'>
5953 # fi.getNode('/MDF/images/1')._v_attrs # print info
5955 # Get list of attributes.
5956 (fi
.getNode('/MDF/images/1')._v
_attrs
)._f
_list
()
5958 # Get attribute with arbitrary name
5959 (fi
.getNode('/MDF/images/1')._v
_attrs
).__getattr
__('EMAN.Class_average')
5960 (fi
.getNode('/MDF/images/1')._v
_attrs
).__getattr
__('EMAN.members')
5963 (fi
.getNode('/MDF/images/1')._v
_attrs
).new_stuff
= 1
5965 # got tables.exceptions.FileModeError: the file is not writable
5969 #*** Traverse the object tree
5970 def nshow(fi
, indent
= 0):
5971 if hasattr(fi
, '_v_name'):
5972 print " "*indent
, fi
._v
_name
, type(fi
)
5973 if isinstance(fi
, tables
.array
.Array
):
5974 # For tables.array, iteration is over the rows; this shows
5975 # 75 1-d numpy arrays per image.
5978 nshow(sub
, indent
= indent
+ 1)
5980 print " "*indent
, type(fi
)
5984 #*** simplified access interface for l3 use
5985 # Inject l3_* methods.
5987 'Return the number of images.'
5988 return self
.getNode('/MDF/images')._v
_nchildren
5989 tables
.file.File
.l3_len
= l3_len
5992 def l3_getimg(self
, index
):
5993 'Return the image at `index`.'
5994 return self
.getNode('/MDF/images')._f
_getChild
(str(index
))._f
_getChild
('image')
5995 tables
.file.File
.l3_getimg
= l3_getimg
5998 def l3_getatts(self
, index
):
5999 ''' Return a (name, value) list holding all the attributes of
6003 attset
= self
.root
.MDF
.images
._f
_getChild
(ind
)._v
_attrs
6004 return [ (att
, attset
.__getattr
__(att
)) for att
in attset
._f
_list
()]
6005 tables
.file.File
.l3_getatts
= l3_getatts
6008 def l3_getatt(self
, index
, name
):
6009 ''' Return the `name` attribute of the image at `index`.'''
6011 attset
= self
.root
.MDF
.images
._f
_getChild
(ind
)._v
_attrs
6012 return attset
.__getattr
__(str(name
))
6013 tables
.file.File
.l3_getatt
= l3_getatt
6017 #*** tables access tests
6021 fi
.l3_getatt(0, 'EMAN.Class_average')
6022 fi
.l3_getatt(0, 'EMAN.nobjects')
6023 fi
.l3_getatt(0, 'EMAN.members')
6028 # Using the simple function
6031 # Updates bounding boxes, among others.
6032 while gtk
.events_pending():
6033 gtk
.main_iteration()
6041 # as long as draw() does not block.
6044 from threading
import Lock
6050 value
.append(raw_input(prompt
))
6052 value
.append(EOFError())
6055 thread
.start_new_thread(_do
, ())
6056 # Manual main loop until input is ready.
6057 while not lck
.acquire(False):
6060 if isinstance(value
[-1], Exception):
6064 #* gui/console hybrid use
6065 #** highly irregular data, not used
6066 inline('from numpy import *; from pylab import *')
6067 for ii
in range(12*3):
6068 a1
= (ii
, array([-2100, -200, -100 / 2.0, -1200]))
6069 # Added to loop body.
6072 a2
= (ii
, sum(a1
[1]))
6073 (ii
% 2 == 0) and -200 or 0
6075 # This is just too painful through the gui; there is too much
6076 # heterogeneous data.
6077 #** highly irregular data, python
6078 # Just defining and editing the textual data structure is FAR
6080 # (month, amount, what)
6081 specials
= [(1, [(-200, "this")]),
6082 (22, [(300, "that")]),
6084 regular
= [(mon
, [(-100, "one"),
6086 ]) for mon
in range(0, 12*3)]
6087 spec_d
= dict(specials
)
6088 # for (month, mon_dat) in regular:
6089 # print (month, mon_dat + spec_d.get(month, []))
6091 [ (month
, mon_dat
+ spec_d
.get(month
, []))
6092 for (month
, mon_dat
) in regular
]
6095 #** highly irregular data, l3
6097 def combine(specials, regular, r_from, r_to):
6098 reg_list = [(mon, regular) for mon in xrange(r_from, r_to)]
6099 spec_d = dict(specials)
6100 return [ (month, mon_dat + spec_d.get(month, []))
6101 for (month, mon_dat) in reg_list]
6104 specials
= [(1, [(-200, "this")]),
6105 (22, [(300, "that")]),
6107 regular
= [(-100, "one"),
6110 combined
= combine(specials
, regular
, 0, 3*12)
6114 # if Env's keys include any python hashables, an Env can accumulate
6115 # (int, val) bindings in addition to (name, val) bindings
6116 stuff
= if ("map", "embedded"):
6117 for ii
in range(0, 3*12):
6118 l3
.env().set(ii
, [(-100, "one"), (-200, "two")])
6120 l3set(1, [(-200, "this")])
6121 l3set(22, [(300, "that")])
6125 #* list comprehension
6126 [(mon
, [(-100, "one"),
6128 ]) for mon
in range(0, 12*3)]
6129 # As tail call, roughly:
6130 def _foo(arg
, seq
, accum
):
6133 _foo(arg
, seq
[1:None], accum
)
6134 _foo(mon
, range(0, 12*3), [])
6135 # this is already FAR to tedious, and a tracked (l3) expansion is not
6139 # From matplotlib-0.90.1/examples/date_demo1.py
6141 # This example requires an active internet connection since it uses
6142 # yahoo finance to get the data for plotting
6144 # The scripts are independently runnable, and must be edited to form a
6148 #** Collect finance data using yahoo's service.
6149 if ("outline", "Collect finance data"):
6151 from matplotlib.finance import quotes_historical_yahoo
6154 # <span background="#ffdddd">Retrieve data for stock symbol.</span>
6155 quotes
= quotes_historical_yahoo(
6157 datetime
.date( 1995, 1, 1 ),
6158 datetime
.date( 2004, 4, 12 ),
6161 error("Unable to get data")
6163 # <span background="#ffdddd">The data attributes of quotes.</span>
6175 if ("outline", "Date plot"):
6176 # <span background="#ffdddd">Plot details.</span>
6181 def plot_date(fname, dates, values):
6182 from pylab import figure, show
6184 from matplotlib.dates import YearLocator, MonthLocator, DateFormatter
6186 fig = figure(figsize=(7,4), dpi=100)
6187 ax = fig.add_subplot(111)
6188 ax.plot_date(dates, values, '-')
6190 # Plot details -- ticks.
6191 years = YearLocator() # every year
6192 months = MonthLocator() # every month
6193 yearsFmt = DateFormatter('%Y')
6195 ax.xaxis.set_major_locator(years)
6196 ax.xaxis.set_major_formatter(yearsFmt)
6197 ax.xaxis.set_minor_locator(months)
6200 for label in ax.get_xticklabels() + ax.get_yticklabels():
6201 label.set_fontsize('8')
6203 # Plot details -- coords. message box.
6206 ax.fmt_xdata = DateFormatter('%Y-%m-%d')
6207 ax.fmt_ydata = price
6213 # <span background="#ffdddd">Plot data.</span>
6214 filename
= plot_date('_plot-%d.png' % new_id(),
6215 [datetime
.date(1995,1,1).toordinal(),
6216 datetime
.date(1997,1,1).toordinal()],
6220 if ("outline", "Moving average."):
6224 # A[t] = (V[t] + V[t-1] + ... + V[ t-n+1 ]) / n
6227 assert len(vec.shape) == 1, 'Expecting vector argument.'
6228 assert n > 1, 'Averaging over less than 2 elements.'
6230 assert N > n, 'Not enough samples for averaging.'
6232 ma = copy(vec) * numpy.nan
6233 for t in xrange(n - 1, N):
6234 ma[t] = 1.0 * sum(vec[t-n+1: t + 1]) / n
6237 mov_avg
= movavg(numpy
.array([1, 2, 3, 4.0]),
6240 #** Moving average via convolution
6242 data
= numpy
.array([1.0, 2,3,4])
6243 weight
= numpy
.array([1.0/2, 1.0/2])
6244 mov_avg
= numpy
.convolve(data
, weight
, mode
='same')
6245 mov_avg
[0:weight
.shape
[0] - 1] = numpy
.nan
6248 #** Moving average, simple plot
6250 matplotlib
.use("gtk")
6257 weight
= [1.0/2, 1.0/2]
6258 mov_avg
= convolve(data
, weight
, mode
='same')
6259 mov_avg
[0:len(weight
) - 1] = nan
6261 t1
= plot(mov_avg
) # t1 won't pickle.
6262 show(mainloop
=False)
6266 #** Date plot as widget
6267 if ("outline", "Date plot"):
6268 # <span background="#ffdddd">Plot details.</span>
6273 def plot_date(dates, values):
6274 from pylab import figure, show
6276 from matplotlib.dates import YearLocator, MonthLocator, DateFormatter
6277 from matplotlib.backends.backend_gtk import FigureCanvasGTK \
6280 fig = figure(figsize=(7,4), dpi=100)
6281 ax = fig.add_subplot(111)
6282 ax.plot_date(dates, values, '-')
6284 # Plot details -- ticks.
6285 years = YearLocator() # every year
6286 months = MonthLocator() # every month
6287 yearsFmt = DateFormatter('%Y')
6289 ax.xaxis.set_major_locator(years)
6290 ax.xaxis.set_major_formatter(yearsFmt)
6291 ax.xaxis.set_minor_locator(months)
6294 for label in ax.get_xticklabels() + ax.get_yticklabels():
6295 label.set_fontsize('8')
6297 # Plot details -- coords. message box.
6300 ax.fmt_xdata = DateFormatter('%Y-%m-%d')
6301 ax.fmt_ydata = price
6305 # <span background="#ffdddd">Plot data.</span>
6306 plot_date([datetime
.date(1995,1,1).toordinal(),
6307 datetime
.date(1997,1,1).toordinal()],
6310 # The display widget is FigureCanvas(fig). But canvas operations will
6311 # destroy this occasionally so the raw figure handle is returned and
6312 # L3 can display Native( fig : <matplotlib.figure.Figure> )
6313 # via Widget(FigureCanvas(fig)).
6318 exec(str, globals())
6320 inline("import matplotlib as M")
6321 inline( "import pylab as P")
6323 fig
= P
.figure(figsize
=(5,4), dpi
=75)
6326 #** doc strings as help entries
6327 from types
import InstanceType
, MethodType
6329 if isinstance(fig
, InstanceType
):
6330 helpfor
= fig
.__class
__
6331 # All member functions of this class.
6332 for (name
, memb
) in pydoc
.allmethods(helpfor
).iteritems():
6333 _docstr
= pydoc
.getdoc(memb
)
6334 head
, body
= pydoc
.splitdoc(_docstr
)
6335 print "\f=================================\n", name
6337 print "--------------------------------------------\n", body
6348 # # Help on instance of Figure in module matplotlib.figure object:
6349 # # class instance(object)
6351 # # Good, but a LOT of content:
6352 help( fig
.__class
__)
6356 #* matplotlib figures on l3 canvas (XY Plot script)
6359 #** Another numpy stupidity
6360 import matplotlib
as M
6364 # Gives TypeError: only length-1 arrays can be converted to Python scalars
6365 xx
= sin(2* nn
* pi
/N
)
6367 xx
= P
.sin(2* nn
* pi
/N
)
6370 #** l3 polygon plots
6371 if ("outline", "XY Polygon Plot"):
6372 # <span background="#ffcccc">Plot details.</span>
6374 def plot_(fname, x, y):
6375 import matplotlib as M
6379 fig = P.figure(figsize=(5,4), dpi=75)
6380 ax = fig.add_subplot(111)
6381 ax.plot(x, y, '-', lw=2)
6385 ax.set_title('Polygon plot')
6391 inline
'from pylab import *'
6392 for N
in range(3, 12):
6393 nn
= arange(0, N
+ 1)
6394 xx
= sin(2* nn
* pi
/N
)
6395 yy
= cos(2* nn
* pi
/N
)
6396 plot_(new_name('poly', '.png'), xx
, yy
)
6402 import matplotlib
as M
6405 def plot_xy(fname
, x
, y
):
6407 plot
= P
.plot(x
, y
, '-', lw
=2)
6409 # P.xlabel('time (s)')
6410 # P.ylabel('voltage (mV)')
6411 # P.title('About as simple as it gets, folks')
6416 plot_xy('simple_plot.png',
6417 P
.arange(0.0, 1.0+0.01, 0.01),
6422 st
= cPickle
.dumps(plot
, protocol
=2)
6423 # UnpickleableError: Cannot pickle <type 'Affine'> objects
6426 #** l3 calling python
6428 def plot_(fname, x, y):
6429 import matplotlib as M
6433 plot = P.plot(x, y, '-', lw=2)
6435 # P.xlabel('time (s)')
6436 # P.ylabel('voltage (mV)')
6437 # P.title('About as simple as it gets, folks')
6442 inline
'from math import pi; import matplotlib as M; import pylab as P'
6443 t
= P
.arange(0.0, 1.0+0.01, 0.01)
6444 s
= P
.cos(2 * pi
* t
)
6445 plot_('simple_plot.png', s
, t
)
6448 # Python image read (load) test
6449 import matplotlib
.image
as mi
6451 img_arr
= mi
.imread('simple_plot.png')
6455 def plot_(fname
, x
, y
):
6456 inline('import matplotlib as M; import pylab as P')
6458 plot
= P
.plot(x
, y
, '-', lw
=2)
6460 # P.xlabel('time (s)')
6461 # P.ylabel('voltage (mV)')
6462 # P.title('About as simple as it gets, folks')
6466 inline
'from math import pi; import matplotlib as M; import pylab as P'
6467 t
= P
.arange(0.0, 1.0+0.01, 0.01)
6468 s
= P
.cos(2 * pi
* t
)
6469 plot_('simple_plot.png', s
, t
)
6473 #** l3 only, with axis
6474 # <span background="#ffcccc">Plot details.</span>
6475 def plot_(fname
, x
, y
):
6476 inline('import matplotlib as M; import pylab as P')
6479 fig
= P
.figure(figsize
=(5,4), dpi
=75)
6480 ax
= fig
.add_subplot(111)
6481 ax
.plot(x
, y
, '-', lw
=2)
6483 ax
.set_xlabel('time (s)')
6484 ax
.set_ylabel('voltage (mV)')
6485 ax
.set_title('About as simple as it gets, folks')
6490 inline
'from math import pi; import pylab as P'
6491 # <span background="#ffdddd">Plot data.</span>
6492 x
= P
.arange(0.0, 1.0+0.01, 0.01)
6493 y
= P
.cos(2 * pi
* x
)
6494 # <span background="#ffdddd">Plot file.</span>
6495 filename
= plot_('_plot-%d.png' % new_id(), x
, y
)
6499 #** l3 with explicit figure in subplot
6500 # Plot details can be adjusted here.
6502 def plot_(fname, x, y):
6503 import matplotlib as M
6507 fig = P.figure(figsize=(5,4), dpi=75)
6508 ax = fig.add_subplot(111)
6509 ax.plot(x, y, '-', lw=2)
6511 ax.set_xlabel('time (s)')
6512 ax.set_ylabel('voltage (mV)')
6513 ax.set_title('About as simple as it gets, folks')
6518 inline
'from math import pi; import matplotlib as M; import pylab as P'
6519 x
= t
= P
.arange(0.0, 1.0+0.01, 0.01)
6520 y
= s
= P
.cos(2 * pi
* t
)
6521 # Insert plot data here.
6522 plot_('simple_plot.png', s
, t
)
6526 #** Plot without intermediate data file
6527 # from .../matplotlib-0.90.1/examples/to_numeric.py
6530 #** Interactive matplotlib window combined with l3gui
6531 import matplotlib
as M
6534 from matplotlib
.axes
import Subplot
6535 from matplotlib
.figure
import Figure
6536 from matplotlib
.numerix
import arange
, sin
, pi
6540 from matplotlib
.backends
.backend_gtkagg
import \
6541 FigureCanvasGTKAgg
as FigureCanvas
6542 from matplotlib
.backends
.backend_gtkagg
import \
6543 NavigationToolbar2GTKAgg
as NavigationToolbar
6545 from matplotlib
.backends
.backend_gtk
import \
6546 FigureCanvasGTK
as FigureCanvas
6548 from matplotlib
.backends
.backend_gtk
import \
6549 NavigationToolbar2GTK
as NavigationToolbar
6552 fig
= Figure(figsize
=(5,4), dpi
=100)
6553 ax
= fig
.add_subplot(111)
6554 t
= arange(0.0,3.0,0.01)
6557 ax
.set_xlabel('time (s)')
6558 ax
.set_ylabel('voltage (mV)')
6559 ax
.set_title('About as simple as it gets, folks')
6564 def plot_win(figure
):
6566 # win.connect("destroy", lambda x: gtk.main_quit())
6567 win
.set_default_size(400,300)
6568 win
.set_title("Interactive plot")
6573 canvas
= FigureCanvas(figure
)
6574 toolbar
= NavigationToolbar(canvas
, win
)
6575 vbox
.pack_start(canvas
)
6576 vbox
.pack_start(toolbar
, False, False)
6582 # Everything is done through the figure and axis (good), but these
6584 (axis
, figure
) = plot_figure()
6585 figure
.savefig('testimage.png') # Also available via plot window.
6588 gtk
.main() # test only.
6592 xx
= P
.arange(0.0, 1.0+0.01, 0.01)
6593 yy
= P
.cos(2*2*pi
*xx
)
6594 fname
= 'simple_plot.png'
6597 plot
= P
.plot(xx
, yy
, '-', lw
=2)
6598 P
.xlabel('time (s)')
6599 P
.ylabel('voltage (mV)')
6600 P
.title('About as simple as it gets, folks')
6607 #** simplest expansion
6608 from l3lang
.cruft
import em
6611 '@[def emph(str)]<span background="#ffcccc"> @str </span>@[end def]', glo
)
6612 print em
.expand("@emph('the comment')", glo
)
6614 #** Single em interpreter, faster.
6615 from l3lang
.cruft
import em
6616 em_inter
= em
.Interpreter()
6619 '@[def emph(str)]<span background="#ffcccc"> @str </span>@[end def]'
6620 '@[def strong(str)]<b> @str </b>@[end def]'
6623 print em_inter
.expand(str, em_glo
)
6625 #*** Expand one time:
6626 emx("@emph('the comment')")
6627 emx("@strong('bold')")
6628 emx("""@emph('the @strong("bold") comment')""")
6631 #*** Nested expansion:
6632 emx("""@emph{the @strong("bold") comment}""")
6634 #*** Ordering in nested expansions.
6635 # In this, em_l inside def gives
6636 # NameError: global name 'em_l' is not defined
6643 <span background="EVEN">
6647 <span background="ODD">
6656 emx("No emphasis @emph{some emphasis @emph{nested emphasis} some emphasis}")
6659 #*** Ordering in nested expansions, 2
6660 # The following cannot work; the em_l state has to be decreased at some
6661 # future time after the macro is expanded .
6664 def __call__(self
, stri
):
6665 self
.__class
__.em_l
+= 1
6667 if self
.__class
__.em_l
% 2:
6669 <span background="EVEN">
6675 <span background="ODD">
6679 self
.__class
__.em_l
-= 1
6685 #*** Ordering in nested expansions, 3
6686 # The nested expansion order is inside-out (which is wrong).
6690 emph_level = empy.getGlobals().get('emph_level', -1) + 1
6691 empy.getGlobals()['emph_level'] = emph_level
6692 if (emph_level % 2) == 0:
6693 rv = empy.expand('<span background="EVEN"> @stri </span>', locals())
6695 rv = empy.expand('<span background="ODD"> @stri </span>', locals())
6696 empy.getGlobals()['emph_level'] = emph_level - 1
6701 emx("@emph('hello @emph(this) world')")
6702 emx("@emph{hello @emph{this} world}")
6705 #*** Ordering in nested expansions, 4
6710 emph_level = empy.getGlobals().get('emph_level', -1) + 1
6711 empy.getGlobals()['emph_level'] = emph_level
6713 exp = lambda strng: empy.expand(strng, locals())
6714 if (emph_level % 2) == 0:
6717 '<span background="EVEN"> @stri </span>',
6723 '<span background="ODD"> @stri </span>',
6726 empy.getGlobals()['emph_level'] = emph_level - 1
6732 # Gives NameError: name 'emph' is not defined
6733 emx("@emph('hello @emph(this) world')")
6734 emx("@emph{hello @emph{this} world}")
6738 #* User-guiding emphasis
6739 #** highlight, raw pango markup
6740 # <span background="#ffcccc">Plot details can be adjusted here.</span>
6742 def plot_(fname, x, y):
6743 import matplotlib as M
6747 fig = P.figure(figsize=(5,4), dpi=75)
6748 ax = fig.add_subplot(111)
6749 ax.plot(x, y, '-', lw=2)
6751 ax.set_xlabel('time (s)')
6752 ax.set_ylabel('voltage (mV)')
6753 ax.set_title('About as simple as it gets, folks')
6759 inline
'from math import pi; import matplotlib as M; import pylab as P'
6760 x
= t
= P
.arange(0.0, 1.0+0.01, 0.01)
6761 y
= s
= P
.cos(2 * pi
* t
)
6762 # <span background="#ffdddd">Insert plot data here.</span>
6764 # <span background="#ffdddd">Output file name.</span>
6766 # <span background="#ffdddd">Your X.</span>
6768 # <span background="#ffdddd">Your Y.</span>
6771 #** highlight, m4 syntax.
6772 # guide(Insert plot data here.)
6774 # guide(Output file name.)
6781 #** highlight, per-line prefix syntax.
6782 #g* Insert plot data here.
6784 #g* Output file name.
6791 #** highlight, long syntax w/ line separation
6792 # This leaves blank lines.
6793 #<span background="#ffdddd">
6794 # Insert plot data here.
6797 # <span background="#ffdddd">Output file name.</span>
6799 # <span background="#ffdddd">Your X.</span>
6801 # <span background="#ffdddd">Your Y.</span>
6807 #** Greyscale other text.
6808 # From any root node:
6809 from l3gui
.widgets
import *
6810 for nd
in self
.iter_visibles():
6811 if isinstance(nd
, l3Rawtext
):
6812 nd
._ltext
.set_property("fill-color", "#" + "d0" * 3)
6814 #** Collect user guiding info from comments.
6815 # Starting from 'eval locally',
6817 # <l3gui.widgets.l3Program instance at 0xb780a70c>
6818 #*** Find all comments.
6819 dt
= self
.w_
.deco_table_
6820 for nd
in self
._l3tree
.top_down():
6821 print nd
, dt
.get(nd
._id
, None)
6823 #*** Traverse comments.
6824 def iter_comments(self
):
6825 dt
= self
.w_
.deco_table_
6826 for nd
in self
._l3tree
.top_down():
6827 comm
= dt
.get(nd
._id
, None)
6832 #*** Find comments with highlighting.
6833 for comm
in iter_comments(self
):
6834 if (comm
.find("<span background") > 0):
6838 #*** Accumulate comments.
6839 print [ comm
for comm
in iter_comments(self
)
6840 if (comm
.find("<span background") > 0)]
6841 print [ comm
.py_string()
6842 for comm
in iter_comments(self
)
6843 if (comm
.find("<span background") > 0)]
6844 print '\n'.join([ comm
.py_string()
6845 for comm
in iter_comments(self
)
6846 if (comm
.find("<span background") > 0)])
6849 #*** Add accumulation to this heading's comment.
6850 # This changes the associated comment and adds state handling details.
6851 # Viewing internal information can be a transient action (use popups)
6852 # or a special view (independent display alongside).
6854 # Use deco_change_label
6855 dt
= self
.w_
.deco_table_
6856 comm
= dt
.get(self
._l3tree
._id
, None)
6859 prepend
= comm
.py_string()
6860 self
._old
_label
= prepend
6863 print (prepend
+ '\n' +
6864 '\n'.join([ comm
.py_string()
6865 for comm
in iter_comments(self
)
6866 if (comm
.find("<span background") > 0)]))
6868 self
.deco_change_label(label
=
6870 '\n'.join([ comm
.py_string()
6871 for comm
in iter_comments(self
)
6872 if (comm
.find("<span background") > 0)])))
6875 #*** Display accumulation as separate node
6876 # Loosely connected to independent
6877 TODO
: add
as menu entry
6878 done
: view_as
-> full member
6879 self
.view_as('flat')
6884 #* matplotlib and tools
6885 from numerix
import absolute
, arange
, array
, asarray
, ones
, divide
,\
6886 transpose
, log
, log10
, Float
, Float32
, ravel
, zeros
,\
6887 Int16
, Int32
, Int
, Float64
, ceil
, indices
, \
6888 shape
, which
, where
, sqrt
, asum
, compress
, maximum
, minimum
, \
6889 typecode
, concatenate
, newaxis
, reshape
, resize
, repeat
, \
6890 cross_correlate
, nonzero
6892 from matplotlib
.numerix
import absolute
, arange
, array
, asarray
, ones
, divide
,\
6893 transpose
, log
, log10
, Float
, Float32
, ravel
, zeros
,\
6894 Int16
, Int32
, Int
, Float64
, ceil
, indices
, \
6895 shape
, which
, where
, sqrt
, asum
, compress
, maximum
, minimum
, \
6896 typecode
, concatenate
, newaxis
, reshape
, resize
, repeat
, \
6897 cross_correlate
, nonzero
6899 inline
'import MLab as M; from matplotlib.numerix import transpose'
6904 # run from l3, gets stuck in
6905 # #0 dlamc3_ (a=0xb7a10030, b=0xb7a0ffe0) at Src/dlamch.c:685
6906 # when run from l3 AND when run in l3's python:
6907 # l3 -> python -> run -> wait.
6910 #* screenshots via gtk
6911 # For capturing images of selected items it's much better to use known
6912 # coordinates and directly produce a file than using the capture ->
6913 # edit -> convert -> save sequence via the gimp or others.
6915 view
= self
.w_
.canvas
.view
6916 selection
= self
.w_
.selector
.get_selection()
6918 (sl
, st
, sr
, sb
) = selection
.get_bounds()
6920 # Get selection corners.
6921 (wl
, wt
) = map(int, view
.world_to_window(sl
, st
))
6922 (wr
, wb
) = map(int, view
.world_to_window(sr
, sb
))
6924 # Compute selection dimensions.
6929 pixbuf
= gtk
.gdk
.Pixbuf(gtk
.gdk
.COLORSPACE_RGB
,
6931 8, # bits_per_sample
6935 # get_from_drawable(src, cmap, src_x, src_y, dest_x, dest_y, width, height)
6936 status
= pixbuf
.get_from_drawable(
6937 view
.get_parent_window(), # gtk.gdk.Window(gtk.gdk.Drawable)
6938 gtk
.gdk
.colormap_get_system(),
6945 print "capture failed"
6947 pixbuf
.save("/tmp/foo.png", "png")
6949 #* system state work
6951 for (mname
, memb
) in self
.__dict
__.iteritems():
6952 print "%-20s %40s" % (mname
, memb
)
6954 # Check completeness.
6955 set([1,2]) - set([1])
6956 set(self
.__dict
__.keys()) - set(dir(self
)) # Empty, good.
6959 #** Print an ordered table of member DATA.
6965 for mname
in sort(self
.__dict
__.keys()):
6966 memb
= self
.__dict
__[mname
]
6967 print " %-20s %-40s" % (mname
, memb
)
6970 #** Print an ordered table of member DATA.
6972 print "%s.%s instance at %x" % (datum
.__module
__,
6973 datum
.__class
__.__name
__,
6976 for mname
in sort(datum
.__dict
__.keys()):
6977 memb
= datum
.__dict
__[mname
]
6978 print " %-20s %-40.39s" % (mname
, memb
)
6981 l3lang.ast.Program instance at -488123d4
6983 _block_env Env-30005-anonymous
6989 #** ordered table of member data 2
6991 # first type occurence listed as subtree
6993 def pot2(datum
, line
= 1, handled
= set()):
6994 # Filter built-in and already printed types
6995 if not (type(datum
) == InstanceType
):
6998 classname
= "%s.%s" % (datum
.__module
__, datum
.__class
__.__name
__)
6999 if classname
in handled
:
7001 handled
.add(classname
)
7004 print "%s.%s instance at %x" % (datum
.__module
__,
7005 datum
.__class
__.__name
__,
7007 for mname
in sort(datum
.__dict
__.keys()):
7008 memb
= datum
.__dict
__[mname
]
7009 print "%4d %-20s %-40.39s" % (line
, mname
, memb
)
7010 line
= pot2(memb
, line
= line
+ 1, handled
= handled
)
7012 pot2(self
._l3tree
, line
= 1, handled
= set())
7014 l3lang.ast.Program instance at -488123d4
7016 2 _block_env Env-30005-anonymous
7017 l3lang.ast.Env instance at -488123d4
7018 3 _bindings {('active', 'df'): None, ('pixel', 'df'
7019 4 _bindings_ids {('active', 'df'): 30509, ('pixel', 'df
7020 5 _bindings_memory {}
7021 6 _children [Env(30536, Env-30005-anonymous, [Progr
7027 #** print ordered table of member data 3
7029 # first type occurence listed as subtree,
7030 # indentation for levels,
7031 # all later occurrences of a type refer to line number
7036 def pot3(datum
, line
= 1, handled
= {}, indent
= 1):
7037 # Filter built-in and already printed types
7038 if not (type(datum
) == InstanceType
):
7041 space
= " " * indent
7042 classname
= "%s.%s" % (datum
.__module
__, datum
.__class
__.__name
__)
7043 if handled
.has_key(classname
):
7044 print "%4d%s%s.%s instance -- see line %d" % (line
,
7047 datum
.__class
__.__name
__,
7051 handled
[classname
] = line
7054 print "%4d%s%s.%s instance at %x" % (line
,
7057 datum
.__class
__.__name
__,
7060 for mname
in sort(datum
.__dict
__.keys()):
7061 memb
= datum
.__dict
__[mname
]
7062 print "%4d%s%-20s %-40.39s" % (line
, space
, mname
, memb
)
7063 line
= pot3(memb
, line
= line
+ 1, handled
= handled
,
7064 indent
= indent
+ 1)
7067 pot3(self
, line
= 1, handled
= {}, indent
= 1)
7069 pot3(self
._l3tree
, line
= 1, handled
= {}, indent
= 1)
7073 #** print ordered table of member data 4
7075 # first type occurence listed as subtree,
7076 # indentation for levels,
7077 # repeated instances of a fixed-member type refer to first's line number,
7078 # distinct instances of container types (Shared) produce new listing.
7085 truncate_lines
= "%-120.119s"
7086 truncate_lines
= "%-80.79s"
7087 def pot4(datum
, line
= 1, handled
= {}, indent
= 1):
7088 # Filter built-in types.
7089 # inheriting from ListType has subtle problems.
7090 if isinstance(datum
, l3lang
.ast
.aList
):
7093 if not (type(datum
) == InstanceType
):
7096 space
= " " * indent
7097 classname
= "%s.%s" % (datum
.__module
__, datum
.__class
__.__name
__)
7099 # Only cross-reference already visited data.
7100 if classname
not in ['l3lang.utils.Shared']:
7101 if handled
.has_key(classname
):
7102 print "%4d%s%s.%s instance -- see line %d" % (line
,
7105 datum
.__class
__.__name
__,
7109 handled
[classname
] = line
7112 if handled
.has_key(id(datum
)):
7113 print "%4d%s%s.%s visited instance -- see line %d" % (
7117 datum
.__class
__.__name
__,
7122 handled
[id(datum
)] = line
7124 # Print info for this datum.
7126 # Only show headers for objects not already described.
7127 print "%4d%s%s.%s instance at 0x%x" % (line
,
7130 datum
.__class
__.__name
__,
7131 (id(datum
) & 0xFFFFFFFFL
))
7134 # Visit datum's children.
7135 for mname
in sort(datum
.__dict
__.keys()):
7136 memb
= datum
.__dict
__[mname
]
7137 print truncate_lines
% ("%4d%s%-20s %-60s" % (line
, space
, mname
, memb
))
7138 line
= pot4(memb
, line
= line
+ 1, handled
= handled
,
7139 indent
= indent
+ 1)
7141 # self is noise_add.l3
7142 pot4(self
, line
= 1, handled
= {}, indent
= 1)
7144 # 325 remember_y 60.25
7145 # 326 w_ <l3lang.utils.Shared instance at 0xb777512c>
7146 # 327 l3lang.utils.Shared visited instance -- see line 21
7148 # 1352 lines without back-reference to already-visited Shareds, e.g.
7150 # 1146 w_ <l3lang.utils.Shared instance at 0xb777512c>
7152 # 1148 _non_pickling_keys []
7156 Include traversal of lists, dicts to cover this:
7158 This is missing _l3tree contents because
7159 type(self._alist.__dict__['_l3tree'])
7160 <class 'l3lang.ast.aList'>
7162 But this is not true; type returns
7163 >>> type(self._l3tree[0])
7164 <class 'l3lang.ast.aList'>
7165 while the instance members are all present:
7166 >>> dir(self._l3tree[0])
7167 ... '_first_char', '_id', '_last_char', '_parent',...
7169 >>> isinstance(self._l3tree[0], l3lang.ast.aList)
7172 Other NESTED types inheriting from python built-ins:
7173 class aList(ListType):
7174 class vaList(aList):
7181 #** print ordered table of member data 5
7183 # - first type occurence listed as subtree,
7184 # - indentation for levels,
7185 # - repeated instances of a fixed-member type refer to first's line number,
7186 # - distinct instances of container types (Shared) produce new listing.
7187 # - make line numbers org-indexable, via [[line]] and <<line>>
7190 # - including indentation level for text reading, didn't help
7197 truncate_lines
= "%-120.119s"
7198 truncate_lines
= "%-80.79s"
7199 def pot5(datum
, line
= 1, handled
= {}, indent
= 1):
7201 This produces a reasonable state dump of the l3 widget provided as
7202 `datum`. The contained l3 program is included but not traversed
7203 recursively, so associated data and clones are completely ignored.
7205 # Filter built-in types.
7206 # inheriting from ListType has subtle problems.
7207 if isinstance(datum
, l3lang
.ast
.aList
):
7210 if not (type(datum
) == InstanceType
):
7213 space
= " " * indent
7214 classname
= "%s.%s" % (datum
.__module
__, datum
.__class
__.__name
__)
7216 # Only cross-reference already visited data.
7217 if classname
not in ['l3lang.utils.Shared']:
7218 if handled
.has_key(classname
):
7219 print "<<%03d>>%s%s.%s instance -- see line [[%03d]]" % (
7223 datum
.__class
__.__name
__,
7227 handled
[classname
] = line
7230 if handled
.has_key(id(datum
)):
7231 print "<<%03d>>%s%s.%s visited instance -- see line [[%03d]]" % (
7235 datum
.__class
__.__name
__,
7240 handled
[id(datum
)] = line
7242 # Print info for this datum.
7244 # Only show headers for objects not already described.
7245 print "<<%03d>>%s%s.%s instance at 0x%x" % (
7249 datum
.__class
__.__name
__,
7250 (id(datum
) & 0xFFFFFFFFL
))
7253 # Visit datum's children.
7254 for mname
in sort(datum
.__dict
__.keys()):
7255 memb
= datum
.__dict
__[mname
]
7256 print truncate_lines
% ("<<%03d>>%s%-20s %-60s" % (line
, space
, mname
, memb
))
7257 line
= pot5(memb
, line
= line
+ 1, handled
= handled
,
7258 indent
= indent
+ 1)
7260 # self is noise_add.l3
7261 pot5(self
, line
= 1, handled
= {}, indent
= 1)
7264 #** print ordered table of member data, org version 1
7265 # - use hex id as address, via org
7266 # - first type occurence listed as subtree,
7267 # - indentation for levels,
7268 # - repeated instances of a fixed-member type refer to first's id
7269 # - distinct instances of container types (Shared) produce new listing.
7271 # - include emacs outline decoration (org-mode)
7274 import l3lang
.ast
as A
7281 return (id(datum
) & 0xFFFFFFFFL
)
7284 #*** special printers
7285 from EMAN2
import EMData
7286 from numpy
import ndarray
7288 accum_types
= (EMData
, ndarray
)
7290 special_printers
= {}
7291 accumulate_interp_res
= {} # Accumulate stuff as side-effect.
7292 limit_output_lines
= 100
7295 #**** Accumulate by EXCLUDING types.
7296 def _special(datum
, line
= 1, handled
= {}, indent
= 1):
7297 '''Print additional information for RamMem._attr_tables.'''
7299 space
= " " * indent
7300 for (id_
, dic1
) in datum
.iteritems():
7302 # mem_str = max_str_len % str(dic1)
7304 if (line
- first_line
) < limit_output_lines
:
7305 print truncate_lines
% (
7313 for key
in sort(dic1
.keys()):
7314 # Side effect: accumulation
7315 if key
== 'interp_result':
7317 # These checks are superficial; real code must use
7318 # pickle w/o memo dict for verification.
7319 if not isinstance(se_val
, (A
.astType
, A
.aNone
, A
.aList
)):
7320 if (isinstance(se_val
, ListType
) and
7322 isinstance(se_val
[0], (A
.astType
, A
.aNone
, A
.aList
))):
7325 accumulate_interp_res
[id_
] = dic1
[key
]
7326 # Print SOME output.
7327 if (line
- first_line
) < limit_output_lines
:
7328 mem_str
= max_str_len
% str(dic1
[key
])
7329 print truncate_lines
% (
7332 space
[0: -(indent
+ 1)] + " ",
7337 special_printers
[('RamMem', '_attr_tables')] = _special
7340 #**** Accumulate by INCLUDING types.
7341 def _special(datum
, line
= 1, handled
= {}, indent
= 1):
7342 '''Print additional information for RamMem._attr_tables.'''
7344 space
= " " * indent
7345 for (id_
, dic1
) in datum
.iteritems():
7347 # mem_str = max_str_len % str(dic1)
7349 if (line
- first_line
) < limit_output_lines
:
7350 print truncate_lines
% (
7358 for key
in sort(dic1
.keys()):
7359 # Side effect: accumulation
7360 if key
== 'interp_result':
7362 if isinstance(se_val
, accum_types
):
7363 accumulate_interp_res
[id_
] = se_val
7365 # Print SOME output.
7366 if (line
- first_line
) < limit_output_lines
:
7367 mem_str
= max_str_len
% str(dic1
[key
])
7368 print truncate_lines
% (
7371 space
[0: -(indent
+ 1)] + " ",
7376 special_printers
[('RamMem', '_attr_tables')] = _special
7379 #**** Accumulate by INCLUDING types and lists/tuples of types
7380 def _special(datum
, line
= 1, handled
= {}, indent
= 1):
7381 '''Print additional information for RamMem._attr_tables.'''
7383 space
= " " * indent
7384 for (id_
, dic1
) in datum
.iteritems():
7386 # mem_str = max_str_len % str(dic1)
7388 if (line
- first_line
) < limit_output_lines
:
7389 print truncate_lines
% (
7397 for key
in sort(dic1
.keys()):
7398 # Side effect: accumulation
7399 if key
== 'interp_result':
7401 if isinstance(se_val
, accum_types
):
7402 accumulate_interp_res
[id_
] = se_val
7403 if isinstance(se_val
, (ListType
, TupleType
)) and \
7404 (len(se_val
) > 0) and \
7406 [ ob
for ob
in se_val
7407 if isinstance(ob
, accum_types
)]) > 0):
7408 accumulate_interp_res
[id_
] = se_val
7411 # Print SOME output.
7412 if ((line
- first_line
) < limit_output_lines
):
7413 mem_str
= max_str_len
% str(dic1
[key
])
7414 print truncate_lines
% (
7417 space
[0: -(indent
+ 1)] + " ",
7422 special_printers
[('RamMem', '_attr_tables')] = _special
7426 truncate_lines
= "%-80.79s"
7427 max_str_len
= "%-60.59s"
7429 truncate_lines
= "%-160.159s"
7430 max_str_len
= "%-.90s"
7431 from time
import time
7432 def poto1(datum
, line
= 1, handled
= {}, indent
= 1):
7433 # Filter built-in types.
7434 # inheriting from ListType has subtle problems.
7435 if isinstance(datum
, l3lang
.ast
.aList
):
7438 if not (type(datum
) == InstanceType
):
7441 space
= " " * indent
7442 classname
= "%s.%s" % (datum
.__module
__, datum
.__class
__.__name
__)
7444 # Only cross-reference already visited data.
7445 if classname
not in ['l3lang.utils.Shared']:
7446 if handled
.has_key(classname
):
7447 print "%s%s.%s instance -- see id [[0x%x]]" % (
7450 datum
.__class
__.__name
__,
7454 handled
[classname
] = hexid(datum
)
7457 if handled
.has_key(id(datum
)):
7458 print "%s%s.%s visited instance -- see id [[0x%x]]" % (
7461 datum
.__class
__.__name
__,
7466 handled
[id(datum
)] = hexid(datum
)
7468 # Print info for this datum.
7470 print "%s%s%s.%s instance at <<0x%x>>" % (
7474 datum
.__class
__.__name
__,
7478 # Visit datum's children.
7479 for mname
in sort(datum
.__dict
__.keys()):
7480 memb
= datum
.__dict
__[mname
]
7481 # Include timing information with lines.
7484 # For instances, produce org-mode <<label>>
7485 # mem_str = max_str_len % str(memb)
7486 mem_str
= max_str_len
% str(memb
)
7487 if "instance at 0x" in mem_str
:
7488 mem_str
= "%s at <<0x%x>>" % (mem_str
[0:-15], hexid(memb
))
7489 elif isinstance(memb
, (InstanceType
, ClassType
, ListType
, DictType
)):
7490 mem_str
= "%s at <<0x%x>>" % (mem_str
, hexid(memb
))
7491 print truncate_lines
% (
7492 "%s%s%-20s %s [%.4fs]" % (
7498 # Default printout for child.
7499 line
= poto1(memb
, line
= line
+ 1, handled
= handled
,
7500 indent
= indent
+ 1)
7501 # Additional custom printout.
7503 line
= special_printers
[(datum
.__class
__.__name
__,
7504 mname
)](memb
, line
= line
+ 1,
7506 indent
= indent
+ 1)
7511 #** Get internals dump
7515 # use 'evaluate locally` on datum
7519 poto1(self
, line
= 1, handled
= {}, indent
= 1)
7521 poto1(w_
.state_
.storage
, line
= 1, handled
= {}, indent
= 1)
7524 #** Compute disk / ram ratio
7527 # Sd = disk state (from accumulate_interp_res)
7528 # St = total state (from save_state)
7529 # S0 = initial state (overhead, from save_state at time 0)
7535 # St(t) = Sr(t) + Sd(t) + S0
7537 # Using known values,
7540 # R = (St - Sd - S0) / Sd
7541 # should (approximately) hold.
7545 # save state to st.t0
7550 poto1(w_
.state_
.storage
, line
= 1, handled
= {}, indent
= 1)
7551 print "items collected: ", len(accumulate_interp_res
)
7553 from l3lang
import utils
7554 utils
.file_cPickle(get_current_state(w_
), "st.total")
7555 utils
.file_cPickle(accumulate_interp_res
, "st.disk")
7557 S0
= os
.path
.getsize("st.t0")
7558 St
= os
.path
.getsize("st.total")
7559 Sd
= os
.path
.getsize("st.disk")
7561 print "ram / disk ratio", 1.0 * (St
- Sd
- S0
) / Sd
7564 #** view interp_result
7565 for (id_
, val
) in accumulate_interp_res
.iteritems():
7566 print "%10d %-.50s" % (id_
, val
)
7568 # What is accumulate_interp_res[33122]?
7569 type(accumulate_interp_res
[33122])
7570 print w_
.state_
.storage
.get_attribute_names(33122)
7571 print w_
.state_
.storage
.get_attribute(33122, 'interp_env')
7577 from cStringIO
import StringIO
7579 from StringIO
import StringIO
7581 pckl_file
= StringIO()
7582 pcklr
= pickle
.Pickler(pckl_file
, protocol
= 2)
7584 pcklr
.dump(accumulate_interp_res
)
7585 print "pickle size", pckl_file
.tell()
7587 # memo[id(obj)] = memo_len, obj
7588 # too many values with no back-link information to identify source.
7589 for (id_
, (index
, obj
)) in pcklr
.memo
.iteritems():
7590 print "%-11x %-6d %-.50s" % (id_
, index
, obj
)
7594 #* Custom pickle with printout.
7595 # Collecting through storage is unreliable; modify pickle itself.
7598 from EMAN2
import EMData
7599 from numpy
import ndarray
7602 from cStringIO
import StringIO
7604 from StringIO
import StringIO
7606 accum_types
= (EMData
, ndarray
)
7607 pckl_file
= StringIO()
7608 g_display_size
= 10000
7609 truncate_lines
= "%-60.59s"
7612 #** pickle modifications.
7614 from copy_reg
import dispatch_table
7615 from copy_reg
import _extension_registry
, _inverted_registry
, _extension_cache
7620 def _real_save(self
, obj
):
7622 me_start
= pckl_file
.tell()
7624 obj_size
= pckl_file
.tell() - me_start
7625 if isinstance(obj
, accum_types
) or (obj_size
> g_display_size
):
7626 print "| %8d | \"%s\" | " % (obj_size
,
7627 truncate_lines
% repr(obj
))
7630 # Check for persistent id (defined by a subclass)
7631 pid
= self
.persistent_id(obj
)
7638 x
= self
.memo
.get(id(obj
))
7640 self
.write(self
.get(x
[0]))
7644 # Check the type dispatch table
7646 f
= self
.dispatch
.get(t
)
7648 f(self
, obj
) # Call unbound method with explicit self
7652 # Check for a class with a custom metaclass; treat as regular class
7654 issc
= issubclass(t
, TypeType
)
7655 except TypeError: # t is not a class (old Boost; see SF #502085)
7658 self
.save_global(obj
)
7662 # Check copy_reg.dispatch_table
7663 reduce = dispatch_table
.get(t
)
7667 # Check for a __reduce_ex__ method, fall back to __reduce__
7668 reduce = getattr(obj
, "__reduce_ex__", None)
7670 rv
= reduce(self
.proto
)
7672 reduce = getattr(obj
, "__reduce__", None)
7676 raise PicklingError("Can't pickle %r object: %r" %
7679 # Check for string returned by reduce(), meaning "save as global"
7680 if type(rv
) is StringType
:
7681 self
.save_global(obj
, rv
)
7685 # Assert that reduce() returned a tuple
7686 if type(rv
) is not TupleType
:
7687 raise PicklingError("%s must return string or tuple" % reduce)
7689 # Assert that it returned an appropriately sized tuple
7691 if not (2 <= l
<= 5):
7692 raise PicklingError("Tuple returned by %s must have "
7693 "two to five elements" % reduce)
7695 # Save the reduce() output and finally memoize the object
7696 self
.save_reduce(obj
=obj
, *rv
)
7700 def save(self
, obj
):
7701 # Produces too many empty () pairs.
7704 _real_save(self
, obj
)
7708 def save(self
, obj
):
7709 _real_save(self
, obj
)
7711 pickle
.Pickler
.save
= save
7715 accum_types
= (EMData
, ndarray
)
7716 pckl_file
= StringIO()
7717 g_display_size
= 100000
7718 truncate_lines
= "%-60.59s"
7719 pcklr
= pickle
.Pickler(pckl_file
, protocol
= 2)
7722 # First get state_.storage,
7723 pcklr
.dump(w_
.state_
.storage
)
7725 # ... then get the REST of state_
7726 pcklr
.dump(w_
.state_
)
7728 #* Custom pickle, collect info, get prefix dump
7729 # Collecting through storage is unreliable; modify pickle itself.
7732 from EMAN2
import EMData
7733 from numpy
import ndarray
7736 from cStringIO
import StringIO
7738 from StringIO
import StringIO
7740 g_accum_types
= (EMData
, ndarray
)
7741 g_pckl_file
= StringIO()
7742 g_display_size
= 10000
7743 g_truncate_lines
= "%-60.59s"
7748 #** pickle modifications.
7750 from copy_reg
import dispatch_table
7751 from copy_reg
import _extension_registry
, _inverted_registry
, _extension_cache
7756 def _real_save(self
, obj
):
7758 me_start
= g_pckl_file
.tell()
7760 obj_size
= g_pckl_file
.tell() - me_start
7761 if isinstance(obj
, g_accum_types
) or (obj_size
> g_display_size
):
7762 # Forming the full repr() takes a LOT of time; maybe
7763 # settle for the type() info...
7764 g_info_stack
.append( (obj_size
, g_truncate_lines
% repr(obj
), obj
) )
7767 # Check for persistent id (defined by a subclass)
7768 pid
= self
.persistent_id(obj
)
7775 x
= self
.memo
.get(id(obj
))
7777 self
.write(self
.get(x
[0]))
7781 # Check the type dispatch table
7783 f
= self
.dispatch
.get(t
)
7785 f(self
, obj
) # Call unbound method with explicit self
7789 # Check for a class with a custom metaclass; treat as regular class
7791 issc
= issubclass(t
, TypeType
)
7792 except TypeError: # t is not a class (old Boost; see SF #502085)
7795 self
.save_global(obj
)
7799 # Check copy_reg.dispatch_table
7800 reduce = dispatch_table
.get(t
)
7804 # Check for a __reduce_ex__ method, fall back to __reduce__
7805 reduce = getattr(obj
, "__reduce_ex__", None)
7807 rv
= reduce(self
.proto
)
7809 reduce = getattr(obj
, "__reduce__", None)
7813 raise PicklingError("Can't pickle %r object: %r" %
7816 # Check for string returned by reduce(), meaning "save as global"
7817 if type(rv
) is StringType
:
7818 self
.save_global(obj
, rv
)
7822 # Assert that reduce() returned a tuple
7823 if type(rv
) is not TupleType
:
7824 raise PicklingError("%s must return string or tuple" % reduce)
7826 # Assert that it returned an appropriately sized tuple
7828 if not (2 <= l
<= 5):
7829 raise PicklingError("Tuple returned by %s must have "
7830 "two to five elements" % reduce)
7832 # Save the reduce() output and finally memoize the object
7833 self
.save_reduce(obj
=obj
, *rv
)
7837 def save(self
, obj
):
7842 _real_save(self
, obj
)
7844 if len(g_info_stack
) > 0:
7845 _tmp
.append(g_info_stack
)
7848 pickle
.Pickler
.save
= save
7852 def dump_stack(stack
, indent
):
7853 # Unwrap outer lists
7854 while isinstance(stack
[-1], ListType
):
7856 # Get the main object head and print info.
7857 (size
, rep
, obj
) = stack
[-1]
7858 print "%s %-8d %s" % ("*" * indent
, size
, rep
)
7859 # Get head's content, if any
7860 [dump_stack(ii
, indent
+ 1) for ii
in stack
[0:-1]]
7864 g_accum_types
= (EMData
, ndarray
)
7865 g_pckl_file
= StringIO()
7867 g_display_size
= 1000
7868 g_truncate_lines
= "%-60.59s"
7870 pcklr
= pickle
.Pickler(g_pckl_file
, protocol
= 2)
7874 pcklr
.dump(w_
.state_
)
7878 dump_stack(g_info_stack
, 0)
7882 pcklr
.dump(self
._l3tree
)
7883 dump_stack(g_info_stack
, 0)
7886 import anydbm
as any
, whichdb
7888 db
= any
.open('l3db.st', 'c')
7890 print whichdb
.whichdb('l3db.st')
7892 db
= any
.open('l3db.st', 'c')
7897 #* Proxy for transparent persistence
7901 def __init__(self
, obj
):
7903 Proxy
.__init
__ = __init__
7905 def to_cache(self
, id):
7909 Proxy
.to_cache
= to_cache
7911 def __getattr__(self
, m_name
):
7912 m_unbnd
= getattr(self
._obj
.__class
__, m_name
)
7917 if isinstance(arg
, Proxy
):
7918 nargs
.append(arg
._obj
)
7921 return (m_unbnd(self
._obj
, *nargs
))
7924 Proxy
.__getattr
__ = __getattr__
7927 #** proxy numeric tests
7929 from cPickle
import dumps
7930 n1
= N
.random
.ranf( (5,4) )
7932 print n1_prox
+ n1_prox
7934 # TODO: getstate / setstate
7935 print len(dumps(n1
))
7936 print len(dumps(n1_prox
))
7937 n1_prox
.to_cache(1234)
7938 print len(dumps(n1_prox
))
7940 # Useless in-memory size guesses (spread too much)
7941 plist
= [Proxy(n1
) for ii
in xrange(10)]
7942 id(plist
[-1]) - id(plist
[-2])
7943 ppos
= [id(foo
) for foo
in plist
]
7945 print map(lambda (x
,y
): x
-y
, zip(ppos
[1:None], ppos
[0:-2]))
7948 #** proxy emdata tests
7949 from EMAN2
import EMData
7953 print "array size", arr_size
7954 e1
.set_size(*arr_size
)
7955 e1
.process_inplace('testimage.noise.uniform.rand')
7956 print sys
.getrefcount(e1
)
7958 print sys
.getrefcount(e1
)
7960 print e1_prox
+ e1_prox
7963 print len(dumps(e1
))
7964 print len(dumps(e1_prox
))
7965 e1_prox
.to_cache(1234)
7966 print len(dumps(e1_prox
))
7971 #** create test cases
7974 from cPickle
import dumps
7976 n1
= N
.random
.ranf( (5,4) )
7978 n1_weak
= weakref
.proxy(n1
)
7981 print sys
.getrefcount(n1
)
7984 # Refcount with member ref.
7986 print sys
.getrefcount(n1
)
7989 # weakref's proxy adds no new fields:
7990 set(dir(n1_weak
)) - set(dir(n1_prox
._obj
))
7992 from EMAN2
import EMData
7995 e1
.process_inplace('testimage.noise.uniform.rand')
7996 print sys
.getrefcount(e1
)
7998 e1weak
= weakref
.proxy(e1
)
8002 #*** numeric array works
8003 print n1_prox
+ n1_prox
8010 # TypeError: unsupported operand type(s) for +: 'instance' and 'instance'
8011 print e1prox
+ e1prox
8013 print operator
.add(e1prox
, e1prox
)
8016 print e1weak
+ e1weak
8017 print operator
.add(e1weak
, e1weak
)
8018 # but produces the equal? result:
8019 # <libpyEMData2.EMData object at 0x156239cc>
8020 # <libpyEMData2.EMData object at 0x156239cc>
8022 # Something is missing causing the discrepancy:
8023 print e1weak
.__add
__(e1weak
)
8024 print e1
.__add__(e1
)
8026 # <libpyEMData2.EMData object at 0x15623cdc>
8030 # <method-wrapper object at 0x1955d3cc>
8031 # <bound method EMData.__add__ of <libpyEMData2.EMData object at 0x1613da54>>
8033 print EMData
.__add
__(e1
,e1
)
8034 print EMData
.__add
__(e1prox
,e1prox
)
8035 print EMData
.__add
__(e1weak
,e1weak
)
8036 # <libpyEMData2.EMData object at 0x15623ca4>
8039 e1prox
._make
_member
_proxy
('__add__')
8041 # Now this runs (work -- who knows):
8042 print e1prox
+ e1prox
8043 print e1prox
.__add
__
8044 print e1weak
.__add
__
8045 # <bound method EMData.__add__ of <libpyEMData2.EMData object at 0x1613da54>>
8046 # <bound method EMData.__add__ of <libpyEMData2.EMData object at 0x1613da54>>
8048 # TypeError: unsupported operand type(s) for +: 'EMData' and 'instance'
8049 print 1.0 * e1prox
+ e1prox
8052 print e1weak
+ e1weak
8055 #* Replace original class with proxy wrapper
8056 # Looks like there is no need for metaclasses, as this will do
8057 # everything needed. However, this will not intercept C code creating
8058 # instances, so it is too limited in practice.
8062 eman2_emdata
= EMAN2
.EMData
8065 class EMData(Proxy
):
8066 def __init__(self
, *args
):
8067 self
._obj
= eman2_emdata(*args
)
8070 # This binding remains valid for all FUTURE references, so it must be
8071 # done before other scripts import the module.
8072 EMAN2
.EMData
= EMData
8078 e1
.process_inplace('testimage.noise.uniform.rand')
8081 # The (C) member functions directly create the new object, so the
8082 # indirection above fails.
8084 tst_add
.print_image()
8086 #* Pickling uniquely
8087 # To get accurate memory stats, avoid repeated pickling given nested
8093 from cStringIO
import StringIO
8095 from StringIO
import StringIO
8097 pckl_file
= StringIO()
8098 pcklr
= pickle
.Pickler(pckl_file
, protocol
= 2)
8101 return pckl_file
.tell()
8104 #* string deepcopy test
8105 from copy
import deepcopy
, copy
8106 orig
= 'the original string'
8108 print id(orig
) - id(cp
)
8109 # so strings 'copy' as reference.