python_code
stringlengths
0
992k
repo_name
stringlengths
8
46
file_path
stringlengths
5
162
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. """ $Id$ unfinished. """ from basic import * from basic import _self # == class ImageChunk(InstanceOrExpr, DelegatingMixin): """ ImageChunk(widget2d) draws widget2d normally, but also captures an image to use for faster redrawing. In some cases, it can significantly speed up drawing of certain constant pictures or text, at least for now while our text drawing is inefficient and we don't yet have the display-list equivalent of ImageChunk. WARNING: See the caveats below about significant limitations in when and how ImageChunk can be used. See also DisplayListChunk [more widely applicable]. The default options redraw the image normally at least once per session, and never store it on disk (except perhaps in temporary files due to implementation kluges). They draw it normally again (and cache a new image) whenever some variable used to draw it changes. Options are provided to change the set of variables whose changes invalidate the cached image, to record a history of changed images for debugging and testing purposes, to keep a saved image on disk for rapid startup, to require developer confirmation of changes to that image, and to bring up debugging panes for control of these options and browsing of past image versions. Caveats: ImageChunk works by grabbing pixels from the color buffer immediately after drawing widget2d. This can only work properly if widget2d is drawn in an unrotated orientation, and always at the same size in pixels on the screen, but ImageChunk doesn't enforce or check this. Therefore it's only suitable for use in 2d screen-aligned widget layouts. It can also be confused by obscuring objects drawn into the same pixels in the color or depth buffers, if they are drawn first (which is not in general easy to control), so it's only safe to use when no such obscuring objects will be drawn, or when they're guaranteed to be drawn later than the ImageChunk. Likely bug: it doesn't yet do anything to make the lbox aligned at precise pixel boundaries. """ # implem: delegate lbox to arg1, but override draw. widget2d = Arg(Widget2D) filename = Arg(str) ###e make temp filename default, using python library calls ##e make sure those are easy to use from exprs #e state: need_redraw, usage tracking (via an lval, standing for the result of drawing?) ###e (we need a standard helper for that) # (maybe an object which can supply the wrapping method we need below) need_redraw = State(bool, True) # note: as of 061204, this (for State here and Set below) works in other files # but is untested here (since other code here remains nim) def usagetrack_draw(self, draw_method, *args, **kws): ##e this needs to be a method inside some sort of lval object, not of self #e begin tracking res = draw_method(*args, **kws) #e end tracking return res # this is the delegate for drawing -- we'll delegate the lbox attrs separately, i think -- or cache them too (usage-tracked)??####e delegate = If( need_redraw, ##e we want this subinstance's draw call to be wrapped in our own code # which does usage tracking around it # and sets need_redraw, False after it. Can we do that, supplying the wrapping method? PixelGrabber( WrapMethod(widget2d, 'draw', _self.usagetrack_draw, ##k is that _self. needed? post_action = Set(need_redraw, False)), ###k args ###IMPLEM post_action ##e designs ok???? filename), Image(...) ) pass # end of class ImageChunk # end of code """ todo: default options: in-ram image, no files, thus not but assume the same instance can be multiply drawn (why not? if anything needs to save one or more locations for redraw, it's an outer thing like a Highlighting) (exception would be if appearence depended on options to: [note, a lot of these would be useful inval-control or inval-debug options in general] not do it on every inval but only when user confirms but only when session starts do it even when not needed if user asks if given other formula invals on session start, reporting changes save it in a file, or not use that file in new sessions, or not intercept a special modkey or debug command on the widget to put up a prefs/inspector pane for that widget """ # end
NanoCAD-master
cad/src/exprs/scratch/ImageChunk.py
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. """ $Id$ """ random point in n-dim-simplex, as n+1 vertex weights: - random point in n-cube - sort the coords - replace each one, and a final added 1, by itself minus the prior one. evidence: each ordering of cube coords corrs to a simplicial region of the cube; the operation shifts that into a standard posn. more evidence: the op appears to be volume-preserving (the sort is, the shears are -- those minus prior ones are shears) and fair and gets the right ineqs on result so what else could it be? this might be a proof. maybe Random(x,y,z) means the above for 3 vertices (of any affine type, incl vector or color or real or complex)? then Random(0,1) is special case, assuming you know you mean Real not Int... RandomChoice(green, red) has two values RandomWeighting(green, red) is the above (point in simplex) (most useful for more vertices) another poss meaning for RandomWeighting would be spherical - rand point on sphere... but that's more natural when you do have a sphere or ball as your legal points, not a simplex! So call that one something else and let it have different args.
NanoCAD-master
cad/src/exprs/scratch/Random.py
# Copyright 2007 Nanorex, Inc. See LICENSE file for details. """ ArgList.py $Id$ scratch file to be merged into attr_decl_macros.py and instance_helpers.py ABANDONED (tentatively) on 070321 -- replaced by a new def ArgList in attr_decl_macros.py, and support features in ExprsMeta.py. """ def ArgList(type_expr): "see rules.py for a docstring #doc" # Coding strategy: create an expr with just enough in it to let ExprsMeta's formula scanner do replacements # that only it can do (for argpos and attr); then let a helper method do most of the work (when self is known, # thus when arglist and its len are known, and type_expr can be evaluated); have it return the list of Instances. # # (#e In future, the helper might return a list-like object which makes Instances lazily, though I'd guess this # rarely matters in practice -- but who knows, what if we use this for the textlines in a text editor?) global _arg_order_counter _arg_order_counter += 1 required = True argpos_expr = _this_gets_replaced_with_argpos_for_current_attr( _arg_order_counter, required ) #e pass an option to say we're the last, or error -- # ie to say the next argpos is -1, or so, or to include an error flag with the counter, # and make that detected as an error in the class decls, maybe in the formula scanner # or whatever makes _this_gets_replaced_with_argpos_for_current_attr actually get replaced, # or the replacement method inside that... #e make it notice error of arg with dflt before arg w/o one too, *or* make that work! # all this can be done by making it accumulate more info than just the true argpos, # for passing from one to the next -- whereever it accums that, presumably in the scanner itself # or a mutable passed with it, maybe in the class's namespace as a kluge (see what the code does now) global _E_ATTR # fyi attr_expr = _E_ATTR res = call_Expr( getattr_Expr( self, '_i_arglist_helper'), attr_expr, argpos_expr, type_expr) # btw: if this returns list of instances, but for convenience uses _ArgOption_helper which returns expr in _self, # then it needs to eval that expr with _self = self. # Far more efficient would be to imitate it, just building the type coercion expr per arg, then making it. return res # method of IorE: def _i_arglist_helper(self, argpos): for pos in range(argpos, len(self._e_args)): ## arg = Arg(type_expr, expr, options) attr_expr = None ###k or use current attrname? yes see below -- assert not None, or if none, change it to argpos, modified dflt_expr = _E_REQUIRED_ARG_ required = True argpos_expr = _this_gets_replaced_with_argpos_for_current_attr( _arg_order_counter, required ) type_expr # pass this arg = _ArgOption_helper( attr_expr, argpos_expr, type_expr, dflt_expr) ### we want argpos_expr in caller, to use it here # we want this to let us separately give argpos for grabarg and index to use # or just use this behavior: ##if attr_expr is not None and argpos_expr is not None: ## # for ArgOrOption, use a tuple of a string and int (attr and argpos) as the index ## index_expr = tuple_Expr( attr_expr, argpos_expr ) # or extend that case stmt if we need to res.append(arg) return [whatever_Arg(expr, index) for pos in range(argpos, map_Expr( func, remaining args - from which it uses argpos helper func runs on the arg exprs and argpos calls .Instance a lot uses same argpos index as if not in a list? no, uses its own plus the one in the list helper can wrap _i_instance does it call grabarg in usual way? I guess so can we generate a bunch of Arg calls w/ special options for index, and return a list of evalexprs of them? ie a list of instances as our value
NanoCAD-master
cad/src/exprs/scratch/ArgList.py
# Copyright 2007 Nanorex, Inc. See LICENSE file for details. """ lambda_Expr.py $Id$ scratch so far, coming out of discussion of a better syntax for testexpr_19f, but it's likely to be made real. """ if 0: # excerpt from test.py # later 070106: (syntax is a kluge; see also testexpr_26) testexpr_19f = eval_Expr( call_Expr( lambda thing: Overlay( thing, DrawInCorner( Boxed( eval_Expr( call_Expr( demo_drag_toolcorner_expr_maker, thing.world )) )) ), testexpr_19b )) ###EVAL_REFORM ###BUG: testexpr_19b is not instantiated (when we eval the call_Expr and ask for thing.world) but needs to be. # Since this whole syntax was a kluge, I should not worry much about making it or something similar still work, # but should instead make a better toplevel syntax for the desired effect, and make *that* work. # I guess that's a lambda wrapper which can have the effect of Arg/Instance decls on the lambda args... # btw, does that mean Arg & Instance need to be upgraded to be usable directly as Exprs? # or do the things they produce work when passed in a list, if we scan them in the same way as ExprsMeta does? if 0: macro = lambda_Expr( [Arg(type, dflt), Instance(expr), Option('name',type,dflt)], lambda arg1, arg2, name = None: blabla ) testexpr_xxx = macro(argexprs) thismacro = lambda_Expr( [Arg(Anything)], lambda thing: # thing will be an Instance when this lambda runs Overlay( thing, DrawInCorner( Boxed( eval_Expr( call_Expr( demo_drag_toolcorner_expr_maker, thing.world )) )) ) ) testexpr_xxx = thismacro(testexpr_19b) # if we could, would we want to implement the ability to mix the decls into the lambda, like this:? lambda_Expr( lambda thing = Arg(Anything): Overlay( thing, ... thing.world ...) ) (testexpr_19b) # guess: yes. # (would we want to make that the only allowed syntax? not sure.) # (would we want a default typedecl of Arg(Anything) (which gets instantiated)? Probably.) # (would the present example also be expressible by inserting testexpr_19b into the lambda arg decl, # either as all of it, or inside Arg?? ####k) if 0: lambda_Expr( lambda thing = testexpr_19b: Overlay( thing, ... thing.world ...) ) () # not sure ... ### lambda_Expr( lambda thing = Instance(testexpr_19b): Overlay( thing, ... thing.world ...) ) () # *maybe* ought to work, # but can this then ever be a supplied arg to the lambda_Expr() as a whole? guess: no. lambda_Expr( lambda thing = Arg(Anything, testexpr_19b): Overlay( thing, ... thing.world ...) ) () # should be made to work. # (implem details: file lambda_Expr with Arg; the mixing in of decls can probably be reliably supported, # even if only by extracting arg-defaults from the lambda and then calling it with a full arglist made using those, # so no need to make a "modified lambda".) # [Should this influence the naming decision for the Python IorE subclass to replace DelegatingIorE and InstanceMacro?]
NanoCAD-master
cad/src/exprs/scratch/lambda_Expr.py
### THIS FILE IS NOT YET IN CVS # Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. #e above: # code for a formula expr, to eval it in an env and object, to a definite value (number or widget or widget expr), # which no longer depends on env (since nothing in env is symbolic) # but doing this might well use attrs stored in env or rules/values stored in object, and we track usage of those, for two reasons: # - the ones in env might change over time # - the ones in the object might turn out to be general to some class object is in, thus the result might be sharable with others in it. # so we have eval methods on expr subclasses, with env and object as args, or some similar equiv arg.
NanoCAD-master
cad/src/exprs/scratch/unclassified.py
# Copyright 2007 Nanorex, Inc. See LICENSE file for details. """ $Id$ code file on selection or region selection? idea: a simple semantics for region selection, if "touches all of the drawn stuff" or "any part of it" is too hard (which it is, for most things except simple shapes), is "touches all of (or any of) the object's control points". it's easy to implement, easy to understand, and (i realize now) insensitive to changes of display prefs. it could be done efficiently enough to do realtime update of region-selected objects (if we improved our "region" representation, anyway). We might do per-chunk caching of a 2d-screen-version of all that chunk's control points, then sort them into cells... (note: an atom's control point is its center, so it's same behavior as now for atoms. For other objs we have some simple def of what they are -- can be more than strictly needed to define it, for this purpose... call it a "selection control point". For simple shapes, sphere cyl cone, we might do the real alg (as if all points were cpoints) -- but only when that shape was itself selectable -- when part of display of some model obj, instead define cpoints for that model obj.) """
NanoCAD-master
cad/src/exprs/scratch/selection-scratch.py
# Copyright 2007 Nanorex, Inc. See LICENSE file for details. """ demo_drag_2_scratch.py $Id$ scratch file about how to rewrite demo_drag in a higher level way """ Vertex = DataType("Vertex", Arg("pos", Position), # relative to what? Option("guide", ModelObject) ) # this is not a correct set of attrs DataType(pos = Arg(Position))(guide = Option(ModelObject)) # nah DataType( lambda pos = Arg(Position), guide = Option(ModelObject): 0 ) # has the data and syntax, but looks too weird and non-POLS -- # but maybe it wouldn't if we *used* the symbols -- replace 0 with a bunch of further decls about those symbols, # like the change-order-policies discussed 1 screen below DataType("Vertex", "pos", Arg(Position), "guide", Option(ModelObject), ) # surprisingly tolerable. hmm. # define IntrinsicVertex as extended/subtype of Vertex, with more data and ways to see it as Vertex IntrinsicVertex = Vertex(pos = RelativePos(_params.lpos, <coordsys>), <other customization>) # Create command, using a formula-customized subtype of IntrinsicVertex as the type to create Create(IntrinsicVertex(lpos = <formula>, guide = <formula>, policy = <formula>)(<data args, opts>)) ## Move( some_vertex, from = pos1, to = pos2) # typical Move command # [unless from or to is py keyword -- rats, 'from' is! Ok, change it:] Move( some_vertex, _from = pos1, to = pos2) #or Move( some_vertex, from_pos = pos1, to_pos = pos2) # also allow from_lpos, to_lpos # == simplest that could work: Vertex = DataType("Vertex", "pos", Arg(Position)) Vertex = DataType( "pos", Arg(Position)) IntrinsicVertex = ... we want to say that pos is a formula of lpos and some coords ( a reversible formula -- lpos can be set by setting pos -- due to coords or the coord-combining-op supporting that) and the obj that supplies the coords is an arg and a policy option says whether we grab a snapshot of those coords from that obj, or continuously regrab them, as obj moves (but even in first case a cmenu item would let us regrab them -- so it still knows the obj) (but it does have its own copy of the coords, I guess -- and the precise type of those depends on the nature of the obj) note: coords is correct but don't be fooled -- it's a semiarb map from some coords to others -- not an affine map! so for a point on a sphere, the intrinsic coords are a surface point on unit sphere and a radius ratio... or a radius offset if you prefer -- different types. what does the eg look like, for a radius ratio, with a policy option for autoupdate or just update? coords = formula(guideshape), update = True or False pos = coords(lpos) # reversible -- how do we say so? pos = Reversible(coords(lpos)) #?? pos = Alias(coords(lpos)) #?? pos = Lvalue(coords(lpos)) #?? pos = Settable(coords(lpos)) #?? # or just let it be implied by the expr coords(lpos) due to the lexically declared type of coords? (sounds too hard for now) # or have a separate list of things you can set, to change other things, which says you can set pos to change lpos? # (a list of different ways to change it, each having a list in priority order of things to keep fixed or set as requested; # in this case the list would say, supply pos, fix coords, derive lpos, I guess... # or that you can derive lpos from pos? # goal: know what can be specified, to get what -- and how to do this (at least, what to ask to do it, ie coords) # does it relate to what data's type needs to know the code to do it? ie it's not just lpos + coords = pos, solved for lpos -- # the knowledge of how is *in coords*, not in some outer + operation. So it's really that coords gets pos from lpos, reversibly. # It's like an optional attr of the formula, or even of the expr coords(lpos). class GuideShapeVertex(Vertex): # (this class form makes it easier to see the symbols and use them in subsequent exprs -- even lambda can't let me use them in # the very next decl -- i'd need nested lambdas for that -- or my own expr syntax parser, of course) guide = Option(GuideShape, "the guide shape used to position the vertex") #e digr: ok place for a docstring, in this syntax? if 0: # problem: depends on knowing that a string is not the default GuideShape! eg this is not good: textmsg = Option(str, "message for statusbar") # unless this is then *both* the default and docstring... very silly but possible -- # has some UI advantages (in a parameter dialog), believe it or not! But too silly to take seriously. # fix that: textmsg = Option(str, <dflt>, "message for statusbar") textmsg = Option(str, doc = "message for statusbar") # but seriously, we might permit it if you *do* know that strings can't belong to the type. Not sure. # Not great if source code changes meaning if someone adds a way to coerce strings into that type! So nevermind. # coords = guide.coords -- Decl about whether snapshotted or updated -- coords_update = Option(bool, False, "whether to continuously update the lpos coordsys (and thus pos) from motion of the guide shape") coords = StateSnapshot(guide.coords, update = coords_update, doc = "intrinsic coordsys for lpos (can map it to abs pos)") # or capitalize guide.Coords since it's a type, in a sense? not sure. it's also or more a func... # why is this not just a formula? because update might be false. But if it's true? because guide shape might *lose* its coords, # e.g. if it disappears entirely (gets deleted from model); # then the update fails, but this does not lose the coords! it's just a warning (about the data object -- maybe not even # seen except on demand, ie really info not warning), and they are still locally there & useable. So it's State for sure. # OTOH it's not settable except by taking a snapshot of the declared formula, I guess... not sure if that's essential. # I wonder if we should even declare it like this: if 0: coords = State(guide.Coords) coords.value = ... # no, too confusing, it's coords as a whole that we're setting... lpos = StateArg(coords.Position, "intrinsic coords -- i.e. local pos") #k and coords.Position is a type which is an aspect of that "func" coords # (which is more than just a func, tho "callable" in Expr sense, i.e. coords(x) is an Expr) pos = coords(lpos, reversible = True, doc = "absolute position, derived from lpos via coords; can be set to adjust lpos") pass # to summarize and fix that, rename some things for clarity, etc: class GuideShapeVertex(Vertex): "#doc" guide = Option(GuideShape, doc = "the guide shape used to position the vertex") coordsys_update = Option(bool, False, "whether to continuously update the lpos coordsys (and thus pos) from motion of the guide shape") coordsys = Snapshot(guide.coordsys, update = coordsys_update, #e rename update -> continuous? auto? always? #e just Snapshot? doc = "intrinsic coordsys for lpos (used to map it to abs pos)") lpos = StateArg(coordsys.Position, "intrinsic coords -- i.e. local pos") pos = coordsys(lpos, reversible = True, doc = "absolute position, derived from lpos via coordsys; can be set to adjust lpos") pass # do we need to declare that outsiders can set .pos, not just internal code? Or is not naming it _x or listing it as private enough? # given the above, what constructors can we use? GuideShapeVertex(lpos, guide = guide1) # custom type: myVert = GuideShapeVertex(coordsys_update = True) def makeone(): # wrong use of Create as executable function! Create( myVert(lpos1) ) Create( myVert(pos = pos1) ) # dubious -- the idea is, pos is not an option, so using it as one must mean setting it in constructor... # btw are we going to let people in general use Args (with known names, as they always have) as Options? at least for customization? #e # when that happens, are they removed from the remaining arglist?
NanoCAD-master
cad/src/exprs/scratch/demo_drag_2_scratch.py
some proto is in scratch/NewInval, not sure if it's latest # Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details.
NanoCAD-master
cad/src/exprs/scratch/displists.py
# Copyright 2007 Nanorex, Inc. See LICENSE file for details. """ $Id$ """ SimpleInsertCommand(Cylinder) -> something to put in a toolbar which can insert a Cylinder it queries Cylinder for its args etc, as name/type pairs Cylinder(__fakeopt__ = True)._e_query_args() -> list of Arg etc exprs for example, Arg(type, dflt_expr, doc = ...) (which we turn into a new kind of toplevel expr; not sure it can be instantiated; but it has a meaning) Stateful(Cylinder) -> something that turned Cyl's args/opts into StateArgs; options control whether state can be a formula... note for an ArgFormula we really have two levels of formula, one the real one and one the computed formula from that; can it be computed by simplification? sometimes yes, but not only. eg it might be computed by being looked up in a file. Editable(Stateful(Cylinder)) -- not sure what that means; does it mean adding a UI interface for editing the state it has? or permitting one to be added, or autoadded, in the right context? Editable(Arg(...)) -- any meaning? Editable(State(...)) State(Editable(int), ...) not sure if those have any meaning --- what is something not normally editable that we can make editable?? then editable(x) for that kind of x might have a meaning. SimplePropertyManager(Cylinder) -> ... class SimplePropertyManager(DelegatingInstanceOrExpr): # args forwhat = Arg(Type, doc = "the type of thing we are a property view/edit interface for") # is a pure expr turned into an Instance of Type?? guess: yes. not sure how that can be semantically clean. ###REVIEW # formulae delegate = MapListToExpr( _self.editfield_for_parameter, forwhat.parameters, KLUGE_for_passing_expr_classes_as_functions_to_ArgExpr(SimpleColumn) ) def _CV_editfield_for_parameter(self, parameter): ###k _CV_ correct here?? and can we return expr and have it made? _CVE_ for that?? ##e or does MapListToExpr do the make if needed?? if not, should it? return parameter.type.standard_editfield ### ??? ###e even if so, doesn't it need some args? it needs some state to modify... # and something needs a way to make one of these forwhat-things or get the user to find one... # to see this more clearly, draw a block diagram which includes the PM and see what it connects to. pass nim in above: - the coercion from expr to Instance of Type; - the exprs (like Arg, but lots more) that need to appear in type1.parameters; - parameter.type.standard_editfield with unspecified further args - something unsaid above that can make a new thing of type forwhat -- - and worse, can make it of Stateful(forwhat) if forwhat doesn't have state, or doesn't have enough (unclear) - and decisions of whether the state can be formulae class SimpleInsertCommand(InstanceOrExpr): ##k super? should say the general type of command (so as to imply the interface we meet) -- CommandTool????? """Be an insert command for a given type, with a SimplePropertyManager for it, and the semantics of an insert command, and the metainfo which (when we are registered) leads a UI constructor to think it natural for us to have a toolbutton on an appropriate Insert toolbar/menu depending on the type of thing we insert and the type of parent (i mean container, not sure if that should be called parent) it might need (eg as a Line needs a Sketch, so should be on its flyout toolbar). Design Q: if we want to use this to do part of the work of making InsertPolyline, how do we mix it with the rest of work (incl a lot of Python methods)? - Can we subclass a customized expr? (not in a normal way anyway, though it might be possible and might make some sense) - Can we subclass it, and give values for its arg? - Can we add options that manage to make all additions/changes needed? - Should we delegate to it from something that adds its own outer layer? If so, how does outer thing modify the PM this makes, if it wants to modify its description before making it, but not by a lot? Can it customize an expr for it in a way that revises/groups/removes/reorders fields?? """ ###k Ambiguity: are our Instances permanent commands, or CommandRuns? Is CommandRun something generic with Command as arg??? ### This relates to recent model/view separation discussions (with CommandRun of a command like one view of a model obj). # args forwhat = Arg(Type, doc = "the type of thing we are a simple insert command for") # property_manager = SimplePropertyManager( forwhat) ###e also pass a World, or an App (eg for prefs & selection state & world)? ###e maybe there is something in between -- much smaller than an App, sort of like an EditableModel... with sel state, history... toolname = "Insert " + forwhat.type_nickname ###WRONG if same button also edits ###e or cmdname, like for Undo -- varies depending, if we can act as Insert Line or Edit Line depending... #e also featurename? #e maybe some metainfo to help it get classified (for tool placement in UI)? # eg "Insert" (tho same button might also edit...) # eg topical stuff found from forwhat # eg this is a way of making type forwhat and a way of using types x,y,z which are major args to forwhat pass Parameter interface: # see also the HJ .desc parsing code name type # for int or real (or similar) range, or range_expr min / min_expr max / max_expr # for some kinds of raw types coordsystem, or space, or units... maybe specifiable by a ref to another param, or by any other expr in _self/_env etc # for coercion other types we can accept, and what we convert them to (might be extensions of the main type) strictness options (eg can we coerce float to int by truncation? yes, or only if exact like 3.0, or no) # fancier types really an array, or a structured set? permit formula as value, or not (if so, in what vars, with what ops?) can a value come with metainfo? source (who says) modtime compute history confidence (qualitative) caveats warnings can it come with extra info? (like a color along with a number) (maybe this is just metainfo) # not sure what category can a value be uncertain? dflt, or dflt_expr in _self (the thing it's a param of) in _env ? can be special symbols like Automatic, Required(?) # fancy properties, not sure what category arg, option, argoroption what superclass was it defined in? (this class or one of its base classes) (ambiguity: what if def is overridden??) state or not expr or instance, if applicable is it computed, or otherwise constrained? (related state?) # this might be about param as class, or about specific value can value vary in time? (seems related to Q of whether it can be a formula, but really, independent/ortho, i think) # UI hints (for editfields in a PM) label (if different from name) widget # what kind of widget to show it in for editing option: whether to compact it 2 or 3 on a row? option: whether to dim it under some conds (and force it to a computed or dflt value) option: whether to leave it out entirely under some conds (and force the value) group # which PM group to put it in maybe, advice about when to show it by default (eg have its group open) -- not sure #e metainfo of kinds a lot of things can have -- # note, this is info about the parameter attribute (a class), not about a specific value of the parameter fullname tooltip topics keywords (for searching out this parameter when browsing all params of all types/exprs) #e author, etc A lot but not all of the parameter interface would apply to any attribute in an IorE class. Is a parameter expr already an instance, since it's mathematical data??? (maybe I asked that above, in slightly diff words... or maybe on paper?) or, is an Instance of it a specific parameter-slot on a specific object??
NanoCAD-master
cad/src/exprs/scratch/editable-scratch.py
# Copyright 2007 Nanorex, Inc. See LICENSE file for details. """ $Id$ """ from exprs.basic import * # stuff to set up the env... see what testdraw does # a place to make instances, new ones have totally fresh state, but only keep one, or let caller supply index... # === def find_or_make(cctype, mode): "Return a confirmation corner instance for mode, of the given cctype." if 1: return None # stub # We keep the instances in a global place shared by all modes, indexed by cc_data. # They have their own state & drawing env, separate from those of other expr Instances # (so far, that just means the ones made by and used in testmode). # For using reloaded code during devel, we can provide a cmenu item or the like, to clear that place. #e # (Thus no need for the index to contain a reload counter.) # # Do we need usage-tracking and remaking of instances? Only if they depend on env.prefs variables. # In theory they might, so we'll provide it. # This code may be split out and refiled... ## LvalDict2() # ... hmm, what do i use for: # MT_try2 (self.Instance with computed index, thus indirectly uses LvalDict2 via _CV_) # ### self.Instance needs optim - option to avoid expr compare, don't even bother with grabarg if instance is cached # and find_or_make_main_instance? (custom compare & cache) # and texture_holder? (texture_holder_for_filename = MemoDict(_texture_holder)) #e refile some of this into other files in exprs module: (might have to split pieces out, to do that) class cc_memoizer(InstanceOrExpr): def find_or_make(self, cctype, mode): "" bgcolor_data = None #e this should be a function of mode.bgcolor which affects the look of the CC icons cc_data = (cctype, bgcolor_data) # this is everything which needs to affect the CC instance. ###e might fail if cctype is an expr, since it might not yet be hashable for use in a dict key... # should fix that! (by interning the expr to get its "hash", probably) return self.cached_instances[cc_data] def _CV_cached_instances(self, index): "compute self.cached_instances[cc_data]" cctype, bgcolor_data = index #e use bgcolor_data to help make the expr ccexpr = interpret_cctype(cctype, bgcolor_data) # None or an expr #e pkg above back into cc_data for passing in to that helper ## return self.Instance(ccexpr, index, skip_expr_compare = True) ###IMPLEM skip_expr_compare ## ###e needs the comparison optim; or, do our own make right here (might be better) ## ## return ccexpr._e_make_in... - not enough, needs various checks, etc... need to split out some of that from .Instance ## # and/or get env.make to do it (maybe it does already?) ### ipath = index #e or (index, self.ipath)? return self.env.make( ccexpr, ipath) pass def kluge_get_glpane_cc_memoizer(glpane): #070414 ###@@@ CALL ME "Find or make a central place to store cached CC Instances." place = get_glpane_InstanceHolder(glpane) return place.Instance(cc_memoizer(), 'kluge_get_glpane_cc_memoizer', skip_expr_compare = True) ###e change that into: InstanceMemoizer subclass with methods to turn args to index, index to expr?? # in fact, best if we could dynamically separate it into an InstanceHolder(glpane) # and a way for one thing inside that (findable at some index and using state at that index or inside self) # to be a cc_memoizer. In fact, since cc_memoizer is an IorE, that might be required... ###k FIGURE OUT # TODO: # ###IMPLEM skip_expr_compare - done, untested, maybe not needed here anymore # see what env.make does... just eval and _e_make_in; call it like env.make(expr, ipath). # set up one of the above cc_memoizer objects # set up its drawing env (with glpane & stateplace), initial ipath, etc -- hmm, is some of that needed in the data? no, to find the obj. # set up cc_memoizer - needs glpane, so needs to be an attr of some object -- which one? glpane itself??? yes! # or should glpane have a mixin which gives it this power to own an env and make objects in it?
NanoCAD-master
cad/src/exprs/scratch/cc_scratch.py
# Copyright 2007 Nanorex, Inc. See LICENSE file for details. """ demo_create_shapes.py -- some demo commands for creating shapes in the model. $Id$ """ from demo_draw_on_surface import * # be really lazy for now -- but don't forget the _private names #e PLAN: do more of the kind of thing now done in demo_draw_on_surface.py, # and integrate it all together using demo_ui.py or so. # # Solve some problems of relations between model objects, and savable model objects, # and autoadding State decls (in wrappers or customizations -- use _e_extend??) to exprs for given attrs. # # Keep in mind the need for selection state, bindings in MT that fit with those in graphics area when sensible, # automaking of PM groups, browsing of available commands (by name or by what they can do)... # sources: #e class Cylinder -- see dna_ribbon_view.py: 179: class Cylinder(Geom3D) # also Cylinder_HelicalPath(Geom3D)... #e class Sphere # other solids # geometry_exprs.py # demo_polyline.py and the see also files it mentions # also 2d shapes? they are sketch entities... i suppose so are 3d shapes... # all shapes might be based on control points (see geometry_exprs.py) # defined in various reference objects or grids... # not all points in a sketch entity have to come from the same ref object! # and they might be lnked to a snapshot of that object, or to a live instance of it in the model! # or to a derived one (formula of ones in the model) which is not itself directly visible in the model. from dna_ribbon_view import Cylinder class Stateful(InstanceOrExpr): """Given an expr and a list of its arg/option attrs, extract the types of those attrs from the expr, and act as a stateful type permitting those attrs to be set/changed. Also be capable of returning metainfo that would let file save/load mappings, property editors, etc, be generated. For example, Stateful(Cylinder, ['axis', 'color', 'radius']) ... #doc more """ ###e what is the state-type -- a plain object, or an expr itself? (eg to support relations, ref geom, relative coords) # Do we pass this in? if so, how? for each attr or for all? for each type, of the types involved in the attrs? # how would the expr say that one arg's precise type, or coordsys, etc, is a function of another arg's value? # args expr = ArgExpr(Anything, doc = "an expr whose arguments we'll extend into state decls") attrs = Arg(list_Expr(str), doc = "list of some or all of its arg attrs, or a filter for them [nim]; we'll only extend these ones") #e can this have a useful default of "all of them"?? #e can we pass it more info like a specific type per attr? # decls = expr._e_attr_decls # list of decls of attrs of expr, in their declared order; each is an AttrDecl object for it.attr ###IMPLEM this attr of an expr, and the AttrDecl object it returns; # I guess/hope that object is just the Arg or Option after _E_ATTR gets replaced by the real attr ### PROBLEM: this will fail: _e_attr can't be symbolic getattr. ## Q: should expr be a true expr, or an Instance representing an expr in a more first-class way? Or can those be the same thing? # A, I hope: those can be the same thing -- exprs (when not symbolic) can be sufficiently first-class for that. # This might require tracking just how symbolic each expr is... actually I guess getattr_Expr always is, since otherwise # it is not formed from getattr. So maybe it won't require that. want_decls = filter_Expr( lambda decl: (not attrs) or (decl.attr in attrs), ###IMPLEM (if review ok): not -> not_Expr, or -> or_Expr, in -> in_Expr -- # BUT review will say no, if I use them in programming, e.g. not exprvar means it's None. #k Can it differ for symbolic case or not?? (All OpExprs would be symbolic, I guess...) ### PROBLEM: attrs won't get replaced with _self.attrs since it's inside a lambda body -- # unless filter_Expr is smart enough to tease apart the lambda for that purpose. # (Or to eval it on a symbolic arg?? And *then* replace in it using scanner? To eval during scanner?) decls ) ###BUG: those should be in the order in the list, not the order in decls, I think # (unless there are issues about a partial order of definining them due to types referring to others' vals... # but i doubt that should be allowed to cause a restriction on order in a file record or PM -- tho I'm not sure ##e) def _C_extended_expr(self): res = self.expr for decl in self.want_decls: kws = {decl.attr : State( decl.type, decl.dflt )} ###IMPLEM this executable form of State res = res._e_extend(**kws) return res ###e now, what do we do with that so that our owner can use it? Do we let it act as our "value"??? (a kind of delegate i guess) #e (or maybe more like a forwarding value, a val we forward to) pass # end of class #e now make a command for creating a Stateful(Cylinder) in the model -- i guess we pass Stateful(Cylinder) as expr arg to another thing # which makes a standard creator command for that expr, extracting state decls from it, and which makes a std PM too class StandardSketchEntityCreatorCommand(InstanceOrExpr): "a standard creator command for a sketch entity of the type described by our arg expr" # note, this is useful even if it doesn't define enough and you have to subclass it (i e delegate to it) in practice, # eg for the mouse behavior part. or maybe you have to pass in some fancier exprs that help it implem that part. expr = ArgExpr(Anything, doc = "an expr for a stateful object of a certain kind...") #doc ##e customizations = Option(Customizations) ###IMPLEM that type, and whatever we do about it in here... see customization below # fields = expr._e_state_fields ### seems wrong -- how would it know? instead, get the types, let env make them into fields ####e # [besides the problem with making a getattr_Expr due to the _e_] field_editor_group = StandardFieldEditorGroup(fields) ###IMPLEM property_manager_groups = [field_editor_group] #e more? btw, don't we want to subdivide the fields into groups? ###e what we *really* want is to be able to apply user (or developer) customization data # to this very object to get a fancier one. Then to develop a type, start with this thing # and edit it using the app's customization features! # This might work by letting customizations be edit commands on the UI we make here, # since the developer might create them by seeing that UI in a first class way and editing it. ###e lots more pass #### PROBLEMS ##### # biggest uncomfortablenesses so far: # - expr prickliness about getattr_Expr from ._e_xxx -- and for that matter the _e_ in the name -- # if we first-classed them into UnderstoodExpr instances or so, we could use regular attrnames on them # - some of those things should be functions anyway, I mean methods with args from somewhere import Cylinder, Sphere, Rect, Line, Circle, Polygon, Polyline # etc for shapeclass in (Cylinder, Sphere, Rect, Line, Circle): #e and more register_command( StandardSketchEntityCreatorCommand( Stateful( shapeclass))) #e hmm, can it really be that simple at the end?? # what about things like their topic, organization into UI, other metainfo... # maybe all that can be added by interactive customization?? # if so, it really can be that simple! # in fact, even simpler -- this would be a rule to apply to every "shape class" that gets registered. # there'd be lots of rules for lots of different kinds of classes... and lots of customization-interference-points... # of course you also want other registered classes to provide customization (like the ones in the same module as the main class)... # == # let's think about how, in practice, we extract the arg decls from an expr... # [continued in new edits to "Arg advice" in attr_decl_macros.py. Search for that phrase or "update 070323".] # == ### TODO ### (besides the entire file) # Let's do one of these entirely by hand. Problem: above won't import. Well, nevermind that for now. (The below won't either!) from dna_ribbon_view import Cylinder, LineSegment, Nanometers class StatefulCylinder(DelegatingInstanceOrExpr): axis = State(LineSegment, (ORIGIN, ORIGIN + DX)) ###e really we want StateArg, etc #e note: for this guy's default value, I was going to say ## Cylinder._e_default_attr_value('axis'), but that's as hard as impleming those Arg decl objects! radius = State( Nanometers, 1.0) color = State( Color, gray) capped = State( bool, True) delegate = Cylinder(axis, radius, color, capped = capped) pass TextEditField ###IMPLEM (like run py code) class MakeCylinder_PM(xxx): delegate = SimpleColumn( ###e what for the axis? need a PM for picking/finding/making a LineSegment. In real life it'll be by relations / ref geom, not coords... #e for radius, a float lineedit widget, with units, or an ability to go find a length dimension to define it from... #e for color, a color edit field... (shows color, lets you give it by name, or stylename, or formula, or use colorchooser, or see recent colors...) #e for capped, a checkbox # [notice how all this totally depends on the type? i think none of these egs depended on anything *but* the type! # and maybe, the extent of fanciness of relations you want for it... but ideally that depends on the type too. # and by this point should be encoded literally into the State type, anyway.] ) pass # == # end
NanoCAD-master
cad/src/exprs/scratch/demo_create_shapes.py
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. """ api_enforcement.py - utilities for API enforcement (experimental). Provides def or class privateMethod, etc. @author: Will @version: $Id$ @copyright: 2006-2007 Nanorex, Inc. See LICENSE file for details. History: Experimental code by Will. May have worked, but never extensively used. Bruce 071107 split it from debug.py into this scratch file. """ # REVIEW: might require some imports from debug.py import sys, os, time, types, traceback from utilities.constants import noop import foundation.env as env from utilities import debug_flags # == API_ENFORCEMENT = False # for performance, commit this only as False class APIViolation(Exception): pass # We compare class names to find out whether calls to private methods # are originating from within the same class (or one of its friends). This # could give false negatives, if two classes defined in two different places # have the same name. A work-around would be to use classes as members of # the "friends" tuple instead of strings. But then we need to do extra # imports, and that seems to be not only inefficient, but to sometimes # cause exceptions to be raised. def _getClassName(frame): """ Given a frame (as returned by sys._getframe(int)), dig into the list of local variables' names in this stack frame. If the frame represents a method call in an instance of a class, then the first local variable name will be "self" or whatever was used instead of "self". Use that to index the local variables for the frame and get the instance that owns that method. Return the class name of the instance. See http://docs.python.org/ref/types.html for more details. """ varnames = frame.f_code.co_varnames selfname = varnames[0] methodOwner = frame.f_locals[selfname] return methodOwner.__class__.__name__ def _privateMethod(friends=()): """ Verify that the call made to this method came either from within its own class, or from a friendly class which has been granted access. This is done by digging around in the Python call stack. The "friends" argument should be a tuple of strings, the names of the classes that are considered friendly. If no list of friends is given, then any calls from any other classes will be flagged as API violations. CAVEAT: Detection of API violations is done by comparing only the name of the class. (This is due to some messiness I encountered while trying to use the actual class object itself, apparently a complication of importing.) This means that some violations may not be detected, if we're ever careless enough to give two classes the same name. ADDITIONAL CAVEAT: Calls from global functions will usually be flagged as API violations, and should always be flagged. But this approach will not catch all such cases. If the first argument to the function happens to be an instance whose class name is the same as the class wherein the private method is defined, it won't be caught. """ f1 = sys._getframe(1) f2 = sys._getframe(2) called = _getClassName(f1) caller = _getClassName(f2) if caller == called or caller in friends: # These kinds of calls are okay. return # Uh oh, an API violation. Print information that will # make it easy to track it down. import inspect f1 = inspect.getframeinfo(f1) f2 = inspect.getframeinfo(f2) lineno, meth = f1[1], f1[2] lineno2, meth2 = f2[1], f2[2] print print (called + "." + meth + " (line " + repr(lineno) + ")" + " is a private method called by") print (caller + "." + meth2 + " (line " + repr(lineno2) + ")" + " in file " + f2[0]) raise APIViolation if API_ENFORCEMENT: privateMethod = _privateMethod else: # If we're not checking API violations, be as low-impact as possible. # In this case 'friends' is ignored. def privateMethod(friends = None): return # end
NanoCAD-master
cad/src/scratch/api_enforcement.py
# Copyright 2004-2007 Nanorex, Inc. See LICENSE file for details. """ General directory view widget. Based on Qt/PyQt example dirview.py, with modifications for use in MMKit. Note: in Qt3 this was used in MMKit.py, but in Qt4 it's not used there. $Id$ This file contains some code from the Qt/PyQt example dirview.py, whose copyright notice reads as follows: ************************************************************************** ** ** Copyright (C) 1992-2000 Trolltech AS. All rights reserved. ** Some corrections by M. Biermaier (http://www.office-m.at) ** ** This file is part of an example program for Qt. This example ** program may be used, distributed and modified without limitation. ** *************************************************************************** """ import sys from PyQt4.Qt import QTreeWidgetItem from PyQt4.Qt import QTreeWidget from PyQt4.Qt import QListView from PyQt4.Qt import QIcon from PyQt4.Qt import QPixmap from PyQt4.Qt import QSize from PyQt4.Qt import QDir from PyQt4.Qt import QApplication from utilities.qt4transition import qt4todo folder_closed_image =[ "16 16 9 1", "g c #808080", "b c #c0c000", "e c #c0c0c0", "# c #000000", "c c #ffff00", ". c None", "a c #585858", "f c #a0a0a4", "d c #ffffff", "..###...........", ".#abc##.........", ".#daabc#####....", ".#ddeaabbccc#...", ".#dedeeabbbba...", ".#edeeeeaaaab#..", ".#deeeeeeefe#ba.", ".#eeeeeeefef#ba.", ".#eeeeeefeff#ba.", ".#eeeeefefff#ba.", ".##geefeffff#ba.", "...##gefffff#ba.", ".....##fffff#ba.", ".......##fff#b##", ".........##f#b##", "...........####."] folder_open_image =[ "16 16 11 1", "# c #000000", "g c #c0c0c0", "e c #303030", "a c #ffa858", "b c #808080", "d c #a0a0a4", "f c #585858", "c c #ffdca8", "h c #dcdcdc", "i c #ffffff", ". c None", "....###.........", "....#ab##.......", "....#acab####...", "###.#acccccca#..", "#ddefaaaccccca#.", "#bdddbaaaacccab#", ".eddddbbaaaacab#", ".#bddggdbbaaaab#", "..edgdggggbbaab#", "..#bgggghghdaab#", "...ebhggghicfab#", "....#edhhiiidab#", "......#egiiicfb#", "........#egiibb#", "..........#egib#", "............#ee#"] folder_locked_image =[ "16 16 10 1", "h c #808080", "b c #ffa858", "f c #c0c0c0", "e c #c05800", "# c #000000", "c c #ffdca8", ". c None", "a c #585858", "g c #a0a0a4", "d c #ffffff", "..#a#...........", ".#abc####.......", ".#daa#eee#......", ".#ddf#e##b#.....", ".#dfd#e#bcb##...", ".#fdccc#daaab#..", ".#dfbbbccgfg#ba.", ".#ffb#ebbfgg#ba.", ".#ffbbe#bggg#ba.", ".#fffbbebggg#ba.", ".##hf#ebbggg#ba.", "...###e#gggg#ba.", ".....#e#gggg#ba.", "......###ggg#b##", ".........##g#b##", "...........####."] pix_file_image =[ "16 16 7 1", "# c #000000", "b c #ffffff", "e c #000000", "d c #404000", "c c #c0c000", "a c #ffffc0", ". c None", "................", ".........#......", "......#.#a##....", ".....#b#bbba##..", "....#b#bbbabbb#.", "...#b#bba##bb#..", "..#b#abb#bb##...", ".#a#aab#bbbab##.", "#a#aaa#bcbbbbbb#", "#ccdc#bcbbcbbb#.", ".##c#bcbbcabb#..", "...#acbacbbbe...", "..#aaaacaba#....", "...##aaaaa#.....", ".....##aa#......", ".......##......."] folderClosedIcon = 0 folderLockedIcon = 0 folderOpenIcon = 0 fileIcon = 0 qt4todo("""The QListView, QListViewItem, QCheckListItem, and QListViewItemIterator classes have been renamed Q3ListView, Q3ListViewItem, Q3CheckListItem, and Q3ListViewItemIterator, and have been moved to the Qt3Support library. New Qt applications should use one of the following four classes instead: QTreeView or QTreeWidget for tree-like structures; QListWidget or the new QListView class for one-dimensional lists. See Model/View Programming for an overview of the new item view classes. http://doc.trolltech.com/4.0/model-view-programming.html Examples involving QTreeWidgetItem: Qt-4.1.4/examples/network/torrent/mainwindow.cpp Qt-4.1.4/examples/tools/plugandpaint/plugindialog.cpp --> Qt-4.1.4/examples/tools/settingseditor/settingstree.cpp <-- Qt-4.1.4/examples/xml/dombookmarks/xbeltree.cpp Qt-4.1.4/examples/xml/saxbookmarks/xbelgenerator.cpp Qt-4.1.4/examples/xml/saxbookmarks/xbelhandler.cpp""") class FileItem(QTreeWidgetItem): def __init__(self, parent, fio, name=None): QTreeWidgetItem.__init__(self) parent.addChild(self) if name is not None: self.setText(1, name) self.f = name self.fileObj = fio def getFileObj(self): return self.fileObj def text(self, column): if column == 0: return self.f #def setup(self): # self.setExpandable(1) # QTreeWidgetItem.setup(self) class Directory(QTreeWidgetItem): def __init__(self, parent, name=None): QTreeWidgetItem.__init__(self) self.filterList = ('mmp', 'MMP') if isinstance(parent, QListView): self.p = None if name: self.f = name else: self.f = '/' else: self.p = parent self.f = name self.readable = QDir( self.fullName() ).isReadable() if not self.readable : self.setIcon(0, folderLockedIcon) else: self.setIcon(0, folderClosedIcon) if name is not None: self.setText(1, name) if isinstance(parent, QTreeWidget): parent.addTopLevelItem(self) else: parent.addChild(self) def setOpen(self, o): if o: self.setIcon(0, folderOpenIcon) else: self.setIcon(0, folderClosedIcon) if o and not self.childCount(): s = self.fullName() thisDir = QDir(s) if not thisDir.isReadable(): self.readable = 0 return files = thisDir.entryInfoList() if files: for f in files: # f is a QFileInfo # f.fileName is '.' or '..' or 'bearings' or... fileName = str(f.fileName()) if fileName == '.' or fileName == '..': continue elif f.isSymLink(): d = QTreeWidgetItem(self, fileName)#, 'Symbolic Link') d.setIcon(0, fileIcon) elif f.isDir(): if fileName == 'CVS': #bruce 060319 skip CVS directories, so developers see same set of directories as end-users # (implements NFR I recently reported) # WARNING: this is only legitimate for some applications of this module. # For now that's ok (we only use it in MMKit). Later this feature should be turned on # by an optional argument to __init__, and generalized to a list of files to not show # or to a filter function. continue d = Directory(self, fileName) else: if f.isFile(): s = 'File' else: s = 'Special' if not fileName[-3:] in self.filterList: continue d = FileItem(self, f.absFilePath(), fileName) d.setIcon(0, fileIcon) qt4todo('QTreeWidgetItem.setOpen(self, o)') def setup(self): self.setExpandable(1) QTreeWidgetItem.setup(self) def fullName(self): if self.p: if not hasattr(self.p, 'fullName'): qt4todo('Make the parent a Directory instead of a DirView') s = self.f else: s = self.p.fullName() + self.f else: s = self.f if not s.endswith('/'): s += '/' return s def text(self, column): if column == 0: return self.f ##elif self.readable: ## return 'Directory' ##else: ## return 'Unreadable Directory' def setFilter(self, filterList): '''This is used to filter out file display in the QListView. @param filterList is a list of file tyes like '.mmp' or '.MMP' etc. ''' self.filterList = filterList class DirView(QTreeWidget): def __init__(self, parent=None, name=None): QTreeWidget.__init__(self, parent) global folderClosedIcon, folderLockedIcon, folderOpenIcon, fileIcon folderClosedIcon = QIcon(QPixmap(folder_closed_image)) folderLockedIcon = QIcon(QPixmap(folder_locked_image)) folderOpenIcon = QIcon(QPixmap(folder_open_image)) fileIcon = QIcon(QPixmap(pix_file_image)) self.setHeaderLabels(["", "Name"]) #self.addColumn("Name", 150) # added 150. mark 060303. [bruce then changed 'width=150' to '150' to avoid exception] # Calling addColumn() here causes DirView to change size after its parent (MMKit) is shown. # I've not been successful figuring out how to control the height of the DirView (QTreeWidget) # after adding this column. See comments in MWsemantics._findGoodLocation() for more # information about how I compensate for this. Mark 060222. #self.setGeometry(QRect(7,-1,191,150)) self.setMinimumSize(QSize(160,150)) # Trying to force height to be 150, but addColumn() overrides this. To see the problem, # simply comment out addColumn() above and enter Build mode. mark 060222. #self.setSizePolicy(QSizePolicy(QSizePolicy.MinimumExpanding,QSizePolicy.MinimumExpanding,0,0,self.sizePolicy().hasHeightForWidth())) qt4todo('self.setTreeStepSize(20)') qt4todo('self.setColumnWidth(0, 150)') # Force the column width to 150 again. Fixes bug 1613. mark 060303. # The only time you'll see bug 1613 is when your partlib path is very long. # The column width is set by the width of the partlib path. # If you have a short path (i.e. /atom/cad/partlib), you wouldn't notice this bug. # A fresh Windows install has its partlib in C:\Program Files\NanoEngineer-1 vx.x.x Alpha\partlib. # This was causing the MMKit to be very wide on Windows by default on startup. #self.connect(self, SIGNAL("selectionChanged(QTreeWidgetItem *)"), self.partChanged) def partChanged(self, item): if isinstance(item, FileItem): fi = item.getFileObj() print "The selected file is: ", str(fi) ######################################################################## # Test code # Here is the example we find in PyQt-x11-gpl-4.0.1/examples/itemviews/dirview.py if __name__ == '__main__': from PyQt4 import QtGui app = QtGui.QApplication(sys.argv) model = QtGui.QDirModel(['*.mmp', '*.MMP'], QDir.AllEntries|QDir.AllDirs, QDir.Name) tree = QtGui.QTreeView() tree.setModel(model) tree.setRootIndex(model.index('../partlib')) tree.setWindowTitle(tree.tr("Dir View")) tree.resize(250, 480) tree.show() for i in range(1,4): tree.hideColumn(i) sys.exit(app.exec_()) if False and __name__ == '__main__': a = QApplication(sys.argv) if 1: mw = DirView() a.setMainWidget(mw) mw.setCaption('PyQt Example - Directory Browser') mw.resize(400, 400) #mw.setSelectionMode(QTreeWidget.Extended) root = Directory(mw)#, '/huaicai') root.setOpen(1) mw.show() a.exec_() else: roots = QDir("/download") fiList = roots.entryInfoList() for drv in fiList: print "The file path is: ", str(drv.absFilePath()) a.exec_() # end
NanoCAD-master
cad/src/scratch/DirView.py
""" Prerequisite_ReferencePlaneIsSelected.py (scratch file) a prerequisite for a command, which requires that a reference plane is selected. $Id$ what is required? a ref plane or equiv is selected write some code to look at selection and determine that given the model or model-with-selection (an assy object?) (or just a "model", implicit that it includes selection?) (why not receive them both? and you could just pass the current part...) anyway... it follows that flow chart i wrote, looking at params and prior-loop state to decide what to do and what to say. it runs through some code to compute this, may have model side effects... when does it run? when we "enter the mode", as part of updating the UI. we can't update the UI until it runs. it might decide to change modes! this might repeat until it settles down! """ ## split the code below out of this class: from Commands.Prerequisite import Prerequisite from utilities import accumulate # combines sublists into a big one... ###IMPLEM class PreCommand(Command): """ Abstract class for a kind of temporary Command which comes before other commands. (Note: Instances of specific subclasses are single runs, as for all Commands.) Subclasses typically need to override enterSelfWithContinuations in a nontrivial way, and also delegate some of the command API to the yes_cmd continuation... eg let it describe the PM (but tell it whether the preq is satisfied) (but modify the PM it makes or describes, to get our own) (or, pass it values to include in the one it makes? more realistic?) conclusion: for now, the preq just tells the main cmd what it wants to know to make its PM and the main cmd has to remember to include that data in its PM desc!! digr: review: when a preq becomes satsified by user action responding to msg, do we print something into statusbar or maybe history? or when it is *not* satisfied, ditto? if so, do it by calling a special log-like function... at what point do we know this happened? ### REVIEW -- do we know yes_cmd/no_cmd at this level or is that constructed? typically the yes_cmd comes from the "stuff after this pre-command" and the no_cmd is an error handling command... which might depend -- on what?? ### """ pass class Prerequisite( PreCommand): # initial values of instance variables prerequisite_msg = None # None, or a message prefix for the PM # methods which subclasses should override def prerequisite_check(self): """ (part of the Prerequisite subclass API) Check whether the prerequisite is satisfied in self's situation (model, selection, prefs and settings). Do things involving the command sequencer, messages, etc, if it is or is not... ### Return True (after side effects on self) if it's satisfied, false if not. """ assert 0, "subclass must override this method" # methods which should not normally be overridden def enterSelfWithContinuations(self, yes_cmd, no_cmd): ### SCRATCH name and API """ (proposed new part of the Command API ### REVIEW/TODO) Enter self, with yes_cmd being the command to run if self *eventually* succeeds (after whatever user interaction we can provide to help that happen), and no_cmd being the command to run if we give up on succeeding. Note: those cmds might be command instances, or just descriptions. ###TODO/REVIEW """ # while self has things to do, do them (influenced by yes_cmd), # then decide which one to replace ourselves with (return value says that) # To stay in self: return True, None # To forward to another command immediately: return False, cmd (description or instance) return True, None ### STUB pass class Prerequisite_ReferencePlaneIsSelected( Prerequisite): # initial values of instance variables offer_ref_planes_for_selection = False # whether our UI (in PM and/or graphics area) needs to offer # the available ref planes for selection ### REVIEW: do we loop around and reset this? (in which case, best to set it at start of prerequisite_check ###TODO) # or do we make a new preq instance in which it's already reset?? ### def prerequisite_check(self): """ (part of the Prerequisite subclass API) Check whether exactly one reference plane (or equivalent) is selected. It's ok if other stuff is also selected. """ # require that among the selected things there is exactly one reference plane or equivalent # (TODO: but if the same or an identical one shows up twice, ignore that!) # (TODO: if there is one explicit plane and other plane-equivalents, # let the explicit plane trump the others) planes = accumulate( lambda node: node.getReferencePlanes(), self.getTopmostSelectedNodes() ) ### IMPLEM in Node & Command # TODO: canonicalize them and remove duplicates if len(planes) == 1: # good! plane = planes[0] self.setReferencePlane(plane) ### IMPLEM - puts it into appropriate slot in PM... how is that specified BTW? ### REVIEW -- is there a PM_ReferencePlaneSelector for the widget or combo which is used to help select a ref plane? # if so, we'd require the PM to contain one (or to be a description to which we can add one) ### SEE mark's user story to see what it says about this return True # success elif len(planes) == 0: self.prerequisite_msg = "Select a reference plane." # TODO: also say "or a surface..." self.offer_ref_planes_for_selection = True return False # failure (of our prerequisite to be met) elif len(planes) > 1: self.prerequisite_msg = "Select a single reference plane." # TODO: also say "or surface..." self.offer_ref_planes_for_selection = True # REVIEW: do we modify the UI in this case to make the already selected ones especially easy to choose from? return False pass # override some graphics area methods to help implement what we do ... also some actions for PM slots in the ref plane selector(?) def leftDown(self, event): ### do we let user click on a ref plane in graphics area (in 3d area or in MT-in-glpane) to select it? pass ###STUB def Draw(self, whatever):###k self.yes_cmd.Draw(whatever) ### TODO: I guess we need to instantiate that no matter what (be optimistic!) # REVIEW: maybe put it inside a wrapper to protect us from exceptions in it? ### now also draw the ref plane stuff -- 3d or MTi-in-glpane, for std planes or ones in model, esp selected ones return # also whatever we need to handle the PM widget for this # REVIEW: the PM widget goes with this preq object... but what delegates to what? it seems like this preq is in control... # as if we took the cmd Seq( preq, yes_cmd) and rewrote it to something fancier, sort of preq(yes_cmd, std_error_handler)
NanoCAD-master
cad/src/scratch/Prerequisite_ReferencePlaneIsSelected.py
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. """ Drawable.py - shared properties of all drawable objects $Id$ [not yet used] """ from graphics.drawables.Selobj import Selobj_API class Drawable(Selobj_API): """ Will wrote: > To implement my Bauble class, I need to go into every mode where > it will be used, and make sure that all this machinery is in > place.... (reviewing the subsequent wiki text as of tonight) Not really -- what you are describing is more like it was an independent jig than part of what you draw for your main jig. Group.addchild, in particular, will mean it shows up in the MT, which is not what we want if it's just some other jig's resize handle. Basically, the existing code you are trying to fit into, selectMode.jigLeftDown, is not general enough. Best solution is to make Bauble inherit a new superclass, Drawable (if you don't mind me later redefining the API, or us doing that together) or BaubleBaseOrWhateverYouCallIt (if you prefer a period in which that and Drawable coexist and are related but different), and then add this new superclass to the list of things SelectAtoms_GraphicsMode treats specially in its event handlers, which is now Atom, Bond, Jig. (If you are willing to let me heavily influence Drawable, as you seem to be, you might as well just start defining it in a new python source file.) This Bauble is not selectable and should not need a .picked attribute, and should never be permitted in any of those lists of selected whatevers in that mode object. What it needs is an allocated glName (like existing not-named-as-such drawables have -- see init code for Atom, Bond, Chunk, maybe Jig or some of its subclasses), some methods you'll learn about when it tracebacks (like draw_in_abs_coords and maybe one for highlight color), and of course a draw method, and a drag method, and special cases in lots of the places in SelectAtoms_GraphicsMode that now have them for Atom, Bond, Jig -- but these should of course be cases for Drawable, not for Bauble. And they might as well come first, so if we ever wanted to make something inherit from both Drawable and Atom or Bond or Jig, the Drawable API would win out in terms of how SelectAtoms_GraphicsMode interacted with it. *** __init__ must set self.glname using alloc_my_glselect_name [note, this has been revised, bruce 080220; class Atom now sets self._glname using assy.alloc_my_glselect_name; glpane has this method as well, as of before 080917] *** Needs a draw_in_abs_coords method Among the special cases will be for mouse down, mouse drag, mouse up. If there is now an object being dragged, or a state variable about what kind of thing is being dragged, it needs to fit into that (tomorrow I can look and see if that scheme needs cleanup or could reasonably be extended as-is). *** special cases go in SelectAtoms_GraphicsMode, not here The code that looks at selobj may also need cases for this, but maybe not, if it doesn't need a context menu and doesn't traceback without it. *** assume I don't need this for now As for when to draw it, draw it when you draw its owning jig -- owning jig needs an attr whose value is the bauble (or maybe more than one bauble, with an attr which is a dict from bauble-role to bauble), and drawing code which (sometimes or always) draws it. *** already doing this As for its position, that might as well be relative to the jig, and whatever code now moves or rotates jigs will need to do the right thing, and I *hope* that code already calls methods on the jig to move it or rotate it, and if so, just override those on your jig to do the right thing. If its position and orientation is fully relative, that code needn't be modified (if your jig has a quat). Warning: someone added quats to motor jigs and others, and then (I think) partly or fully abandoned them and didn't clean up the mess, so there may be quats that are not modified and/or not honored, etc, on some jigs. Either that, or there are partly-redundant quat and other attrs, so that the situation with rot methods is confusing. And it may be that the move/rotate code (in Move Mode) is not very general and will need to be taught to send a nicer method call to Jigs which own Baubles. *** motion relative to the jig is a good idea As for what the Bauble drag method does (when called by the new Drawable special case in SelectAtoms_GraphicsMode leftDrag or whatever), that is to actually modify its own relative posn in the jig, and then do gl_update so that everything (including its parent jig, thus itself) gets redrawn, soon after the event is done being handled. The convention for drags is to record the 3d point at which the mouse clicked on the Drawable (known from the depth buffer value -- the code for clicking on a Jig shows you how to figure this out, and the new code for doing this for Drawables also belongs in SelectAtoms_GraphicsMode), then interpret mouse motion as being in the plane through that point and parallel to the screen, so it's now a 3d vector, then translate the object by that, then apply whatever constraints its position has (e.g. project to a plane it's confined to or limit the amount of the drag), but do this in a way that lacks history-dependence (this would matter when reaching limits). We've never yet had drag-constraints except when dragging bondpoints. Anything not equivalent to that will seem wrong and be a bug. All the above is for non-selectable non-Node Drawables. =========================================================== the current code may assume the glName stack is only 1 deep at most, and if you give Bauble a glName of its own, then to obey that, the owning Jig needs to not draw it until it pops its own main glName, if it has one (which it needs if it can be highlighted or dragged as a whole Jig). or we could fix the current code to not make that assumption. === see also http://www.nanoengineer-1.net/mediawiki/index.php?title=Drawable_objects see also class Bauble, and handles.py """ def __init__(self): self.glname = self.assy.alloc_my_glselect_name(self) # or self.glpane, or ... #bruce 080917 revised def draw_in_abs_coords(self, glpane, color): raise Exception, 'abstract method, must be overloaded'
NanoCAD-master
cad/src/scratch/Drawable.py
# Copyright 2009 Nanorex, Inc. See LICENSE file for details. """ TransformState.py -- mutable transform classes, shared by TransformNodes NOT YET USED as of 090204... declared a scratch file, bruce 090225; see comments in TransformNode docstring for why. @author: Bruce @version: $Id$ @copyright: 2009 Nanorex, Inc. See LICENSE file for details. """ from foundation.state_utils import StateMixin from foundation.state_utils import copy_val from utilities.Comparison import same_vals # == ORIGIN = V(0, 0, 0) _IDENTITY_TRANSLATION = V(0, 0, 0) _IDENTITY_ROTATION = Q(1, 0, 0, 0) # review: let these be class attrs of the types, or of the classes V and Q? # REVIEW: does same_vals think 0 and 0.0 are the same? if not, should we use 0.0 here? # TEST whether anything looks like identity... note that if initial values use 0 this might be ok # == class TransformState(StateMixin, object): """ A mutable orthonormal 3d transform, represented as a rotation followed by a translation (with the rotation and translation being undoable state). Changes to the transform value can be subscribed to. ###doc how """ # REVIEW: # - can you subscribe separately to changes to its translation and rotation? # - if so, are they public usagetracked attrs? # - make value accessible as data object? (if so, let it be an attr self.value) # (note: a ref to this would autosubscribe to the two components; or we could cache constructed object) # - permit comparison as if we were data? (no, buggy if someone uses '==' when they mean 'is') # todo: # - undoable state for the data # - finish nim ops to change the data (translate, rotate, etc), # - make sure the data (or overall value only?) can be subscribed to # TODO: make the State version work... initially we just use hand-invals, below. # but we'll need to make State work here as soon as we need to usage-track these # for purposes of properly implementing the DrawingSet graphics API. # ##rotation = State(Quaternion) ## ##translation = State(Vector3D) ## ## ### IMPLEM: ## # - how do we make State work here? ###REVIEW how we do it in Test_ConnectWithState, funmode ## # - and how do we let it be undoable state? compatible with _s_attr decls?? ### ## # - get default value from type; ## # - define these type names ## ### REVIEW: ## # - review type name: Vector vs Vector3 vs Vector3D ? Or just use V and Q? rotation = _IDENTITY_ROTATION translation = _IDENTITY_TRANSLATION # not yet needed: ## value = TransformData( rotation, translation ) # REVIEW expr name, whether this formula def is appropriate # TODO: add formula for matrix? (to help merge with TransformControl?) def _kluge_manual_inval(self): """ Kluge: manually invalidate our overall transform value. @note: calls only needed until we support State decls for self.rotation and self.translation; implem only needed in some subclasses """ return def applyDataFrom(self, other): """ """ self.rotate( other.rotation, center = ORIGIN) self.translate( other.translation) def translate(self, vector): # see also 'def move' in other classes self.translation = self.translation + vector self._kluge_manual_inval() def rotate(self, quat, center = None): """ Rotate self around self.translation, or around the specified center. """ self.rotation = self.rotation + quat # review operation order, compare with chunk.py -- ### also compare default choice of center, THIS MIGHT BE WRONG if center is not None: offset = self.translation - center self.translate( quat.rot(offset) - offset ) # REVIEW - compare with chunk.py self._kluge_manual_inval() return def is_identity(self): # review: optimize? special fast case if data never modified? return same_vals( (self.translation, self.rotation), (_IDENTITY_TRANSLATION, _IDENTITY_ROTATION) ) pass # == class StaticTransform( TransformState): """ A subclass of TransformState that keeps track of which nodes it belongs to, and owns a TransformControl, and maintains it to always hold the same transform value as self. """ # REVIEW: merge this class with TransformControl? ### IMPLEM: intercept changes and inval or update our TC... and its own subscribers in the graphics code... transformControl = None def __init__(self, value = None, tc = None): self._nodes = {} if value is not None: # copy our value from the given value or TransformState if isinstance(value, TransformState): self.rotation = copy_val(value.rotation) self.translation = copy_val(value.translation) else: assert 0 # nim assert tc ### probably required by other code... REVIEW if tc is not None: self.transformControl = tc ### IMPLEM proper fields/effects and maintenance of the relationship return def add_node(self, node): self._nodes[node] = node return def del_node(self, node): del self._nodes[node] return def nodecount(self): """ Return the number of nodes we belong to. """ return len(self._nodes) def iternodes(self): """ yield the nodes we belong to """ return self._nodes.itervalues() pass # == class DynamicTransform( TransformState): """ A subclass of TransformState that keeps track of which objects bridge between nodes which have it and nodes which don't have it, and passes its value invalidations on to those objects. """ def __init__(self, nodes): """ Initialize self, and add self to the given nodes. """ TransformState.__init__(self) self._nodes = nodes # list, not dict -- no need to modify or index # only needed for self.destroy(); # not needed for determining whether node-bridging objects added # later are self-bridging, since our nodes point to us too # (and anyway, AFAIK we never add bridging objects later) for node in nodes: node.dynamic_transform = self ### REVIEW; needs to inval subscribers self._bridging_objects = self._get_bridging_objects() # note: if our initial value wasn't identity, we'd also need to call # self._invalidate_transform_value() here. return def _get_bridging_objects(self): # Anything on one of our nodes which bridges *anything*, # is also known to be on self, therefore one of *our* bridging objects. # More precisely: it's on self; it's not only on self (or not bridging); # thus it's a self-bridging object (a node on self, a node not on self). res = [] for node in self.nodes: res.extend( node.bridging_objects() ) ### REVIEW: can one be included more than once? if so, use a dict... # guess: yes, once we have multi-node ones. ### return res def _kluge_manual_inval(self): TransformState._kluge_manual_inval(self) self._invalidate_transform_value() def _invalidate_transform_value(self): for bo in self._bridging_objects: bo.invalidate_distortion() return pass # end
NanoCAD-master
cad/src/scratch/TransformState.py
#!/usr/bin/env python # Copyright 2005-2007 Nanorex, Inc. See LICENSE file for details. """ this is just some drag & drop example code -- it's not part of our product. note -- it runs in Qt3 but has not been ported to Qt4. it comes with a test file 'butterfly.png' which needs to be next to it for it to work. it's made from a PyQt example which was made from a Qt example and might be partly copyright by one or both of them. it was made from examples3/canvas/canvas.py in a PyQt distro, which had no copyright notice, but a nearby example, examples3/dirview.py, has a copyright from Trolltech which says "This example program may be used, distributed and modified without limitation." $Id$ if it's here in cad/src, that's just so it can import some code modules from our product and/or be shared with other developers for testing. It need not be distributed with our product, but if it is this doesn't seem to be a problem. You can try running it as "./ExecSubDir.py scratch/canvas-b-3.py", but it uses features of Qt3 that no longer exist in Qt4, so it needs to be ported before it will work. The current dir probably needs to be the same dir as this code module so it can find the 'butterfly.png' file. """ import sys from PyQt4.Qt import * # this statement has been ported to Qt4, but nothing else has! import random import time #bruce try: from utilities.debug import print_compact_stack except: print "could not import print_compact_stack" def print_compact_stack(msg): print "nim: print_compact_stack(%r)" % msg pass no_dragevent_item = True # 050127 True = 1 False = 0 butterfly_fn = QString.null butterflyimg = [] logo_fn = QString.null logoimg = [] bouncy_logo = None views = [] class ImageItem(QCanvasRectangle): def __init__(self,img,canvas): QCanvasRectangle.__init__(self,canvas) self.imageRTTI=984376 self.image=img self.pixmap=QPixmap() self.setSize(self.image.width(), self.image.height()) self.pixmap.convertFromImage(self.image, Qt.OrderedAlphaDither) def rtti(self): return self.imageRTTI def hit(self,p): ix = p.x()-self.x() iy = p.y()-self.y() if not self.image.valid( ix , iy ): return False self.pixel = self.image.pixel( ix, iy ) return (qAlpha( self.pixel ) != 0) def drawShape(self,p): p.drawPixmap( self.x(), self.y(), self.pixmap ) def bruce_start_drag(self, dragsource): # drag and (don't bother to) drop this image! print "bruce_start_drag" if 0: # use QImageDrag print 'making: dragobj = QImageDrag( self.image, dragsource)' dragobj = QImageDrag( self.image, dragsource) ## the source has to be a QWidget -- not the canvas! TypeError: argument 2 of QImageDrag() has an invalid type print "made dragobj" else: # use QTextDrag print 'making: dragobj = QTextDrag( "copying 5 items", dragsource)' dragobj = QTextDrag( "copying 5 items", dragsource) print "made it" if 0: print "not setting a custom pixmap this time" pass # don't set a custom pixmap elif 1: # set a custom pixmap print "now will set its pixmap to display during the drag",dragobj # warning, there is self.pixmap but that's the butterfly... hmm, would it work? let's try it: pixmap = self.pixmap dragobj.setPixmap(pixmap) print "set the pixmap to (presumably) the butterfly:",pixmap if 1: # try to modify the one Qt made for us to use? no, that fails (null pixmap), so: # try to modify the one we set, above. print "will try to modify the pixmap we just told Qt to use..." pixmap = dragobj.pixmap() print "this is the pixmap object:",pixmap # it's different id than the one we set, probably setPixmap copies it print "this is another get of that, is it same id?",dragobj.pixmap() # no! i guess it copies on get, at least. # let's hope we own it! try this twice to find out... i mean click on two butterflys in a row... # hmm, can we draw on it? p = painter = QPainter(pixmap) # if we never did dragobj.setPixmap ourselves, then [for QImageDrag or QTextDrag] we get # QPainter::begin: Cannot paint null pixmap color = Qt.blue p.setPen(QPen(color, 3)) # 3 is pen thickness w,h = 100,9 x,y = pos = (0,0) x += int(time.time()) % 10 # randomize coords y += int(time.time()*10.0) % 10 p.drawEllipse(x,y,h,h) # this worked, various sizes of butterfly got this blue circle (same size) in topleft corner print "after drawing, pixmap is ",pixmap ## this is needed: del p, painter print "after del p,painter, pixmap is ",pixmap ## since without it we got (various ones of these, I guess randomly): [btw that checksum on free, verify on malloc is a clever idea! ###@@@] # ##Qt: QPaintDevice: Cannot destroy paint device that is being painted. Be sure to QPainter::end() painters! ##Segmentation fault ##Exit 139 # ##Qt: QPaintDevice: Cannot destroy paint device that is being painted. Be sure to QPainter::end() painters! ##*** malloc[1008]: error for object 0x9abb0d0: Incorrect checksum for freed object - object was probably modified after being freed; break at szone_error ##Segmentation fault ##Exit 139 dragobj.setPixmap(pixmap) # needed?? yes! print "setting pixmap back into dragobj, might not be needed" """ making: dragobj = QTextDrag( "copying 5 items", dragsource) made it will try to modify the pixmap Qt made for us to use... this is the pixmap object: <__main__.qt.QPixmap object at 0x88bd0> QPainter::begin: Cannot paint null pixmap QPainter::setPen: Will be reset by begin() """ pass wantdel = dragobj.dragCopy() # during this call, we do recursive event processing, including the expected dragEnter event, and moves and drop, # plus another *initial* unexpected dragEnter event, different event object. To debug those, print the stack! # then our dropevent has an exception (for known reasons). # Then, this prints: wantdel = None, target = source = the figureeditor obj (expected). print "dragged image: wantdel = %r, target = %r, dragsource = %r" % (wantdel, dragobj.target(), dragsource) ###e delete it? class NodeItem(QCanvasEllipse): def __init__(self,canvas): QCanvasEllipse.__init__(self,6,6,canvas) self.__inList=[] self.__outList=[] self.setPen(QPen(Qt.black)) self.setBrush(QBrush(Qt.red)) self.setZ(128) def addInEdge(self,edge): self.__inList.append(edge) def addOutEdge(self,edge): self.__outList.append(edge) def moveBy(self,dx,dy): QCanvasEllipse.moveBy(self,dx,dy) for each_edge in self.__inList: each_edge.setToPoint( int(self.x()), int(self.y()) ) for each_edge in self.__outList: each_edge.setFromPoint( int(self.x()), int(self.y()) ) class EdgeItem(QCanvasLine): __c=0 def __init__(self,fromNode, toNode,canvas): QCanvasLine.__init__(self,canvas) self.__c=self.__c+1 self.setPen(QPen(Qt.black)) self.setBrush(QBrush(Qt.red)) fromNode.addOutEdge(self) toNode.addInEdge(self) self.setPoints(int(fromNode.x()),int(fromNode.y()), int(toNode.x()), int(toNode.y())) self.setZ(127) def setFromPoint(self,x,y): self.setPoints(x,y,self.endPoint().x(),self.endPoint().y()) def setToPoint(self,x,y): self.setPoints(self.startPoint().x(), self.startPoint().y(),x,y) def count(self): return self.__c def moveBy(self,dx,dy): pass class FigureEditor(QCanvasView): def __init__(self,canvas1,parent,name,wflags): QCanvasView.__init__(self,canvas1,parent,name,wflags) # bruce cmt: last arg: WFlags f = 0 self.__moving=0 self.__moving_start= 0 # bruce added the rest # note: self.canvas() returns canvas1, no need to store it self.viewport().setAcceptDrops(True) # does doing this first make autoscroll work??? ###@@@ [using viewport, does it now???] ## self.viewport().setDragAutoScroll(True) ###@@@ bruce hack experiment 050103. doesn't work. [using viewport, does it now???] self.setDragAutoScroll(True) # Qt doc says "Of course this works only if the viewport accepts drops." and refers to "drag move events"... # so maybe it's only for "drag and drop". print "self.dragAutoScroll()",self.dragAutoScroll() def contentsMousePressEvent(self,e): # QMouseEvent e point = self.inverseWorldMatrix().map(e.pos()) ilist = self.canvas().collisions(point) #QCanvasItemList ilist for each_item in ilist: if each_item.rtti()==984376: # bruce comment: this is for the custom image item class if not each_item.hit(point): continue self.__moving=each_item self.__moving_start=point try: ###@@@ bruce exper meth = self.__moving.bruce_start_drag except AttributeError: pass else: dragsource = self meth(dragsource) # lack of separate call was hiding bugs! # recursive event processing occurs during that call. return self.__moving=0 def clear(self): ilist = self.canvas().allItems() for each_item in ilist: if each_item: each_item.setCanvas(None) del each_item self.canvas().update() def contentsMouseMoveEvent(self,e): ## print "contentsMouseMoveEvent" if self.__moving : point = self.inverseWorldMatrix().map(e.pos()); self.__moving.moveBy(point.x() - self.__moving_start.x(),point.y() - self.__moving_start.y()) self.__moving_start = point self.canvas().update() ###@@@ bruce added the rest; changed them to contents methods late in testing, 37pm ## def contentsDragEnterEvent(self, event): ## print "does this exist?" # apparently not. but try again with no other one... still not. ## # BUT IT DOES if we do self.viewport().setAcceptDrops(True) instead of self.setAcceptDrops(True)! ## # And then that does make autoscroll work, though it work pretty badly, just like in the Mac finder. def contentsDragEnterEvent(self, event): # the dup ones can't be told apart by any method i know of except lack of move/drop/leave. print_compact_stack("dragEnterEvent stack (fyi): ") # nothing on stack except this code-line and app.exec_() [not even a call of this method] try: event.bruce_saw_me except: event.bruce_saw_me = 1 else: event.bruce_saw_me = event.bruce_saw_me + 1 self.oldevent = event ###@@@ ok = QTextDrag.canDecode(event) or QImageDrag.canDecode(event) or QUriDrag.canDecode(event) print "drag enter %r, pos.x = %r, ok = %r (determines our acceptance)" % (event, event.pos().x(), ok) print "event.bruce_saw_me",event.bruce_saw_me ## try doing this later: event.accept(ok) canvas = self.canvas() i = QCanvasText(canvas) i.setText("drag action type %r, %r" % (event.action(), time.asctime())) self.dragevent_item = i i.show() # would removing this fix the dup enter? no, but it makes the text invisible! self.dragevent_item_move_to_event(event) event.accept(ok) # try doing this here, does it remove that duplicate enter? # no; moving codeline to here has no effect i can notice. def contentsDragMoveEvent(self, event): ##print "contentsDragMoveEvent" self.dragevent_item_move_to_event(event) def dragevent_item_move_to_event(self, event): if no_dragevent_item: return ## print "drag move, raw x,y = (%r, %r)" % (event.pos().x(), event.pos().y()) # this seems to happen once after the drop! # do we need a different retval from the dropEvent processor?? point = self.inverseWorldMatrix().map(event.pos()) # using event.pos() directly failed when scrollbar was moved # why does this work whether the event was given to a contents method or a scrollview method? ###@@@ is it same or only close? x = point.x() y = point.y() self.dragevent_item.move(x,y) def contentsDragLeaveEvent(self, event): print "drag leave, event == %r" % event ## pos = %r" % event.pos() # AttributeError: pos ###@@@ ## self.dragevent_item_move_to_event(event) self.dragevent_item.setColor(Qt.red) # guesses def contentsDropEvent(self, event): print "drop event %r" % event ###@@@ for i in range(20): fmt = event.format(i) print "dropevent.format[%d] = %r" % (i, fmt) # should be list of available formats! if i > 0 and fmt == None: break okimage = QImageDrag.canDecode(event) okuri = QUriDrag.canDecode(event) oktext = QTextDrag.canDecode(event) print "oktext = %r, okimage = %r, okuri = %r" % (oktext, okimage, okuri) print "event.source(), event.action()",event.source(), event.action() print "accepting it iff we can decode it, but not creating anything" print "fyi: QDropEvent.Copy, QDropEvent.Move, QDropEvent.Link are:",QDropEvent.Copy, QDropEvent.Move, QDropEvent.Link if okimage: print "accepting image" img = QImage() res = QImageDrag.decode(event, img) #guess print "got this res & image (discarding it but accepting the event): %r, %r" % (res,img) event.accept(True) elif oktext: print "accepting text" str1 = QString() # see dropsite.py in examples3 res = QTextDrag.decode(event, str1) text = str(str1) print "got this res and text: %r, %r" % (res,text) # guess: from finder it will be filename event.accept(True) # was still acceptAction for a long time, by accident ## event.acceptAction(True) # DANGER, acceptAction MIGHT DELETE IT -- but it did not, maybe since text only? # or acceptAction? no, that's if we actually understand and do the specific requested action. # from finder with a file, it's Move! else: event.accept(False) ## return True ####@@@ guess; wrong: TypeError: invalid result type from FigureEditor.dropEvent() class BouncyLogo(QCanvasSprite): def __init__(self,canvas): # Make sure the logo exists. global bouncy_logo if bouncy_logo is None: bouncy_logo=QCanvasPixmapArray("qt-trans.xpm") QCanvasSprite.__init__(self,None,canvas) self.setSequence(bouncy_logo) self.setAnimated(True) self.initPos() self.logo_rtti=1234 def rtti(self): return self.logo_rtti def initPos(self): self.initSpeed() trial=1000 self.move(random.random()%self.canvas().width(), random.random()%self.canvas().height()) self.advance(0) trial=trial-1 while (trial & (self.xVelocity()==0 )& (self.yVelocity()==0)): elf.move(random.random()%self.canvas().width(), random.random()%self.canvas().height()) self.advance(0) trial=trial-1 def initSpeed(self): speed=4.0 d=random.random()%1024/1024.0 self.setVelocity(d*speed*2-speed, (1-d)*speed*2-speed) def advance(self,stage): if stage == 0: vx=self.xVelocity() vy=self.yVelocity() if (vx == 0.0) & (vy == 0.0): self.initSpeed() vx=self.xVelocity() vy=self.yVelocity() nx=self.x()+vx ny=self.y()+vy if (nx<0) | (nx >= self.canvas().width()): vx=-vx if (ny<0) | (ny >= self.canvas().height()): vy=-vy for bounce in [0,1,2,3]: l=self.collisions(False) for hit in l: if (hit.rtti()==1234) & (hit.collidesWith(self)): if bounce == 0: vx=-vx elif bounce == 1: vy=-vy vx=-vx elif bounce == 2: vx=-vx elif bounce == 3: vx=0 vy=0 self.setVelocity(vx,vy) break if (self.x()+vx < 0) | (self.x()+vx >= self.canvas().width()): vx=0 if (self.y()+vy < 0) | (self.y()+vy >= self.canvas().height()): vy=0 self.setVelocity(vx,vy) elif stage == 1: QCanvasItem.advance(self,stage) class Main (QMainWindow): def __init__(self,canvas1,parent,name,wflags=0): QMainWindow.__init__(self,parent,name,wflags) self.editor=FigureEditor(canvas1,self,name,wflags) self.printer=QPrinter() self.dbf_id=0 self.canvas=canvas1 self.mainCount=0 file=QPopupMenu(self.menuBar()) file.insertItem("&Fill canvas", self.init, Qt.CTRL+Qt.Key_F) file.insertItem("&Erase canvas", self.clear, Qt.CTRL+Qt.Key_E) file.insertItem("&New view", self.newView, Qt.CTRL+Qt.Key_N) file.insertItem("(text editor)", self.textEditor) file.insertSeparator(); file.insertItem("&Print", self._print, Qt.CTRL+Qt.Key_P) file.insertSeparator() file.insertItem("E&xit", qApp, SLOT("quit()"), Qt.CTRL+Qt.Key_Q) self.menuBar().insertItem("&File", file) edit = QPopupMenu(self.menuBar() ) edit.insertItem("Add &Circle", self.addCircle, Qt.ALT+Qt.Key_C) edit.insertItem("Add &Hexagon", self.addHexagon, Qt.ALT+Qt.Key_H) edit.insertItem("Add &Polygon", self.addPolygon, Qt.ALT+Qt.Key_P) edit.insertItem("Add Spl&ine", self.addSpline, Qt.ALT+Qt.Key_I) edit.insertItem("Add &Text", self.addText, Qt.ALT+Qt.Key_T) edit.insertItem("Add &Line", self.addLine, Qt.ALT+Qt.Key_L) edit.insertItem("Add &Rectangle", self.addRectangle, Qt.ALT+Qt.Key_R) edit.insertItem("Add &Sprite", self.addSprite, Qt.ALT+Qt.Key_S) edit.insertItem("Create &Mesh", self.addMesh, Qt.ALT+Qt.Key_M ) edit.insertItem("Add &Alpha-blended image", self.addButterfly, Qt.ALT+Qt.Key_A) self.menuBar().insertItem("&Edit", edit) view = QPopupMenu(self.menuBar() ); view.insertItem("&Enlarge", self.enlarge, Qt.SHIFT+Qt.CTRL+Qt.Key_Plus); view.insertItem("Shr&ink", self.shrink, Qt.SHIFT+Qt.CTRL+Qt.Key_Minus); view.insertSeparator(); view.insertItem("&Rotate clockwise", self.rotateClockwise, Qt.CTRL+Qt.Key_PageDown); view.insertItem("Rotate &counterclockwise", self.rotateCounterClockwise, Qt.CTRL+Qt.Key_PageUp); view.insertItem("&Zoom in", self.zoomIn, Qt.CTRL+Qt.Key_Plus); view.insertItem("Zoom &out", self.zoomOut, Qt.CTRL+Qt.Key_Minus); view.insertItem("Translate left", self.moveL, Qt.CTRL+Qt.Key_Left); view.insertItem("Translate right", self.moveR, Qt.CTRL+Qt.Key_Right); view.insertItem("Translate up", self.moveU, Qt.CTRL+Qt.Key_Up); view.insertItem("Translate down", self.moveD, Qt.CTRL+Qt.Key_Down); view.insertItem("&Mirror", self.mirror, Qt.CTRL+Qt.Key_Home); self.menuBar().insertItem("&View", view) self.options = QPopupMenu( self.menuBar() ); self.dbf_id = self.options.insertItem("Double buffer", self.toggleDoubleBuffer) self.options.setItemChecked(self.dbf_id, True) self.menuBar().insertItem("&Options",self.options) self.menuBar().insertSeparator(); help = QPopupMenu( self.menuBar() ) help.insertItem("&About", self.help, Qt.Key_F1) help.insertItem("&About Qt", self.aboutQt, Qt.Key_F2) help.setItemChecked(self.dbf_id, True) self.menuBar().insertItem("&Help",help) self.statusBar() self.setCentralWidget(self.editor) self.printer = 0 self.tb=0 self.tp=0 self.init() def init(self): self.clear() r=24 r=r+1 random.seed(r) for i in range(self.canvas.width()/56): self.addButterfly() for j in range(self.canvas.width()/85): self.addHexagon() for k in range(self.canvas.width()/128): self.addLogo() def newView(self): m=Main(self.canvas,None,"new window",Qt.WDestructiveClose) qApp.setMainWidget(m) m.show() qApp.setMainWidget(None) views.append(m) def textEditor(self): try: from qt_debug_hacks import make_DebugTextEdit self.te2 = make_DebugTextEdit() except: raise # for now self.texted = QTextEdit(self) self.texted.setFixedSize(100,100) # w,h self.texted.show() # puts it in upper left corner, over the canvas def clear(self): self.editor.clear() def help(self): QMessageBox.information(None, "PyQt Canvas Example", "<h3>The PyQt QCanvas classes example</h3><hr>" "<p>This is the PyQt implementation of " "Qt canvas example.</p> by Sadi Kose " "<i>(kose@nuvox.net)</i><hr>" "<ul>" "<li> Press ALT-S for some sprites." "<li> Press ALT-C for some circles." "<li> Press ALT-L for some lines." "<li> Drag the objects around." "<li> Read the code!" "</ul>","Dismiss") def aboutQt(self): QMessageBox.aboutQt(self,"PyQt Canvas Example") def toggleDoubleBuffer(self): s = not self.options.isItemChecked(self.dbf_id) self.options.setItemChecked(self.dbf_id,s) self.canvas.setDoubleBuffering(s) def enlarge(self): self.canvas.resize(self.canvas.width()*4/3, self.canvas.height()*4/3) def shrink(self): self.canvas.resize(self.canvas.width()*3/4, self.canvas.height()*3/4) def rotateClockwise(self): m = self.editor.worldMatrix() m.rotate( 22.5 ) self.editor.setWorldMatrix( m ) def rotateCounterClockwise(self): m = self.editor.worldMatrix() m.rotate( -22.5 ) self.editor.setWorldMatrix( m ) def zoomIn(self): m = self.editor.worldMatrix() m.scale( 2.0, 2.0 ) self.editor.setWorldMatrix( m ) def zoomOut(self): m = self.editor.worldMatrix() m.scale( 0.5, 0.5 ) self.editor.setWorldMatrix( m ) def mirror(self): m = self.editor.worldMatrix() m.scale( -1, 1 ) self.editor.setWorldMatrix( m ) def moveL(self): m = self.editor.worldMatrix() m.translate( -16, 0 ) self.editor.setWorldMatrix( m ) def moveR(self): m = self.editor.worldMatrix() m.translate( +16, 0 ) self.editor.setWorldMatrix( m ) def moveU(self): m = self.editor.worldMatrix() m.translate( 0, -16 ) self.editor.setWorldMatrix( m ) def moveD(self): m = self.editor.worldMatrix(); m.translate( 0, +16 ); self.editor.setWorldMatrix( m ) def _print(self): if not self.printer: self.printer = QPrinter() if self.printer.setup(self) : pp=QPainter(self.printer) self.canvas.drawArea(QRect(0,0,self.canvas.width(),self.canvas.height()),pp,False) def addSprite(self): i = BouncyLogo(self.canvas) i.setZ(256*random.random()%256); i.show(); def addButterfly(self): if butterfly_fn.isEmpty(): return if not butterflyimg: butterflyimg.append(QImage()) butterflyimg[0].load(butterfly_fn) butterflyimg.append(QImage()) butterflyimg[1] = butterflyimg[0].smoothScale( int(butterflyimg[0].width()*0.75), int(butterflyimg[0].height()*0.75) ) butterflyimg.append(QImage()) butterflyimg[2] = butterflyimg[0].smoothScale( int(butterflyimg[0].width()*0.5), int(butterflyimg[0].height()*0.5) ) butterflyimg.append(QImage()) butterflyimg[3] = butterflyimg[0].smoothScale( int(butterflyimg[0].width()*0.25), int(butterflyimg[0].height()*0.25) ) i = ImageItem(butterflyimg[int(4*random.random()%4)],self.canvas) i.move((self.canvas.width()-butterflyimg[0].width())*random.random()%(self.canvas.width()-butterflyimg[0].width()), (self.canvas.height()-butterflyimg[0].height())*random.random()%(self.canvas.height()-butterflyimg[0].height())) i.setZ(256*random.random()%256+250); i.show() def addLogo(self): if logo_fn.isEmpty(): return; if not logoimg: logoimg.append(QImage()) logoimg[0].load( logo_fn ) logoimg.append(QImage()) logoimg[1] = logoimg[0].smoothScale( int(logoimg[0].width()*0.75), int(logoimg[0].height()*0.75) ) logoimg.append(QImage()) logoimg[2] = logoimg[0].smoothScale( int(logoimg[0].width()*0.5), int(logoimg[0].height()*0.5) ) logoimg.append(QImage()) logoimg[3] = logoimg[0].smoothScale( int(logoimg[0].width()*0.25), int(logoimg[0].height()*0.25) ); i = ImageItem(logoimg[int(4*random.random()%4)],self.canvas) i.move((self.canvas.width()-logoimg[0].width())*random.random()%(self.canvas.width()-logoimg[0].width()), (self.canvas.height()-logoimg[0].width())*random.random()%(self.canvas.height()-logoimg[0].width())) i.setZ(256*random.random()%256+256) i.show() def addCircle(self): i = QCanvasEllipse(50,50,self.canvas) i.setBrush( QBrush(QColor(256*random.random()%32*8,256*random.random()%32*8,256*random.random()%32*8) )) i.move(self.canvas.width()*random.random()%self.canvas.width(),self.canvas.width()*random.random()%self.canvas.height()) i.setZ(256*random.random()%256) i.show() def addHexagon_old(self): i = QCanvasPolygon(self.canvas) size = canvas.width() / 25 pa=QPointArray(6) pa.setPoint(0,QPoint(2*size,0)) pa.setPoint(1,QPoint(size,-size*173/100)) pa.setPoint(2,QPoint(-size,-size*173/100)) pa.setPoint(3,QPoint(-2*size,0)) pa.setPoint(4,QPoint(-size,size*173/100)) pa.setPoint(5,QPoint(size,size*173/100)) i.setPoints(pa) i.setBrush( QBrush(QColor(256*random.random()%32*8,256*random.random()%32*8,256*random.random()%32*8) )) i.move(self.canvas.width()*random.random()%self.canvas.width(),self.canvas.width()*random.random()%self.canvas.height()) i.setZ(256*random.random()%256) i.show() def addHexagon(self):###brucehack 050106... these triangles look bad, need antialiasing, i suppose should be images i = QCanvasPolygon(self.canvas) w = h = 9 pa=QPointArray(3) pa.setPoint(0,QPoint(0,0)) # pa.setPoint(1,QPoint(size,-size*173/100)) pa.setPoint(1,QPoint(w,h/2)) # pa.setPoint(3,QPoint(-2*size,0)) pa.setPoint(2,QPoint(0,h)) # pa.setPoint(5,QPoint(size,size*173/100)) i.setPoints(pa) i.setBrush( QBrush(QColor(128,128,128) )) i.move(self.canvas.width()*random.random()%self.canvas.width(),self.canvas.width()*random.random()%self.canvas.height()) i.show() def addPolygon(self): i = QCanvasPolygon(self.canvas) size = self.canvas.width()/2 pa=QPointArray(6) pa.setPoint(0, QPoint(0,0)) pa.setPoint(1, QPoint(size,size/5)) pa.setPoint(2, QPoint(size*4/5,size)) pa.setPoint(3, QPoint(size/6,size*5/4)) pa.setPoint(4, QPoint(size*3/4,size*3/4)) pa.setPoint(5, QPoint(size*3/4,size/4)) i.setPoints(pa) i.setBrush(QBrush( QColor(256*random.random()%32*8,256*random.random()%32*8,256*random.random()%32*8)) ) i.move(self.canvas.width()*random.random()%self.canvas.width(),self.canvas.width()*random.random()%self.canvas.height()) i.setZ(256*random.random()%256) i.show() def addSpline(self): i = QCanvasSpline(self.canvas) size = canvas.width()/6 pa=QPointArray(12) pa.setPoint(0,QPoint(0,0)) pa.setPoint(1,QPoint(size/2,0)) pa.setPoint(2,QPoint(size,size/2)) pa.setPoint(3,QPoint(size,size)) pa.setPoint(4,QPoint(size,size*3/2)) pa.setPoint(5,QPoint(size/2,size*2)) pa.setPoint(6,QPoint(0,size*2)) pa.setPoint(7,QPoint(-size/2,size*2)) pa.setPoint(8,QPoint(size/4,size*3/2)) pa.setPoint(9,QPoint(0,size)) pa.setPoint(10,QPoint(-size/4,size/2)) pa.setPoint(11,QPoint(-size/2,0)) i.setControlPoints(pa) i.setBrush( QBrush(QColor(256*random.random()%32*8,256*random.random()%32*8,256*random.random()%32*8) )) i.move(self.canvas.width()*random.random()%self.canvas.width(),self.canvas.width()*random.random()%self.canvas.height()) i.setZ(256*random.random()%256) i.show() def addText(self): i = QCanvasText(self.canvas) i.setText("QCanvasText") i.move(self.canvas.width()*random.random()%self.canvas.width(),self.canvas.width()*random.random()%self.canvas.height()) i.setZ(256*random.random()%256) i.show() def addLine(self): i = QCanvasLine(self.canvas); i.setPoints( self.canvas.width()*random.random()%self.canvas.width(), self.canvas.width()*random.random()%self.canvas.height(), self.canvas.width()*random.random()%self.canvas.width(), self.canvas.width()*random.random()%self.canvas.height() ) i.setPen( QPen(QColor(256*random.random()%32*8,256*random.random()%32*8,256*random.random()%32*8), 6) ) i.setZ(256*random.random()%256) i.show() def ternary(self,exp,x,y): if exp: return x else: return y def addMesh(self): x0 = 0; y0 = 0; if not self.tb: self.tb = QBrush( Qt.red ) if not self.tp: self.tp = QPen( Qt.black ) nodecount = 0; w = self.canvas.width() h = self.canvas.height() dist = 30 rows = h / dist cols = w / dist #ifndef QT_NO_PROGRESSDIALOG #progress=QProgressDialog( "Creating mesh...", "Abort", rows, # self, "progress", True ); #endif lastRow=[] for c1 in range(cols): lastRow.append(NodeItem(self.canvas)) for j in range(rows): n = self.ternary(j%2 , cols-1 , cols) prev = 0; for i in range(n): el = NodeItem( self.canvas ) nodecount=nodecount+1 r = 20*20*random.random() xrand = r %20 yrand = (r/20) %20 el.move( xrand + x0 + i*dist + self.ternary(j%2 , dist/2 , 0 ), yrand + y0 + j*dist ); if j > 0 : if i < cols-1 : EdgeItem( lastRow[i], el, self.canvas ).show() if j%2 : EdgeItem( lastRow[i+1], el, self.canvas ).show() elif i > 0 : EdgeItem( lastRow[i-1], el, self.canvas ).show() if prev: EdgeItem( prev, el, self.canvas ).show() if i > 0 : lastRow[i-1] = prev prev = el el.show() lastRow[n-1]=prev #ifndef QT_NO_PROGRESSDIALOG #progress.setProgress( j ) #if progress.wasCancelled() : # break #endif #ifndef QT_NO_PROGRESSDIALOG #progress.setProgress( rows ) #endif #// qDebug( "%d nodes, %d edges", nodecount, EdgeItem::count() ); def addRectangle(self): i = QCanvasRectangle( self.canvas.width()*random.random()%self.canvas.width(), self.canvas.width()*random.random()%self.canvas.height(), self.canvas.width()/5,self.canvas.width()/5,self.canvas) z = 256*random.random()%256 i.setBrush( QBrush(QColor(z,z,z) )) i.setPen( QPen(QColor(self.canvas.width()*random.random()%32*8, self.canvas.width()*random.random()%32*8, self.canvas.width()*random.random()%32*8), 6) ) i.setZ(z) i.show() if __name__ == '__main__': app=QApplication(sys.argv) if len(sys.argv) > 1: butterfly_fn=QString(sys.argv[1]) else: butterfly_fn=QString("butterfly.png") if len(sys.argv) > 2: logo_fn = QString(sys.argv[2]) else: logo_fn=QString("qtlogo.png") canvas=QCanvas(800,600) canvas.setAdvancePeriod(30) m=Main(canvas,None,"pyqt canvas example") m.resize(m.sizeHint()) qApp.setMainWidget(m) m.setCaption("Qt Canvas Example ported to PyQt") if QApplication.desktop().width() > m.width() + 10 and QApplication.desktop().height() > m.height() + 30: m.show() else: m.showMaximized() m.show(); #// m.help(); qApp.setMainWidget(None); QObject.connect( qApp, SIGNAL("lastWindowClosed()"), qApp, SLOT("quit()") ) app.exec_() ###@@@ this is first on dragEnterEvent stack # We need to explicitly delete the canvas now (and, therefore, the main # window beforehand) to make sure that the sprite logo doesn't get garbage # collected first. views = [] del m del canvas
NanoCAD-master
cad/src/scratch/canvas-b-3.py
# Copyright 2009 Nanorex, Inc. See LICENSE file for details. """ TransformNode.py -- mutable transform classes, shared by TransformNodes NOT YET USED as of 090204... declared obsolete as of bruce 090225: - much of the specific code is obsolete, since we abandoned the idea of a number-capped TransformControl object (no need to merge TCs when too many are used) - the concept of a separated dynamic and static transform, and letting them be pointers to separate objects, potentially shared, is a good one, which will be used in some form if we ever optimize rigid drag of multiple chunks bridges by external bonds (as I hope we will), but there is no longer time to implement it in this form (new superclass for Chunk), before the next release, since it impacts too much else about a Chunk. If we implement that soon, it will be in some more klugy form which modifies Chunk to a lesser degree. Therefore, this file (and TransformState which it uses) are now scratch files. However, I'm leaving some comments that refer to TransformNode in place (in still-active files), since they also help point out the code which any other attempt to optimize rigid drags would need to modify. In those comments, dt and st refer to dynamic transform and static transform, as used herein. @author: Bruce @version: $Id$ @copyright: 2009 Nanorex, Inc. See LICENSE file for details. """ from foundation.state_constants import S_CHILD from graphics.drawing.TransformControl import TransformControl Node3D _DEBUG = True # for now class TransformNode(Node3D): # review superclass and its name """ A Node3D which can be efficiently moved (in position and orientation) by modifying a contained transform. Children and control points may store relative and/or absolute coordinates, but the relative ones are considered fundamental by most operations which modify the transform (so the absolute ones must be invalidated or recomputed, and modifying the transform moves the node). (But certain operations can explicitly cause data to flow the other way, i.e. modify the transform and relative coordinates in such a way that the absolute position and coordinates remain unchanged.) The transform is actually the composition of two "transform components": an optional outer "dynamic transform" (used for efficient dragging of sets of TransformNodes) and an inner "static transform" (often non-identity for long periods, so we needn't remake or transform all affected CSDLs after every drag operation). Each transform component can be shared with other nodes. That is, several nodes can refer to the same mutable transform, so that changes to it affect all of them. The way self's overall transform is represented by these component transforms can change (by replacing one of them with a copy, and/or merging the dynamic transform into the static transform), without changing the overall transform value. We optimize for the lack of absolute position change in such cases. """ # pointer to our current (usually shared) dynamic transform, or None. # (Note: this affects rendering by making sure self is in a DrawingSet # which will be drawn within GL state which includes this transform.) dynamic_transform = None _s_attr_dynamic_transform = S_CHILD # (_s_attr: perhaps unnecessary, since no Undo checkpoints during drag) # pointer to our current (usually shared) static transform, or None # (note: affects rendering by means of an associated TransformControl, # which transforms the relative coordinates used to make self's CSDLs # into absolute coordinates (not counting dynamic_transform) used to draw # self) static_transform = None _s_attr_static_transform = S_CHILD # REVIEW: does the static_transform contain its TransformControl? # I now think it's contained, and that we won't allocate an ST unless a # TC is available, and that we'll use None for the "identity ST". #### ### REVIEW: should we limit the set of static transforms for all purposes (incl Undo) # due to a limitation on the number of TransformControls which arises from the rendering implementation? # If we do that, should we also remake CSDLs, or just transform them (presumably no difference in end result)? # Note: transforming them is what requires them to have mutable TC refs -- a change to their current API. ### def set_dynamic_transform(self, t): # review: use a setter? the initial assert might not be appropriate then... #### FIX: I don't like having a setter but also allowing direct sets, like we use in other code. #### pick one way and always use that way. Make sure setting it does proper invals, checking t.is_identity() or t is None. # If I want to put off letting nodes be new-style classes, then make raw version private and use setter explicitly... # but I can't put that off for long, if I also want these things to act like state -- actually I can if setters do inval manually... # but what about usage tracking? I'd need getters which do that manually... ##### DECIDE # (about new-style nodes -- as of 090206 I think I've revised enough code to make them ok, but this is untested.) """ """ assert not self.dynamic_transform self.dynamic_transform = t ##### TODO: MAKE SURE this invalidates subscribers to self.dynamic_transform (our dynamic transform id), # but doesn't invalidate our overall transform value [###REVIEW: could it do so by using the following code?] assert t.is_identity() # if it wasn't, we'd also need to invalidate our overall transform value return ### TODO: setter for static needs to list self inside it, so it can merge with others and affect us def set_static_transform(self, st): self.static_transform.del_node(self) self.static_transform = st ##### TODO: MAKE SURE this invalidates subscribers to self.static_transform st.add_node(self) return def bridging_objects(self): """ Return the list of objects which "bridge" more than one TransformNode including this one, and whose TransformNodes presently have different dynamic_transforms (not all the same one) (regardless of the current transform values of those dynamic transforms). """ res = [] for obj in self.potential_bridging_objects(): if obj.is_currently_bridging_dynamic_transforms(): res.append(obj) return res def potential_bridging_objects(self): """ Return a list of objects whose coordinates depend on the value of self's dynamic_transform and also on the value of one or more other nodes' dynamic_transforms (though we don't remove the ones for which the other nodes depend on the *same* dynamic transform). (These are the objects which might get distorted due to a change in self's dynamic transform value, if the other nodes have different dynamic transforms at the time.) [subclasses should override as needed; overridden in class Chunk] """ # note: implem is per-subclass, for now; might generalize later # so this class maintains a set of them -- depends on whether # subclasses maintain distinct custom types, as Chunk may do # when it has error indicators implemented similarly to ExternalBondSet; # right now, I don't know if they'll be kept in the same dict as it is # or not. return () pass # == def merge_dynamic_into_static_transform(nodes): """ Given a set of TransformNodes with the same dynamic transform, but perhaps different static transforms, which may or may not be shared with nodes not in the set, remove the dynamic transform from all the nodes without changing their overall transforms, by merging it into their static transforms. This requires splitting any static transforms that bridge touched and untouched nodes (so we can merge the dynamic transform into only the one on the touched nodes), and if we run out of TransformControls needed to make more static transforms, merging some static transforms into the identity (and either remaking or transforming all our CSDLs, or invalidating them so that happens lazily). """ assert nodes dt = nodes[0].dynamic_transform assert dt is not None for node in nodes: assert node.dynamic_transform is dt for node in nodes: node.dynamic_transform = None ### TODO: make this invalidate subscribers to that field if dt.is_identity(): return # now, fold the value of dt into the static transforms on nodes, # splitting the ones that also cover unaffected nodes. # get the affected static transforms and their counts statics = {} # maps static transform to number of times we see it in nodes for node in nodes: st = node.static_transform # might be None statics.setdefault(st, 0) statics[st] += 1 # see which statics straddle the boundary of our set of nodes # (since we'll need to split each of them in two) straddlers = {} for st, count in statics.iteritems(): # count is the number of nodes which have st; # does that cover all of st's nodes? if st is not None: assert count <= st.nodecount() if count < st.nodecount(): straddlers[st] = st # or store a number? else: straddlers[st] = st # None is always a straddler continue # allocate more TCs (up to the externally known global limit) # for making more static transforms when we split the straddlers want_TCs = len(straddlers) if want_TCs: new_TCs = allocate_TransformControls(want_TCs) if len(new_TCs) < want_TCs: # There are not enough new TCs to split all the straddlers, # so merge some statics as needed, transforming their CSDL primitives print "fyi: want %d new TransformControls, only %d available; merging" % \ (len(new_TCs), want_TCs) print "THIS IS NIM, BUGS WILL ENSUE" assert 0 # (We're hoping that we'll find a way to allocate as many TCs as needed, # so we never need to write this code. OTOH, initially we might need to # make this work in the absence of any TCs, i.e. implem and always use # this code, never allocating STs at all. ###) # now split each straddler in two, leaving the original on the "other nodes" # (this matters if one of them is a "permanent identity StaticTransform") if _DEBUG: print "splitting %d straddlers" % want_TCs replacements = {} # map old to new, for use on nodes for straddler, tc in zip(straddlers, new_TCs): # note: straddler might be None replacements[straddler] = StaticTransform(straddler, tc) for node in nodes: st = node.static_transform if st in replacements: node.set_static_transform(replacements[st]) ### IMPLEM: inval that field but not the overall transform... # now push the data from dt into each (owned or new) static transform for st in statics.keys(): if st in replacements: st = replacements[st] st.applyDataFrom(dt) ### more... only if we need to wrap some some specialized code to inval just the right aspects of the nodes ### return def allocate_TransformControls(number): res = [] for i in range(number): tc = allocate_TransformControl() if tc: res.append(tc) else: break return res def allocate_TransformControl(): return TransformControl() ### STUB; todo: check tc.transform_id against limit? recycle? # end
NanoCAD-master
cad/src/scratch/TransformNode.py
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. ''' buckyball.py -- Buckyball generator, for putting endcaps on nanotubes The order of a buckyball is how many hexagons go between the pentagons. This code fails for order 6 and higher, something in the edges() method. Orders 3 and 4 look like this: http://www.geocities.com/geodesicsnz/3viy.jpg http://www.geocities.com/geodesicsnz/4viy-01.jpg Diameters for different orders: 1 - 3.9 Angstroms 2 - 8.0 A 3 - 12.8 A 4 - 17.7 A 5 - 23.5 A The geometry for a buckyball works like this. Each carbon lies in the center of a triangle. Vectors of unit length are used to represent the vertices of the triangles. Edges are the connections between adjacent vectors; three contiguous edges define a triangle. The positions of carbon atoms are taken by getting a vector for the center of the triangle, and scaling it to make the bond lengths work. Once you have vectors for all the carbons, you can get bonds. Each bond crosses an edge, so edges are given two atom indices for the bond crossing them. There is a sequence of data structures with interdependencies, so an invalidation idiom is used to decide when any one of them should be recomputed. The dependencies (as of this writing) are: _edges -> _triangles -> _carbons -> _bonds. $Id$ ''' __author__ = "Will" from math import sin, cos, pi, floor from geometry.VQT import V, vlen from geometry.NeighborhoodGenerator import NeighborhoodGenerator from model.bonds import bond_atoms, CC_GRAPHITIC_BONDLENGTH from model.bond_constants import V_GRAPHITE from model.chem import Atom class BuckyBall: class Edge: def __init__(self, i, j): assert i != j if i > j: i, j = j, i self.i, self.j = i, j self.atom1 = None self.atom2 = None def ij(self): # ascending order return (self.i, self.j) def ji(self): # descending order return (self.j, self.i) def add_atom(self, a): # a is an int, an index into the list returned by # BuckyBall.carbons() if self.atom1 == None: self.atom1 = a elif self.atom2 == None: self.atom2 = a else: assert False, 'more than two atoms for an edge??' def atoms(self): a1, a2 = self.atom1, self.atom2 assert a1 != None and a2 != None if a1 > a2: a1, a2 = a2, a1 # a1 and a2 are ints, indices into the list returned by # BuckyBall.carbons() return (a1, a2) class EdgeList: def __init__(self): self.lst = [ ] self.dct = { } def append(self, edge): dct = self.dct i, j = edge.ij() self.lst.append(edge) if not dct.has_key(i): dct[i] = [ ] if not dct.has_key(j): dct[j] = [ ] dct[i].append((edge, j)) dct[j].append((edge, i)) def adjoining(self, i): lst = [ ] for e, j in self.dct[i]: lst.append(j) return lst def edgeFor(self, i, j): for e, j1 in self.dct[i]: if j == j1: return e assert False, 'edge not found' def __iter__(self): return self.lst.__iter__() def anyOldBond(self): return self.lst[0].atoms() def bondlist(self): lst = [ ] for i in self.dct.keys(): for e, j in self.dct[i]: if j > i: lst.append(e.atoms()) return lst def mmpBonds(self): dct = { } for i in self.dct.keys(): for e, j in self.dct[i]: if j > i: a1, a2 = e.atoms() if not dct.has_key(a2): dct[a2] = [ ] if a1+1 not in dct[a2]: dct[a2].append(a1+1) return dct def __init__(self, bondlength=CC_GRAPHITIC_BONDLENGTH, order=1): assert order <= 5, 'edges algorithm fails for order > 5' lst = [ ] a = 0.8 ** 0.5 b = 0.2 ** 0.5 lst.append(V(0.0, 0.0, 1.0)) lst.append(V(0.0, 0.0, -1.0)) for i in range(10): t = i * pi * 36 / 180 bb = (i & 1) and -b or b lst.append(V(a * cos(t), a * sin(t), bb)) self.lst = lst self.order = 1 self._invalidate_all() if order > 1: self._subtriangulate(order) self._invalidate_all() self.bondlength = bondlength def _invalidate_all(self): self._edges = None self._triangles = None self._carbons = None self._bonds = None self._bondlist = None def edges(self): if self._edges == None: minLength = 1.0e20 for i in range(len(self.lst)): u = self.lst[i] for j in range(i+1, len(self.lst)): d = vlen(self.lst[j] - u) if d < minLength: minLength = d maxLength = 1.5 * minLength _edges = self.EdgeList() for i in range(len(self.lst)): u = self.lst[i] for j in range(i+1, len(self.lst)): d = vlen(self.lst[j] - u) if d < maxLength: _edges.append(self.Edge(i, j)) self._edges = _edges # invalidate _triangles self._triangles = None return self._edges def triangles(self): if self._triangles == None: edges = self.edges() tlst = [ ] n = len(self.lst) for e in edges: i, j = e.ij() ei = edges.adjoining(i) ej = edges.adjoining(j) for x in ei: if x in ej: tri = [i, j, x] tri.sort() tri = tuple(tri) if tri not in tlst: tlst.append(tri) self._triangles = tlst # invalidate _carbons self._carbons = None return self._triangles def carbons(self): if self._carbons == None: edges = self.edges() lst = [ ] carbonIndex = 0 for tri in self.triangles(): a, b, c = tri ab = edges.edgeFor(a, b) ab.add_atom(carbonIndex) ac = edges.edgeFor(a, c) ac.add_atom(carbonIndex) bc = edges.edgeFor(b, c) bc.add_atom(carbonIndex) v0, v1, v2 = self.lst[a], self.lst[b], self.lst[c] v = (v0 + v1 + v2) / 3.0 lst.append(v) carbonIndex += 1 # get a bond length a1, a2 = edges.anyOldBond() bondlen = vlen(lst[a1] - lst[a2]) # scale to get the correct bond length factor = self.bondlength / bondlen for i in range(len(lst)): lst[i] = factor * lst[i] self._carbons = lst # invalidate _bonds self._bonds = None return self._carbons def radius(self): carbons = self.carbons() assert len(carbons) > 0 totaldist = 0.0 n = 0 # just averge the first ten (or fewer) for c in carbons[:10]: totaldist += vlen(c) n += 1 return totaldist / n def mmpBonds(self): if self._bonds == None: # bonds are perpendicular to edges self._bonds = self.edges().mmpBonds() return self._bonds def bondlist(self): if self._bondlist == None: # bonds are perpendicular to edges self._bondlist = self.edges().bondlist() return self._bondlist def _subtriangulate(self, n): # don't put new vectors right on top of old ones # this is similar to the neighborhood generator gap = 0.001 occupied = { } def quantize(v): return (int(floor(v[0] / gap)), int(floor(v[1] / gap)), int(floor(v[2] / gap))) def overlap(v): x0, y0, z0 = quantize(v) for x in range(x0 - 1, x0 + 2): for y in range(y0 - 1, y0 + 2): for z in range(z0 - 1, z0 + 2): key = (x, y, z) if occupied.has_key(key): return True return False def occupy(v): key = quantize(v) occupied[key] = 1 def add_if_ok(v): if not overlap(v): occupy(v) self.lst.append(v) for v in self.lst: occupy(v) for tri in self.triangles(): v0, v1, v2 = self.lst[tri[0]], self.lst[tri[1]], self.lst[tri[2]] v10, v21 = v1 - v0, v2 - v1 for i in range(n + 1): for j in range(i + 1): v = v21 * (1. * j / n) + v10 * (1. * i / n) + v0 add_if_ok(v / vlen(v)) self.order *= n def add_to_mol(self, mol): maxradius = 1.5 * self.bondlength positions = self.carbons() atoms = [ ] for newpos in positions: newguy = Atom('C', newpos, mol) atoms.append(newguy) newguy.set_atomtype('sp2') ngen = NeighborhoodGenerator(atoms, maxradius) for atm1 in atoms: p1 = atm1.posn() for atm2 in ngen.region(p1): if atm2.key < atm1.key: bond_atoms(atm1, atm2, V_GRAPHITE) # clean up singlets for atm in atoms: for s in atm.singNeighbors(): s.kill() atm.make_enough_bondpoints() ############################# if __name__ == '__main__': mmp_header = '''mmpformat 050920 required; 060421 preferred kelvin 300 group (View Data) info opengroup open = True csys (HomeView) (1.000000, 0.000000, 0.000000, 0.000000) (10.000000) (0.000000, 0.000000, 0.000000) (1.000000) csys (LastView) (1.000000, 0.000000, 0.000000, 0.000000) (10.000000) (0.000000, 0.000000, 0.000000) (1.000000) egroup (View Data) group (Buckyball) info opengroup open = True mol (Buckyball) def ''' mmp_footer = '''egroup (Buckyball) end1 group (Clipboard) info opengroup open = False egroup (Clipboard) end molecular machine part gp ''' def writemmp(bball, filename): outf = open(filename, 'w') outf.write(mmp_header) carbons = bball.carbons() mmpbonds = bball.mmpBonds() for i in range(len(carbons)): x, y, z = carbons[i] outf.write('atom %d (6) (%d, %d, %d) def\n' % (i + 1, int(1000 * x), int(1000 * y), int(1000 * z))) outf.write('info atom atomtype = sp2\n') if mmpbonds.has_key(i) and len(mmpbonds[i]) > 0: outf.write('bondg ' + ', '.join(map(str, mmpbonds[i])) + '\n') outf.write(mmp_footer) outf.close() for i in range(1, 6): b = BuckyBall(i) writemmp(b, 'buckyball-%d.mmp' % i)
NanoCAD-master
cad/src/scratch/buckyball.py
# Copyright 2007-2008 Nanorex, Inc. See LICENSE file for details. """ @author: Ninad @copyright: 2007-2008 Nanorex, Inc. See LICENSE file for details. @version:$Id$ History: 2008-09-09: Moved common code from Rotarymotor and LinearMotor_EditCommand to here. TODO: """ from command_support.EditCommand import EditCommand from commands.SelectAtoms.SelectAtoms_GraphicsMode import SelectAtoms_GraphicsMode _superclass = EditCommand class Motor_EditCommand(EditCommand): """ Superclass for various Motor edit commands """ __abstract_command_class = True #GraphicsMode GraphicsMode_class = SelectAtoms_GraphicsMode prefix = '' # Not used by jigs. # All jigs like rotary and linear motors already created their # name, so do not (re)create it from the prefix. create_name_from_prefix = False propMgr = None #See Command.anyCommand for details about the following flags command_should_resume_prevMode = True command_has_its_own_PM = True from utilities.constants import CL_EDIT_GENERIC command_level = CL_EDIT_GENERIC def command_entered(self): """ Overrides superclass method. @see: baseCommand.command_entered() """ self.struct = None _superclass.command_entered(self) self.o.assy.permit_pick_atoms()
NanoCAD-master
cad/src/command_support/Motor_EditCommand.py
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. """ GeneratorController.py - subclass of GeneratorBaseClass, which can control the interaction between a dialog and a plugin_generator (supplied as constructor arguments) @author: Bruce @version: $Id$ @copyright: 2006-2007 Nanorex, Inc. See LICENSE file for details. Note: this is presently used only by features that never got fully ported to Qt4, and which should be heavily rewritten when they do get ported (for example, to use EditCommand instead of GeneratorBaseClass). However, until that happens, this file should remain in the source code so it can be maintained in trivial ways (imports, external method names). """ import foundation.env as env from command_support.GeneratorBaseClass import GeneratorBaseClass class GeneratorController(GeneratorBaseClass): """ Provide the slot methods from GeneratorBaseClass to receive button clicks from a generator dialog, and let it run the sponsor button image in that dialog, but to set parameters for GeneratorBaseClass or to actually generate something, ask our own plugin_generator (an init argument) what to do. This might need to keep refs to the dialog and to its plugin_generator, which means it will have cyclic refs (since at least the dialog has to know who it is), which means it might need a destroy method (at least to break the cycles). """ def __init__(self, win, dialog, plugin_generator): # set up attributes which GeneratorBaseClass expects to find gen = self.gen = plugin_generator self.sponsor_keyword = gen.topic self.prefix = "%s-" % gen.what_we_generate # GBC appends a serno and uses it for a history message; # if we want to use the same thing as the node name, we have to ##### self.cmdname = "Insert %s" % gen.what_we_generate # used for Undo history # tell the dialog to tell us when we need to generate things, and to call our meet_dialog method dialog.set_controller(self) # (It might be better if we could do this after GeneratorBaseClass.__init__, # since if this gets button presses and calls build_struct right now, it won't work; # but we can't, since GBC needs self.sponsor_btn which the above method's callback to here # (meet_dialog) sets from the dialog. # But the caller has normally not shown the dialog yet, so hopefully that can't happen. # Maybe this can be cleaned up somehow, perhaps only by modifying GeneratorBaseClass.) GeneratorBaseClass.__init__(self, win) # set some attrs our own methods need self.paramnames = gen.paramnames_order return def meet_dialog(self, dialog): """ Start controlling this dialog's appearance and implementing its buttons. [This is a callback from dialog set_controller().] """ self.dialog = dialog self.sponsor_btn = dialog.sponsor_btn # we have to set this so our superclass can see it ###e more #k not sure if we need this anymore as a separate method -- it's just a callback from set_controller return def forget_dialog(self, dialog): """ Stop controlling this dialog in any way. """ if self.dialog is dialog: self.sponsor_btn = None self.dialog = None ##e more else: print "error: self.dialog %r is not dialog %r" % (self.dialog, dialog) return def destroy(self): """ To be called from the owning generator, only. """ ####@@@@ but it's also called below if self.dialog: self.dialog.set_controller(None) # calls self.forget_dialog self.gen = None #e anything needed in the superclasses? return # These are defined in GeneratorBaseClass and don't need to be overridden here, # but they do need to be called from our dialog when its buttons are clicked on. # I think we'll also need to add a "restore defaults". ##def done_btn_clicked(self): # same as ok ##def preview_btn_clicked(self): ##def whatsthis_btn_clicked(self): ##def ok_btn_clicked(self): ##def cancel_btn_clicked(self): def gather_parameters(self): getters = self.dialog.param_getters res = [] for paramname in self.paramnames: getter = getters[paramname] #e need error msg if missing from dialog, but exception from here still makes sense val = getter() #e catch this too, turn into error msg (our own kind of exception, caught by caller) res.append(val) return tuple(res) def build_struct(self, name, params, position): # name = self.name # set by the superclass (though it would make more sense if it passed it to us) return self.gen.build_struct(name, params, position) # needed by GeneratorBaseClass since we're not inheriting QDialog but delegating to one; # this is also the only way we can find out when the dialog gets dismissed # (at least I think it is, and it's also a guess that we always find out this way) def accept(self): if self.dialog: self.dialog.accept() self.dismissed() def reject(self): if self.dialog: self.dialog.reject() self.dismissed() def dismissed(self): if env.debug(): print "debug fyi: dismissed -- should we tell owner to destroy us? is it even still there?" ####@@@@ self.destroy() # let's just take the initiative ourselves, though it might cause bugs, maybe we should do it later... pass # end of class GeneratorController # end
NanoCAD-master
cad/src/command_support/GeneratorController.py
# Copyright 2004-2008 Nanorex, Inc. See LICENSE file for details. """ MotorPropertyManager.py @author: Ninad @version: $Id$ @copyright: 2004-2008 Nanorex, Inc. See LICENSE file for details. """ from PyQt4.Qt import QColorDialog from PM.PM_GroupBox import PM_GroupBox from PM.PM_SelectionListWidget import PM_SelectionListWidget from PM.PM_Constants import PM_PREVIEW_BUTTON, PM_RESTORE_DEFAULTS_BUTTON from widgets.widget_helpers import QColor_to_RGBf from utilities.exception_classes import AbstractMethod from command_support.EditCommand_PM import EditCommand_PM from utilities.debug import print_compact_traceback class MotorPropertyManager(EditCommand_PM): """ The MotorProperty manager class provides UI and propMgr object for the MotorEditCommand. """ # The title that appears in the Property Manager header. title = "Motor" # The name of this Property Manager. This will be set to # the name of the PM_Dialog object via setObjectName(). pmName = title # The relative path to the PNG file that appears in the header #This should be overridden in subclasses iconPath = "ui/actions/Simulation/Motor_JUNK.png" def __init__(self, command): """ Construct the Motor Property Manager. """ EditCommand_PM.__init__( self, command) msg = "Attach a " + self.title + " to the selected atoms" # This causes the "Message" box to be displayed as well. self.updateMessage(msg) self.glpane = self.win.glpane # Hide Restore defaults button for Alpha9. self.hideTopRowButtons(PM_PREVIEW_BUTTON | PM_RESTORE_DEFAULTS_BUTTON) def show(self): """ Show the motor Property Manager. """ EditCommand_PM.show(self) #It turns out that if updateCosmeticProps is called before #EditCommand_PM.show, the 'preview' properties are not updated #when you are editing an existing R.Motor. Don't know the cause at this #time, issue is trivial. So calling it in the end -- Ninad 2007-10-03 if self.command and self.command.struct: self.command.struct.updateCosmeticProps(previewing = True) self.updateAttachedAtomListWidget() def connect_or_disconnect_signals(self, isConnect): """ Connect or disconnect widget signals sent to their slot methods. This can be overridden in subclasses. By default it does nothing. @param isConnect: If True the widget will send the signals to the slot method. @type isConnect: boolean """ if isConnect: change_connect = self.win.connect else: change_connect = self.win.disconnect EditCommand_PM.connect_or_disconnect_signals(self, isConnect) self.attachedAtomsListWidget.connect_or_disconnect_signals(isConnect) def close(self): """ Close this Property manager. """ if self.attachedAtomsListWidget: self.attachedAtomsListWidget.clearTags() EditCommand_PM.close(self) def enable_or_disable_gui_actions(self, bool_enable = False): """ Enable or disable some gui actions when this property manager is opened or closed, depending on the bool_enable. This is the default implementation. Subclasses can override this method. @param bool_enable: If True, the gui actions or widgets will be enabled otherwise disabled. @type bool_enable: boolean """ #It is important to not allow attaching jigs while still editing a #motor. See bug 2560 for details. for action in self.win.simulationMenu.actions(): try: action.setEnabled(bool_enable) except Exception: print_compact_traceback("Ignored exception while disabling "\ " an action.") return def change_jig_color(self): """ Slot method for the ColorComboBox. @note: This overrides change_jig_color in class MotorPropertyManager. """ color = self.motorColorComboBox.getColor() self.command.struct.color = color self.command.struct.normcolor = color self.glpane.gl_update() return def change_motor_size(self, gl_update = True): """ Slot method to change the jig's size and/or spoke radius. Abstract method """ raise AbstractMethod() def reverse_direction(self): """ Slot for reverse direction button. Reverses the direction of the motor. """ if self.command.struct: self.command.struct.reverse_direction() self.glpane.gl_update() def updateAttachedAtomListWidget(self, atomList = None): """ Update the list of attached atoms in the self.selectedAtomsListWidget """ if atomList is None: if self.command.struct: atomList = self.command.struct.atoms[:] if atomList is not None: self.attachedAtomsListWidget.insertItems(row = 0, items = atomList ) def updateMessage(self, msg = ''): """ Updates the message box with an informative message @param msg: Message to be displayed in the Message groupbox of the property manager @type msg: string """ self.MessageGroupBox.insertHtmlMessage(msg, setAsDefault = False, minLines = 5) #Define the UI for the property manager===================== def _addGroupBoxes(self): """Add the 3 groupboxes for the Motor Property Manager. """ self.pmGroupBox1 = PM_GroupBox(self, title = "Motor Parameters") self._loadGroupBox1(self.pmGroupBox1) self.pmGroupBox2 = PM_GroupBox(self, title = "Motor Size and Color") self._loadGroupBox2(self.pmGroupBox2) self.pmGroupBox3 = PM_GroupBox(self, title = "Motor Atoms") self._loadGroupBox3(self.pmGroupBox3) def _loadGroupBox1(self, pmGroupBox): """ Load widgets in groupbox 1. Abstract method (overriden in subclasses) """ raise AbstractMethod() def _loadGroupBox2(self, pmGroupBox): """ Load widgets in groupbox 2. Abstract method (overriden in subclasses) """ raise AbstractMethod() def _loadGroupBox3(self, pmGroupBox): """ Load widgets in groupbox 3. This is the default implementation. Can be overridden in subclasses. """ self.attachedAtomsListWidget = \ PM_SelectionListWidget(pmGroupBox, self.win, heightByRows = 6 )
NanoCAD-master
cad/src/command_support/MotorPropertyManager.py
# Copyright 2004-2008 Nanorex, Inc. See LICENSE file for details. """ Command.py -- provides class basicCommand, superclass for commands [see also baseCommand.py, once ongoing refactoring is completed] @version: $Id$ @copyright: 2004-2008 Nanorex, Inc. See LICENSE file for details. History: bruce 071009 split modes.py into Command.py and GraphicsMode.py, leaving only temporary compatibility mixins in modes.py. For prior history see modes.py docstring before the split. Bruce & Ninad did a big command sequencer refactoring, circa 080812 TODO: A lot of methods in class Command are private helper methods, available to subclasses and/or to default implems of public methods, but are not yet named as private or otherwise distinguished from API methods. We should turn anyCommand into Command_API, add all the API methods to it, and rename the other methods in class Command to look private. """ from PyQt4.Qt import QToolButton from utilities.debug import print_compact_traceback, print_compact_stack from utilities.debug_prefs import debug_pref, Choice_boolean_False from utilities import debug_flags from platform_dependent.PlatformDependent import shift_name from platform_dependent.PlatformDependent import control_name from platform_dependent.PlatformDependent import context_menu_prefix from foundation.FeatureDescriptor import find_or_make_FeatureDescriptor from foundation.FeatureDescriptor import basicCommand_Descriptor from foundation.FeatureDescriptor import register_abstract_feature_class from foundation.state_utils import StateMixin from utilities.constants import noop from model.jigs import Jig # this is used only for cmenu making # TODO: probably it should be factored into a method on the object being tested from command_support.GraphicsMode_API import GraphicsMode_interface from command_support.baseCommand import baseCommand import foundation.changes as changes # == class anyCommand(baseCommand, StateMixin): """ abstract superclass for all Command objects in NE1, including nullCommand. @note: command base class methods are divided somewhat arbitrarily between baseCommand, anyCommand, and basicCommand. In some cases, methods defined in baseCommand are overridden in anyCommand or basicCommand. For more info see baseCommand docstring. """ #bruce 071008 added object superclass; 071009 split anyMode -> anyCommand # Default values for command-object or command-subclass attributes. # External code assumes every command has these attributes, but it should # treat them as read-only; command-related code (in this file) can override # them in subclasses and/or instances, and modify them directly. # note: soon, command_level and command_parent, and some other of the # following default values, will be inherited from a new superclass baseCommand. __abstract_command_class = True featurename = "" # Command's property manager. Subclasses should initialize the propMgr object # if they need one. [in command_enter_PM (after refactoring) or __init__] propMgr = None command_should_resume_prevMode = False # Boolean; whether this command, when exiting, should resume the prior command # if one is saved as commandSequencer.prevMode # (which it is presumed to have suspended when it was entered). # TODO: make this also control whether it *does* save prevMode when it's entered; # presently that is done by entering it using a special method, # commandSequencer.userEnterCommand. # [bruce 071011, to be revised (replaces need for customized Done methods)] # # WARNING: in the new command API as of 2008-09-26, this no longer #controls command nesting as described above, but it has other effects, #e.g. on want_confirmation_corner_type. command_has_its_own_PM = True # note: following comment predates the command stack refactoring circa 080806. # This flag now means only that the command should create its own PM # in self.propMgr rather than letting one from the parent (if any) # remain visible. # # REVIEW: can this be replaced by bool(self.PM_class) once that's # fully implemented? [bruce 080905 question] # #command_has_its_own_PM means, for example, the command has its own PM, #and/or the Done/Cancel button corner (confirmation #corner). #For most of the commands, this is True (e.g. BuildAtoms mode , #BuildCrystal Mode, DnaDuplexEdit Controller etc.) # For many temporary commands #such as Zoom/Pan/Rotate/Line_Command # it is False. That means when the temporary command is active, # it is only doing some thing in the glpane and giving the user an # impression as if he is still in the previous command he was # working on. A good example is PanMode. If user is in Build Atoms mode # and needs to Pan the view, he can simply activate the PanTool(PanMode) # The PanMode, being the temporary mode, has not gui of its own. All it # needs to do is to Pan the view. Thus it continues to use the PM and # flyout toolbar from Build Atoms mode, giving the user an impression # that he is still operating on the old mode. # This flag is also used in fixing bugs like 2566. # This flag also means that if you hit 'Done' or 'Cancel' of the # previous mode (while in a temporary mode) , then 'that previous mode' # will exit. The related code makes sure to first leave the temporary # mode(s) before leaving the regular mode (the command with # command_has_its_own_PM set to True). See also, flag # 'exit_using_done_cancel' in basicCommand.Done used (= False) for a # typical exit of a temporary mode . See that method for detailed # comment. -- Ninad 2007-11-09 def __repr__(self): #bruce 080829, modified from Utility.py version """ [subclasses can override this, and often do] """ classname = self.__class__.__name__.split('.')[-1] return "<%s at %#x>" % (classname, id(self)) # (default methods that should be noops in both nullCommand and Command # can be put here instead if desired; for docstrings, see basicCommand) def isCurrentCommand(self): #bruce 071008 # WARNING: this value of False means the nullCommand should never itself # run code which assumes that this returns true when self is current. # The reason for this stub value is in case this method is ever called on nullCommand # at an early stage of startup, before the usual method would work. return False def keep_empty_group(self, group): #bruce 080305 """ When self is the current command, and an empty group with group.autodelete_when_empty set to true is noticed by self.autodelete_empty_groups(), should that group be kept (not killed) by that method? (Otherwise it will be killed, at least by the default implementation of that method.) @note: subclasses should override this to return True for certain kinds of empty groups which they want to preserve while they are the current command (and which would otherwise be deleted due to having group.autodelete_when_empty set). """ return False def autodelete_empty_groups(self, topnode): """ Kill all empty groups under topnode (which may or may not be a group) for which group.autodelete_when_empty is true and group.temporarily_prevent_autodelete_when_empty is false and self.keep_empty_group(group) returns False. But set group.temporarily_prevent_autodelete_when_empty on all empty groups under topnode for which group.autodelete_when_empty is true and self.keep_empty_group(group) returns True. Do this bottom-up, so killing inner empty groups (if it makes their containing groups empty) subjects their containing groups to this test. @note: called by master_model_updater, after the dna updater. @note: overridden in nullCommand to do nothing. Not normally overridden otherwise, but can be, provided the flag group.temporarily_prevent_autodelete_when_empty is both honored and set in the same way (otherwise, Undo bugs like bug 2705 will result). """ #bruce 080305; revised 080326 as part of fixing bug 2705 # (to set and honor temporarily_prevent_autodelete_when_empty) if not topnode.is_group(): return for member in topnode.members[:]: self.autodelete_empty_groups(member) if (not topnode.members and topnode.autodelete_when_empty and not topnode.temporarily_prevent_autodelete_when_empty ): if not self.keep_empty_group(topnode): topnode.kill() else: topnode.temporarily_prevent_autodelete_when_empty = True # Note: not doing this would cause bug 2705 or similar # if undo got back to this state during a command # whose keep_empty_group no longer returned True # for topnode, since then, topnode would get deleted, # and subsequent redos would be modifying incorrect state, # e.g. adding children to topnode and assuming it remains alive. pass return def isHighlightingEnabled(self): """ Should be overridden in subclasses. Default implementation returns True @see: BuildAtoms_Command.isHighlightingEnabled() """ return True def isWaterSurfaceEnabled(self): """ Should be overridden in subclasses. Default implementation returns True The graphicsMode of current command calls this method to enable/disable water surface and for deciding whther to highlight object under cursor. @see: BuildAtoms_Command.isWaterSurfaceEnabled() @see: BuildAtoms_GraphicsMode. """ return False pass # end of class anyCommand # == class nullCommand(anyCommand): """ do-nothing command (for internal use only) to avoid crashes in case of certain bugs during transition between commands """ # needs no __init__ method; constructor takes no arguments # WARNING: the next two methods are similar in all "null objects", of which # we have nullCommand and nullGraphicsMode so far. They ought to be moved # into a common nullObjectMixin for all kinds of "null objects". [bruce 071009] def noop_method(self, *args, **kws): if debug_flags.atom_debug: print "fyi: atom_debug: nullCommand noop method called -- " \ "probably ok; ignored" return None #e print a warning? def __getattr__(self, attr): # in class nullCommand # note: this is not inherited by other Command classes, # since we are not their superclass if not attr.startswith('_'): if debug_flags.atom_debug: print "fyi: atom_debug: nullCommand.__getattr__(%r) -- " \ "probably ok; returned noop method" % attr return self.noop_method else: raise AttributeError, attr #e args? # Command-specific attribute null values # (the nullCommand instance is not put into the command sequencer's _commandTable) is_null = True commandName = 'nullCommand' # this will be overwritten in the nullCommand instance # when the currentCommand is changing [bruce 050106] # [not sure if that was about commandName or msg_commandName or both] # Command-specific null methods def autodelete_empty_groups(self, topnode): return pass # end of class nullCommand # == class basicCommand(anyCommand): """ Common code between class Command (see its docstring) and old-code-compatibility class basicMode. Will be merged with class Command (keeping that one's name) when basicMode is no longer needed. @note: command base class methods are divided somewhat arbitrarily between baseCommand, anyCommand, and basicCommand. In some cases, methods defined in baseCommand are overridden in anyCommand or basicCommand. For more info see baseCommand docstring. """ # TODO: split into minimalCommand, which does as little as possible # which meets the Command API and permits switching between commands # in conjunction with the Command Sequencer; and basicCommand, which # has all the rest (the basic functionality of an NE1 command). # (This is not urgent, since all commands should have that basic # functionality. It might make things clearer or ease refactoring # some of minimalCommand into the Command Sequencer.) # (later clarification: this comment is not about _minimalCommand in # test_commands.py, though that might hold some lessons for this.) # [bruce 071011 comment] # Subclasses should define the following class constants, # and normally need no __init__ method. # If they have an __init__ method, it must call Command.__init__ # and pass the CommandSequencer in which this command can run. commandName = "(bug: missing commandName)" featurename = "Undocumented Command" __abstract_command_class = True PM_class = None #Command subclasses can override this class constant with the appropriate #Property Manager class, if they have their own Property Manager object. #This is used by self._createPropMgrObject(). #See also self.command_enter_PM. #NOTE 2008-09-02: The class constant PM_class was introduced today and #will soon be used in all commands. But before that, it will be tested #in a few command classes [ -- Ninad comment]. This comment can be #deleted when all commands that have their own PM start using this. # Note: for the new command API as of 2008-09-26, this is always used, # since base class command_enter_PM calls _createPropMgrObject. # [bruce 080909] def __init__(self, commandSequencer): """ This is called once on each newly constructed Command. Some kinds of Commands are constructed again each time they are invoked; others have a single instance which is reused for multiple invocations, but never across open files -- at least in the old mode code before 071009 -- not sure, after that). In the old code, it's called once per new assembly, since the commands store the assembly internally, and that happens once or twice when we open a new file, or once when we use file->close. This method sets up that command to be available (but not yet active) in that commandSequencer's _commandTable (mapping commandName to command object for reusable command objects -- for now that means all of them, by default -- TODO, revise this somehow, maybe control it by a per-Command class constant). REVIEW: are there ever more args, or if the UI wants this to immediately do something, does it call some other method immediately? Guess: the latter. """ glpane = commandSequencer.assy.glpane assert glpane assert glpane is not commandSequencer # this might happen due to bugs in certain callers, # since in old code they were the same object self.pw = None # pw = part window # TODO: remove this, or rename it -- most code uses .win for the same thing # verify self.commandName is set for our subclass assert not self.commandName.startswith('('), \ "bug: commandName class constant missing from subclass %s" % \ self.__class__.__name__ # check whether subclasses override methods we don't want them to # (after this works I might remove it, we'll see) # [most methods have been removed after the command api was revised -- bruce 080929] weird_to_override = [ 'StartOver' #bruce 080806 ] # not 'modifyTransmute', 'keyPress', they are normal to override; # not 'draw_selection_curve', 'Wheel', they are none of my business; # not 'makemenu' since no relation to new mode changes per se. # [bruce 040924] weird_to_override += [ 'command_Done', 'command_Cancel', #bruce 080827 ] for attr in weird_to_override: def same_method(m1, m2): # m1/m2.im_class will differ (it's the class of the query, # not where func is defined), so only test im_func return m1.im_func == m2.im_func if not same_method( getattr(self, attr) , getattr(basicCommand, attr) ): print "fyi (for developers): subclass %s overrides basicCommand.%s; " \ "this is deprecated after mode changes of 040924." % \ (self.__class__.__name__, attr) # other inits self.glpane = glpane # REVIEW: needed? self.win = glpane.win ## self.commandSequencer = self.win.commandSequencer #bruce 070108 # that doesn't work, since when self is first created during GLPane creation, # self.win doesn't yet have this attribute: # (btw the exception from this is not very understandable.) # So instead, we define a property that does this alias, below. # Note: the attributes self.o and self.w are deprecated, but often used. # New code should use some other attribute, such as self.glpane or # self.commandSequencer or self.win, as appropriate. [bruce 070613, 071008] self.o = self.glpane # REVIEW: needed? (deprecated) self.w = self.win # (deprecated) # store ourselves in our command sequencer's _commandTable # [revised to call a commandSequencer method, bruce 080209] ###REVIEW whether this is used for anything except changing to # new command by name [bruce 070613 comment] commandSequencer.store_commandObject(self.commandName, self) # note: this can overwrite a prior instance of the same command, # e.g. when setAssy is called. # exercise self.get_featurename(), just for its debug prints self.get_featurename() return # from basicCommand.__init__ # == def command_enter_PM(self): """ Overrides superclass method. @see: baseCommand.command_enter_PM() for documentation """ #important to check for old propMgr object. Reusing propMgr object #significantly improves the performance. if not self.propMgr: self.propMgr = self._createPropMgrObject() #@bug BUG: following is a workaround for bug 2494. #This bug is mitigated as propMgr object no longer gets recreated #for modes -- ninad 2007-08-29 if self.propMgr: changes.keep_forever(self.propMgr) def _createPropMgrObject(self): """ Returns the property manager object for this command. @see: self._createFlyoutToolbarObject() """ if self.PM_class is None: return None propMgr = self.PM_class(self) return propMgr def get_featurename(clas): #bruce 071227, revised into classmethod 080722 """ Return the "feature name" to be used for the wiki help feature page (not including the initial "Feature:" prefix), for this basicCommand concrete subclass. Usually, this is one or a few space-separated capitalized words. [overrides baseCommand method] """ # (someday: add debug command to list all known featurenames, # by object type -- optionally as wiki help links, for testing; # later: see "export command table", which does part of this) my_command_descriptor = find_or_make_FeatureDescriptor( clas) # note: this knows how to look up clas.featurename; # and that it might need to use basicCommand_Descriptor, # because that's been registered for use with all # subclasses of basicCommand (below). assert my_command_descriptor, "probably an abstract class: %r" % (clas,) return my_command_descriptor.featurename get_featurename = classmethod( get_featurename) # == def _get_commandSequencer(self): return self.win.commandSequencer #bruce 070108 commandSequencer = property(_get_commandSequencer) def _get_assy(self): #bruce 071116 return self.commandSequencer.assy assy = property(_get_assy) #bruce 071116 # == def isCurrentCommand(self): #bruce 071008, for Command API """ Return a boolean to indicate whether self is the currently active command. (Compares instance identity, not just class name or command name.) This can be used in "slot methods" that receive Qt signals from a PM to reject signals that are meant for a newer command object of the same class, in case the old command didn't disconnect those signals from its own methods (as it ideally should do). Warning: this is False even if self is temporarily suspended by e.g. Pan Tool, which has no PM of its own (so self's UI remains fully displayed); this needs to be considered when this method is used to determine whether UI actions should have an effect. Warning: this is False while a command is still being entered (i.e. during the calls of command_entered ). But it's not a good idea to rely on that behavior -- if you do, you should redefine this function to guarantee it, and add suitable comments near the places which *could* in principle be modified to set .currentCommand to the command object being entered, earlier than they do now. """ return self.commandSequencer.is_this_command_current(self) def set_cmdname(self, name): """ Helper method for setting the cmdname to be used by Undo/Redo. Called by undoable user operations which run within the context of this Command. """ self.win.assy.current_command_info(cmdname = name) ### TODO: move this up, and rename to indicate it's about the graphics area's # empty space context menus call_makeMenus_for_each_event = False # default value of class attribute; subclasses can override def setup_graphics_menu_specs(self): # review: rename/revise for new command api? not urgent. [080806] ### TODO: make this more easily customized, esp the web help part; ### TODO if possible: fix the API (also of makeMenus) to not depend # on setting attrs as side effect """ Call self.makeMenus(), then postprocess the menu_spec attrs it sets on self, namely some or all of Menu_spec, Menu_spec_shift, Menu_spec_control, debug_Menu_spec, and make sure the first three of those are set on self in their final (modified) forms, ready for the caller to (presumably) turn into actual menus. (TODO: optim: if we know we're being called again for each event, optim by producing only whichever menu_specs are needed. This is not always just one, since we sometimes copy one into a submenu of another.) """ # Note: this was split between Command.setup_graphics_menu_specs and # GraphicsMode._setup_menus, bruce 071009 # lists of attributes of self we examine and perhaps remake: mod_attrs = ['Menu_spec_shift', 'Menu_spec_control'] all_attrs = ['Menu_spec'] + mod_attrs + ['debug_Menu_spec'] # delete any Menu_spec attrs previously set on self # (needed when self.call_makeMenus_for_each_event is true) for attr in all_attrs: if hasattr(self, attr): del self.__dict__[attr] #bruce 050416: give it a default menu; for modes we have now, # this won't ever be seen unless there are bugs #bruce 060407 update: improve the text, re bug 1739 comment #3, # since it's now visible for zoom/pan/rotate tools self.Menu_spec = [("%s" % self.get_featurename(), noop, 'disabled')] self.makeMenus() # bruce 040923 moved this here, from the subclasses; # for most modes, it replaces self.Menu_spec # bruce 041103 changed details of what self.makeMenus() should do # self.makeMenus should have set self.Menu_spec, and maybe some sister attrs assert hasattr(self, 'Menu_spec'), "%r.makeMenus() failed to set up" \ " self.Menu_spec (to be a menu spec list)" % self # should never happen after 050416 orig_Menu_spec = list(self.Menu_spec) # save a copy for comparisons, before we modify it # define the ones not defined by self.makeMenus; # make them all unique lists by copying them, # to avoid trouble when we modify them later. for attr in mod_attrs: if not hasattr(self, attr): setattr(self, attr, list(self.Menu_spec)) # note: spec should be a list (which is copyable) for attr in ['debug_Menu_spec']: if not hasattr(self, attr): setattr(self, attr, []) for attr in ['Menu_spec']: setattr(self, attr, list(getattr(self, attr))) if debug_flags.atom_debug and self.debug_Menu_spec: # put the debug items into the main menu self.Menu_spec.extend( [None] + self.debug_Menu_spec ) # note: [bruce 050914, re bug 971; edited 071009, 'mode' -> 'command'] # for commands that don't remake their menus on each use, # the user who turns on ATOM-DEBUG won't see the menu items # defined by debug_Menu_spec until they remake all command objects # (lazily?) by opening a new file. This might change if we remake # command objects more often (like whenever the command is entered), # but the best fix would be to remake all menus on each use. # But this requires review of the menu-spec making code for # each command (for correctness when run often), so for now, # it has to be enabled per-command by setting # command.call_makeMenus_for_each_event for that command. # It's worth doing this in the commands that define # command.debug_Menu_spec.] # new feature, bruce 041103: # add submenus to Menu_spec for each modifier-key menu which is # nonempty and different than Menu_spec # (was prototyped in extrudeMode.py, bruce 041010] doit = [] for attr, modkeyname in [ ('Menu_spec_shift', shift_name()), ('Menu_spec_control', control_name()) ]: submenu_spec = getattr(self, attr) if orig_Menu_spec != submenu_spec and submenu_spec: doit.append( (modkeyname, submenu_spec) ) if doit: self.Menu_spec.append(None) for modkeyname, submenu_spec in doit: itemtext = '%s-%s Menu' % (context_menu_prefix(), modkeyname) self.Menu_spec.append( (itemtext, submenu_spec) ) # note: use PlatformDependent functions so names work on Mac or non-Mac, # e.g. "Control-Shift Menu" vs. "Right-Shift Menu", # or "Control-Command Menu" vs. "Right-Control Menu". # [bruce 041014] if isinstance( self.o.selobj, Jig): # NFR 1740. mark 060322 # TODO: find out whether this works at all (I would be surprised if it does, # since I'd think that we'd never call this if selobj is not None); # if it does, put it on the Jig's cmenu maker, not here, if possible; # if it doesn't, also put it there if NFR 1740 remains undone and desired. # [bruce comment 071009] ##print "fyi: basicCommand.setup_graphics_menu_specs sees isinstance(selobj, Jig)" ## # see if this can ever happen ## # yes, this happened when I grabbed an RMotor's GLPane cmenu. [bruce 071025] from foundation.wiki_help import wiki_help_menuspec_for_object ms = wiki_help_menuspec_for_object( self.o.selobj ) if ms: self.Menu_spec.append( None ) self.Menu_spec.extend( ms ) else: featurename = self.get_featurename() if featurename: from foundation.wiki_help import wiki_help_menuspec_for_featurename ms = wiki_help_menuspec_for_featurename( featurename ) if ms: self.Menu_spec.append( None ) # there's a bug in this separator, for BuildCrystal_Command... # [did I fix that? I vaguely recall fixing a separator # logic bug in the menu_spec processor... bruce 071009] # might this look better before the above submenus, with no separator? ## self.Menu_spec.append( ("web help: " + self.get_featurename(), ## self.menucmd_open_wiki_help_page ) ) self.Menu_spec.extend( ms ) return # from setup_graphics_menu_specs def makeMenus(self): # review: rename/revise for new command api? not urgent. [080806] ### TODO: rename to indicate it's about the graphics area's empty space context menus; # move above setup_graphics_menu_specs """ [Subclasses can override this to assign menu_spec lists (describing the context menus they want to have) to self.Menu_specs (and related attributes). [### TODO: doc the related attributes, or point to an example that shows them all.] Depending on a class constant call_makeMenus_for_each_event (default False), this will be called once during init (default behavior) or on every mousedown that needs to put up a context menu (useful for "dynamic context menus").] """ pass ###e move the default menu_spec to here in case subclasses want to use it? # == # confirmation corner methods [bruce 070405-070409, 070627] def _KLUGE_visible_PM_buttons(self): #bruce 070627 """ private method (but ok for use by self._ccinstance), and a kluge: return the Done and Cancel QToolButtons of the current PM, if they are visible, or None for each one that is not visible. Used both for deciding what CC buttons to show, and for acting on the buttons (assuming they are QToolButtons). """ # note: this is now much less of a kluge, but still somewhat klugy # (since it makes one UI element depend on another one), # so I'm not renaming it. [bruce 080929 comment] pm = self.propMgr #bruce 080929 revision, used to call _KLUGE_current_PM # (but recently, it passed an option that made it equivalent) if not pm: return None, None # no CC if no PM is visible def examine(buttonname): try: button = getattr(pm, buttonname) assert button assert isinstance(button, QToolButton) vis = button.isVisibleTo(pm) # note: we use isVisibleTo(pm) rather than isVisible(), # as part of fixing bug 2523 [bruce 070829] if vis: res = button else: res = None except: print_compact_traceback("ignoring exception (%r): " % buttonname) res = None return res return ( examine('done_btn'), examine('abort_btn') ) def want_confirmation_corner_type(self): # review: rename for new Command API? not urgent. [080806] """ Subclasses should return the type of confirmation corner they currently want, typically computed from their current state. This makes use of various attrs defined on self, so it should be called on whichever command the confirmation corner would terminate, which is not necessarily the current command. The return value can be one of the strings 'Done+Cancel' or 'Done' or 'Cancel', or None (for no conf. corner). Or it can be one of those values with 'Transient-Done' in place of 'Done'. (Later we may add other possible values, e.g. 'Exit'.) @see: confirmation_corner.py, for related info [Many subclasses will need to override this; we might also revise the default to be computed in a more often correct manner.] """ # What we do: # find the current PM, and ask which of these buttons are visible to it: # pm.done_btn.isVisibleTo(pm) # pm.abort_btn.isVisibleTo(pm). # We also use them to perform the actions (they are QToolButtons). # KLUGE: we do this in other code which finds them again redundantly # (calling the same kluge helper function). done_button_vis, cancel_button_vis = self._KLUGE_visible_PM_buttons() # each one is either None, or a QToolButton (a true value), # currently displayed on the current PM res = [] if done_button_vis: #For temporary commands with their own gui (the commands that #are expected to return to the previous command when done), #use the 'Transient-Done' confirmation corner images. if self.command_has_its_own_PM and \ self.command_should_resume_prevMode: res.append('Transient-Done') else: res.append('Done') if cancel_button_vis: res.append('Cancel') if not res: res = None else: res = '+'.join(res) return res def should_exit_when_ESC_key_pressed(self): # not overridden, as of 080815 """ @return: whether this command should exit when the ESC key is pressed @rtype: boolean [May be overridden in subclasses.] Default implementation returns the value of self.command_should_resume_prevMode (except for the default command, which returns False). For now, if you hit Escape key in all such commands, the command will exit. @see: ESC_to_exit_GraphicsMode_preMixin.keyPress() """ return (self.command_should_resume_prevMode and not self.is_default_command()) # methods for leaving this command (from a dashboard tool or an # internal request). # Notes on state-accumulating modes, e.g. Build Crystal, Extrude, # and [we hoped at the time] Build Atoms [bruce 040923]: # # [WARNING: these comments are MOSTLY OBSOLETE now that # USE_COMMAND_STACK is true (new command API, which # is the default API as of 2008-09-26) ] # # Each command which accumulates state, meant to be put into its # model (assembly) in the end, decides how much to put in as it # goes -- that part needs to be "undone" (removed from the # assembly) to support a Cancel event -- versus how much to retain # internally -- that part needs to be "done" (put into in the # assembly) upon a Done event. (BTW, as I write this, I think # that only BuildAtoms_Command (so far) puts any state into the assembly # before it's Done.) # # Both kinds of state (stored in the command or in the assembly) # should be considered when overriding self.haveNontrivialState() # -- it should say whether Done and Cancel should have different # ultimate effects. (Note "should" rather than "would" -- # i.e. even if Cancel does not yet work, like in BuildAtoms_Command, # haveNontrivialState should return True based on what Cancel # ought to do, not based on what it actually does. That way the # user won't miss a warning message saying that Cancel doesn't # work yet.) # # StateDone should actually put the unsaved state from here into # the assembly; StateCancel should remove the state which was # already put into the assembly by this command's operation (but only # since the last time it was entered). Either of those can also # emit an error message and return True to refuse to do the # requested operation of Done or Cancel (they normally return # None). If they return True, we assume they made no changes to # the stored state, in the command or in the assembly (but we have no # way of enforcing that; bugs are likely if they get this wrong). # # I believe that exactly one of StateDone and StateCancel will be # called, for any way of leaving a command, except for Abandon, if # self.haveNontrivialState() returns true; if it returns false, # neither of them will be called. # # -- bruce 040923 def _warnUserAboutAbandonedChanges(self): #bruce 080908 split this out """ Private helper method for command subclasses overriding command_will_exit which (when commandSequencer.exit_is_forced is true) need to warn the user about changes being abandoned when closing a model, which were not noticed by a file modified check due to logic bugs in how that works and how those changes are stored. Most commands don't need to call this; only commands that store changes in self rather than in assy might need to call it. It does nothing if self.commandSequencer.warn_about_abandoned_changes is False. @see: ExtrudeMode.command_will_exit() where it is called. """ if not self.commandSequencer.warn_about_abandoned_changes: return msg = "%s with changes is being forced to abandon those changes!\n" \ "Sorry, no choice for now." % (self.get_featurename(),) self._warning_for_abandon( msg, bother_user_with_dialog = 1 ) return def warning(self, *args, **kws): # find out whether this ever happens. If not, remove it. [bruce 080912] print_compact_stack( "fyi: deprecated method basicCommand.warning(*%r, **%r) was called: " % (args, kws)) self._warning_for_abandon(*args, **kws) def _warning_for_abandon(self, str1, bother_user_with_dialog = 0, ensure_visible = 1): """ Show a warning to the user, without interrupting them (i.e. not in a dialog) unless bother_user_with_dialog is true, or unless ensure_visible is true and there's no other way to be sure they'll see the message. (If neither of these options is true, we might merely print the message to stdout.) Also always print the warning to the console. In the future, this might go into a status bar in the window, if we can be sure it will remain visible long enough. For now, that won't work, since some status bar messages I emit are vanishing almost instantly, and I can't yet predict which ones will do that. Due to that problem and since the stdout/stderr output might be hidden from the user, ensure_visible implies bother_user_with_dialog for now. (And when we change that, we have to figure out whether all the calls that no longer use dialogs are still ok.) In the future, all these messages will also probably get timestamped and recorded in a log file, in addition to whereever they're shown now. @see: env.history; other methods named warning. """ # bruce 040922 wrote this (in GLPane, named warning) # bruce 080912: this was almost certainly only called by # self._warnUserAboutAbandonedChanges. # so I moved its body here from class GLPane, # and renamed it, and added a deprecated compatibility # call from the old method name (warning). # TODO: cleanup; merge with other 'def warning' methods and with # env.history / statusbar methods. # Or, perhaps just inline it into its sole real caller. from PyQt4.Qt import QMessageBox use_status_bar = 0 # always 0, for now use_dialog = bother_user_with_dialog if ensure_visible: prefix = "WARNING" use_dialog = 1 ###e for now, and during debugging -- ### status bar would be ok when we figure out how to ### guarantee it lasts else: prefix = "warning" str1 = str1[0].upper() + str1[1:] # capitalize the sentence msg = "%s: %s" % (prefix, str1,) ###e add a timestamp prefix, at least for the printed one # always print it so there's a semi-permanent record they can refer to print msg if use_status_bar: # do this first ## [this would work again as of 050107:] self.win.statusBar().message( msg) assert 0 # this never happens for now if use_dialog: # use this only when it's worth interrupting the user to make # sure they noticed the message.. see docstring for details ##e also linebreak it if it's very long? i might hope that some # arg to the messagebox could do this... QMessageBox.warning(self.o, prefix, msg) # args are widget, title, content return def StartOver(self): # only callable from UI of Extrude & Build Crystal; # needs rename [bruce 080806 comment] """ Support Start Over action for a few commands which implement this [subclasses should NOT override this] """ #bruce 080827 guess; UNTESTED ### self.command_Cancel() self.commandSequencer.userEnterCommand(self.commandName) # == def find_self_or_parent_command_named(self, commandName): #bruce 080801; maybe untested """ Return the first command of self and its parentCommands (if any) which has the given commandName, or None if none does (often an error, but no error message is printed). """ # note: this could be rewritten to not use self.commandSequencer # at all (a nice cleanup, but not urgent or required). cseq = self.commandSequencer res = cseq.find_innermost_command_named( commandName, starting_from = self ) return res def find_parent_command_named(self, commandName): #bruce 080801 """ Return the first of self's parentCommands (if any) which has the given commandName, or None if none does (often an error, but no error message is printed). @note: we expect at most one active command to have a given commandName (at a given time), but this may not be checked or enforced. """ # review: can this be simplified, now that new command api is always used? # e.g. it could probably work without referencing self.commandSequencer. cseq = self.commandSequencer commands = cseq.all_active_commands( starting_from = self ) for command in commands[1:]: # only look at our parent commands if command.commandName == commandName: return command return None # == def _args_and_callback_for_request_command(self): #bruce 080801, might be revised/renamed """ ###doc """ cseq = self.commandSequencer return cseq._f_get_data_while_entering_request_command() pass # end of class basicCommand register_abstract_feature_class( basicCommand, basicCommand_Descriptor ) # == class Command(basicCommand): """ Subclass this class to create a new Command, or more often, a new general type of Command. This class contains code which most Command classes need. [See basicCommand docstring about how and when that class will be merged with this class.] A Command is a temporary mode of interaction for the entire UI which the user enters in order to accomplish a specific operation or kind of interaction. Some Commands exit very soon and on their own, but most can endure indefinitely until the user activates a Done or Cancel action to exit them. An instance of a Command subclass corresponds to a single run of a command, which may or may not have actually become active and/or still be active. Mode-like commands may repeatedly become active due to separate user actions, whereas operation-like commands are more likely to be active just once (with new instances of the same class being created when the user again asks for the same operation to occur). """ # default values of class constants (often overridden by subclasses) GraphicsMode_class = None # Each Command subclass must override this class constant with the # most abstract GraphicsMode subclass which they are able to work with. # In concrete Command subclasses, it must be a subclass of # GraphicsMode_interface, whose constructor takes a single argument, # which will be the command instance. # # Command subclasses which inherit (say) SomeCommand can also define # a corresponding GraphicsMode subclass (and assign it to this class attribute) # using SomeCommand.GraphicsMode_class as its superclass. # # (This works when the set of methods can be known at import time. # The init args, kws, and side effects needn't be known then, # since the Command methods which supply them can be overridden.) # # The main issue in this scheme is the import dependence between # any Command subclass and the GraphicsMode methods used to # implement it, though logically, it'd be better if it was only # dependent then on the API of those GraphicsMode methods, # and not on their implem until it had to be instantiated. # Eventually, to librarify this code, we'll need to solve that problem. def __init__(self, commandSequencer): basicCommand.__init__(self, commandSequencer) # also create and save our GraphicsMode, # so command sequencer can find it inside us for use by the glpane # (and how does it know when we change it or we get changed, # which means its GM changed?) self._create_GraphicsMode() return def _create_GraphicsMode(self): GM_class = self.GraphicsMode_class # maybe: let caller pass something to replace this? assert issubclass(GM_class, GraphicsMode_interface) args = [self] # the command is the only ordinary init argument kws = {} # TODO: let subclasses add kws to this # NOT TODO [see end of comment for why not]: # permit the following to sometimes share a single GM instance # between multiple commands (might or might not be important) # (possible importance: if something expensive like expr instances # are cached in the GM instance itself; for now they're cached in # the GLPane based on the Command or GM name, so this doesn't matter) # Big difficulty with that: how can graphicsMode.command point back to self? # We'd have to reset it with every delegation, or pass it as an argument # into every method (or attr get) -- definitely worse than the benefit, # so NEVERMIND. Instead, just share anything expensive that a GM sets up. self.graphicsMode = GM_class(*args, **kws) pass pass commonCommand = basicCommand # use this for mixin classes that need to work in both basicCommand and Command # end
NanoCAD-master
cad/src/command_support/Command.py
# Copyright 2004-2009 Nanorex, Inc. See LICENSE file for details. """ GraphicsMode_API.py -- API class for whatever is used as a GraphicsMode @version: $Id$ @copyright: 2004-2009 Nanorex, Inc. See LICENSE file for details. History: Bruce 071028 split this out of GraphicsMode.py, in which it was called anyGraphicsMode. All external refs to anyGraphicsMode are now refs to GraphicsMode_API. Bruce 081002 added all GraphicsMode API methods to this class, AFAIK (to fully document the API). Used null methods and values (legal to use, which do nothing) unless no real GraphicsMode can be correct without overriding them (like for Command.commandName). Note that this API consists mainly of methods/attrs expected by GLPane, rather than by self.command, since when a Command expects certain methods in its GraphicsMode, it's enough for those to be defined in that command's own GraphicsMode_class (assuming subclasses of that command use graphicsmode classes which are subclasses of that GM class, as should generally be true). TODO: See the TODO comment in module GraphicsMode. """ class GraphicsMode_interface(object): #bruce 090307 """ This can be used in isinstance/issubclass assertions, and inherited by classes which intend to delegate to an actual GraphicsMode (such as Delegating_GraphicsMode) and which therefore don't want to inherit the default method implementations in GraphicsMode_API. """ pass # == class Delegating_GraphicsMode(GraphicsMode_interface): #bruce 090307 """ Abstract class for GraphicsModes which delegate almost everything to their parentGraphicsMode. @see: related class Overdrawing_GraphicsMode_preMixin, used in TemporaryCommand_Overdrawing """ # implem note: We can't use idlelib.Delegator to help implement this class, # since the delegate needs to be dynamic. def __init__(self, command): self.command = command return def __get_parentGraphicsMode(self): #bruce 081223 [copied from GraphicsMode] # review: does it need to check whether the following exists? return self.command.parentCommand.graphicsMode parentGraphicsMode = property(__get_parentGraphicsMode) # use this when you need to wrap a method, then delegate explicitly # (but rely on __getattr__ instead, when you can delegate directly) def __getattr__(self, attr): if self.command.parentCommand: if self.command.parentCommand.graphicsMode: # aka parentGraphicsMode return getattr(self.command.parentCommand.graphicsMode, attr) # may raise AttributeError else: # parentCommand has no graphicsMode [never yet seen] print "%r has no graphicsMode!" % self.command.parentCommand raise AttributeError, attr pass else: # self.command has no parentCommand [never yet seen] print "%r has no parentCommand!" % self.command raise AttributeError, attr pass pass # == class GraphicsMode_API(GraphicsMode_interface): """ API class and abstract superclass for most GraphicsMode objects, including nullGraphicsMode. @note: for isinstance/issubclass tests, and fully-delegating GraphicsModes, use GraphicsMode_interface instead. """ # GraphicsMode-specific attribute null values compass_moved_in_from_corner = False # when set, tells GLPane to render compass in a different place [bruce 070406] render_scene = None # optional scene-rendering method [bruce 070406] # When this is None, it tells GLPane to use its default method. # (TODO, maybe: move that default method into basicGraphicsMode's implem # of this, and put a null implem in this class.) # Note: to use this, override it with a method (or set it to a # callable) which is compatible with GLPane.render_scene() # but which receives a single argument which will be the GLPane. check_target_depth_fudge_factor = 0.0001 # affects GLPane's algorithm for finding selobj (aka objectUnderMouse) # default methods of various kinds: # selobj-related def selobj_highlight_color(self, selobj): """ @see: Select_GraphicsMode version, for docstring """ return None def selobj_still_ok(self, selobj): """ @see: GraphicsMode version, for docstring """ return True # also: glpane asks for self.command.isHighlightingEnabled() # (as part of a kluge used for updates during event processing); # review: should we define that in this API, and delegate it to command # in basicGraphicsMode? Or, better, refactor the sole call in GLPane_*.py # to call selobj_highlight_color instead (which is None whenever # the selobj should not be highlighted). [bruce 081002 comment] # drawing stages def gm_start_of_paintGL(self, glpane): return def Draw(self): # this should never happen as of bruce 090311 print "bug: old code is calling %r.Draw(): " % self return def Draw_preparation(self): return def Draw_axes(self): return def Draw_other_before_model(self): return def Draw_model(self): return def Draw_other(self): return def Draw_after_highlighting(self, pickCheckOnly = False): return def draw_overlay(self): # misnamed return def Draw_highlighted_selobj(self, glpane, selobj, hicolor): """ @see: GraphicsMode version, for docstring """ return def gm_end_of_paintGL(self, glpane): return # cursor def update_cursor(self): return # key events def keyPressEvent(self, event): return def keyReleaseEvent(self, event): return # mouse wheel event def Wheel(self, event): return # mouse events # (todo: refactor to have fewer methods, let GraphicsMode # split them up if desired, since some GMs don't want to) def mouse_event_handler_for_event_position(self, wX, wY): return None def bareMotion(self, event): """ Mouse motion with no buttons pressed. @return: whether this event was "discarded" due to the last mouse wheel event occurring too recently @rtype: boolean @note: GLPane sometimes generates a fake bareMotion event with no actual mouse motion @see: Select_GraphicsMode_MouseHelpers_preMixin.bareMotion @see: SelectChunks_GraphicsMode.bareMotion for 'return True' """ return False # russ 080527 added return value to API def leftDouble(self, event): pass def leftDown(self, event): pass def leftDrag(self, event): pass def leftUp(self, event): pass def leftShiftDown(self, event): pass def leftShiftDrag(self, event): pass def leftShiftUp(self, event): pass def leftCntlDown(self, event): pass def leftCntlDrag(self, event): pass def leftCntlUp(self, event): pass def middleDouble(self, event): pass def middleDown(self, event): pass def middleDrag(self, event): pass def middleUp(self, event): pass def middleShiftDown(self, event): pass def middleShiftDrag(self, event): pass def middleShiftUp(self, event): pass def middleCntlDown(self, event): pass def middleCntlDrag(self, event): pass def middleCntlUp(self, event): pass def middleShiftCntlDown(self, event): pass def middleShiftCntlDrag(self, event): pass def middleShiftCntlUp(self, event): pass def rightDouble(self, event): pass def rightDown(self, event): pass def rightDrag(self, event): pass def rightUp(self, event): pass def rightShiftDown(self, event): pass def rightShiftDrag(self, event): pass def rightShiftUp(self, event): pass def rightCntlDown(self, event): pass def rightCntlDrag(self, event): pass def rightCntlUp(self, event): pass ### REVIEW: # other methods/attrs that may be part of the GraphicsMode API, # even though they are not called from GLPane itself # (some of them are called on "current GraphicsMode"): # - end_selection_from_GLPane # - isCurrentGraphicsMode # - get_prefs_value # - UNKNOWN_SELOBJ attr # - command attr # See also TODO comment in DynamicTip.py, suggesting a new API method # to ask what to display in the tooltip. pass # end of class GraphicsMode_API # end
NanoCAD-master
cad/src/command_support/GraphicsMode_API.py
# Copyright 2007-2008 Nanorex, Inc. See LICENSE file for details. """ This is a superclass for the property managers of various command objects @author: Ninad @copyright: 2007-2008 Nanorex, Inc. See LICENSE file for details. @version:$Id$ History: 2008-10-01 : Created this to make it a common superclass of all command PMs Moved common code from EditCommand_PM to here. TODO as of 2008-10-01 - get rid of "not KEEP_SIGNALS_CONNECTED" case - revise/ remove self.enable_or_disable_gui_actions() completely """ from PM.PM_Dialog import PM_Dialog from utilities.exception_classes import AbstractMethod #debug flag to keep signals always connected from utilities.GlobalPreferences import KEEP_SIGNALS_ALWAYS_CONNECTED from utilities.Comparison import same_vals _superclass = PM_Dialog class Command_PropertyManager(PM_Dialog): """ This is a superclass for the property managers of various command objects @see: B{PlanePropertyManager} as an example @see: B{PM_Dialog} """ # The title that appears in the Property Manager header. title = "Property Manager" # The name of this Property Manager. This will be set to # the name of the PM_Dialog object via setObjectName(). pmName = title # The relative path to the PNG file that appears in the header iconPath = "" def __init__(self, command): """ Constructor for Command_PropertyManager. """ self.command = command self.win = self.command.win self.w = self.win self.pw = self.command.pw self.o = self.win.glpane _superclass.__init__(self, self.pmName, self.iconPath, self.title) if KEEP_SIGNALS_ALWAYS_CONNECTED: self.connect_or_disconnect_signals(True) def show(self): """ Shows the Property Manager. Extends superclass method. """ _superclass.show(self) if not KEEP_SIGNALS_ALWAYS_CONNECTED: self.connect_or_disconnect_signals(True) self.enable_or_disable_gui_actions(bool_enable = False) def close(self): """ Closes the Property Manager. Extends superclass method. """ if not KEEP_SIGNALS_ALWAYS_CONNECTED: self.connect_or_disconnect_signals(False) self.enable_or_disable_gui_actions(bool_enable = True) _superclass.close(self) def connect_or_disconnect_signals(self, isConnect): """ Connect or disconnect widget signals sent to their slot methods. This can be overridden in subclasses. By default it does nothing. @param isConnect: If True the widget will send the signals to the slot method. @type isConnect: boolean """ pass def enable_or_disable_gui_actions(self, bool_enable = False): """ Enable or disable some gui actions when this property manager is opened or closed, depending on the bool_enable. Subclasses can override this method. """ pass def update_UI(self): """ Update whatever is shown in this PM based on current state of the rest of the system, especially the state of self.command and of the model it shows. This method SHOULD NOT BE overridden in subclasses. Instead override the submethods '_update_UI_check_change_indicators' and '_update_UI_do_updates' """ anything_changed = self._update_UI_check_change_indicators() if not anything_changed: return self._update_UI_do_updates() return def _update_UI_check_change_indicators(self): """ This method does a basic check to see if something in the assembly changed since last call of this method. It compares various change indicators defined in assembly class against an attribute of this class. This class attr stores the previous values of all these change indicators when it was last called. @see: self.update_UI() """ current_change_indicators = (self.win.assy.model_change_indicator(), self.win.assy.selection_change_indicator(), self.win.assy.command_stack_change_indicator()) if same_vals(current_change_indicators, self._previous_all_change_indicators): return False self._previous_all_change_indicators = current_change_indicators return True def _update_UI_do_updates(self): """ Subclasses must override this method to do the actual updates. """ pass def _addGroupBoxes(self): """ Add various group boxes to this PM. Abstract method. """ raise AbstractMethod() def _addWhatsThisText(self): """ Add what's this text. Abstract method. """ raise AbstractMethod()
NanoCAD-master
cad/src/command_support/Command_PropertyManager.py
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. """ ParameterDialog.py -- generate dialogs for editing sets of parameters, from descriptions of the parameters and of how to edit them, encoded as data which can (in principle) be manipulated at a high level in python, or which can be parsed from easily readable/editable text files. @author: Bruce @version: $Id$ @copyright: 2006-2007 Nanorex, Inc. See LICENSE file for details. """ # original source (heavily modified): # # Form implementation generated from reading ui file '.../nanotube_mac.ui' # # Created: Tue May 16 12:05:20 2006 # by: The PyQt User Interface Compiler (pyuic) 3.14.1 from PyQt4 import QtGui from PyQt4.Qt import Qt from PyQt4.Qt import QDialog from PyQt4.Qt import QFrame from PyQt4.Qt import QTextEdit from PyQt4.Qt import QPixmap from PyQt4.Qt import QVBoxLayout from PyQt4.Qt import QColor from PyQt4.Qt import QHBoxLayout from PyQt4.Qt import QLabel from PyQt4.Qt import QSizePolicy from PyQt4.Qt import QFont from PyQt4.Qt import QPushButton from PyQt4.Qt import QSpacerItem from PyQt4.Qt import QToolButton from PyQt4.Qt import QIcon from PyQt4.Qt import QGroupBox from PyQt4.Qt import QSize from PyQt4.Qt import QGridLayout from PyQt4.Qt import QComboBox from PyQt4.Qt import QLineEdit from PyQt4.Qt import QSpinBox from PyQt4.Qt import QString from PyQt4.Qt import QToolTip from PyQt4.Qt import QApplication from PyQt4.Qt import SIGNAL from PyQt4.Qt import SLOT from command_support.generator_button_images import image0_data, image1_data, image2_data, image3_data, image4_data, image5_data, image6_data, image7_data from widgets.widget_controllers import CollapsibleGroupController_Qt, FloatLineeditController_Qt #e might be gotten from env instead... from utilities.debug import print_compact_traceback from utilities.qt4transition import qt4todo import foundation.env as env # for env.debug(); warning: some methods have a local variable which overrides this from utilities.icon_utilities import imagename_to_pixmap from tokenize import generate_tokens #bruce 080101 moved to toplevel, untested from utilities.parse_utils import parse_top, Whole #bruce 080101 moved to toplevel, untested # image uses -- we should rename them ####@@@@ ##self.heading_pixmap.setPixmap(self.image1) # should be: title_icon #### ##self.sponsor_btn.setPixmap(self.image2) ##self.done_btn.setIcon(QIcon(self.image3)) ##self.abort_btn.setIcon(QIcon(self.image4)) ##self.preview_btn.setIcon(QIcon(self.image5)) ##self.whatsthis_btn.setIcon(QIcon(self.image6)) ##self.nt_parameters_grpbtn.setIcon(QIcon(self.image7)) ## class parameter_dialog(QDialog): # was nanotube_dialog class parameter_dialog_or_frame: """ use as a pre-mixin before QDialog or QFrame """ ####@@@@ def __init__(self, parent = None, desc = None, name = None, modal = 0, fl = 0, env = None, type = "QDialog"): if env is None: import foundation.env as env # this is a little weird... probably it'll be ok, and logically it seems correct. self.desc = desc self.typ = type if type == "QDialog": QDialog.__init__(self,parent,name,modal,fl) elif type == "QTextEdit": QTextEdit.__init__(self, parent, name) elif type == "QFrame": QFrame.__init__(self,parent,name) else: print "don't know about type == %r" % (type,) self.image1 = QPixmap() self.image1.loadFromData(image1_data,"PNG") # should be: title_icon #### self.image3 = QPixmap() self.image3.loadFromData(image3_data,"PNG") self.image4 = QPixmap() self.image4.loadFromData(image4_data,"PNG") self.image5 = QPixmap() self.image5.loadFromData(image5_data,"PNG") self.image6 = QPixmap() self.image6.loadFromData(image6_data,"PNG") self.image7 = QPixmap() self.image7.loadFromData(image7_data,"PNG") self.image0 = QPixmap(image0_data) # should be: border_icon #### self.image2 = QPixmap(image2_data) # should be: sponsor_pixmap #### try: ####@@@@ title_icon_name = self.desc.options.get('title_icon') border_icon_name = self.desc.options.get('border_icon') if title_icon_name: self.image1 = imagename_to_pixmap(title_icon_name) ###@@@ pass icon_path ###@@@ import imagename_to_pixmap or use env function # or let that func itself be an arg, or have an env arg for it ###e rename it icon_name_to_pixmap, or find_icon? (the latter only if it's ok if it returns an iconset) ###e use iconset instead? if border_icon_name: self.image0 = imagename_to_pixmap(border_icon_name) except: print_compact_traceback("bug in icon-setting code, using fallback icons: ") pass if not name: self.setName("parameter_dialog_or_frame") ### ###k guess this will need: if type == 'QDialog' self.setIcon(self.image0) # should be: border_icon #### nanotube_dialogLayout = QVBoxLayout(self,0,0,"nanotube_dialogLayout") self.heading_frame = QFrame(self,"heading_frame") self.heading_frame.setPaletteBackgroundColor(QColor(122,122,122)) self.heading_frame.setFrameShape(QFrame.NoFrame) self.heading_frame.setFrameShadow(QFrame.Plain) heading_frameLayout = QHBoxLayout(self.heading_frame,0,3,"heading_frameLayout") self.heading_pixmap = QLabel(self.heading_frame,"heading_pixmap") self.heading_pixmap.setSizePolicy(QSizePolicy(QSizePolicy.Fixed,QSizePolicy.Fixed,0,0,self.heading_pixmap.sizePolicy().hasHeightForWidth())) self.heading_pixmap.setPixmap(self.image1) # should be: title_icon #### self.heading_pixmap.setScaledContents(1) heading_frameLayout.addWidget(self.heading_pixmap) self.heading_label = QLabel(self.heading_frame,"heading_label") self.heading_label.setPaletteForegroundColor(QColor(255,255,255)) heading_label_font = QFont(self.heading_label.font()) heading_label_font.setPointSize(12) heading_label_font.setBold(1) self.heading_label.setFont(heading_label_font) heading_frameLayout.addWidget(self.heading_label) nanotube_dialogLayout.addWidget(self.heading_frame) self.body_frame = QFrame(self,"body_frame") self.body_frame.setFrameShape(QFrame.StyledPanel) self.body_frame.setFrameShadow(QFrame.Raised) body_frameLayout = QVBoxLayout(self.body_frame,3,3,"body_frameLayout") self.sponsor_frame = QFrame(self.body_frame,"sponsor_frame") self.sponsor_frame.setPaletteBackgroundColor(QColor(255,255,255)) self.sponsor_frame.setFrameShape(QFrame.StyledPanel) self.sponsor_frame.setFrameShadow(QFrame.Raised) sponsor_frameLayout = QHBoxLayout(self.sponsor_frame,0,0,"sponsor_frameLayout") self.sponsor_btn = QPushButton(self.sponsor_frame,"sponsor_btn") self.sponsor_btn.setAutoDefault(0) #bruce 060703 bugfix self.sponsor_btn.setSizePolicy(QSizePolicy(QSizePolicy.Preferred,QSizePolicy.Preferred,0,0,self.sponsor_btn.sizePolicy().hasHeightForWidth())) self.sponsor_btn.setPaletteBackgroundColor(QColor(255,255,255)) self.sponsor_btn.setPixmap(self.image2) # should be: sponsor_pixmap #### [also we'll need to support >1 sponsor] self.sponsor_btn.setFlat(1) sponsor_frameLayout.addWidget(self.sponsor_btn) body_frameLayout.addWidget(self.sponsor_frame) layout59 = QHBoxLayout(None,0,6,"layout59") left_spacer = QSpacerItem(20,20,QSizePolicy.Expanding,QSizePolicy.Minimum) layout59.addItem(left_spacer) self.done_btn = QToolButton(self.body_frame,"done_btn") self.done_btn.setIcon(QIcon(self.image3)) layout59.addWidget(self.done_btn) self.abort_btn = QToolButton(self.body_frame,"abort_btn") self.abort_btn.setIcon(QIcon(self.image4)) layout59.addWidget(self.abort_btn) self.preview_btn = QToolButton(self.body_frame,"preview_btn") self.preview_btn.setIcon(QIcon(self.image5)) layout59.addWidget(self.preview_btn) self.whatsthis_btn = QToolButton(self.body_frame,"whatsthis_btn") self.whatsthis_btn.setIcon(QIcon(self.image6)) layout59.addWidget(self.whatsthis_btn) right_spacer = QSpacerItem(20,20,QSizePolicy.Expanding,QSizePolicy.Minimum) layout59.addItem(right_spacer) body_frameLayout.addLayout(layout59) self.groups = [] self.param_getters = {} # map from param name to get-function (which gets current value out of its widget or controller) for group_desc in self.desc.kids('group'): # == start parameters_grpbox ### this will differ for Windows style header_refs = [] # keep python refcounted refs to all objects we make (at least the ones pyuic stored in self attrs) self.parameters_grpbox = QGroupBox(self.body_frame,"parameters_grpbox") self.parameters_grpbox.setFrameShape(QGroupBox.StyledPanel) self.parameters_grpbox.setFrameShadow(QGroupBox.Sunken) self.parameters_grpbox.setMargin(0) self.parameters_grpbox.setColumnLayout(0,Qt.Vertical) self.parameters_grpbox.layout().setSpacing(1) self.parameters_grpbox.layout().setMargin(4) parameters_grpboxLayout = QVBoxLayout(self.parameters_grpbox.layout()) parameters_grpboxLayout.setAlignment(Qt.AlignTop) layout20 = QHBoxLayout(None,0,6,"layout20") self.nt_parameters_grpbtn = QPushButton(self.parameters_grpbox,"nt_parameters_grpbtn") self.nt_parameters_grpbtn.setSizePolicy(QSizePolicy(QSizePolicy.Minimum,QSizePolicy.Fixed,0,0,self.nt_parameters_grpbtn.sizePolicy().hasHeightForWidth())) self.nt_parameters_grpbtn.setMaximumSize(QSize(16,16)) self.nt_parameters_grpbtn.setAutoDefault(0) self.nt_parameters_grpbtn.setIcon(QIcon(self.image7)) ### not always right, but doesn't matter self.nt_parameters_grpbtn.setFlat(1) layout20.addWidget(self.nt_parameters_grpbtn) self.parameters_grpbox_label = QLabel(self.parameters_grpbox,"parameters_grpbox_label") self.parameters_grpbox_label.setSizePolicy(QSizePolicy(QSizePolicy.Preferred,QSizePolicy.Minimum,0,0,self.parameters_grpbox_label.sizePolicy().hasHeightForWidth())) self.parameters_grpbox_label.setAlignment(QLabel.AlignVCenter) layout20.addWidget(self.parameters_grpbox_label) gbx_spacer1 = QSpacerItem(67,16,QSizePolicy.Expanding,QSizePolicy.Minimum) layout20.addItem(gbx_spacer1) parameters_grpboxLayout.addLayout(layout20) nt_parameters_body_layout = QGridLayout(None,1,1,0,6,"nt_parameters_body_layout") ### what is 6 -- is it related to number of items??? # is it 6 in all the ones we got, but that could be a designer error so i better look it up sometime. # == start its kids # will use from above: self.parameters_grpbox, nt_parameters_body_layout nextrow = 0 # which row of the QGridLayout to start filling next (loop variable) hidethese = [] # set of objects to hide or show, when this group is closed or opened for param in group_desc.kids('parameter'): # param (a group subobj desc) is always a parameter, but we already plan to extend this beyond that, # so we redundantly test for this here. getter = None paramname = None # set these for use by uniform code at the end (e.g. for tooltips) editfield = None label = None if param.isa('parameter'): label = QLabel(self.parameters_grpbox,"members_label") label.setAlignment(QLabel.AlignVCenter | QLabel.AlignRight) nt_parameters_body_layout.addWidget(label,nextrow,0) hidethese.append(label) thisrow = nextrow nextrow += 1 #e following should be known in a place that knows the input language, not here paramname = param.options.get('name') or (param.args and param.args[0]) or "?" paramlabel = param.options.get('label') or paramname ##e wrong, label "" or none ought to be possible # QtGui.QApplication.translate(self.__class__.__name__, "xyz") label.setText(QtGui.QApplication.translate(self.__class__.__name__, paramlabel)) if param.isa('parameter', widget = 'combobox', type = ('str',None)): self.members_combox = QComboBox(0,self.parameters_grpbox,"members_combox") ###k what's 0? editfield = self.members_combox #### it probably needs a handler class, and then that could do this setup self.members_combox.clear() default = param.options.get('default', None) # None is not equal to any string thewidgetkid = param.kids('widget')[-1] # kluge; need to think what the desc method for this should be for item in thewidgetkid.kids('item'): itemval = item.args[0] itemtext = itemval self.members_combox.insertItem(QtGui.QApplication.translate(self.__class__.__name__, itemtext)) #k __tr ok?? if itemval == default: #k or itemtext? pass ##k i find no setItem in our py code, so not sure yet what to do for this. nt_parameters_body_layout.addWidget(self.members_combox,thisrow,1) hidethese.append(self.members_combox) getter = (lambda combobox = self.members_combox: str(combobox.currentText())) ##e due to __tr or non-str values, it might be better to use currentIndex and look it up in a table # (though whether __tr is good here might depend on what it's used for) elif param.isa('parameter', widget = ('lineedit', None), type = ('str',None)): # this covers explicit str|lineedit, and 3 default cases str, lineedit, neither. # (i.e. if you say parameter and nothing else, it's str lineedit by default.) self.length_linedit = QLineEdit(self.parameters_grpbox,"length_linedit") editfield = self.length_linedit nt_parameters_body_layout.addWidget(self.length_linedit,thisrow,1) hidethese.append(self.length_linedit) default = str(param.options.get('default', "")) self.length_linedit.setText(QtGui.QApplication.translate(self.__class__.__name__, default)) # __tr ok? getter = (lambda lineedit = self.length_linedit: str(lineedit.text())) elif param.isa('parameter', widget = ('lineedit', None), type = 'float'): self.length_linedit = QLineEdit(self.parameters_grpbox,"length_linedit") editfield = self.length_linedit nt_parameters_body_layout.addWidget(self.length_linedit,thisrow,1) hidethese.append(self.length_linedit) controller = FloatLineeditController_Qt(self, param, self.length_linedit) header_refs.append(controller) getter = controller.get_value elif param.isa('parameter', widget = ('spinbox', None), type = 'int') or \ param.isa('parameter', widget = ('spinbox'), type = None): self.chirality_N_spinbox = QSpinBox(self.parameters_grpbox,"chirality_N_spinbox") # was chirality_m_spinbox, now chirality_N_spinbox editfield = self.chirality_N_spinbox ### seems like Qt defaults for min and max are 0,100 -- way too small a range! if param.options.has_key('min') or 1: self.chirality_N_spinbox.setMinimum(param.options.get('min', -999999999)) # was 0 if param.options.has_key('max') or 1: self.chirality_N_spinbox.setMaximum(param.options.get('max', +999999999)) # wasn't in egcode, but needed self.chirality_N_spinbox.setValue(param.options.get('default', 0)) # was 5 ##e note: i suspect this default 0 should come from something that knows this desc grammar. suffix = param.options.get('suffix', '') if suffix: self.chirality_N_spinbox.setSuffix(QtGui.QApplication.translate(self.__class__.__name__, suffix)) else: self.chirality_N_spinbox.setSuffix(QString.null) # probably not needed nt_parameters_body_layout.addWidget(self.chirality_N_spinbox,thisrow,1) hidethese.append(self.chirality_N_spinbox) getter = self.chirality_N_spinbox.value # note: it also has .text, which includes suffix else: print "didn't match:",param ###e improve this # things done the same way for all kinds of param-editing widgets if 1: #bruce 060703 moved this down here, as bugfix # set tooltip (same one for editfield and label) tooltip = param.options.get('tooltip', '') ###e do it for more kinds of params; share the code somehow; do it in controller, or setup-aid? ###k QToolTip appropriateness; tooltip option might be entirely untested if tooltip and label: QToolTip.add(label, QtGui.QApplication.translate(self.__class__.__name__, tooltip)) if tooltip and editfield: QToolTip.add(editfield, QtGui.QApplication.translate(self.__class__.__name__, tooltip)) ##k ok?? review once not all params have same-row labels. if getter and paramname and paramname != '?': self.param_getters[paramname] = getter ### also bind these params to actions... continue # next param header_refs.extend( [self.parameters_grpbox, self.nt_parameters_grpbtn, self.parameters_grpbox_label] ) # now create the logic/control object for the group group = CollapsibleGroupController_Qt(self, group_desc, header_refs, hidethese, self.nt_parameters_grpbtn) ### maybe ask env for the class to use for this? self.groups.append(group) ### needed?? only for scanning the params, AFAIK -- oh, and to maintain a python refcount. # from languageChange: if 1: # i don't know if these are needed: self.parameters_grpbox.setTitle(QString.null) self.nt_parameters_grpbtn.setText(QString.null) self.parameters_grpbox_label.setText(QtGui.QApplication.translate(self.__class__.__name__, group_desc.args[0])) # was "Nanotube Parameters" ##e note that it's questionable in the syntax design for this property of a group (overall group label) # to be in that position (desc arg 0). # == end its kids parameters_grpboxLayout.addLayout(nt_parameters_body_layout) body_frameLayout.addWidget(self.parameters_grpbox) # == end parameters groupbox continue # next group nanotube_dialogLayout.addWidget(self.body_frame) spacer14 = QSpacerItem(20,20,QSizePolicy.Minimum,QSizePolicy.Expanding) nanotube_dialogLayout.addItem(spacer14) layout42 = QHBoxLayout(None,4,6,"layout42") btm_spacer = QSpacerItem(59,20,QSizePolicy.Expanding,QSizePolicy.Minimum) layout42.addItem(btm_spacer) self.cancel_btn = QPushButton(self,"cancel_btn") self.cancel_btn.setAutoDefault(0) #bruce 060703 bugfix layout42.addWidget(self.cancel_btn) self.ok_btn = QPushButton(self,"ok_btn") self.ok_btn.setAutoDefault(0) #bruce 060703 bugfix layout42.addWidget(self.ok_btn) nanotube_dialogLayout.addLayout(layout42) self.languageChange() self.resize(QSize(246,618).expandedTo(self.minimumSizeHint())) ### this size will need to be adjusted (guess -- it's only place overall size is set) qt4todo('self.clearWState(Qt.WState_Polished)') ## self.connect(self.nt_parameters_grpbtn,SIGNAL("clicked()"),self.toggle_nt_parameters_grpbtn) #### # new: for button, methodname in ((self.sponsor_btn, 'do_sponsor_btn'), #e generalize to more than one sponsor button (self.done_btn, 'do_done_btn'), (self.abort_btn, 'do_abort_btn'), (self.preview_btn, 'do_preview_btn'), (self.whatsthis_btn, 'do_whatsthis_btn'), (self.cancel_btn, 'do_cancel_btn'), (self.ok_btn, 'do_ok_btn')): if hasattr(self, methodname): self.connect(button, SIGNAL("clicked()"), getattr(self, methodname)) return def languageChange(self): opts = self.desc.option_attrs self.setCaption(QtGui.QApplication.translate(self.__class__.__name__, opts.caption)) # was "Nanotube" self.heading_label.setText(QtGui.QApplication.translate(self.__class__.__name__, opts.title)) # was "Nanotube" self.sponsor_btn.setText(QString.null) self.done_btn.setText(QString.null) QToolTip.add(self.done_btn,QtGui.QApplication.translate(self.__class__.__name__, "Done")) self.abort_btn.setText(QString.null) QToolTip.add(self.abort_btn,QtGui.QApplication.translate(self.__class__.__name__, "Cancel")) self.preview_btn.setText(QString.null) QToolTip.add(self.preview_btn,QtGui.QApplication.translate(self.__class__.__name__, "Preview")) self.whatsthis_btn.setText(QString.null) QToolTip.add(self.whatsthis_btn,QtGui.QApplication.translate(self.__class__.__name__, "What's This Help")) ### move these up: ## if 0: ## self.parameters_grpbox.setTitle(QString.null) ## self.nt_parameters_grpbtn.setText(QString.null) ## self.parameters_grpbox_label.setText(QtGui.QApplication.translate(self.__class__.__name__, "Nanotube Parameters")) ## if 0: ## self.members_label.setText(QtGui.QApplication.translate(self.__class__.__name__, "Members :")) ## self.length_label.setText(QtGui.QApplication.translate(self.__class__.__name__, "Length :")) ## self.chirality_n_label.setText(QtGui.QApplication.translate(self.__class__.__name__, "Chirality (n) :")) ## self.members_combox.clear() ## self.members_combox.insertItem(QtGui.QApplication.translate(self.__class__.__name__, "C - C")) ## self.members_combox.insertItem(QtGui.QApplication.translate(self.__class__.__name__, "B - N")) ## self.length_linedit.setText(QtGui.QApplication.translate(self.__class__.__name__, "20.0 A")) ## self.chirality_N_spinbox.setSuffix(QString.null) self.cancel_btn.setText(QtGui.QApplication.translate(self.__class__.__name__, "Cancel")) self.ok_btn.setText(QtGui.QApplication.translate(self.__class__.__name__, "OK")) return pass # end of class parameter_dialog_or_frame -- maybe it should be renamed # == class ParameterDialogBase(parameter_dialog_or_frame): """ #doc """ controller = None def __init__(self, parent, description, env = None): """ If description is a string, it should be a filename. Or (someday) it could be a ThingData, or (someday) maybe a menu_spec_like python list. This initializes the dialog, a Qt widget (not sure if it will be a widget when we have a "pane" option -- most likely we'll use some other class for that, not this one with an option). But it doesn't show it or connect it to a controller. """ desc = get_description(description) # might raise exceptions on e.g. syntax errors in description file parameter_dialog_or_frame.__init__(self, parent, desc, env = env, type = self.type) # self.type is a subclass-constant # sets self.desc (buttons might want to use it) def set_controller(self, controller): if self.controller: self.controller.forget_dialog(self) self.controller = controller if self.controller: self.controller.meet_dialog(self) return def set_defaults(self, dict1): if env.debug(): print "debug: set_defaults is nim" ####k is it even sensible w/o a controller being involved?? return def show(self): if self.controller: self.controller.setSponsor() if self.typ == "QDialog": QDialog.show(self) elif self.typ == "QTextEdit": QTextEdit.show(self) elif self.typ == "QFrame": QFrame.show(self) else: print "don't know about self.typ == %r" % (self.typ,) # bindings for the buttons -- delegate them to controller if we have one. def do_sponsor_btn(self): ## print "do_sponsor_btn: delegating" # does SponsorableMixin have something like sponsor_btn_clicked? yes, under that name and open_sponsor_homepage. if self.controller: self.controller.sponsor_btn_clicked() def do_done_btn(self): ## print "do_done_btn: delegating" if self.controller: self.controller.done_btn_clicked() def do_abort_btn(self): ## print "do_abort_btn: delegating" if self.controller: self.controller.cancel_btn_clicked() #bruce 080815 revised (guess), was abort_btn_clicked() def do_preview_btn(self): ## print "do_preview_btn: delegating" if self.controller: self.controller.preview_btn_clicked() def do_whatsthis_btn(self): ## print "do_whatsthis_btn: delegating" if self.controller: self.controller.whatsthis_btn_clicked() def do_cancel_btn(self): ## print "do_cancel_btn: delegating" if self.controller: self.controller.cancel_btn_clicked() def close(self, e=None): ## print "close: delegating" res = True # fixing bug 2138: Qt wants the return value of .close to be of the correct type, apparently boolean; # it may mean whether to really close (guess) [bruce 060719] if self.controller: res = self.controller.close() return res def do_ok_btn(self): ## print "do_ok_btn: printing then delegating" if 0: print "printing param values" getters = self.param_getters.items() getters.sort() for paramname, getter in getters: try: print "param %s = %r" % (paramname, getter()) except: print_compact_traceback("exception trying to get param %s: " % (paramname,)) if self.controller: self.controller.ok_btn_clicked() #e might need to intercept accept, reject and depend on type == 'QDialog' -- or, do in subclass pass class ParameterDialog( ParameterDialogBase, QDialog): type = 'QDialog' pass class ParameterPane( ParameterDialogBase, QFrame): type = 'QFrame' def accept(self): pass def reject(self): pass pass class ParameterPaneTextEditTest( ParameterDialogBase, QTextEdit): ##k see if this works any better type = 'QTextEdit' def accept(self): pass def reject(self): pass pass # == debug_parse = False def get_description(filename): """ #doc... For now, only the filename option is supported. Someday, support the other ones mentioned in our caller, ParameterDialog.__init__.__doc__. """ assert type(filename) == type(""), "get_description only supports filenames for now (and not even unicode filenames, btw)" file = open(filename, 'rU') gentok = generate_tokens(file.readline) res, newrest = parse_top(Whole, list(gentok)) if debug_parse: print len(` res `), 'chars in res' #3924 ## print res # might be an error message if newrest and debug_parse: # boolean test, since normal value is [] print "res is", res # assume it is an error message print "newrest is", newrest print "res[0].pprint() :" print res[0].pprint() #k if debug_parse: print "parse done" desc = res[0] #k class ThingData in parse_utils - move to another file? it stays with the toplevel grammar... return desc # from get_description # == TEST CODE, though some might become real if __name__ == '__main__': # this has the parsing calls class NTdialog(parameter_dialog_or_frame, QDialog): # in real life this will be something which delegates to controller methods def __init__(self, parent = None, desc = None): parameter_dialog_or_frame.__init__(self, parent, desc) # sets self.desc (buttons might want to use it) def do_sponsor_btn(self): print "do_sponsor_btn: nim" def do_done_btn(self): print "do_done_btn: nim" def do_abort_btn(self): print "do_abort_btn: nim" def do_preview_btn(self): print "do_preview_btn: nim" def do_whatsthis_btn(self): print "do_whatsthis_btn: nim" def do_cancel_btn(self): print "do_cancel_btn: nim" def do_ok_btn(self): print "do_ok_btn: printing param values" getters = self.param_getters.items() getters.sort() for paramname, getter in getters: try: print "param %s = %r" % (paramname, getter()) except: print_compact_traceback("exception trying to get param %s: " % (paramname,)) print pass import sys a = QApplication(sys.argv) ## filename = "testui.txt" filename = "../plugins/CoNTub/HJ-params.desc" desc = get_description(filename) parent = None # should be win or app? w = NTdialog(parent, desc) ### also, env to supply prefs, state to control w.show() a.connect(a, SIGNAL('lastWindowClosed()'), a, SLOT('quit()')) print "about to exec_" a.exec_() print "exiting, test done" # end
NanoCAD-master
cad/src/command_support/ParameterDialog.py
NanoCAD-master
cad/src/command_support/__init__.py
# Copyright 2004-2008 Nanorex, Inc. See LICENSE file for details. """ modes.py -- provides basicMode, the superclass for old modes which haven't yet been split into subclasses of Command and GraphicsMode. @author: Bruce @version: $Id$ @copyright: 2004-2008 Nanorex, Inc. See LICENSE file for details. History: (For earlier history see modes.py docstring before the split of 071009.) bruce 050507 moved Hydrogenate and Dehydrogenate into another file bruce 071009 moved modeMixin [now CommandSequencer] into its own file bruce 071009 split modes.py into Command.py and GraphicsMode.py, leaving only temporary compatibility mixins in modes.py. TODO: Sometime, separate public (API) and private methods within each of Command.py and GraphicsMode.py (see their module docstrings for details). Refactor the subclasses of basicMode, then get rid of it. Same with the other classes in this file. Notes on how we'll do that [later: some of this has been done]: At some point soon we'll have one currentCommand attr in glpane, later moved to a separate object, the command sequencer. And glpane.mode will be deprecated, but glpane.graphicsMode will refer to a derived object which the current command can return, perhaps self (for old code) or not (for new code). (The null object we store in there can then also be a joint or separate object, independently from everything else. For now it's still called nullMode (and it's created and stored by CommandSequencer) but that will be revised.) But that doesn't remove the fact that generators (maybe even when based on EditCommand [update 071228 - this issue was recently fixed for EditCommand) still sort of treat their PM as a guest in some mode and as the "current command". So "make generators their own command" will be a refactoring we need soon, perhaps before "split old modes into their Command and GraphicsMode pieces". [update 071228 - Ninad was able to split them before fixing this, and has then fixed this for EditCommand, though not yet for GeneratorBaseClass.] But when we "make generators their own command", what GM will they use? We might have to split one out of the old modes for that purpose even though it can't yet replace the ones it splits out of. [update 071228 - they can probably use one of Select*_GraphicsMode since those are all split now.] """ from command_support.Command import anyCommand, nullCommand, basicCommand from command_support.GraphicsMode import nullGraphicsMode, basicGraphicsMode from command_support.GraphicsMode_API import GraphicsMode_API # == ### TODO: fill these in, especially __init__ methods; remove the ones we don't need class anyMode(anyCommand, GraphicsMode_API): # used only in this file (where it provides some default methods and attrs # to the classes here, but surely redundantly with their other # superclasses, so it's probably not needed), # and in old comments in other files. pass class nullMode(nullCommand, nullGraphicsMode, anyMode): # used in CommandSequencer and test_commands # see discussion in this module's docstring # duplicated properties in nullMode and basicMode, except for debug prints: def __get_command(self): print "\n * * * nullMode.__get_command, should probably never happen\n" # happens?? never yet seen, should probably never happen return self command = property(__get_command) def __get_graphicsMode(self): # print "\n * * * nullMode.__get_graphicsMode, remove when seen often\n" # should happen often, did happen at least once; # happens a few times when you enter Extrude return self graphicsMode = property(__get_graphicsMode) pass class basicMode(basicCommand, basicGraphicsMode, anyMode): """ Compatibility mixture of Command and GraphicsMode for old code which uses one object for both. """ def __init__(self, commandSequencer): glpane = commandSequencer.assy.glpane #bruce 080813 revised this basicCommand.__init__(self, commandSequencer) basicGraphicsMode.__init__(self, glpane) # no need to pass self as command, due to property below return # duplicated properties in nullMode and basicMode, except for debug prints: def __get_command(self): ## print "basicMode.__get_command, remove when seen" # should happen often, and does return self command = property(__get_command) def __get_graphicsMode(self): ## print "basicMode.__get_graphicsMode, remove when seen" # should happen often, and does return self graphicsMode = property(__get_graphicsMode) pass # end of class basicMode # end
NanoCAD-master
cad/src/command_support/modes.py
# -*- coding: utf-8 -*- # Copyright 2005-2007 Nanorex, Inc. See LICENSE file for details. # Form implementation generated from reading ui file 'JigPropDialog.ui' # # Created: Wed Sep 20 07:56:23 2006 # by: PyQt4 UI code generator 4.0.1 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui class Ui_JigPropDialog(object): def setupUi(self, JigPropDialog): JigPropDialog.setObjectName("JigPropDialog") JigPropDialog.resize(QtCore.QSize(QtCore.QRect(0,0,245,145).size()).expandedTo(JigPropDialog.minimumSizeHint())) JigPropDialog.setSizeGripEnabled(True) self.vboxlayout = QtGui.QVBoxLayout(JigPropDialog) self.vboxlayout.setMargin(11) self.vboxlayout.setSpacing(6) self.vboxlayout.setObjectName("vboxlayout") self.hboxlayout = QtGui.QHBoxLayout() self.hboxlayout.setMargin(0) self.hboxlayout.setSpacing(6) self.hboxlayout.setObjectName("hboxlayout") self.vboxlayout1 = QtGui.QVBoxLayout() self.vboxlayout1.setMargin(0) self.vboxlayout1.setSpacing(6) self.vboxlayout1.setObjectName("vboxlayout1") self.nameTextLabel = QtGui.QLabel(JigPropDialog) self.nameTextLabel.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.nameTextLabel.setObjectName("nameTextLabel") self.vboxlayout1.addWidget(self.nameTextLabel) self.colorTextLabel = QtGui.QLabel(JigPropDialog) self.colorTextLabel.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter) self.colorTextLabel.setObjectName("colorTextLabel") self.vboxlayout1.addWidget(self.colorTextLabel) self.hboxlayout.addLayout(self.vboxlayout1) self.vboxlayout2 = QtGui.QVBoxLayout() self.vboxlayout2.setMargin(0) self.vboxlayout2.setSpacing(6) self.vboxlayout2.setObjectName("vboxlayout2") self.nameLineEdit = QtGui.QLineEdit(JigPropDialog) self.nameLineEdit.setEnabled(True) self.nameLineEdit.setObjectName("nameLineEdit") self.vboxlayout2.addWidget(self.nameLineEdit) self.hboxlayout1 = QtGui.QHBoxLayout() self.hboxlayout1.setMargin(0) self.hboxlayout1.setSpacing(6) self.hboxlayout1.setObjectName("hboxlayout1") self.hboxlayout2 = QtGui.QHBoxLayout() self.hboxlayout2.setMargin(0) self.hboxlayout2.setSpacing(6) self.hboxlayout2.setObjectName("hboxlayout2") self.jig_color_pixmap = QtGui.QLabel(JigPropDialog) self.jig_color_pixmap.setMinimumSize(QtCore.QSize(40,0)) self.jig_color_pixmap.setScaledContents(True) self.jig_color_pixmap.setObjectName("jig_color_pixmap") self.hboxlayout2.addWidget(self.jig_color_pixmap) self.choose_color_btn = QtGui.QPushButton(JigPropDialog) self.choose_color_btn.setEnabled(True) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Policy(5),QtGui.QSizePolicy.Policy(0)) sizePolicy.setHorizontalStretch(1) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.choose_color_btn.sizePolicy().hasHeightForWidth()) self.choose_color_btn.setSizePolicy(sizePolicy) self.choose_color_btn.setObjectName("choose_color_btn") self.hboxlayout2.addWidget(self.choose_color_btn) self.hboxlayout1.addLayout(self.hboxlayout2) spacerItem = QtGui.QSpacerItem(40,20,QtGui.QSizePolicy.Expanding,QtGui.QSizePolicy.Minimum) self.hboxlayout1.addItem(spacerItem) self.vboxlayout2.addLayout(self.hboxlayout1) self.hboxlayout.addLayout(self.vboxlayout2) self.vboxlayout.addLayout(self.hboxlayout) spacerItem1 = QtGui.QSpacerItem(20,20,QtGui.QSizePolicy.Minimum,QtGui.QSizePolicy.Expanding) self.vboxlayout.addItem(spacerItem1) self.hboxlayout3 = QtGui.QHBoxLayout() self.hboxlayout3.setMargin(0) self.hboxlayout3.setSpacing(6) self.hboxlayout3.setObjectName("hboxlayout3") spacerItem2 = QtGui.QSpacerItem(40,20,QtGui.QSizePolicy.Expanding,QtGui.QSizePolicy.Minimum) self.hboxlayout3.addItem(spacerItem2) self.ok_btn = QtGui.QPushButton(JigPropDialog) self.ok_btn.setAutoDefault(True) self.ok_btn.setDefault(True) self.ok_btn.setObjectName("ok_btn") self.hboxlayout3.addWidget(self.ok_btn) self.cancel_btn = QtGui.QPushButton(JigPropDialog) self.cancel_btn.setAutoDefault(True) self.cancel_btn.setDefault(False) self.cancel_btn.setObjectName("cancel_btn") self.hboxlayout3.addWidget(self.cancel_btn) self.vboxlayout.addLayout(self.hboxlayout3) self.retranslateUi(JigPropDialog) QtCore.QObject.connect(self.cancel_btn,QtCore.SIGNAL("clicked()"),JigPropDialog.reject) QtCore.QObject.connect(self.ok_btn,QtCore.SIGNAL("clicked()"),JigPropDialog.accept) QtCore.QMetaObject.connectSlotsByName(JigPropDialog) JigPropDialog.setTabOrder(self.nameLineEdit,self.choose_color_btn) JigPropDialog.setTabOrder(self.choose_color_btn,self.ok_btn) JigPropDialog.setTabOrder(self.ok_btn,self.cancel_btn) def retranslateUi(self, JigPropDialog): JigPropDialog.setWindowTitle(QtGui.QApplication.translate("JigPropDialog", "Jig Properties", None, QtGui.QApplication.UnicodeUTF8)) self.nameTextLabel.setText(QtGui.QApplication.translate("JigPropDialog", "Name:", None, QtGui.QApplication.UnicodeUTF8)) self.colorTextLabel.setText(QtGui.QApplication.translate("JigPropDialog", "Color:", None, QtGui.QApplication.UnicodeUTF8)) self.choose_color_btn.setToolTip(QtGui.QApplication.translate("JigPropDialog", "Change Color", None, QtGui.QApplication.UnicodeUTF8)) self.choose_color_btn.setText(QtGui.QApplication.translate("JigPropDialog", "Choose...", None, QtGui.QApplication.UnicodeUTF8)) self.ok_btn.setText(QtGui.QApplication.translate("JigPropDialog", "&OK", None, QtGui.QApplication.UnicodeUTF8)) self.ok_btn.setShortcut(QtGui.QApplication.translate("JigPropDialog", "Alt+O", None, QtGui.QApplication.UnicodeUTF8)) self.cancel_btn.setText(QtGui.QApplication.translate("JigPropDialog", "&Cancel", None, QtGui.QApplication.UnicodeUTF8)) self.cancel_btn.setShortcut(QtGui.QApplication.translate("JigPropDialog", "Alt+C", None, QtGui.QApplication.UnicodeUTF8))
NanoCAD-master
cad/src/command_support/JigPropDialog.py
# Copyright 2008 Nanorex, Inc. See LICENSE file for details. """ @author: Ninad @copyright: 2008 Nanorex, Inc. See LICENSE file for details. @version:$Id$ History: 2008-05-13 Created TODO: 2008-05-13 This is an initial implementation subjected to heavy revision. Initial purpose is just to RESIZE given structures (of same type) together. Can be extended in future but needs refactoring then. - This class assumes attr currentStruct for the current command and also assumes a method currentStruct.getAxisEndPoints! Note that this will be true for currentStruct = DnaSegment, CntSegment BUT NOT FOR DnaStrand so when we support resizing multiple dnastrands, this must be refactored. - Created to initially support resizing multiple dna segments. Can be extended for other commands such as strand, nanotube resizing. This class assumes certain things such as the struct being edited will have resize handles. If it is not the case, refactoring is needed to move methods such as self.updateAverageEndPoints() to the subclasses. - Need safety features to make sure that structures provided by the list of structures (in self._structList) are of valid structure type (e.g. if you are resizing multiple Dnasegments, self._structList must contain all instances of DnaSegment only. """ from geometry.VQT import V class EditCommand_StructureList: def __init__(self, editCommand, structList = ()): self.editCommand = editCommand self._structList = [] self.setStructList(structList = structList) #self.end1 , self.end2 are the average endpoints calculated using #endpoints of structs within structList. self.end1 = None self.end2 = None #TODO: revise the following. #@see self._getAverageEndPoints() where these lists are being used. #@see: comments in DnaSegmentList.getAxisEndAtomAtPosition() self.endPoints_1 = [] self.endPoints_2 = [] self.endPointsDict = {} #unused as of 2008-05-13 (used in some commented #out code) self.updateAverageEndPoints() def parent_node_of_class(self, clas): """ Returns parent node of the class <clas> for the 'currentStructure' of self's editcommand being edited. If there is no currentStructure, it returns the parent node of specified class of the 'first structure' in the self._structList. """ if self.editCommand.currentStruct: if self.editCommand.currentStruct.killed(): return None return self.editCommand.currentStruct.parent_node_of_class(clas) if not self._structList: return None firstStruct = self._structList[0] if firstStruct is None: return None if firstStruct.killed(): return None return firstStruct.parent_node_of_class(clas) def killed(self): """ Always returns False as of 2008-05-16. There is no UI to 'delete' this list object. (its internal) This method is implemented just to handle the calls in , for example, EditCommand.hasValidStructure() @see: MultipleDnaSegment_EditCommand.hasValidStructure() """ return False def isEmpty(self): """ Returns True if if the self._sturctList is empty. """ if len(self._structList) == 0: return True return False def updateStructList(self): """ Update the structure list , removing the invalid items in the structure @see:MultipleDnaSegmentResize_PropertyManager.model_changed() @see: self.getstructList() """ #@TODO: Should this always be called in self.getStructList()??? But that #could be SLOW because that method gets called too often by #the edit command's graphics mode. def func(struct): if struct is not None and not struct.killed(): if not struct.isEmpty(): return True return False new_list = filter( lambda struct: func(struct) , self._structList ) if len(new_list) != len(self._structList): self._structList = new_list def getStructList(self): """ Returns the list of structures being edited together. @see: MultipleDnaSegmentResize_graphicsMode._drawHandles() """ #Should we call self.updateStructList() here?? But that could be #too slow because this method is called quite often in the #graphics mode.draw of the command return self._structList def setStructList(self, structList = () ): """ Replaces the list of structures (self._structList) with the given one. @param structList: List containing the structures to be edited at once This list will replace the existing self._structList @type: list @see: MultipleSegmentResize_EditCommand.setStructList() (calls this method. ) """ self._structList = list(structList) self.updateAverageEndPoints() def addToStructList(self, struct): """ Add the given structure to the list of structures being edited together. @param struct: Structure to be added to the self._structList """ if struct is not None and not struct in self._structList: self._structList.append(struct) self.updateAverageEndPoints() def removeFromStructList(self, struct): """ Remove the given structure from the list of structures being edited together. @param struct: Structure to be removed from the self._structList """ if struct in self._structList: self._structList.remove(struct) self.updateAverageEndPoints() def updateAverageEndPoints(self): """ Update self's average end points. """ #(may need refactoring in future) self.end1, self.end2 = self._getAverageEndPoints() def _getAverageEndPoints(self): """ Subclasses should override this method. Default implementation assumes an attr (method) getAxisEndPoints for structures in self._structList This is not True for some structures such as DnaStrand. """ endPoint1 = V(0.0, 0.0, 0.0) endPoint2 = V(0.0, 0.0, 0.0) n1 = 0 n2 = 0 self.endPoints_1 = [] self.endPoints_2 = [] self.endPointsDict = {} for struct in self._structList: end1, end2 = struct.getAxisEndPoints() if end1 is not None: endPoint1 += end1 self.endPoints_1.append(end1) if end2 is not None: endPoint2 += end2 n2 += 1 self.endPoints_2.append(end2) n1 = len(self.endPoints_1) n2 = len(self.endPoints_2) if n1 > 0: endPoint1 /= n1 self.endPoints_1.append(endPoint1) ##self.endPointsDict[endPoint1] = self.endPoints_1 if n2 > 0: endPoint2 /= n2 self.endPoints_2.append(endPoint2) ##self.endPointsDict[endPoint2] = self.endPoints_2 return (endPoint1, endPoint2) def getAxisEndPoints(self): """ @TODO: Revise/ Refactor this. This needs to be implemented in a subclass rather than here because not all structures that this class will support have an attr getAxisEndPoints. (e.g. DnaStrand). (although several strutures will have this attr) """ currentStruct = self.editCommand.currentStruct if currentStruct and hasattr(currentStruct, 'getAxisEndPoints'): return self.editCommand.currentStruct.getAxisEndPoints() self.updateAverageEndPoints() return (self.end1, self.end2) def getProps(self): """ Returns the properties of editCommand's currentStruct. If there is no currentStruct, it uses the firstStruct in self._structList """ if self.editCommand.currentStruct: return self.editCommand.currentStruct.getProps() if not self._structList: return () firstStruct = self._structList[0] if firstStruct is None: return () return firstStruct.getProps() def setProps(self, props): """ TODO: expand this method """ pass
NanoCAD-master
cad/src/command_support/EditCommand_StructureList.py
# Copyright 2004-2007 Nanorex, Inc. See LICENSE file for details. """ JigProp.py $Id$ History: Original code from GroundProps.py and cleaned up by Mark. """ __author__ = "Mark" from PyQt4.Qt import QDialog from PyQt4.Qt import SIGNAL from PyQt4.Qt import QColorDialog from utilities.icon_utilities import geticon from command_support.JigPropDialog import Ui_JigPropDialog from widgets.widget_helpers import RGBf_to_QColor, QColor_to_RGBf from widgets.widget_helpers import get_widget_with_color_palette # This Jig Property dialog and its slot methods can be used for any simple jig # that has only a name and a color attribute changable by the user. # It is currently used by both the Anchor and AtomSet jig. Mark 050928. class JigProp(QDialog, Ui_JigPropDialog): """ This Jig Property dialog and its slot methods can be used for any simple jig that has only a name and a color attribute changable by the user. It is currently used by both the Anchor and AtomSet jig. """ def __init__(self, jig, glpane): """ Constructor for the class JigProp. @param jig: the jig whose property dialog will be shown @type jig: L{Jig} @param glpane: GLPane object @type glpane: L{GLPane} """ QDialog.__init__(self) self.setupUi(self) self.connect(self.cancel_btn, SIGNAL("clicked()"), self.reject) self.connect(self.ok_btn, SIGNAL("clicked()"), self.accept) self.connect(self.choose_color_btn, SIGNAL("clicked()"), self.change_jig_color) # Set the dialog's border icon and caption based on the jig type. jigtype_name = jig.__class__.__name__ # Fixes bug 1208. mark 060112. self.setWindowIcon(geticon("ui/border/"+ jigtype_name)) self.setWindowTitle(jigtype_name + " Properties") self.jig = jig self.glpane = glpane def setup(self): """ Initializes the dialog and it's widgets """ # Save the jig's attributes in case of Cancel. self.jig_attrs = self.jig.copyable_attrs_dict() # Jig color # Used as default color by Color Chooser self.jig_QColor = RGBf_to_QColor(self.jig.normcolor) self.jig_color_pixmap = get_widget_with_color_palette( self.jig_color_pixmap, self.jig_QColor) # Jig name self.nameLineEdit.setText(self.jig.name) def change_jig_color(self): """ Slot method to change the jig's color. """ color = QColorDialog.getColor(self.jig_QColor, self) if color.isValid(): self.jig_QColor = color self.jig_color_pixmap = get_widget_with_color_palette( self.jig_color_pixmap, self.jig_QColor) self.jig.color = self.jig.normcolor = QColor_to_RGBf(color) self.glpane.gl_update() def accept(self): """ Slot for the 'OK' button """ self.jig.try_rename(self.nameLineEdit.text()) self.jig.assy.w.win_update() # Update model tree self.jig.assy.changed() QDialog.accept(self) def reject(self): """ Slot for the 'Cancel' button """ self.jig.attr_update(self.jig_attrs) # Restore attributes of the jig. self.glpane.gl_update() QDialog.reject(self)
NanoCAD-master
cad/src/command_support/JigProp.py
# Copyright 2004-2009 Nanorex, Inc. See LICENSE file for details. """ GraphicsMode.py -- base class for "graphics modes" (display and GLPane event handling) @version: $Id$ @copyright: 2004-2009 Nanorex, Inc. See LICENSE file for details. History: bruce 071009 split modes.py into Command.py and GraphicsMode.py, leaving only temporary compatibility mixins in modes.py. For prior history see modes.py docstring before the split. TODO: A lot of methods in class GraphicsMode are private helper methods, available to subclasses and/or to default implems of public methods, but are not yet named as private or otherwise distinguished from API methods. We should turn anyGraphicsMode into GraphicsMode_API [done as of 071028], add all the API methods to it, and rename the other methods in class GraphicsMode to look private. """ import math # just for pi from Numeric import exp from PyQt4.Qt import Qt from PyQt4.Qt import QMenu from geometry.VQT import V, Q, vlen, norm, planeXline, ptonline from graphics.drawing.CS_draw_primitives import drawline from graphics.drawing.CS_draw_primitives import drawTag from graphics.drawing.drawers import drawOriginAsSmallAxis from graphics.drawing.drawers import drawaxes, drawPointOfViewAxes from graphics.drawing.drawers import drawrectangle from utilities.debug import print_compact_traceback, print_compact_stack from utilities import debug_flags import foundation.env as env from graphics.behaviors.shape import get_selCurve_color from utilities.constants import SELSHAPE_RECT from utilities.constants import yellow from utilities.prefs_constants import zoomInAboutScreenCenter_prefs_key from utilities.prefs_constants import zoomOutAboutScreenCenter_prefs_key from utilities.prefs_constants import displayOriginAxis_prefs_key from utilities.prefs_constants import displayOriginAsSmallAxis_prefs_key from utilities.prefs_constants import displayPOVAxis_prefs_key from utilities.prefs_constants import displayConfirmationCorner_prefs_key from utilities.prefs_constants import panArrowKeysDirection_prefs_key from model.chem import Atom from model.bonds import Bond from foundation.Utility import Node import time from command_support.GraphicsMode_API import GraphicsMode_API # == class nullGraphicsMode(GraphicsMode_API): """ do-nothing GraphicsMode (for internal use only) to avoid crashes in case of certain bugs during transition between GraphicsModes """ # needs no __init__ method; constructor takes no arguments # WARNING: the next two methods are similar in all "null objects", of which # we have nullCommand and nullGraphicsMode so far. They ought to be moved # into a common nullObjectMixin for all kinds of "null objects". [bruce 071009] def noop_method(self, *args, **kws): if debug_flags.atom_debug: print "fyi: atom_debug: nullGraphicsMode noop method called -- probably ok; ignored" return None #e print a warning? def __getattr__(self, attr): # in class nullGraphicsMode # note: this is not inherited by other GraphicsMode classes, # since we are not their superclass if not attr.startswith('_'): if debug_flags.atom_debug: print "fyi: atom_debug: nullGraphicsMode.__getattr__(%r) -- probably ok; returned noop method" % attr return self.noop_method else: raise AttributeError, attr #e args? # GraphicsMode-specific null methods def setDrawTags(self, *args, **kws): # This would not be needed here if calls were fixed, # as commented on them; thus, not part of GraphicsMode_API # [bruce 081002 comment] pass pass # end of class nullGraphicsMode # == class basicGraphicsMode(GraphicsMode_API): """ Common code between class GraphicsMode (see its docstring) and old-code-compatibility class basicMode. Will be merged with class GraphicsMode (keeping that one's name) when basicMode is no longer needed. """ # Initialize timeAtLastWheelEvent to None. It is assigned # in self.wheelEvent and used in SelectChunks_GraphicsMode.bareMotion # to disable highlighting briefly after any mouse wheel event. # Motivation: when user is scrolling the wheel to zoom in or out, # and at the same time the mouse moves slightly, we want to make sure # that the object under the cursor is not highlighted (mainly for # performance reasons). timeAtLastWheelEvent = None # NOTE: subclasses will have to make self.command point to the command # object (a running command which owns the graphics mode object). # This is done differently in different subclasses, since in some of # them, those are the same object. # Draw tags on entities in the 3D workspace if wanted. See self._drawTags # for details. _tagPositions = () _tagColor = yellow picking = False # used as instance variable in some mouse methods def __init__(self, glpane): """ """ # guessing self.pw is only needed in class Command (or not at all): ## self.pw = None # pw = part window # initialize attributes used by methods to refer to # important objects in their runtime environment # make sure we didn't get passed the commandSequencer by accident glpane.gl_update # not a call, just make sure it has this method self.glpane = glpane self.win = glpane.win ## self.commandSequencer = self.win.commandSequencer #bruce 070108 # that doesn't work, since when self is first created during GLPane creation, # self.win doesn't yet have this attribute: # (btw the exception from this is not very understandable.) # So instead, we define a property that does this alias, below. # Note: the attributes self.o and self.w are deprecated, but often used. # New code should use some other attribute, such as self.glpane or # self.commandSequencer or self.win, as appropriate. [bruce 070613, 071008] self.o = self.glpane # (deprecated) self.w = self.win # (deprecated) # set up context menus self._setup_menus_in_init() return # from basicGraphicsMode.__init__ def Enter_GraphicsMode(self): """ Perform side effects in self (a GraphicsMode) when entering it or reentering it. Typically this involves resetting or initializing state variables. @note: Called in self.command.command_entered. @see: B{baseCommand.command_entered} """ #NOTE: See a comment in basicCommand.Enter for things still needed # to be done self.picking = False def isCurrentGraphicsMode(self): #bruce 071010, for GraphicsMode API """ Return a boolean to indicate whether self is the currently active GraphicsMode. See also Command.isCurrentCommand. """ # see WARNING in CommandSequencer about this needing revision if .graphicsMode # might have been wrapped with an API-enforcement (or any other) proxy. return self.glpane.graphicsMode is self def __get_parentGraphicsMode(self): #bruce 081223 # review: does it need to check whether the following exists? return self.command.parentCommand.graphicsMode parentGraphicsMode = property(__get_parentGraphicsMode) def _setup_menus_in_init(self): if not self.command.call_makeMenus_for_each_event: self._setup_menus( ) def _setup_menus_in_each_cmenu_event(self): if self.command.call_makeMenus_for_each_event: self._setup_menus( ) def _setup_menus(self): """ Call self.command.setup_graphics_menu_specs(), assume it sets all the menu_spec attrs on self.command, Menu_spec, Menu_spec_shift, Menu_spec_control, and turn them into self._Menu1 etc, which are QMenus, one of which will be posted by the caller depending on the modkeys of an event. (TODO: when we know we're called for each event, optim by producing only one of those QMenus, and tell setup_graphics_menu_specs to optim in a similar way.) """ # Note: this was split between Command.setup_graphics_menu_specs and # GraphicsMode._setup_menus, bruce 071009 command = self.command command.setup_graphics_menu_specs() self._Menu1 = QMenu() self.makemenu(command.Menu_spec, self._Menu1) self._Menu2 = QMenu() self.makemenu(command.Menu_spec_shift, self._Menu2) self._Menu3 = QMenu() self.makemenu(command.Menu_spec_control, self._Menu3) return # == # confirmation corner methods [bruce 070405-070409, 070627] _ccinstance = None def draw_overlay(self): #bruce 070405, revised 070627 """ called from GLPane with same drawing coordsys as for model [part of GLPane's drawing interface to modes] """ # conf corner is enabled by default for A9.1 (070627); # requires exprs module and Python Imaging Library if not env.prefs[displayConfirmationCorner_prefs_key]: return # which command should control the confirmation corner? command = self.command #bruce 071015 to fix bug 2565 # (originally done inside find_or_make_confcorner_instance) # Note: we cache this on the Command, not on the GraphicsMode. # I'm not sure that's best, though since the whole thing seems to assume # they have a 1-1 correspondence, it may not matter much. # But in the future if weird GraphicsModes needed their own # conf. corner styles or implems, it might need revision. #bruce 080905 fix bug 2933 command = command.command_that_supplies_PM() # figure out what kind of confirmation corner command wants, and draw it import graphics.behaviors.confirmation_corner as confirmation_corner cctype = command.want_confirmation_corner_type() self._ccinstance = confirmation_corner.find_or_make_confcorner_instance(cctype, command) # Notes: # - we might use an instance cached in command (in an attr private to that helper function); # - this might be as specific as both args passed above, or as shared as one instance # for the entire app -- that's up to it; # - if one instance is shared for multiple values of (cctype, command), # it might store those values in that instance as a side effect of # find_or_make_confcorner_instance; # - self._ccinstance might be None. if self._ccinstance is not None: # it's an instance we want to draw, and to keep around for mouse event handling # (even though it's not necessarily still valid the next time we draw; # fortunately we'll rerun this method then and recompute cctype and command, etc) self._ccinstance.draw() return def mouse_event_handler_for_event_position(self, wX, wY): #bruce 070405 """ Some mouse events should be handled by special "overlay" widgets (e.g. confirmation corner buttons) rather than by the GLPane & mode's usual event handling functions. This mode API method is called by the GLPane to determine whether a given mouse position (in OpenGL-style window coordinates, 0,0 at bottom left) lies over such an overlay widget. Its return value is saved in glpane.mouse_event_handler -- a public fact, which can be depended on by mode methods such as update_cursor -- and should be None or an object that obeys the MouseEventHandler interface. (Note that modes themselves don't (currently) provide that interface -- they get their mouse events from GLPane in a more-digested way than that interface supplies.) Note that this method is not called for all mouse events -- whether it's called depends on the event type (and perhaps modkeys). The caller's policy as of 070405 (fyi) is that the mouse event handler is not changed during a drag, even if the drag goes off the overlay widget, but it is changed during bareMotion if the mouse goes on or off of one. But that policy is the caller's business, not self's. [Subclasses should override this if they show extra or nonstandard overlay widgets, but as of the initial implem (070405), that's not likely to be needed.] """ if self._ccinstance is not None: method = getattr(self._ccinstance, 'want_event_position', None) if method: if method(wX, wY): return self._ccinstance elif debug_flags.atom_debug: print "atom_debug: fyi: ccinstance %r with no want_event_position method" % (self._ccinstance,) return None # == # Note: toplevel drawing methods in the GraphicsMode API for its GLPane # have names starting with Draw_ (capital 'D') whenever they are intended # for drawing the model, or objects in the same 3d space. They are called # within the stereo image loop, and with absolute model coordinates current. # # (There is one exception: Draw_preparation is named this way, but is called # only once per paintGL call, because it's intended not for drawing, but for # preparing for the other Draw_ methods to be called. Its name matches their # names to indicate this association.) # # Other drawing methods in this API start with "draw" (lower-case 'd') # (or perhaps something else if they are older and I missed them in my # review today), and are called under other conditions. [bruce 090311] def Draw(self): #bruce 090310-11 split this up and removed it from the GraphicsMode API """ [temporary method for compatibility as we refactor Draw; should not be overridden or extended -- instead, override or extend one of the following methods which it calls] """ # this should never be called as of 090311 print_compact_stack( "bug: old code is calling %r.Draw(): " % self) self.Draw_preparation() #bruce 090310 do this first, not last or in middle as before # note: this is the wrong (suboptimal) place to call Draw_preparation. # The new code that replaces this method calls it correctly -- # outside the stereo loop, and not for internal highlighting draws. self.Draw_axes() self.Draw_other_before_model() self.Draw_model() self.Draw_other() return def Draw_preparation(self): #bruce 090310-11 split .Draw API """ Do whatever updates and calculations are needed before drawing anything during one paintGL call. Unlike the other Draw_ methods, this is only called once per paintGL call -- not once per stereo image, and not during internal redraws to implement mouseover highlighting. (A potential use for this method is to decide what needs to be drawn at all by other Draw_ methods during the same paintGL call.) [subclasses should extend as needed] """ # bruce 040929/041103 debug code -- for developers who enable this # feature, check for bugs in atom.picked and mol.picked for everything # in the assembly; print and fix violations. (This might be slow, which # is why we don't turn it on by default for regular users.) if debug_flags.atom_debug: self.o.assy.checkpicked(always_print = 0) return def Draw_axes(self): #bruce 090310-11 split .Draw API """ Draw the origin and/or point of view axes, according to user prefs. [subclasses can extend or override, but perhaps none of them do] @todo: probably merge this into GLPane, which has related code to help draw the same axes. """ # Draw the Origin axes. # WARNING: this code is duplicated, or almost duplicated, # in GraphicsMode.py and GLPane.py. # It should be moved into a common method in drawers.py, # and called from GLPane like the related code -- no need for it to be # in the GraphicsMode API since nothing overrides it (and if something # wanted to override it correctly, it would need to affect the code now # in GLPane as well, so more refactoring would be required). # [bruce 080710/090311 comment] if env.prefs[displayOriginAxis_prefs_key]: if env.prefs[displayOriginAsSmallAxis_prefs_key]: #ninad060920 drawOriginAsSmallAxis(self.o.scale, (0.0, 0.0, 0.0)) #ninad060921: note: we are also drawing a dotted origin displayed only when #the solid origin is hidden. See def standard_repaint_0 in GLPane.py #ninad060922 passing self.o.scale makes sure that the origin / pov axes are not zoomable else: drawaxes(self.o.scale, (0.0, 0.0, 0.0), coloraxes = True) # Note: the next statement seems redundant with what follows it. # It was introduced in svn revision 5253, Wed Sep 20 21:15:08 2006 UTC, # by Ninad, who also added the "cross wire" part to the comment below # [signed ninad060920] at the same time. So I'm guessing it was unintended. # But it's been in the program for so long that by now it might be intended # behavior. However, since it makes the following code useless, and also # slows down axis drawing, I'll treat it as a mistake and comment it out. # [bruce 090310] ## if env.prefs[displayPOVAxis_prefs_key]: ## drawPointOfViewAxes(self.o.scale, -self.o.pov) # Draw the Point of View axis unless it is at the origin (0, 0, 0) AND draw origin as cross wire is true ninad060920 if env.prefs[displayPOVAxis_prefs_key]: if not env.prefs[displayOriginAsSmallAxis_prefs_key]: if vlen(self.o.pov): drawPointOfViewAxes(self.o.scale, -self.o.pov) else: # POV is at the origin (0, 0, 0). Draw it if the Origin axis is not drawn. Fixes bug 735. if not env.prefs[displayOriginAxis_prefs_key]: drawPointOfViewAxes(self.o.scale, -self.o.pov) else: drawPointOfViewAxes(self.o.scale, -self.o.pov) pass return def Draw_other_before_model(self): #bruce 090310-11 split .Draw API """ Draw things in immediate mode OpenGL (not using CSDLs/DrawingSets) (but it's ok to compile and/or call OpenGL display lists) which need to be drawn before the model, but which lie in the same 3d space as the model. @see: Draw_model (for more info about what goes in what method) @see: Draw_other (for drawing after the model) [subclasses should extend as needed] """ # TODO: detect error of using CSDLs in this method return def Draw_model(self): #bruce 090310-11 split .Draw API """ Draw whatever part of the model (or anything else in the same 3d space) is desired by self, using CSDLs and DrawingSets (if they are enabled). @note: the base implementation draws nothing, since not all modes want to always draw the model. @note: these methods are probably misnamed -- the real difference between Draw_other* and Draw_model is whether they can use CSDLs/dsets (ColorSortedDisplayLists and DrawingSets). Draw_model can, and these can be cached so it needn't be called again on every frame. The Draw_other* methods currently can't, and they are called more often -- up to several times per paintGL call (due to mouseover highlighting). @note: if immediate-mode OpenGL is used here, including calls of OpenGL display lists, it won't be visible when certain drawing speed optimizations are turned on (which avoid calls of this method by reusing cached DrawingSets). @note: as of 090311, many Node.draw methods violate the rule about not using immediate-mode OpenGL in this method. @see: Draw_other, Draw_other_before_model, Draw_axes, Draw_preparation [subclasses should extend as needed] """ # review: we might revise this API to draw the model (i.e. to call # self.part.draw) by default, so the few modes that don't want to # draw it should override this to draw nothing (rather than lots of # modes having to call that themselves); or we might add a class attr # about whether to draw it. return def Draw_other(self): #bruce 090310-11 split .Draw API """ Draw things in immediate mode OpenGL (not using CSDLs/DrawingSets) (but it's ok to compile and/or call OpenGL display lists) which need to be drawn after the model, but which lie in the same 3d space as the model. @see: Draw_model (for more info about what goes in what method) @note: this is typically used for things like handles, cursor text, selection curve, interactive construction guides, etc, but that's only because they are not presently drawn using CSDLs/DrawingSets. If they are drawn that way in the future, they should be moved out of Draw_other and into Draw_model. [subclasses should extend as needed, and/or extend the methods called by the base implementation (which are part of this class's API for its subclasses, but are not part of the GraphicsMode_interface itself): _drawTags, _drawSpecialIndicators, _drawLabels] """ # TODO: detect error of using CSDLs in this method # Review: it might be cleaner to revise _drawTags, # _drawSpecialIndicators, and _drawLabels, to be public methods # of GraphicsMode_API. Presently they are not part of it at all; # they are only part of the subclass-extending API of this base # class GraphicsMode. [bruce 081223 comment] #Draw tags if any self._drawTags() #Draw Special indicators if any (subclasses can draw custom indicators) self._drawSpecialIndicators() #Draw labels if any self._drawLabels() return # == def setDrawTags(self, tagPositions = (), tagColor = yellow): # by Ninad """ Public method that accepts requests to draw tags at the given tagPositions. @note: this saves its arguments as private state in self, but does not actually draw them -- that is done later by self._drawTags(). Thus, this method is safe to call outside of self.Draw_*() and without ensuring that self.glpane is the current OpenGL context. @param tagPositions: The client can provide a list or tuple of tag base positions. The default value for this parameter is an empty tuple. Thus, if no tag position is specified, it won't draw any tags and will also clear the previously drawn tags. @type tagPositions: list or tuple @param tagColor: The color of the tags @type tagColor: B{A} @see: self._drawTags @see: InsertDna_PropertyManager.clearTags for an example """ #bruce 081002 renamed from drawTags -> setDrawTags, to avoid confusion, # since it sets state but doesn't do any drawing self._tagPositions = list(tagPositions) self._tagColor = tagColor def _drawTags(self): """ Private method, called in self.Draw_other, that actually draws the tags saved in self._tagPositions by self.setDrawTags. """ if self._tagPositions: for basePoint in self._tagPositions: if self.glpane.scale < 5: lineScale = 5 else: lineScale = self.glpane.scale endPoint = basePoint + self.glpane.up*0.2*lineScale pointSize = round(self.glpane.scale*0.5) drawTag(self._tagColor, basePoint, endPoint, pointSize = pointSize) return def _drawSpecialIndicators(self): """ Subclasses should override this method. Default implementation does nothing. Many times, the graphics mode needs to draw some things to emphasis some entities in the 3D workspace. Example: In MultiplednaSegmentResize_GraphicsMode, it draws transparent cylinders around the DnaSegments being resized at once. This visually distinguishes them from the rest of the segments. @see: MultipleDnaSegmentResize_GraphicsMode._drawSpecialIndicators() @TODO: cleanup self._drawTags() that method and this method look similar but the actual implementation is different. """ return def _drawLabels(self): """ Subclasses should override this method. Default implementation does nothing. Many times, the graphics mode needs to draw some labels on the top of everything. Called in self.Draw_other(). Example: For a DNA, user may want to turn on the labels next to the atoms indicating the base numbers. @see: BreakOrJoinStrands_GraphicsMode._drawLabels() for an example. @see: self._drawSpecialIndicators() @see: self.Draw_other() """ return # == def Draw_after_highlighting(self, pickCheckOnly = False): #bruce 050610 """ Do more drawing, after the main drawing code has completed its highlighting/stenciling for selobj. Caller will leave glstate in standard form for Draw_* methods. Implems are free to turn off depth buffer read or write (but must restore standard glstate when done, just as for other GraphicsMode Draw_*() method). Warning: anything implems do to depth or stencil buffers will affect the standard selobj-check in bareMotion (which as of 050610 was only used in BuildAtoms_Graphicsmode). [New method in mode API as of bruce 050610. General form not yet defined -- just a hack for Build mode's water surface. Could be used for transparent drawing in general. UPDATE 2008-06-20: Another example use of this method: Used for selecting a Reference Plane when user clicks inside the filled plane (i.e. not along the edges). See new API method Node.draw_after_highlighting [note capitalization and arg signature difference] which is called here. It fixes bug 2900-- Ninad ] @see: Plane.draw_after_highlighting() @see: Node.draw_after_highlighting() """ return self.o.assy.part.topnode.draw_after_highlighting( self.glpane, self.glpane.displayMode, pickCheckOnly = pickCheckOnly ) def selobj_still_ok(self, selobj): """ [overrides GraphicsMode_API method] Say whether a highlighted mouseover object from a prior draw (done by the same GraphicsMode) is still ok. In this implementation: if our special cases of various classes of selobj don't hold, we ask selobj (using a method of the same name in the selobj API, though it's not defined in Selobj_API for now); if that doesn't work, we assume selobj defines .killed, and answer yes unless it's been killed. """ try: # This sequence of conditionals fix bugs 1648 and 1676. mark 060315. # [revised by bruce 060724 -- merged in selobj.killed() condition, dated 050702, # which was part of fix 1 of 2 redundant fixes for bug 716 (both fixes are desirable)] if isinstance(selobj, Atom): return not selobj.killed() and selobj.molecule.part is self.o.part elif isinstance(selobj, Bond): return not selobj.killed() and selobj.atom1.molecule.part is self.o.part elif isinstance(selobj, Node): # e.g. Jig return not selobj.killed() and selobj.part is self.o.part else: try: method = selobj.selobj_still_ok # REVIEW: this method is not defined in Selobj_API; can it be? except AttributeError: pass else: res = method(self.o) # this method would need to compare glpane.part to something in selobj ##e it might be better to require selobj's to return a part, compare that here, # then call this for further conditions if res is None: print "likely bug: %r.selobj_still_ok(glpane) returned None, "\ "should return boolean (missing return statement?)" % (selobj,) return res if debug_flags.atom_debug: print "debug: selobj_still_ok doesn't recognize %r, assuming ok" % (selobj,) return True except: if debug_flags.atom_debug: print_compact_traceback("atom_debug: ignoring exception: ") return True # let the selobj remain pass def Draw_highlighted_selobj(self, glpane, selobj, hicolor): """ [overrides GraphicsMode_API method] Draw selobj in highlighted form for being the "object under the mouse", as appropriate to this graphics mode. [TODO: document this properly: Use hicolor as its color if you return sensible colors from method XXX.] Subclasses should override this as needed (for example, to highlight a larger object that contains selobj), though many don't need to. Note: selobj is typically glpane.selobj, but don't assume this. """ #bruce 090311 renamed this from drawHighlightedObjectUnderMouse; # it now starts with Draw_ since it's called inside the stereo loop selobj.draw_in_abs_coords(glpane, hicolor) def draw_glpane_label(self, glpane): """ [part of the GraphicsMode API for drawing into a GLPane] This is called with model coordinates, but outside of stereo loops, once per paintGL call, after model drawing. It is meant to allow the GraphicsMode to draw a text label for the entire GLPane. The default implementation determines the text by calling glpane.part.glpane_label_text() and draws it using glpane.draw_glpane_label_text (which uses a standard location and style for a whole-glpane label). """ #bruce 090219 moved this here from part.py, renamed from draw_text_label # (after refactoring it the prior day, 090218) # (note: caller catches exceptions, so we don't have to bother) # (not named with a capital 'D' since not inside stereo loop [bruce 090311]) text = self.glpane.part.glpane_label_text() if text: glpane.draw_glpane_label_text(text) return # == def end_selection_from_GLPane(self): """ GraphicsMode API method that decides whether to do some additional selection/ deselection (delegates this to a node API method) Example: If all content od a Dna group is selected (such as direct members, other logical contents), then pick the whole DnaGroup @see: Node.pick_if_all_glpane_content_is_picked() @see: Select_GraphicsMode.end_selection_curve() for an example use """ part = self.win.assy.part class_list = (self.win.assy.DnaStrandOrSegment, self.win.assy.DnaGroup, self.win.assy.NanotubeSegment ) topnode = part.topnode topnode.call_on_topmost_unpicked_nodes_of_certain_classes( lambda node: node.pick_if_all_glpane_content_is_picked(), class_list ) return def dragstart_using_GL_DEPTH(self, event, **kws): """ Use the OpenGL depth buffer pixel at the coordinates of event (which works correctly only if the proper GL context, self.o, is current -- caller is responsible for this) to guess the 3D point that was visually clicked on. See GLPane version's docstring for details. [Note: this is public for event handlers using this object (whether in subclasses or external objects), but it's not part of the GraphicsMode interface from the GLPane.] """ res = self.o.dragstart_using_GL_DEPTH(event, **kws) # note: res is a tuple whose length depends on **kws return res def dragstart_using_plane_depth(self, event, plane= None, planeAxis = None, planePoint = None, ): res = self.o.dragstart_using_plane_depth(event, plane= plane, planeAxis = planeAxis, planePoint = planePoint, ) # note: res is a tuple whose length depends on **kws return res def dragto(self, point, event, perp = None): """ Return the point to which we should drag the given point, if event is the drag-motion event and we want to drag the point parallel to the screen (or perpendicular to the given direction "perp" if one is passed in), keeping the point visibly touching the mouse cursor hotspot. (This is only correct for extended objects if 'point' (as passed in, and as retval is used) is the point on the object surface which was clicked on (not e.g. the center). For example, dragto(a.posn(),...) is incorrect code, unless the user happened to start the drag with a mousedown right over the center of atom <a>. See jigDrag in some subclasses for an example of correct usage.) """ #bruce 041123 split this from two methods, and bugfixed to make dragging # parallel to screen. (I don't know if there was a bug report for that.) # Should be moved into modes.py and used in Move_Command too. #[doing that, 060316] p1, p2 = self.o.mousepoints(event) if perp is None: perp = self.o.out point2 = planeXline(point, perp, p1, norm(p2-p1)) # args are (ppt, pv, lpt, lv) if point2 is None: # should never happen (unless a bad choice of perp is passed in), # but use old code as a last resort (it makes sense, and might even be equivalent for default perp) if env.debug(): #bruce 060316 added debug print; it should remain indefinitely if we rarely see it print "debug: fyi: dragto planeXline failed, fallback to ptonline", point, perp, p1, p2 point2 = ptonline(point, p1, norm(p2-p1)) return point2 def dragto_with_offset(self, point, event, offset): #bruce 060316 for bug 1474 """ Convenience wrapper for dragto: Use this to drag objects by points other than their centers, when the calling code prefers to think only about the center positions (or some other reference position for the object). Arguments: - <point> should be the current center (or other reference) point of the object. - The return value will be a new position for the same reference point as <point> comes from (which the caller should move the object to match, perhaps subject to drag-constraints). - <event> should be an event whose .pos().x() and .pos.y() supply window coordinates for the mouse - <offset> should be a vector (fixed throughout the drag) from the center of the object to the actual dragpoint (i.e. to the point in 3d space which should appear to be gripped by the mouse, usually the 3d position of a pixel which was drawn when drawing the object and which was under the mousedown which started the drag). By convention, modes can store self.drag_offset in leftDown and pass it as <offset>. Note: we're not designed for objects which rotate while being dragged, as in e.g. dragSinglets, though using this routine for them might work better than nothing (untested ##k). In such cases it might be better to pass a different <offset> each time (not sure), but the only perfect solution is likely to involve custom code which is fully aware of how the object's center and its dragpoint differ, and of how the offset between them rotates as the object does. """ return self.dragto(point + offset, event) - offset # middle mouse button actions -- these support a trackball, and # are the same for all GraphicsModes (with a few exceptions) def middleDown(self, event): """ Set up for rotating the view with MMB+Drag. """ self.update_cursor() self.o.SaveMouse(event) self.o.trackball.start(self.o.MousePos[0], self.o.MousePos[1]) self.picking = True # Turn off hover highlighting while rotating the view with middle mouse button. Fixes bug 1657. Mark 060805. self.o.selobj = None # <selobj> is the object highlighted under the cursor. def middleDrag(self, event): """ Rotate the view with MMB+Drag. """ # Huaicai 4/12/05: Originally 'self.picking = False in both middle*Down # and middle*Drag methods. Change it as it is now is to prevent # possible similar bug that happened in the Move_Command where # a *Drag method is called before a *Down() method. This # comment applies to all three *Down/*Drag/*Up methods. if not self.picking: return self.o.SaveMouse(event) q = self.o.trackball.update(self.o.MousePos[0], self.o.MousePos[1]) self.o.quat += q self.o.gl_update() def middleUp(self, event): self.picking = False self.update_cursor() def middleShiftDown(self, event): """ Set up for panning the view with MMB+Shift+Drag. """ self.update_cursor() # Setup pan operation farQ_junk, self.movingPoint = self.dragstart_using_GL_DEPTH( event) self.startpt = self.movingPoint # Used in leftDrag() to compute move offset during drag op. # REVIEW: needed? the subclasses that use it also set it, so probably not. # TODO: confirm that guess, then remove this set. (In fact, this makes me wonder # if some or all of the other things in this method are redundant now.) [bruce 071012 comment] self.o.SaveMouse(event) #k still needed?? probably yes; might even be useful to help dragto for atoms #e [bruce 060316 comment] self.picking = True # Turn off hover highlighting while panning the view with middle mouse button. Fixes bug 1657. Mark 060808. self.o.selobj = None # <selobj> is the object highlighted under the cursor. def middleShiftDrag(self, event): """ Pan view with MMB+Shift+Drag. Move point of view so that the model appears to follow the cursor on the screen. """ point = self.dragto( self.movingPoint, event) self.o.pov += point - self.movingPoint self.o.gl_update() def middleShiftUp(self, event): self.picking = False self.update_cursor() def middleCntlDown(self, event): """ Set up for rotating view around POV axis with MMB+Cntl+Drag. """ self.update_cursor() self.o.SaveMouse(event) self.Zorg = self.o.MousePos self.Zq = Q(self.o.quat) self.Zpov = self.o.pov self.picking = True # Turn off hover highlighting while rotating the view with middle mouse button. Mark 060808. self.o.selobj = None # <selobj> is the object highlighted under the cursor. def middleCntlDrag(self, event): """ Rotate around the point of view (POV) axis """ if not self.picking: return self.o.SaveMouse(event) dx, dy = (self.o.MousePos - self.Zorg) * V(1,-1) self.o.pov = self.Zpov w = self.o.width+0.0 self.o.quat = self.Zq + Q(V(0,0,1), 2*math.pi*dx/w) self.o.gl_update() def middleCntlUp(self, event): self.picking = False self.update_cursor() def middleShiftCntlDown(self, event): # mark 060228. """ Set up zooming POV in/out """ self.middleCntlDown(event) def middleShiftCntlDrag(self, event): """ Zoom (push/pull) point of view (POV) away/nearer """ if not self.picking: return self.o.SaveMouse(event) dx, dy = (self.o.MousePos - self.Zorg) * V(1,-1) self.o.quat = Q(self.Zq) h = self.o.height+0.0 self.o.pov = self.Zpov-self.o.out*(2.0*dy/h)*self.o.scale self.o.gl_update() def middleShiftCntlUp(self, event): self.picking = False self.update_cursor() # right button actions... #doc def rightDown(self, event): self._setup_menus_in_each_cmenu_event() self._Menu1.exec_(event.globalPos()) #ninad061009: Qpopupmenu in qt3 is QMenu in Qt4 #apparently QMenu._exec does not take option int indexAtPoint. # [bruce 041104 comment:] Huaicai says that menu.popup and menu.exec_ # differ in that menu.popup returns immediately, whereas menu.exec_ # returns after the menu is dismissed. What matters most for us is whether # the callable in the menu item is called (and returns) just before # menu.exec_ returns, or just after (outside of all event processing). # I would guess "just before", in which case we have to worry about order # of side effects for any code we run after calling exec_, since in # general, our Qt event processing functions assume they are called purely # sequentially. I also don't know for sure whether the rightUp() method # would be called by Qt during or after the exec_ call. If any of this # ever matters, we need to test it. Meanwhile, exec_ is probably best # for context menus, provided we run no code in the same method after it # returns, nor in the corresponding mouseUp() method, whose order we don't # yet know. (Or at least I don't yet know.) # With either method (popup or exec_), the menu stays up if you just # click rather than drag (which I don't like); this might be fixable in # the corresponding mouseup methods, but that requires worrying about the # above-described issues. def rightShiftDown(self, event): self._setup_menus_in_each_cmenu_event() # Previously we did this: # self._Menu2.exec_(event.globalPos(),3) # where 3 specified the 4th? action in the list. The exec_ method now # needs a pointer to the action itself, not a numerical index. The only # ways I can see to do that is with lots of bookkeeping, or if the menu # had a listOfActions method. This isn't important enough for the former # and Qt does not give us the latter. So forget about the 3. self._Menu2.exec_(event.globalPos()) def rightCntlDown(self, event): self._setup_menus_in_each_cmenu_event() # see note above self._Menu3.exec_(event.globalPos()) # other events def Wheel(self, event): mod = event.modifiers() ### REVIEW: this might need a fix_buttons call to work the same # on the Mac [bruce 041220] dScale = 1.0/1200.0 if mod & Qt.ShiftModifier and mod & Qt.ControlModifier: # Shift + Control + Wheel zooms at same rate as without a modkey. pass elif mod & Qt.ShiftModifier: # Shift + Wheel zooms in quickly (2x), dScale *= 2.0 elif mod & Qt.ControlModifier: # Control + Wheel zooms in slowly (.25x). dScale *= 0.25 farQ_junk, point = self.dragstart_using_GL_DEPTH( event) # russ 080116 Limit mouse acceleration on the Mac. delta = max( -360, min(event.delta(), 360)) * self.w.mouseWheelDirection factor = exp(dScale * delta) #print "Wheel factor=", factor, " delta=", delta #bruce 070402 bugfix: original formula, factor = 1.0 + dScale * delta, was not reversible by inverting delta, # so zooming in and then out (or vice versa) would fail to restore original scale precisely, # especially for large delta. (Measured deltas: -360 or +360.) # Fixed by using an exponential instead. self.rescale_around_point_re_user_prefs( factor , point ) # note: depending on factor < 1.0 and user prefs, point is not always used. # Turn off hover highlighting while zooming with mouse wheel. Fixes bug 1657. Mark 060805. self.o.selobj = None # <selobj> is the object highlighted under the cursor. # Following fixes bug 2536. See also SelectChunks_GraphicsMode.bareMotion # and the comment where this is initialized as a class variable. # [probably by Ninad 2007-09-19] # # update, bruce 080130: change time.clock -> time.time to fix one cause # of bug 2606. See comments where this is used for more info. self.timeAtLastWheelEvent = time.time() self.o.gl_update() return def rescale_around_point_re_user_prefs(self, factor, point = None): #bruce 060829; revised/renamed/moved from GLPane, 070402 """ Rescale by factor around point or center of view, depending on zoom direction and user prefs. (Factor < 1.0 means zooming in.) If point is not supplied, the center of view remains unchanged after the rescaling, and user prefs have no effect. Note that point need not be in the plane of the center of view, and if it's not, the depth of the center of view will change. If callers wish to avoid this, they can project point onto the plane of the center of view. """ if point is not None: # decide whether to recenter around point (or do nothing, i.e. stay centered on center of view). if factor < 1.0: # zooming in recenter = not env.prefs[zoomInAboutScreenCenter_prefs_key] else: # zooming out recenter = not env.prefs[zoomOutAboutScreenCenter_prefs_key] if not recenter: point = None glpane = self.o glpane.rescale_around_point(factor, point) # note: point might have been modified above return # Key event handling revised by bruce 041220 to fix some bugs; # see comments in the GLPane methods, which now contain Mac-specific Delete # key fixes that used to be done here. For the future: The keyPressEvent and # keyReleaseEvent methods must be overridden by any mode which needs to know # more about key events than event.key() (which is the same for 'A' and 'a', # for example). As of 041220 no existing mode needs to do this. def keyPressEvent(self, event): """ [some modes will need to override this in the future] """ # Holding down X, Y or Z "modifier keys" in MODIFY and TRANSLATE modes generates # autorepeating keyPress and keyRelease events. For now, ignore autorepeating key events. # Later, we may add a flag to determine if we should ignore autorepeating key events. # If a mode needs these events, simply override keyPressEvent and keyReleaseEvent. # Mark 050412 #bruce 060516 extending this by adding keyPressAutoRepeating and keyReleaseAutoRepeating, # usually but not always ignored. if event.isAutoRepeat(): self.keyPressAutoRepeating(event.key()) else: self.keyPress(event.key()) return def keyReleaseEvent(self, event): """ """ # Ignore autorepeating key events. Read comments in keyPressEvent above for more detail. # Mark 050412 #bruce 060516 extending this; see same comment. if event.isAutoRepeat(): self.keyReleaseAutoRepeating(event.key()) else: self.keyRelease(event.key()) return # the old key event API (for modes which don't override keyPressEvent etc) def keyPress(self, key): # several modes extend this method, some might replace it def zoom(dScale): self.o.scale *= dScale self.o.gl_update() def pan(offsetVector, panIncrement): planePoint = V(0.0, 0.0, 0.0) offsetPoint = offsetVector * self.o.scale * panIncrement povOffset = planeXline(planePoint, self.o.out, offsetPoint, self.o.out) self.glpane.pov += povOffset self.glpane.gl_update() if key == Qt.Key_Delete: self.w.killDo() # Zoom in & out for Eric and Paul: # - Eric D. requested Period/Comma keys for zoom in/out. # - Paul R. requested Minus/Equal keys for zoom in/out. # Both sets of keys work with Ctrl/Cmd pressed for less zoom. # I took the liberty of implementing Plus and Less keys for zoom out # a lot, and Underscore and Greater keys for zoom in a lot. If this # conflicts with other uses of these keys, it can be easily changed. # Mark 2008-02-28. elif key in (Qt.Key_Minus, Qt.Key_Period): # Zoom in. dScale = 0.95 if self.o.modkeys == 'Control': # Zoom in a little. dScale = 0.995 zoom(dScale) elif key in (Qt.Key_Underscore, Qt.Key_Greater): # Zoom in a lot. dScale = 0.8 zoom(dScale) elif key in (Qt.Key_Equal, Qt.Key_Comma): # Zoom out. dScale = 1.05 if self.o.modkeys == 'Control': dScale = 1.005 zoom(dScale) elif key in (Qt.Key_Plus, Qt.Key_Less): # Zoom out a lot. dScale = 1.2 zoom(dScale) # Pan left, right, up and down using arrow keys, requested by Paul. # Mark 2008-04-13 elif key in (Qt.Key_Left, Qt.Key_Right, Qt.Key_Up, Qt.Key_Down): panIncrement = 0.1 * env.prefs[panArrowKeysDirection_prefs_key] if self.o.modkeys == 'Control': panIncrement *= 0.25 elif self.o.modkeys == 'Shift': panIncrement *= 4.0 if key == Qt.Key_Left: pan(-self.o.right, panIncrement) elif key == Qt.Key_Right: pan(self.o.right, panIncrement) elif key == Qt.Key_Up: pan(self.o.up, panIncrement) elif key == Qt.Key_Down: pan(-self.o.up, panIncrement) # comment out wiki help feature until further notice, wware 051101 # [bruce 051130 revived/revised it, elsewhere in file] #if key == Qt.Key_F1: # import webbrowser # # [will 051010 added wiki help feature] # webbrowser.open(self.__WikiHelpPrefix + self.__class__.__name__) #bruce 051201: let's see if I can bring this F1 binding back. # It works for Mac (only if you hold down "fn" key as well as F1); # but I don't know whether it's appropriate for Mac. # F1 for help (opening separate window, not usually an external website) # is conventional for Windows (I'm told). # See bug 1171 for more info about different platforms -- this should be revised to match. # Also the menu item should mention this accel key, but doesn't. elif key == Qt.Key_F1: featurename = self.command.get_featurename() if featurename: from foundation.wiki_help import open_wiki_help_dialog open_wiki_help_dialog( featurename) pass elif 0 and debug_flags.atom_debug:#bruce 051201 -- might be wrong depending on how subclasses call this, so disabled for now print "atom_debug: fyi: glpane keyPress ignored:", key return def keyPressAutoRepeating(self, key): #bruce 060416 if key in (Qt.Key_Period, Qt.Key_Comma): self.keyPress(key) return def keyRelease(self, key): # mark 2004-10-11 #e bruce comment 041220: lots of modes change cursors on this, but they # have bugs when more than one modifier is pressed and then one is # released, and perhaps when the focus changes. To fix those, we need to # track the set of modifiers and use some sort of inval/update system. # (Someday. These are low-priority bugs.) pass def keyReleaseAutoRepeating(self, key): #bruce 060416 if key in (Qt.Key_Period, Qt.Key_Comma): self.keyRelease(key) return def update_cursor(self): # mark 060227 """ Update the cursor based on the current mouse button and mod keys pressed. """ # print "basicMode.update_cursor(): button = %s, modkeys = %s, mode = %r, handler = %r" % \ # ( self.o.button, self.o.modkeys, self, self.o.mouse_event_handler ) handler = self.o.mouse_event_handler # [bruce 070405] # Note: use of this attr here is a sign that this method really belongs in class GLPane, # and the glpane should decide whether to pass this update call to that attr's value or to the mode. # Or, better, maybe the mouse_event_handler should be temporarily on top of the command stack # in the command sequencer, overriding the mode below it for some purposes. # [bruce 070628 comment] if handler is not None: wX, wY = self.o._last_event_wXwY #bruce 070626 handler.update_cursor(self, (wX, wY)) return if self.o.button is None: self.update_cursor_for_no_MB() elif self.o.button == 'LMB': self.update_cursor_for_LMB() elif self.o.button == 'MMB': self.update_cursor_for_MMB() elif self.o.button == 'RMB': self.update_cursor_for_RMB() else: print "basicMode.update_cursor() button ignored:", self.o.button return def update_cursor_for_no_MB(self): # mark 060228 """ Update the cursor for operations when no mouse button is pressed. The default implementation just sets it to a simple arrow cursor """ self.o.setCursor(self.w.SelectArrowCursor) def update_cursor_for_LMB(self): # mark 060228 """ Update the cursor for operations when the left mouse button (LMB) is pressed """ pass def update_cursor_for_MMB(self): # mark 060228 """ Update the cursor for operations when the middle mouse button (MMB) is pressed """ #print "basicMode.update_cursor_for_MMB(): button=",self.o.button if self.o.modkeys is None: self.o.setCursor(self.w.RotateViewCursor) elif self.o.modkeys == 'Shift': self.o.setCursor(self.w.PanViewCursor) elif self.o.modkeys == 'Control': self.o.setCursor(self.w.RotateZCursor) elif self.o.modkeys == 'Shift+Control': self.o.setCursor(self.w.ZoomPovCursor) else: print "Error in update_cursor_for_MMB(): Invalid modkey=", self.o.modkeys return def update_cursor_for_RMB(self): # mark 060228 """ Update the cursor for operations when the right mouse button (RMB) is pressed """ pass def makemenu(self, menu_spec, menu = None): glpane = self.o return glpane.makemenu(menu_spec, menu) def draw_selection_curve(self): # REVIEW: move to a subclass? """ Draw the (possibly unfinished) freehand selection curve. """ color = get_selCurve_color(self.selSense, self.o.backgroundColor) pl = zip(self.selCurve_List[:-1], self.selCurve_List[1:]) for pp in pl: # Draw the selection curve (lasso). drawline(color, pp[0], pp[1]) if self.selShape == SELSHAPE_RECT: # Draw the selection rectangle. drawrectangle(self.selCurve_StartPt, self.selCurve_PrevPt, self.o.up, self.o.right, color) if debug_flags.atom_debug and 0: # (keep awhile, might be useful) # debug code bruce 041214: also draw back of selection curve pl = zip(self.o.selArea_List[:-1], self.o.selArea_List[1:]) for pp in pl: drawline(color, pp[0], pp[1]) def get_prefs_value(self, prefs_key): #bruce 080605 """ Get the prefs_value to use for the given prefs_key in this graphicsMode. This is env.prefs[prefs_key] by default, but is sometimes overridden for specific combinations of graphicsMode and prefs_key, e.g. to return the value of a "command-specific pref" instead of the global one. @note: callers can continue to call env.prefs[prefs_key] directly except for specific prefs_keys for which some graphicsModes locally override them. (This is not yet declared as a property of a prefs_key, so there is not yet any way to detect the error of not calling this when needed for a specific prefs_key.) @note: the present implementation usage tracks env.prefs[whatever key or keys it accesses], but ideally, whenever the result depends on the specific graphicsMode, it would also track a variable corresponding to the current graphicsMode (so that changes to the graphicsMode would invalidate whatever was derived from the return value). Until that's implemented, callers must use other methods to invalidate the values they derived from this when our actual return value changes, if that might have been due to a change in current graphicsMode. [some subclasses should override this for specific prefs_keys, but use the passed prefs_key otherwise; ideally they should call their superclass version of this method for whatever prefs lookups they end up doing, rather than using env.prefs directly.] """ return env.prefs[prefs_key] pass # end of class basicGraphicsMode # == class GraphicsMode(basicGraphicsMode): """ Subclass this class to provide a new mode of interaction for the GLPane. """ def __init__(self, command): self.command = command glpane = self.command.glpane ### REVIEW: do commands continue to have this directly?? basicGraphicsMode.__init__(self, glpane) return # Note: the remaining methods etc are not needed in basicGraphicsMode # since it is always mixed in after basicCommand # (since it is only for use in basicMode) # and they are provided by basicCommand or basicMode. def _get_commandSequencer(self): return self.command.commandSequencer commandSequencer = property(_get_commandSequencer) ### REVIEW: needed in this class? def set_cmdname(self, name): ### REVIEW: needed in this class? # Note: used directly, not in a property. """ Helper method for setting the cmdname to be used by Undo/Redo. Called by undoable user operations which run within the context of this Graphics Mode's Command. """ self.command.set_cmdname(name) return pass commonGraphicsMode = basicGraphicsMode # use this for mixin classes that need to work in both basicGraphicsMode and GraphicsMode # end
NanoCAD-master
cad/src/command_support/GraphicsMode.py
# Copyright 2006-2008 Nanorex, Inc. See LICENSE file for details. """ GeneratorBaseClass.py -- DEPRECATED base class for generator dialogs or their controllers, which supplies ok/cancel/preview logic and some other common behavior. Sometimes abbreviated as GBC in docstrings, comments, or identifier prefixes. @author: Will @version: $Id$ @copyright: 2006-2008 Nanorex, Inc. See LICENSE file for details. History: Originated by Will PM code added later by Ninad and/or Mark Some comments and docstrings clarified for upcoming code review [bruce 070719] TODO (as of 070719): Needs refactoring so that: - a generator is a Command, but is never the same object as a PropertyManager (PM) -- at the moment, all GBC subclasses are also their own PMs except some experimental ones in test_commands.py. Our plans for the Command Sequencer and associated Command objects require this refactoring. (After this refactoring, GBC will be the base class for generator *commands*, not for generator *dialogs*.) - no sponsor code appears here (it's an aspect of a PM, not of a Command, except insofar as a command needs a topic classification (e.g. sponsor keywords) which influences the choice of sponsor) After discussion during a code review on 070724, it became clear that GBC needs to be split into two classes, "generator command" and "generator PM", with much of the "generator PM" part then getting merged into PropMgrBaseClass (or its successor, PM_Dialog). These will have new names (not containing "BaseClass", which is redundant). Tentative new names: GeneratorCommand, GeneratorPM. The GeneratorPM class will contain the generator-specific parts of the button click slots; the button-click method herein need to be split into their PM and command-logic parts, when they're split between these classes. Also needs generalization in several ways (mentioned but not fully explained): - extend API with subclasses to permit better error handling - extend API with subclasses to permit modifying an existing structure - permitting use for Edit Properties - helping support turning existing generators into "regenerators" for use inside "featurelike nodes" """ from PyQt4.Qt import Qt from PyQt4.Qt import QApplication from PyQt4.Qt import QCursor from PyQt4.Qt import QWhatsThis import foundation.env as env from utilities import debug_flags from utilities.Log import redmsg, orangemsg, greenmsg, quote_html from utilities.Comparison import same_vals from utilities.debug import print_compact_traceback from utilities.constants import gensym from utilities.constants import permit_gensym_to_reuse_name from utilities.exception_classes import CadBug, PluginBug, UserError, AbstractMethod # == class GeneratorBaseClass: ### REVIEW: docstring needs reorganization, and clarification re whether all # generators have to inherit it """ DEPRECATED, and no longer used for supported commands as of circa 080727. (Still used for some test/example commands.) Mixin-superclass for use in the property managers of generator commands. In spite of the class name, this class only works when inherited *after* a property manager class (e.g. PM_Dialog) in a class's list of superclasses. TODO: needs refactoring and generalization as described in module docstring. In particular, it should not inherit from SponsorableMixin, and subclasses should not be required to inherit from QDialog, though both of those are the case at present [070719]. Background: There is some logic associated with Preview/OK/Abort for any structure generator command that's complicated enough to put in one place, so that individual generators can focus on building a structure, rather than on the generic logic of a generator or its GUI. Note: this superclass sets and maintains some attributes in self, including win, struct, previousParams, and name. Here are the things a subclass needs to do, to be usable with this superclass [as of 060621]: - have self.sponsor_btn, a Qt button of a suitable class. - bind or delegate button clicks from a generator dialog's standard buttons to all our xxx_btn_clicked methods (not sure about sponsor_btn). ###VERIFY - implement the abstract methods (see their docstrings herein for what they need to do): - gather_parameters - build_struct - provide self.prefix, apparently used to construct node names (or, override self._create_new_name()) - either inherit from QDialog, or provide methods accept and reject which have the same effect on the actual dialog. [As of bruce 070719 I am not sure if not inheriting QDialog is possible.] There are some other methods here that merit mentioning: done_btn_clicked, cancel_btn_clicked, close. """ # default values of class constants; subclasses should override these as # needed cmd = "" # DEPRECATED, but widely used [bruce 060616 comment] # WARNING: subclasses often set cmd to greenmsg(self.cmdname + ": "), # from which we have to klugily deduce self.cmdname! Ugh. cmdname = "" # subclasses should set this to their (undecorated) command # name, for use by Undo and history. (Note: this name is passed to Undo # by calls from some methods here to assy.current_command_info.) # TODO: this attribute should be renamed to indicate that it's part of # a specific interface. (Right now it's a standard attribute name # used by convention in many files, and that renaming should be done # consistently to all of them at once if possible. Note that it is # used for several purposes (with more planned in the future), not # only for Undo. Note that a "command metadata interface" might # someday include other attributes besides the name.) create_name_from_prefix = True # whether we'll create self.name from # self.prefix (by appending a serial number) def __init__(self, win): """ @param win: the main window object """ self.win = win self.pw = None # pw = part window. Its subclasses will create their # partwindow objects (and destroy them after Done) ###REVIEW: I think this (assignment or use of self.pw) does not # belong in this class [bruce 070615 comment] self.struct = None self.previousParams = None #bruce 060616 added the following kluge to make sure both cmdname and # cmd are set properly. if not self.cmdname and not self.cmd: self.cmdname = "Generate something" if self.cmd and not self.cmdname: # deprecated but common, as of 060616 self.cmdname = self.cmd # fallback value; usually reassigned below try: cmdname = self.cmd.split('>')[1] cmdname = cmdname.split('<')[0] cmdname = cmdname.split(':')[0] self.cmdname = cmdname except: if debug_flags.atom_debug: print "fyi: %r guessed wrong about format of self.cmd == %r" \ % (self, self.cmd,) pass elif self.cmdname and not self.cmd: # this is intended to be the usual situation, but isn't yet, as of # 060616 self.cmd = greenmsg(self.cmdname + ": ") self.change_random_seed() return def build_struct(self, name, params, position): """ Build the structure (model object) which this generator is supposed to generate. This is an abstract method and must be overloaded in the specific generator. (WARNING: I am guessing the standard type names for tuple and position.) @param name: The name which should be given to the toplevel Node of the generated structure. The name is also passed in self.name. (TODO: remove one of those two ways of passing that info.) The caller will emit history messages which assume this name is used. If self.create_name_from_prefix is true, the caller will have set this name to self.prefix appended with a serial number. @type name: str @param params: The parameter tuple returned from self.gather_parameters(). For more info, see docstring of gather_parameters in this class. @type params: tuple @param position: The position in 3d model space at which to create the generated structure. (The precise way this is used, if at all, depends on the specific generator.) @type position: position @return: The new structure, i.e. some flavor of a Node, which has not yet been added to the model. Its structure should depend only on the values of the passed params, since if the user asks to build twice, this method may not be called if the params have not changed. """ raise AbstractMethod() def remove_struct(self): """ Private method. Remove the generated structure, if one has been built. """ ### TODO: rename to indicate it's private. if self.struct != None: self.struct.kill() # BUG: Ninad suspects this (or a similar line) might be # implicated in bug 2045. [070724 code review] self.struct = None self.win.win_update() # includes mt_update return # Note: when we split this class, the following methods will be moved into # GeneratorPM and/or PM_Dialog (or discarded if they are already overridden # correctly by PM_Dialog): # - all xxx_btn_clicked methods (also to be renamed, btn -> button) # - close # [070724 code review] def restore_defaults_btn_clicked(self): """Slot for the Restore Defaults button.""" ### TODO: docstring needs to say under what conditions this should be # overridden. ### WARNING: Mark says this is never called in practice, since it's # overridden by the same method in PropMgrBaseClass, and that this # implementation is incorrect and can be discarded when we refactor # this class. # [070724 code review] if debug_flags.atom_debug: print 'restore defaults button clicked' def preview_btn_clicked(self): """Slot for the Preview button.""" if debug_flags.atom_debug: print 'preview button clicked' self.change_random_seed() self._ok_or_preview(previewing = True) def ok_btn_clicked(self): """Slot for the OK button.""" ### NEEDS RENAMING, ok -> done -- or merging with existing # done_btn_clicked method, below! The existence of both those methods # makes me wonder whether this one is documented correctly as being # the slot [bruce 070725 comment]. ### WARNING: Mark says PropMgrBaseClass depends on its subclasses # inheriting this method. This should be fixed when we refactor. # (Maybe this is true for some other _btn_clicked methods as well.) # [070724 code review] if debug_flags.atom_debug: print 'ok button clicked' self._gensym_data_for_reusing_name = None # make sure gensym-assigned # name won't be reused next time self._ok_or_preview(doneMsg = True) self.change_random_seed() # for next time if not self.pluginException: # if there was a (UserError, CadBug, PluginBug) then behave # like preview button - do not close the dialog ###REVIEW whether that's a good idea in case of bugs # (see also the comments about return value of self.close(), # which will be moved to GeneratorPM when we refactor) # [bruce 070615 comment & 070724 code review] self.accept() self.struct = None # Close property manager. Fixes bug 2524. [Mark 070829] # Note: this only works correctly because self.close comes from # a PM class, not from this class. [bruce 070829 comment] self.close() return def handlePluginExceptions(self, aCallable): """ Execute aCallable, catching exceptions and handling them as appropriate. (WARNING: I am guessing the standard type name for a callable.) @param aCallable: any Python callable object, which when called with no arguments implements some operation within a generator. @type aCallable: callable """ # [bruce 070725 renamed thunk -> aCallable after code review] ### TODO: teach the exceptions caught here to know how to make these # messages in a uniform way, to simplify this code. # [070724 code review] self.pluginException = False try: return aCallable() except CadBug, e: reason = "Bug in the CAD system" except PluginBug, e: reason = "Bug in the plug-in" except UserError, e: reason = "User error" except Exception, e: #bruce 070518 revised the message in this case, # and revised subsequent code to set self.pluginException # even in this case (since I am interpreting it as a bug) reason = "Exception" #TODO: should improve, include exception name print_compact_traceback(reason + ": ") env.history.message(redmsg(reason + ": " + quote_html(" - ".join(map(str, e.args))) )) self.remove_struct() self.pluginException = True return def _ok_or_preview(self, doneMsg = False, previewing = False): """ Private method. Do the Done or Preview operation (and set the Qt wait cursor while doing it), according to flags. """ ### REVIEW how to split this between GeneratorCommand and GeneratorPM, # and how to rename it then # [070724 code review] QApplication.setOverrideCursor( QCursor(Qt.WaitCursor) ) self.win.assy.current_command_info(cmdname = self.cmdname) def aCallable(): self._build_struct(previewing = previewing) if doneMsg: env.history.message(self.cmd + self.done_msg()) self.handlePluginExceptions(aCallable) QApplication.restoreOverrideCursor() self.win.win_update() def change_random_seed(self): #bruce 070518 added this to API """ If the generator makes use of randomness in gather_parameters, it may do so deterministically based on a saved random seed; if so, this method should be overloaded in the specific generator to change the random seed to a new value (or do the equivalent). """ return def gather_parameters(self): """ Return a tuple of the current parameters. This is an abstract method which must be overloaded in the specific generator. Each subclass (specific generator) determines how many parameters are contained in this tuple, and in what order. The superclass code assumes only that the param tuple can be correctly compared by same_vals. This method must validate the parameters, and raise an exception if they are invalid. """ raise AbstractMethod() def done_msg(self): """ Return the message to print in the history when the structure has been built. This may be overloaded in the specific generator. """ return "%s created." % self.name _gensym_data_for_reusing_name = None def _revert_number(self): """ Private method. Called internally when we discard the current structure and want to permit a number which was appended to its name to be reused. WARNING: the current implementation only works for classes which set self.create_name_from_prefix to cause our default _build_struct to set the private attr we use here, self._gensym_data_for_reusing_name, or which set it themselves in the same way (when they call gensym). """ if self._gensym_data_for_reusing_name: prefix, name = self._gensym_data_for_reusing_name # this came from our own call of gensym, or from a caller's if # it decides to set that attr itself when it calls gensym # itself. permit_gensym_to_reuse_name(prefix, name) self._gensym_data_for_reusing_name = None return def _build_struct(self, previewing = False): """Private method. Called internally to build the structure by calling the (generator-specific) method build_struct (if needed) and processing its return value. """ params = self.gather_parameters() if self.struct is None: # no old structure, we are making a new structure # (fall through) pass elif not same_vals( params, self.previousParams): # parameters have changed, update existing structure self._revert_number() # (fall through, using old name) pass else: # old structure, parameters same as previous, do nothing return # self.name needed for done message if self.create_name_from_prefix: # create a new name name = self.name = gensym(self.prefix, self.win.assy) # (in _build_struct) self._gensym_data_for_reusing_name = (self.prefix, name) else: # use externally created name self._gensym_data_for_reusing_name = None # (can't reuse name in this case -- not sure what prefix it was # made with) name = self.name if previewing: env.history.message(self.cmd + "Previewing " + name) else: env.history.message(self.cmd + "Creating " + name) self.remove_struct() self.previousParams = params self.struct = self.build_struct(name, params, - self.win.glpane.pov) self.win.assy.addnode(self.struct) # Do this if you want it centered on the previous center. # self.win.glpane.setViewFitToWindow(fast = True) # Do this if you want it centered on the origin. self.win.glpane.setViewRecenter(fast = True) self.win.win_update() # includes mt_update return def done_btn_clicked(self): "Slot for the Done button" if debug_flags.atom_debug: print "done button clicked" self.ok_btn_clicked() def cancel_btn_clicked(self): "Slot for the Cancel button" if debug_flags.atom_debug: print "cancel button clicked" self.win.assy.current_command_info(cmdname = self.cmdname + " (Cancel)") self.remove_struct() self._revert_number() self.reject() # Close property manager. Fixes bug 2524. [Mark 070829] # Note: this only works correctly because self.close comes from # a PM class, not from this class. [bruce 070829 comment] self.close() return def close(self, e = None): """ When the user closes the dialog by clicking the 'X' button on the dialog title bar, do whatever the cancel button does. """ print "\nfyi: GeneratorBaseClass.close(%r) was called" % (e,) # I think this is never called anymore, # and would lead to infinite recursion via cancel_btn_clicked # (causing bugs) if it was. [bruce 070829] # Note: Qt wants the return value of .close to be of the correct type, # apparently boolean; it may mean whether to really close (just a guess) # (or it may mean whether Qt needs to process the same event further, # instead) # [bruce 060719 comment, updated after 070724 code review] try: self.cancel_btn_clicked() return True except: #bruce 060719: adding this print, since an exception here is either # an intentional one defined in this file (and should be reported as # an error in history -- if this happens we need to fix this code to # do that, maybe like _ok_or_preview does), or is a bug. Not # printing anything here would always hide important info, whether # errors or bugs. print_compact_traceback("bug in cancel_btn_clicked, or in not reporting an error it detected: ") return False pass # end of class GeneratorBaseClass # end
NanoCAD-master
cad/src/command_support/GeneratorBaseClass.py
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. """ generator_button_images.py -- A few hardcoded images useful in generator dialogs. (These should probably be replaced with files in cad/images. Or, they might become obsolete sometime soon.) @author: Mark @version: $Id$ @copyright: 2006-2007 Nanorex, Inc. See LICENSE file for details. """ # FYI, this is where this file originally came from: # # Form implementation generated from reading ui file '...\nanotube_mac.ui' # # Created: Tue May 16 12:05:20 2006 # by: The PyQt User Interface Compiler (pyuic) 3.14.1 image0_data = [ "20 20 3 1", "# c #1c0a08", "a c #8d8483", ". c #ffffff", "....................", "....................", "....................", "....................", "####################", ".a.a##a.a##a.a##a.a.", ".#a#..#a#..#a#..#a#.", "#...##...##...##...#", ".#.#..#.#..#.#..#.#.", "..#....#....#....#..", "..#....#....#....#..", ".#.#..#.#..#.#..#.#.", "#...##...##...##...#", ".#a#..#a#..#a#..#a#.", ".a.a##a.a##a.a##a.a.", "####################", "....................", "....................", "....................", "...................." ] image1_data = \ "\x89\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d" \ "\x49\x48\x44\x52\x00\x00\x00\x16\x00\x00\x00\x16" \ "\x08\x06\x00\x00\x00\xc4\xb4\x6c\x3b\x00\x00\x00" \ "\x83\x49\x44\x41\x54\x78\x9c\xed\x94\x31\x0e\x80" \ "\x20\x0c\x45\x7f\x8d\x03\xc2\x15\xe0\xae\x78\x56" \ "\xcf\x60\x1c\xbf\x8b\x98\x86\xb8\x60\xda\xc1\xc4" \ "\x2e\x25\x8f\xe6\x43\xe8\x2f\x42\x12\x1e\x31\xb9" \ "\xa8\xfe\xc2\x3a\x66\x00\x28\x69\x31\xed\xe0\xb6" \ "\x1f\x32\xb5\x05\x80\xb5\x65\x55\x33\xcc\xae\x0c" \ "\x90\x04\x49\xe4\x18\x98\x63\xa8\x39\x06\x5a\xb0" \ "\x7b\xa3\x01\x55\xf8\x9a\xdd\xc2\x1a\xf4\x37\x79" \ "\xcb\xf0\x74\x9a\x05\x73\xb3\x9b\xef\x53\xb8\x37" \ "\xcf\xd2\x6e\x73\x67\xf2\x5a\xd2\xa2\x27\x71\x98" \ "\xb5\x10\x92\x2e\x23\x2d\xfc\x3f\xfa\xcf\x0a\x9f" \ "\x4d\xff\x95\x1c\x27\xfa\xbd\x8e\x00\x00\x00\x00" \ "\x49\x45\x4e\x44\xae\x42\x60\x82" image2_data = [ "135 40 764 2", "i0 c #045d95", "jQ c #0467a6", "jU c #055e96", "jT c #05629e", "i4 c #0564a0", "i5 c #0566a4", "jJ c #0768a5", "jN c #0769a6", "jI c #0769a7", "jb c #0a6aa7", "ir c #0a6ba8", "j. c #0b5f95", "i8 c #0b659d", "i9 c #0b6ba8", "iv c #0b6ca8", "iu c #0c6398", "iE c #0d68a2", "iD c #0e6399", "iy c #0e6ca9", "iz c #0e6da9", "i3 c #0f5b8b", "bO c #105b8a", "i# c #106da8", "i. c #106eaa", "hX c #106faa", ".P c #115987", ".O c #116499", ".U c #11669b", "hZ c #116faa", "hs c #136397", "hq c #136ba2", "hv c #136ea8", "hr c #1370ab", ".V c #165a7d", "hw c #166394", "g9 c #1670a9", "g5 c #1672ac", "hm c #1772ac", "hn c #1773ac", "#9 c #185f8d", "jc c #19608d", "jY c #19638f", "gT c #1972aa", "gS c #1974ad", "gU c #1a5a82", "jR c #1a5c86", "jZ c #1a618b", "j1 c #1a638f", "a3 c #1a75ad", "g8 c #1b6695", "a2 c #1b6a9a", "gC c #1b6c9f", "#7 c #1b71a7", "#8 c #1b75ae", "jX c #1c5c83", "gA c #1c73a9", "gZ c #1c76ae", "jM c #1d628d", "#Y c #1d6a9a", "g2 c #1d76ae", "gB c #1d76af", "jH c #20638e", "#W c #2077ae", "#X c #2078af", "gf c #2078b0", "a4 c #215a7e", "h9 c #216691", "iA c #226087", "f2 c #2277ab", "gL c #2279b0", "gO c #237ab0", "f1 c #237ab1", "gR c #246a95", "h0 c #266a94", "aP c #2772a0", "fJ c #2775a5", "fL c #28668c", "gr c #287db2", ".C c #297aad", ".I c #297db1", "gu c #297eb2", "fK c #297eb3", "g6 c #2a668a", "bN c #2a698f", ".D c #2a7eb3", ".N c #2b644a", ".E c #2b677f", "fl c #2b77a6", "aO c #2b80b3", "g# c #2e81b4", "fm c #2f81b4", "fk c #2f82b5", "e3 c #3077a3", "bP c #316888", "gV c #316b8e", "#T c #3283b5", "#S c #3283b6", "e2 c #337ca9", "fX c #3382b3", "ib c #346d90", "aB c #3477a1", "e0 c #3478a1", "fY c #3482b3", "fW c #3483b4", "fV c #3483b5", "fS c #3484b6", "iZ c #356989", "eY c #3585b5", "eZ c #3586b7", "#I c #3685b7", "#H c #3686b7", "iq c #387092", "es c #387ca5", "fG c #3883b2", "eu c #3a87b6", "fy c #3a87b7", "fv c #3a87b8", "fz c #3a88b8", "ey c #3b708f", "hW c #3b7293", "ex c #3b89b8", "et c #3b89b9", "aA c #3c89b9", ".T c #3d708e", "c3 c #3d7aa0", ".r c #3d85b2", "j2 c #3e6980", "hj c #3e7494", "fj c #3e7596", "#s c #3e7891", "fg c #3e87b4", ".x c #3e89b7", "gv c #3f7799", "fa c #3f8bba", "ic c #40728f", "dT c #408ab7", "fd c #408bb9", ".s c #408bba", "#E c #417fa5", "dO c #418dbb", "gY c #427695", "cZ c #4283ab", ".J c #437795", "ac c #437b9b", "c2 c #4387b1", "eV c #438ab6", ".t c #45788b", "gK c #457897", "eS c #458ebb", "ap c #467fa3", "cX c #468eba", "eP c #468fbc", "#C c #478fbb", "cY c #4790bd", "gq c #487a98", "#q c #488bb4", "#D c #4891bd", "gc c #497a98", "#R c #497c9b", "cl c #4982a5", "dS c #4a7e9e", "cS c #4a81a2", ".n c #4a84a7", "ep c #4a8fb9", ".i c #4b84a6", "el c #4b92bd", "ar c #4b92be", "g. c #4c7c99", "a8 c #4c7f9d", "em c #4c92be", "#r c #4c93be", "aq c #4c93bf", "aI c #4d7388", "fZ c #4d7c99", "cn c #4d93be", "cs c #4d94bf", "ge c #4e7a95", "cm c #4e94bf", "fR c #4f7e9a", "dP c #4f809c", "fH c #507e9a", "#G c #507f9d", "bT c #5091b8", "dG c #5094be", "ct c #517c94", "dN c #517e98", ".j c #51819e", "dB c #5196c0", "fu c #52809b", "bK c #52829f", "fh c #53809b", ".o c #53819b", "bS c #5384a2", "aJ c #5387a5", "g4 c #547e97", "am c #54829e", "aT c #548aa9", "cP c #5494bc", "bJ c #5498c1", "cQ c #558099", "aZ c #5592b6", "cO c #5596bd", "as c #567d93", "f# c #56829c", "a7 c #5694b9", "cV c #5698bf", "fn c #577e94", "eW c #57829c", "aK c #578baa", "cg c #5793b8", "aX c #5795bb", "cU c #5798c0", "cT c #5799c1", "cN c #579ac2", ".y c #58849d", "dH c #5889a6", "aU c #588ead", "ch c #5896bb", "jK c #598299", "jO c #59829a", "eO c #59849d", "eq c #5a849e", "d3 c #5a850c", "iM c #5a8609", "ce c #5a869f", "aY c #5a9cc3", "ix c #5b8199", "d2 c #5b8411", "ei c #5c869e", "cJ c #5c890b", "cd c #5d9dc4", "gg c #5e8398", "ii c #5e8d09", "dZ c #5e8e08", "eM c #5e9104", "dA c #6088a0", "da c #608f0b", "iI c #609106", "f0 c #61869b", "ia c #61879b", "fA c #61889f", "b0 c #618f10", "f9 c #61910a", "dc c #619209", "hy c #619404", "gF c #619406", "ef c #619503", "jP c #62859b", "ci c #62889e", "ca c #628c16", "cF c #628c17", "ah c #628ea2", "fO c #62920c", "hG c #62930a", "gi c #629603", "eC c #629703", "dh c #629704", "dL c #6389a0", "cM c #638aa1", "go c #638f12", "gI c #639013", "iL c #639508", "dY c #639803", "#O c #639903", "#P c #639a02", "dm c #648b1d", "b5 c #648f17", "b2 c #64930f", "bX c #649a05", "ja c #65889d", "iU c #659017", "cG c #659d02", "bI c #668a9e", "cc c #668ca2", "fQ c #669412", "in c #669414", "ft c #669908", "dt c #66990b", "iR c #669e02", "d5 c #67901b", "dz c #679318", "#M c #679f02", "c. c #67a002", "#4 c #688c2b", "e7 c #68911e", "eG c #68911f", "eg c #689515", ".W c #689a31", "ik c #68a002", "iW c #68a003", "ds c #68a101", "d6 c #68a102", "dg c #68a103", "dp c #699617", "hR c #69a201", "ec c #69a301", "iV c #69a302", "gP c #6a93ac", "#2 c #6a9421", "#3 c #6a9422", "f8 c #6aa303", "iO c #6aa502", "hf c #6b9224", "hV c #6b9321", "f6 c #6b981a", "f5 c #6ba405", "cw c #6ba501", "hH c #6ba502", "#x c #6ba602", "#L c #6ba702", ".m c #6c8c9f", "#1 c #6c902b", "iP c #6c9126", "e. c #6c9325", "f7 c #6c991b", "ih c #6ca701", "d9 c #6ca702", "dl c #6ca802", "aV c #6d8693", "hL c #6d9325", "ho c #6d95ad", "b6 c #6da901", "cy c #6da902", "#m c #6e926f", "cx c #6eaa02", "bW c #6eab02", "cC c #6f932d", "io c #6fab01", "c# c #6fac01", "cK c #6fac02", "cz c #6fad02", "gX c #70952e", "g3 c #7097ae", "hU c #70ad02", "fP c #70ae01", "b1 c #70ae02", "#V c #7191a3", "ab c #7193a6", "ed c #71952d", "eK c #71952e", "cA c #719530", "#N c #71af02", "dU c #7291a1", "ag c #7396a3", "#d c #73a231", "aS c #748f9e", ".H c #749870", "aL c #7592a2", "cr c #7693a4", "gw c #7695a8", "gx c #7696a8", "hC c #769a35", "iJ c #77983b", "h. c #7896a5", "fe c #7898aa", "if c #78993b", "hN c #799445", "ew c #7996a7", "hT c #799c3a", ".0 c #7ab315", ".h c #7b95a4", "eX c #7b97a6", "co c #7b98a7", "#6 c #7b9aa9", "#n c #7b9aad", ".Q c #7b9bad", "#h c #7c8e5b", "c7 c #7c964c", "#B c #7c98a6", "b7 c #7c9948", "iX c #7e9a4b", "fs c #7fa33e", "e# c #809d4a", "aN c #809eaf", "h5 c #80a2b4", "fr c #80a33e", "fq c #80a33f", "dC c #81929b", "cf c #819daa", "bx c #819eac", "al c #819eae", "#J c #819faf", "h6 c #81a2b4", "cL c #829d4f", "en c #829ead", "e8 c #829f4c", "eJ c #829f4d", ".w c #82a17b", "eT c #82a1b2", "h4 c #82a5b7", "gp c #839f4e", "h1 c #83a5b7", "f3 c #849daa", "hu c #849dab", "ai c #85a1a8", "i2 c #85a1af", "h3 c #86aabe", "c8 c #879767", "hS c #87a058", "h2 c #87aabe", "iQ c #88a257", "hM c #89a356", "gJ c #89a357", "az c #89a3b1", "ad c #89a6b6", "gj c #89aa4d", "by c #8a9ea7", "ev c #8aa3b0", "hI c #8ba160", "iG c #8ba35e", "dV c #8ba45d", "gW c #8baa50", "dy c #8ca165", "eA c #8ca45d", "fp c #8ca65e", "bE c #8caab9", "ha c #8cab51", "bU c #8da5b1", "bD c #8daab9", "gy c #8ea0ab", "#U c #8ea7b5", "bC c #8eaab8", "bF c #8eaab9", "cW c #90a4ae", "iK c #90a668", "hB c #90ac5a", ".9 c #90c139", "f4 c #91a960", "b# c #92a867", "bw c #93a4ad", "i1 c #93a6b1", "is c #93a8b3", "ba c #93a967", "#c c #93abb5", "hY c #94a9b4", "bk c #94aa68", "#l c #94bf49", "e1 c #95a5ad", "be c #95a674", "#p c #95a9b3", "hk c #95a9b4", "bf c #95aa6a", "g0 c #96aab4", "iF c #96abb5", "d# c #97a47d", "gM c #97abb5", "#w c #98a879", "bj c #98a978", "ip c #98ab74", "gs c #98abb5", "bb c #98ad71", "gz c #99aab3", "ga c #99acb6", "fT c #9aadb6", "gk c #9baa7e", "hl c #9baeb8", "bs c #9bb36f", "fF c #9cacaf", "fw c #9cadb6", "g1 c #9caeb9", "gN c #9cafb9", "bq c #9cb36f", "br c #9cb370", "fb c #9daeb6", "gt c #9db0b9", "bt c #9db470", "an c #9db6c3", "eQ c #9eaeb7", "gb c #9eb0b9", "hz c #9eb276", "ej c #9fafb7", "fU c #9fb0ba", "fx c #9fb1ba", "bp c #9fb376", "#u c #a0aa8c", "df c #a0ae84", "hJ c #a0b080", "fc c #a0b1ba", "#z c #a1ae88", "eR c #a1b2ba", "b9 c #a1b47b", "hF c #a1b57a", "i6 c #a2b1b8", "hp c #a2b1b9", "ek c #a2b2ba", "hO c #a2b580", "#Z c #a2b8c3", "iw c #a3b1b9", "bg c #a3b286", "hD c #a3b77d", "aW c #a4b3b9", "hE c #a4b87e", "iH c #a5b386", "dW c #a5b485", "e4 c #a5b9c1", "#A c #a6af94", "ea c #a6b48a", "e9 c #a6b48b", "j0 c #a6bbc4", "#v c #a8b590", "dk c #a9ad9e", "dF c #a9b9c0", "bM c #a9bac1", "dq c #aab78f", ".8 c #aad065", "bu c #abb990", "j# c #abbfc7", "i7 c #acb8bf", "#y c #acbb8d", "aQ c #acc0ca", "#e c #acd16b", "ig c #aeba96", "a0 c #aebdc3", ".F c #aed373", "a6 c #afbabf", "hb c #b0b99e", "bl c #b0bc95", "bG c #b0bfc4", "ht c #b0c2ca", "gG c #b1b99f", ".G c #b1d471", "dd c #b2b7a7", "fI c #b2bfc5", "gD c #b3c0c5", "#b c #b4c0c5", "jV c #b4c3c9", ".B c #b6c1c6", "hA c #b6c2a1", "bB c #b6c3c8", "a. c #b6cad2", "cv c #b7bfa7", "bV c #b7c0a6", "jF c #b7c3ca", "jE c #b7c4ca", "du c #b8bfa8", "c1 c #b8c1c6", "de c #babfb1", "eo c #bac5c6", "dI c #bbc2c5", "#o c #bbc6cb", "bY c #bcc8a6", ".u c #bcdb85", ".q c #bdc5c9", "iC c #bec8cc", "eU c #bec9c9", "ff c #bec9ca", "jD c #bec9ce", ".k c #becbd0", "aC c #becfd6", "bQ c #bed1d8", ".v c #bedc83", "c4 c #bfced4", "do c #c0c4b7", "#K c #c0c7b1", ".1 c #c0dd94", "c0 c #c1ccd0", "g7 c #c1cfd2", "iT c #c2cab0", "jq c #c3cab5", "jt c #c3cab6", ".2 c #c3d3da", "jh c #c4c9b7", "bo c #c4cab4", "jf c #c4cbb5", "er c #c5ced1", "#t c #c5d4d5", "dK c #c6cbcc", "dD c #c7cacb", "fC c #c7cfd0", "eb c #c8cfba", "he c #c8cfbb", "fB c #c8cfd0", "af c #c8d0cc", "a1 c #c8d0d3", "it c #c8d1d4", "dn c #c9cbc3", "c9 c #c9cbc5", "#F c #c9d4d8", "d. c #cacbc5", "d8 c #caccc4", "dJ c #caced0", "fD c #cad2d4", ".6 c #cad7dc", ".p c #cbd7da", ".3 c #cbdde4", "jW c #cccfd0", "hQ c #ccd1c0", "jr c #ccd1c2", "dr c #ccd3bd", "hx c #ccd5d8", "b3 c #ced5c1", "#Q c #ced8b9", ".M c #cee2b1", "jw c #cfd3c4", "cH c #cfd6c1", "dE c #d0d2d3", "ji c #d0d4c8", "fE c #d0d9db", "dx c #d1d3cb", "bc c #d1d8c2", "hd c #d2d4ca", "eH c #d2d4cb", "jG c #d2d6d7", "jn c #d2d7c5", "d7 c #d3d5cc", "c6 c #d3d6cd", "jm c #d3d9c5", "dw c #d4d6cd", "dv c #d4d6ce", "jo c #d4d8c9", "h7 c #d4d9dc", "a9 c #d4e0e4", "il c #d5d7d0", "iS c #d5d7d1", "jk c #d5dbc6", "ck c #d5dbdc", "jl c #d5dcc5", "jx c #d6d9cc", "cR c #d6e0e4", "js c #d7dacf", "ao c #d7dadb", "b. c #d7dbcd", "fo c #d7ddca", "je c #d8dbd2", "fM c #d8e4e8", "dj c #d9dcd3", "jz c #dae4e5", "fN c #dbe2cb", "jA c #dbe4e5", "cb c #dce1cf", "gQ c #dde0e1", "hh c #dde1d1", "jd c #e0e8e9", "dX c #e1e3db", "eE c #e2e4db", "ee c #e2e7d8", ".7 c #e2edef", "eB c #e3e5dd", "eF c #e3e5de", ".Z c #e3efc9", "bh c #e4e6df", "di c #e4e7df", "jy c #e4eaeb", "gh c #e5e7df", "jj c #e5e7e0", "h8 c #e5e7e8", "jS c #e5eef0", "bR c #e6e9e9", "aH c #e7e9e9", ".e c #e7ebec", "eL c #e7ecdc", "iB c #e7f0f2", "jL c #e8ebec", "aj c #e8f0ea", "ez c #e8f0f2", "a5 c #e8f2f5", "bL c #e9eeee", "jC c #e9eeef", "ie c #ebede3", "gE c #ebede4", ".b c #eceded", "dR c #eceeee", "hP c #edeeeb", ".S c #edf0f1", "fi c #edf1f1", "#0 c #eef0e8", "bv c #eef3e5", "cq c #eef8fb", "aa c #eff3f4", ".X c #eff7e0", "cj c #f0f4f5", "jp c #f1f1ef", "jB c #f1f4f4", "cI c #f1f6e6", "c5 c #f2f3f0", "aE c #f2f4f3", "ju c #f3f4f3", ".l c #f3f4f4", "d0 c #f3f5ec", "eD c #f3f5ed", "h# c #f3f5ee", "iY c #f3f5ef", "dQ c #f3f6f6", "cu c #f3f9fa", "im c #f4f5ed", "jv c #f4f5f0", "av c #f4f6f6", "#g c #f5f5f3", "db c #f5f7ee", "gn c #f5f7f0", "ak c #f5f9fa", "bH c #f5fafb", ".c c #f6f8f7", "dM c #f6f8f8", "ij c #f7f7f3", "iN c #f7f8f3", "aF c #f7f9f8", ".f c #f7fafa", "gH c #f8f9f6", "bZ c #f8faf1", "d1 c #f8faf2", "bm c #f8faf3", "#. c #f8fbee", "#5 c #f8fbef", ".5 c #f8fcfd", "j4 c #f8fdfd", "j5 c #f8fefe", "hc c #f9f9f5", "aw c #f9fafa", "ae c #f9fcfd", "jg c #fafaf8", "aD c #fafaf9", "aG c #fafbfa", "gd c #fafbfb", "#i c #fafcf5", "gm c #fafcf8", "ax c #fafcfb", "id c #fafcfc", "j3 c #fafcfd", "b4 c #fafdf4", "cp c #fafefe", "gl c #fbfcf7", "bd c #fbfcf8", "hK c #fbfcfa", ".g c #fbfcfb", "#a c #fbfcfc", "cE c #fbfdf4", "#k c #fbfdf6", "bA c #fbfdfd", ".K c #fbfefe", "d4 c #fcfcf7", "au c #fcfcfc", "b8 c #fcfdf9", "cD c #fcfdfb", "aR c #fcfdfc", "aM c #fcfdfd", "bi c #fcfef9", ".z c #fcfefe", "e6 c #fdfdf8", "hg c #fdfdfb", ".4 c #fdfdfc", ".d c #fdfdfd", "bz c #fdfdfe", "cB c #fdfefa", "bn c #fdfefb", "#j c #fdfefc", "ay c #fdfefd", ".R c #fdfefe", "hi c #fefefb", "#f c #fefefc", ".L c #fefefd", ".a c #fefefe", "a# c #fefeff", "eh c #fefffc", "e5 c #fefffd", ".# c #fefffe", ".Y c #feffff", "eI c #fffefc", "## c #fffefe", "at c #fffeff", "eN c #fffffc", "f. c #fffffd", ".A c #fffffe", "Qt c #ffffff", "QtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQt", "QtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQt", "QtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQt.#.#.#.a.b.c.a.#.#.a.d.e.f.a.a.aQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQt", "QtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQt.a.a.g.h.i.j.k.a.a.l.m.n.o.p.a.a.aQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQt", "QtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQt.a.a.q.r.s.s.t.u.v.w.x.s.s.y.z.aQt.A.AQtQtQtQtQtQtQtQtQtQtQtQtQtQtQt", "QtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQt.a.a.B.C.D.D.E.F.G.H.I.D.D.J.K.aQt.A.AQtQtQtQtQtQtQtQtQtQtQtQtQtQtQt", "QtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQt.a.L.M.N.O.P.Q.R.a.S.T.U.V.W.X.#.AQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQt", "QtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQt.A.Y.A.a.Z.0.1.2.3.z.a.4.a.5.6.7.8.9#..a.A##QtQtQtQtQtQtQtQtQtQtQtQtQtQtQt", "QtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQt.a#a#b#c#d#e#f.a.L.a#g#h#i.L#j.a#k#l#m#n#o.aQtQtQtQtQtQtQtQtQtQtQtQtQtQtQt", "QtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQt.a#p#q#r#s#t.a.a#u#v#w#x#y#z#A.L.a#B#C#D#E#FQtQtQtQtQtQtQtQtQtQtQtQtQtQtQt", "QtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQt.a#G#H#H#I#J.a.a#K#L#M#N#O#P#Q.a.R#R#S#S#T#UQtQtQtQtQtQtQtQtQtQtQtQtQtQtQt", "QtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQt.a#V#W#X#Y#Z.a.a#0#1#2#3#3#4#5.a.a#6#7#8#9a.QtQtQtQtQtQtQtQtQtQtQtQtQtQtQt", "QtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQta#aaabacadae.a.a.aafagahaiaj.L.a.aakalaman.zQtQtQtQtQtQtQtQtQtQtQtQtQtQtQt", "QtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQt.A.a.a.R.aa#.a.Laoapaqaqaras.5.a.a.a.a.a.a.aQtQtQtQtQtQtQtQtQtQtQtQtQtQtQt", "QtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtat.aauavawaxay.aazaAaAaAaAaBaC.aaDaEaFaG.a.aQtQtQtQtQtQtQtQtQtQtQtQtQtQtQt", "QtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQt.a.aaHaIaJaKaLaMaNaOaOaOaOaPaQaRaSaTaUaV.aQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQt", "QtQtQtQtQtQtQtQtQtQtQtQtQtQtQtat##.#Qt.YQtQtQtQtQtQt.a.a####.aQtQt##Qt.YQt.Y.###.Y.a.a.#.A.A.#.aQt.YQtQtQtQtQtQtQtQt.A.Aat.#.Y.#.aa#.A.a.AQtQtQt.Y.Yat.a.Yat.A.a.Y.AQtatQtQtQta#at.a.a.aa#atatQta#.Y.a.a.aaWaXaYaZa0a1a2a3a3a3a4a5a6a7aYa8a9.a.aQtQtQtQtQtQtQtQtQtQtQtQtQtQtQt", "QtQtQtQtQtQtQtQtQtQtQtQtQtQtQtb.b#bababababababababababbbc.L.aQt.Ybdbebababababababfbgbh.a.#bibjbababababababababababkblbm.a.a.#.abnbobpbqbrbrbqbqbsbtbubv.a.a.abwbxbxbxbxbxbxbybz.abAbBbCbDbDbEbEbEbFbGbHaxbIbJbJbKbLbMbNbObPbQbRbSbJbTbU.a.a.AQtQtQtQtQtQtQtQtQtQtQtQtQtQtQt", "QtQtQtQtQtQtQtQtQtQtQtQtQtQtQtbVbW#N#N#N#N#N#N#N#N#N#N#NbXbY.aQt.YbZb0#N#N#N#N#N#N#Nb1b2b3.ab4b5#N#N#N#N#N#N#N#N#N#N#Nb6b7b8.a.L#fb9c.#N#N#N#N#N#N#N#Nc#cacb.a.acccdcdcdcdcdcdceaM.zcfcgcdcdcdcdcdcdcdchcicjckclcmcnco.Rcpcqcp.acrcscmctcu##.a.AQtQtQtQtQtQtQtQtQtQtQtQtQtQtQt", "QtQtQtQtQtQtQtQtQtQtQtQtQtQtQtcvcwbW#N#Ncxcycycycycycz#N#NcAcB.#a#bZb0#N#N#N#N#N#N#N#N#NcCcDcEcFcyb1#Nczcycycycycycx#N#NcGcH.a.acIcJ#N#NcKcycycycycyb1#Nb1cL.L.acMcNcNcOcPcPcPcQbAcRcScNcNcTcUcUcUcUcNcNcV#p.acWcXcYcZc0.a.a.ac1c2cYc3c4.a.#a#.YQtQtQtQtQtQtQtQtQtQtQtQtQtQtQt", "QtQtQtQtQtQtQtQtQtQtQtQtQtQtQtc5c6c7#N#Nc8c9c9c9d.c9d#cx#Ndadb.aa#bZb0#Ndcdddedededfdg#Ndhdi.Ldjdkdl#Ndmdnd.d.d.c9dodp#Nb1dq.a##drds#NdtdudvdwdvdvdxdycK#Ndz#f.#dAdBdBdCdDdDdDdE.adFdGdBdHdIdJdJdJdK#VdBdBdL.adMdNdOdOdPdQ.adRdSdOdTdU.R.aQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQt", "QtQtQtQtQtQtQtQtQtQtQtQtQtQtQt.a.adV#N#NdW.AQtQt.a.#dXdY#NdZd0.aatd1d2#Md3c5.a.a.ad4d5#Nd6d7.a.ad8d9#Ne.#f.aQtQt.a.ae##N#Nea.a.Aebec#Ned.L.a.A.A.a.aeeef#Negeh.Yeiararejatat.a.a.aekelemen.a.aQt.a.aeoepemeq.a.aereseteuev.aewexeteyez.a.aQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQt", "QtQtQtQtQtQtQtQtQtQtQtQtQtQtQt.A.aeA#N#NdW.A.A.Aa#.aeBeC#NdZeD.A.a.LbheEeF.4.a.a.acBeG#Nd6eH.a.ad8d9#Ne.eIQt.A.A.#.aeJ#N#Nea.#.aebec#NeK.L.YQtQt.a.aeLeM#NegeN.#eOePePeQa#at##a#.aeReSePeT.#.a.a.a.aeUeVePeW.#.a.aeXeYeZe0e1e2eZe3e4.a.a.aQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQt", "QtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQt.AdV#N#NdW.AQtQtQtQteFeC#NdZeDQt.#.a.a.L.L#f#fe5e5e6e7#Nd6eHQtQtd8d9#Ne.eNQtQtQtQt.Ae8#N#Ne9.AQtebec#NeKf.QtQtQtQtQteLeM#NegeN.Yf#fafafbQtQtQtQtQtfcfd.sfe.#.a.YQt.afffg.sfh.YQt.afifjfkfkflfkfmfncp.aatQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQt", "QtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQt.AdV#N#NdW.AQtQtQtQteFeC#NdZeDQt.a.Lfofpfqfrfqfqfqfsft#Nd6eHQtQtd8d9#Ne.eNQtQtQtQt.Ae8#N#Ne9.AQtebec#NeKf.QtQtQtQtQteLeM#NegeN.YfufvfvfwQtQtQtQtQtfxfyfzfAfBfCfDfEfEfFfGfzfH.YQt.a.afIfJfKfKfKfLfM.a.YQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQt", "QtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQt.AdV#N#NdW.AQtQtQtQteFeC#NdZeDQt.afNfOfP#N#N#N#N#N#N#N#Nd6eHQtQtd8d9#Ne.eNQtQtQtQt.Ae8#N#Ne9.AQtebec#NeKf.QtQtQtQtQteLeM#NfQeN.YfRfSfSfTQtQtQtQtQtfUfVfSfWfXfXfXfYfYfXfSfSfZ.#.#.a.aayf0f1f1f2f3.a.a.YQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQt", "QtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQt.AdV#N#NdW.AQtQtQtQteFeC#NdZeDQt.Lf4#N#Nf5f6f7f7f7f6f8#Nd6eHQtQtd8d9#Ne.eNQtQtQtQt.Ae8#N#Ne9.AQtebec#NeKf.QtQtQtQtQteLeM#Nf9eN.Yg.g#g#gaQtQtQtQtQtgbg#g#g#g#g#g#g#g#g#g#g#gc.a.a.#.agdgegfgf#Xgg.R.aQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQt", "QtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQt.AdV#N#NdW.AQtQtQtQtghgi#NdZeDQte5gj#N#Ngkglbdbdgmgngo#Nd6eHQtQtd8d9#Ne.eNQtQtQtQt.Agp#N#Ne9.AQtebec#NeKf.QtQtQtQtQteLeM#Nf9eN.YgqgrgrgsQtQtQtQtQtgtgrgugvgwgxgxgxgxgxgxgxgy.a.a.a.agzgAgBgBgBgCgD.aQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQt", "QtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQt.AdV#N#NdW.AQtQtQtQtgEgF#NdZeD.ae5gj#N#NgG.a.a.#.agHgI#Nd6eH.a.Ad8d9#Ne.eNQtQtQtQt.AgJ#N#Nea.A.aebec#NeKf.QtQtQt.AQteLeM#Nf9eN.YgKgLgLgMQtQtQtQt.YgNgLgOgP.a.a.YQtQt.a.a.a.a.a##.agQgRgSgTgUgSgSgVaa.a.AQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQt", "QtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQt.AdV#N#NdW.AQtQtQtQtgEgF#NdZd0.Y.LgW#N#NgG.a.a.a.#gHgI#Nd6eH.a.#d8d9#Ne.eNQtQtQtQt.AgJ#N#Ne9.a.aebec#NgX.LQt.AQt.a.AeLeM#Nf9eN.#gYgZgZg0QtQtQtQt.Yg1g2g2g3.aa#a#QtQt.a.a.a.a.a.aaug4g5g5g6g7g8g5g9h..a.a##QtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQt", "QtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQt.AdV#N#NdW.AQtQtQtQtgEgF#NdZh#.a.Lha#N#Nhb.a.a.#.ahcgI#Nd6hd.L.ad8d9#Ne.eNQtQtQtQt.AgJ#N#Ne9.a.aheec#Nhfhg.a.AQt.A.ahheC#Nf9hi.#hjg5g5hkQtQtQt.a.ahlhmhnho.aa#.YQtQt##.a.a.a.a.ahphqhrhsht.ahuhvhrhwhx.a.aQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQt", "QtQtQtQtQtQtQtQtQtQtQtQtQtQtQt##.#dV#N#NdW.AQtQtQt.AgEgF#NhyhzhA.LhB#N#NhChDhEhEhEhFhG#NhHhIhJhKd8d9#NhLeNatQtQtQt.AhM#N#NhNhOhPhQhR#NhHhShEhEhEhEhDhThU#NhVeh.#hWhXhXhYQt.YQt.a.agNhZhZh0h1h2h3h2h4h5h5h6h7.ah8h9i.i#ia.z.adQibi.i.icid.a.#.#QtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQt", "QtQtQtQtQtQtQtQtQtQtQtQtQtQtQt.a.adV#N#NdW.AQtQt.A.AiegF#N#N#Nif.Ligih#N#N#N#N#N#N#N#N#N#N#Niiijd8d9#Ne.#f.a.aQt.###gJ#N#N#Nikilimin#N#N#N#N#N#N#N#N#N#Nioip.L.#iqiririsa#a#Qt.a.aitiuiviviviviviviviviviviw.dixiyiziAiB.a.a.aiCiDiziEiF.a.#.aatQtQtQtQtQtQtQtQtQtQtQtQtQtQtQt", "QtQtQtQtQtQtQtQtQtQtQtQtQtQtQt.a.LiGcKcKiH.aQtQt.A.agEiIcKcKcKiJ.LbdiKiLcycycycycyd9hHhHhHhHiMiNd8iOcKiPhi.#QtQt.a.aiQcKcKcKiRiS.aiTiUiVcKcKcKcKcKcKcKiWiXiY.a.aiZi0i0i1a#atQtQt.a.ai2i3i4i5i5i5i5i5i5i5i5i6i7i8i9j.j#.a##.a.a.ajajbi9jcjd.a.a.aQtQtQtQtQtQtQtQtQtQtQtQtQtQtQt", "QtQtQtQtQtQtQtQtQtQtQtQtQtQtQt.a.ajejfjfeF.aQt.A.A.ajgjhjfjfjfji.a.a.Ljjjkjljljljljmjnjnjnjnjo.4jpjqjfjr.L.#QtQt.a.ajsjfjfjfjtju.a.ajvjwjfjfjfjfjfjfjfjxhg.a.a.ajyjzjAjB.aQtQtQt.a.a.ajCjDjEjEjEjEjEjEjFjFjGjHjIjJjK.K.aata#.a.ajLjMjIjNjO.z.a.aQtQtQtQtQtQtQtQtQtQtQtQtQtQtQt", "QtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQt.aQtQt.aQtQtQtQtQt.a.aQtQt.a.aQtQt.a.aQtQtQtQtQtQtQtQtQtQtQtQt.a.aQtQt.aQtQtQtQt.a.a.a.a.a.a.aQtQtQtQtQtQtQtQtQtQtQtQtQtQt.a.a.a.aQtQtQtQtQtQtQtQt.a.a.aQtQtQtQtQt.a.a.ajPjQjQjRjS.a.aQtQt.a.a.aeRjTjQjUjV.a.aQtQtQtQtQtQtQtQtQtQtQtQtQtQtQt", "QtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQt.A.ajWjXjYjZj0.a.a.aQtQt.#.a.aaRctj1jYj2j3.aQtQtQtQtQtQtQtQtQtQtQtQtQtQtQt", "QtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQt##.aayj4j4j5.R.a.a.aQtQt.#.a.L.a.zj4j4j4.a.aQtQtQtQtQtQtQtQtQtQtQtQtQtQtQt", "QtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQt", "QtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQtQt" ] image3_data = \ "\x89\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d" \ "\x49\x48\x44\x52\x00\x00\x00\x16\x00\x00\x00\x16" \ "\x08\x06\x00\x00\x00\xc4\xb4\x6c\x3b\x00\x00\x03" \ "\x01\x49\x44\x41\x54\x78\x9c\x9d\xd3\x5d\x88\x94" \ "\x65\x14\xc0\xf1\xff\xf3\xf5\xce\xb3\x33\xeb\x8c" \ "\xc9\xe4\xae\x88\xad\x29\xa5\x2d\xbb\x21\x06\x6d" \ "\x42\xb5\x64\x48\x10\x0b\x45\x97\xc2\x5e\x77\x15" \ "\x45\x44\x20\x28\x94\x50\xdd\x46\x41\x17\x86\x7d" \ "\x50\x1b\x65\x26\x45\x1f\x5a\xe8\x45\xb5\xa9\x5d" \ "\x04\x11\xb1\x6a\x94\xb2\xe9\xae\xe3\xc8\xec\xec" \ "\x7c\xef\xbc\xef\xbc\x73\xba\xd0\x8d\xb4\x75\x77" \ "\x76\x1f\x78\x6e\x0e\xe7\xfc\x38\xe7\xf0\x3c\x4a" \ "\x44\x58\xe9\x51\x2f\x2b\x4f\x17\x0e\x80\x9f\x48" \ "\xd2\x44\xf3\x2d\x35\xa0\xa2\x57\x8c\xde\xa9\x86" \ "\x4d\xce\xfc\x6e\x67\xed\xa4\x9d\xb5\x93\x76\xab" \ "\x3d\x6f\x56\x99\xdf\x48\xf1\x3a\xd0\x6d\x57\x84" \ "\x2a\x75\x9b\x7e\x58\xbf\xe1\xee\x72\x9b\x31\xd7" \ "\x62\x72\x59\x08\xc7\xc3\x59\x6a\xbc\x2f\x22\x95" \ "\x65\xc3\x4a\x29\xa5\xfb\xf4\x0b\xc1\x83\xc1\xa0" \ "\xf6\xd7\x06\x96\xba\x10\x7d\x1d\x35\x25\x27\x7b" \ "\x45\xe4\x7b\x80\xe5\x77\x6c\xd9\x61\xef\xb5\xcf" \ "\xb8\x8d\x4e\xa1\x80\x36\x84\xa7\x42\xe2\x33\xf1" \ "\xdb\xc0\xd8\x7c\xda\xb2\x76\xac\x94\x0a\xec\x26" \ "\xbb\xcf\xef\xf4\xab\x4c\x60\x30\xce\xd0\x3e\xd7" \ "\x26\x3c\x1e\x8e\x13\xf3\x8a\x88\x84\x2b\x82\x4d" \ "\xda\xec\xf2\xc3\x7e\xa7\x5b\xeb\x30\xce\x20\x93" \ "\xc2\xdc\x47\x73\x57\xa5\x2c\x2f\x8a\x48\xee\xbf" \ "\xb9\x1d\xc3\x4a\xa9\xb4\x1d\xb4\xaf\xfa\x87\x7c" \ "\xa0\x03\x0d\x75\xa8\x7f\x5a\x6f\xc5\xb9\x78\x3f" \ "\x70\xfa\xe6\xfc\x8e\x61\xb3\xde\x3c\x95\x7a\x3c" \ "\x35\x60\xd3\x16\xad\x34\x8d\xcf\x1b\x44\x13\xd1" \ "\x11\xe0\x1d\x59\xe0\x33\x74\x04\x2b\xa5\x92\x7e" \ "\x9b\x7f\xde\x0f\x7a\x6d\x02\x43\xf4\x4b\x44\xe3" \ "\x44\xe3\x2c\x6d\xf6\x89\x48\x7d\xa1\x9a\x8e\x60" \ "\xdf\xef\xef\xeb\x7e\xb4\xfb\x1e\xdb\x65\xa1\x04" \ "\xd5\x43\x55\x91\x39\x39\x20\x22\x7f\xdc\xaa\xa6" \ "\x23\xd8\xf5\xbb\x51\xdf\xef\xad\x76\x9a\xc6\x78" \ "\x83\xf0\x7c\x38\x01\x1c\x5a\xac\xc6\x2a\xa7\x1e" \ "\x4b\xdd\x9f\xda\xa6\x32\x2a\x31\x1f\x94\xaa\x44" \ "\xb5\x93\xb5\x73\xc4\x7c\x45\x0f\xae\xf7\xd9\xde" \ "\x11\x9b\xb6\x44\xd3\x11\xd5\x6f\xaa\x82\x70\x50" \ "\x44\xa6\x16\x85\x11\xd6\xbb\x3b\xdc\xfe\xec\xd3" \ "\xd9\x60\xfe\x7b\xc6\x85\x98\xe9\xcb\xd3\xd5\xe6" \ "\x9f\xcd\x91\x35\x4f\xac\x59\x9b\xdc\x9e\xec\x31" \ "\xce\x30\x73\x64\x86\xf0\x42\x78\x09\xf8\x72\xa9" \ "\x29\x35\x31\x1f\x56\xbe\xab\xbc\x5b\xfb\xa1\x86" \ "\xcb\x38\x5c\xc6\xe1\x37\x79\x56\x3f\xb9\xba\x1b" \ "\xcd\x68\xf2\xee\xe4\xee\xc4\xba\x84\x6e\x5d\x6c" \ "\x51\x39\x5e\x01\x38\x0c\xfc\xb5\x24\x2c\x22\x61" \ "\x3c\x13\xbf\x54\x78\xaf\x70\x3a\x3c\x1b\x62\x02" \ "\x83\x09\x0c\x99\x5d\x19\x12\x1b\x13\x23\x89\x0d" \ "\x89\x47\x8c\x33\x94\xbe\x28\xd1\xca\xb7\xa6\x80" \ "\x83\x0b\x3d\xaf\xff\x77\x0c\x88\x48\x2e\xbc\x10" \ "\x3e\x97\x7f\x33\x7f\x25\xbe\x1a\x63\x02\x43\xd7" \ "\xe6\x2e\xb2\xa3\xd9\x9e\xc4\x86\x44\x26\xfa\x3b" \ "\xa2\x7c\xac\x0c\x70\x0c\x98\x58\x0a\xfd\x17\xbe" \ "\x8e\xff\x5c\x19\xaf\xec\xc9\xbf\x95\x0f\x69\x82" \ "\x0e\x34\xd9\xdd\x59\x82\x75\x01\xc5\xc3\x45\xa2" \ "\x2b\x51\x19\xf8\xa0\x93\x6e\x6f\x80\xaf\x9f\xb1" \ "\xe2\x67\xc5\x03\x85\xb1\x02\xda\x68\x5c\xc6\xd1" \ "\x2e\xb6\x29\x9d\x28\x01\x1c\x05\x4e\x75\x82\xce" \ "\x77\x7a\xc3\x05\x7a\xdd\xed\xee\xc7\x2d\x9f\x6c" \ "\x91\xa1\x99\x21\xe9\x7b\xad\x4f\x50\x94\x80\xe1" \ "\x9b\x73\x17\xbb\x0b\x07\x61\x28\xb9\x35\x39\x35" \ "\x70\x74\x40\xd2\x3b\xd2\x02\x7c\x0c\x04\xcb\x81" \ "\xd5\xad\x56\xa6\x94\x1a\x4e\x3f\x90\xde\x5e\xfb" \ "\xb5\x56\x8e\xe7\xe2\x93\x22\x72\xa6\xe3\x35\x00" \ "\xff\x00\x03\x11\x91\x02\x90\xac\x08\x8c\x00\x00" \ "\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82" image4_data = \ "\x89\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d" \ "\x49\x48\x44\x52\x00\x00\x00\x16\x00\x00\x00\x16" \ "\x08\x06\x00\x00\x00\xc4\xb4\x6c\x3b\x00\x00\x03" \ "\x15\x49\x44\x41\x54\x78\x9c\xb5\xd4\x5f\x68\x95" \ "\x75\x1c\xc7\xf1\xf7\xf7\xf9\x3d\xe7\x39\xcf\x4e" \ "\x4c\x0b\xc2\x46\x61\x8a\xb9\x10\xaf\xc2\x2e\x86" \ "\xa8\xb0\x41\x37\x25\x48\x85\xd9\x45\x5e\xb4\x90" \ "\x86\x4d\x02\xa1\x70\x14\x52\xbb\x10\x46\x66\xb4" \ "\xfe\xc0\x06\x6b\x20\x2a\x4d\x27\x91\x15\x5e\x44" \ "\xa5\x56\x28\xbb\x08\x02\x65\xe2\x22\x87\x0a\x9b" \ "\x86\xb8\xa1\xb9\x7f\x3d\xe7\xf7\xe9\xe2\x9c\x33" \ "\x9f\x73\x76\x0e\xcd\x8b\x7e\xf0\x85\xe7\x79\x7e" \ "\xbf\xdf\xeb\xfb\x7b\xbe\xf0\xfd\x99\x24\xfe\x8f" \ "\x11\xa4\x5f\x76\x45\x51\x53\x7b\x14\x7d\xb8\x2b" \ "\x8e\x9f\x5c\xcc\xe6\x4e\xb3\xd0\xcc\xac\xda\x9c" \ "\x95\x4e\xfc\x76\x14\x35\x79\xef\x8f\x60\xf6\x04" \ "\xf0\xf1\xb5\x24\x79\xeb\x98\x94\xaf\x85\xee\x31" \ "\xab\xcf\x87\xe1\x7b\x82\x39\x20\x8b\x73\xbd\x07" \ "\x66\x66\x46\x4a\xf3\x61\xe9\xc1\x49\x9b\x32\x66" \ "\xab\x00\x3c\xbc\xb6\x3a\x0c\xbf\x06\xce\xd4\x42" \ "\x43\xe7\xba\x1c\xb4\x01\x0e\xf8\x21\x99\x9d\xbd" \ "\x9d\x5e\x33\x5f\x8a\x81\x24\x99\xb8\x29\xf9\x18" \ "\xc8\xc1\x92\x2c\xbc\xd3\x65\xf6\x50\x25\xfa\x81" \ "\x59\x7d\xce\xb9\xae\xac\x59\x5b\x0c\xee\x96\x74" \ "\xeb\xa0\xf7\x7f\xed\x87\xfa\xaa\xf0\x15\x48\x7e" \ "\xf2\x5e\xff\x48\xc4\x85\x78\x26\x08\xc3\xf7\x3b" \ "\xcd\xa2\x34\x8a\x73\x5d\x75\xd0\x16\x4b\x6e\xcc" \ "\x7b\x06\xf3\xf9\xa5\x63\xde\x4f\x02\xd7\xab\xd6" \ "\xd8\xcc\x96\x18\x9c\xd8\x68\xd6\xfc\x7c\x10\xe0" \ "\x00\xc1\xb4\x49\x1d\x75\xde\xf7\x8d\x43\xf2\x60" \ "\x18\xee\x47\x6a\x07\xdc\x4d\xe0\x90\xf7\xfe\x8a" \ "\xd4\x03\x74\x48\xba\x53\x15\x2e\xe2\xcd\x59\x18" \ "\x78\x31\x08\x1e\xd9\x64\x56\xfa\x9d\x39\xe0\x08" \ "\xd2\x1f\x32\xdb\x6b\x50\x37\x05\xf4\x7b\xcf\x05" \ "\xe9\x24\xb0\x5d\xd2\x44\x65\xc9\x2a\x61\x03\xda" \ "\x63\x38\xf0\x92\x59\xd4\x72\x0f\x07\xc8\x03\x2e" \ "\x01\x8e\x4a\xfc\x28\x8d\x78\xd8\x2a\xe9\x7c\x25" \ "\x5a\x56\x63\x00\x15\xb2\xf4\xcf\x40\xdf\x71\x29" \ "\xff\xab\x44\x06\xc8\x16\xc2\x65\x81\x3b\xc0\x88" \ "\x74\xdb\xc3\xee\x5a\xe8\x02\xb8\x88\x4f\x01\x1d" \ "\xd3\xf0\xf9\x6f\x30\x0b\x10\xa7\x62\x25\xd0\x19" \ "\x04\x7f\x0f\x3a\x17\x0c\x9a\xb9\x5a\xb0\xd5\x6a" \ "\xe9\x2f\xcc\x56\x67\x82\xe0\xe4\x32\x68\x84\x42" \ "\xa1\x33\x40\xaa\xcd\x26\x0c\x0e\x26\xde\x7f\xba" \ "\x59\xba\xbc\x28\xf8\x3b\xb3\xdc\x03\x41\xf0\x99" \ "\x49\xad\x00\x53\x40\x8f\xc4\xa3\x66\x6c\x01\x72" \ "\x69\x00\x86\xbd\xd4\x3d\x03\x03\xcf\x4a\xf3\x4d" \ "\xb2\x10\x36\xb3\x73\xd0\x8e\xd9\x47\x06\x19\x0f" \ "\x1c\x06\x7a\xa5\x49\x60\x69\x0b\xd8\xeb\x66\x3c" \ "\x5e\xbe\x6b\x0e\x38\x8b\xd4\x93\x81\x6f\x9f\x96" \ "\xa6\x16\xc0\xbf\x9b\x35\x7b\xb3\xa3\x01\x2c\x03" \ "\x38\x0b\xbc\x2b\x5d\x9b\x84\x37\x80\x0d\xc0\xab" \ "\x8d\xd0\xb0\xc3\x8c\x96\x62\x79\xca\x12\x48\xdb" \ "\x9f\x92\x06\x91\x34\x1f\xc3\xb0\x62\xd8\x6c\xe8" \ "\xa2\x99\x2e\x9a\xe9\x17\x33\xad\x83\x69\xa0\xb5" \ "\x78\x00\x03\xd6\x03\xa7\x62\xf0\xdb\x40\xdf\x17" \ "\xd7\x96\x62\x08\x76\x48\x62\x1e\x1d\x83\xdc\x28" \ "\xf4\x8f\x82\x46\x41\x97\x41\x3b\x41\x01\xf4\x02" \ "\x51\xfa\x00\x40\x03\xf0\x09\x70\xb7\x11\xb4\x0f" \ "\xf4\x15\x68\x0f\x24\xeb\xa1\xad\x0c\xbe\x0e\x2f" \ "\x8f\xc1\xdc\x38\x68\x1c\x74\x1a\xb4\x1c\x2e\x01" \ "\xab\xd2\x68\x0a\x8f\x80\x56\xe0\xcf\x10\x94\x03" \ "\x01\x9e\x42\x27\xde\x83\x4f\xc0\xe6\x2f\x61\xfc" \ "\x06\xe8\x67\xd0\x0b\x85\x45\xbb\xab\xa1\x15\x09" \ "\xd6\x02\x3d\xc0\x37\xc0\x2b\xc0\xc3\x65\x30\xf0" \ "\x66\x0e\xfc\x73\xa0\x35\x85\xec\x17\x80\xc7\xfe" \ "\x0b\x2e\xee\x0d\x81\xb8\xec\x5b\x6a\x72\x23\xd0" \ "\x0d\x5c\x05\x4e\x01\xdb\x16\x83\xd6\x8a\x6a\x97" \ "\xd0\x4a\x60\xb2\xda\x8d\x75\x3f\xe3\x5f\xbf\xdc" \ "\x0a\xd6\x89\xe2\x2b\xac\x00\x00\x00\x00\x49\x45" \ "\x4e\x44\xae\x42\x60\x82" image5_data = \ "\x89\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d" \ "\x49\x48\x44\x52\x00\x00\x00\x16\x00\x00\x00\x16" \ "\x08\x06\x00\x00\x00\xc4\xb4\x6c\x3b\x00\x00\x02" \ "\xcf\x49\x44\x41\x54\x78\x9c\xed\x94\x4d\x68\x13" \ "\x51\x10\xc7\xe7\xbd\x7d\xd9\xec\x26\xeb\x26\x6d" \ "\x92\x4d\x25\xa5\xb5\x55\x14\x2b\xf6\x54\xb4\x45" \ "\xbc\x68\x05\xa9\x1f\x07\xc5\x83\x20\xa2\x20\xa5" \ "\x07\x45\x0f\x1e\x44\x54\xd0\x83\x52\x4f\x82\x9e" \ "\xc4\x0f\x54\x5a\x44\x2a\xa2\x22\x0a\x85\x88\x8a" \ "\x1f\x68\x6c\x6b\xd1\xaa\x68\x1b\x5b\x35\x31\xb5" \ "\x36\x5d\x9b\xd8\xdd\xcd\xdb\x37\x9e\x52\xab\xf6" \ "\xda\x83\xe0\x9c\xe6\xf0\x9f\x1f\x33\xf0\x9f\x3f" \ "\x41\x44\x98\x89\xa2\x33\x42\xfd\x0f\xfe\xb7\xc1" \ "\xac\xd8\x6c\xdf\x7e\x58\x09\xea\x64\xbf\x99\x1d" \ "\x6b\xe8\x7f\x9f\x2c\x7b\xd1\xfd\xb2\xd7\x2e\x90" \ "\x4e\xcb\xd5\xdb\x10\x13\x85\xa9\x43\xfb\xf6\x9d" \ "\xae\xd0\x54\x7a\x24\xd9\x3f\x58\x73\x37\xfe\x08" \ "\x32\x5f\x46\x13\x0e\x61\xd7\x0a\x85\x67\x9d\x45" \ "\x0d\x41\x44\x68\x6c\xdc\x13\x35\x42\x70\x6d\x5e" \ "\x55\xb4\x6a\x51\x59\x30\x13\x09\x07\xa5\xec\xc8" \ "\xc8\xc4\x95\xdb\x0f\xd4\xf8\xc3\x44\xdf\x48\xde" \ "\x6d\x41\x1c\xcc\x02\x00\xac\x5b\xb7\x73\xe5\xfc" \ "\xea\xc8\x89\x9a\xaa\x98\x1a\x55\xa9\xe9\xf1\xc8" \ "\xac\xa7\xe7\x0d\xbf\x70\x33\x1e\x18\x18\x4a\xdf" \ "\xb0\xc5\x87\xbd\x88\x28\x18\x00\x80\x65\x7d\x3d" \ "\xee\x73\xf5\xc0\xfa\x85\x91\x97\xaa\x4f\x25\x00" \ "\x02\xa2\xb1\x52\x38\xb0\x6d\xad\x69\x04\xfc\x95" \ "\x67\xaf\xde\x39\x02\x00\xbb\x9a\x9a\xb6\xe8\x32" \ "\xa1\x47\x17\xe9\x86\xb9\x34\xa6\x66\x8a\xdb\x95" \ "\x2f\x5f\x08\x75\xf3\x42\xa3\x2d\xad\xe7\x57\x27" \ "\x53\xe5\x09\x00\x68\x67\x73\x6a\x36\xce\x2e\x95" \ "\xed\xfa\x5a\xb4\x13\xe9\x87\xf7\x27\xac\xef\x63" \ "\xce\x8f\xcc\xb0\xad\x06\x82\x1e\x35\x1c\xf2\xd6" \ "\x32\x57\x53\x55\xba\x86\x90\xc8\xa9\x05\xd5\x95" \ "\x2b\x4a\x34\xc5\x08\xc7\x20\xfe\xee\x56\x1f\xcf" \ "\x0f\x0f\xdb\xdc\xca\x73\x9f\x11\x55\x14\x3d\x28" \ "\xaf\xac\x28\xb5\xce\xa5\x3f\xed\x00\x80\x76\x96" \ "\x4e\xa6\x9a\x1d\xef\x84\xfc\xe3\xf3\xdb\xfe\x57" \ "\xdc\x11\xc0\xc5\xaf\x1f\x67\x94\x00\x63\xd4\xb5" \ "\xb4\x7a\x46\xe5\xe6\x54\xfa\x63\x1d\x61\xfc\x6b" \ "\xdf\xd0\xe3\x8f\xbf\xe9\x00\x4c\x60\x94\xc8\xd4" \ "\x97\x67\x44\xde\x40\x48\xc9\x56\xc6\x1d\x1b\x73" \ "\x85\x71\x74\xfd\x0e\x4a\x42\xfc\x1e\x1c\x5c\xa0" \ "\x2d\x38\x14\x84\xe4\x11\x88\x31\xcb\x12\x8a\x4d" \ "\x39\x82\x2a\xfe\x0e\x18\x2e\x70\x5c\xb8\x12\xa2" \ "\x47\x00\x50\x97\x0a\xc1\x4f\xda\x08\xd9\x17\x4e" \ "\xa0\x6c\x3a\xdb\xf4\x73\x2d\x02\xc4\x6b\x0a\xf0" \ "\xed\xa6\x92\x76\xe8\x1b\x2a\x5a\x1e\xa8\x67\x3a" \ "\x6d\x37\xd7\x2a\x04\x28\x5d\x88\xa9\x36\x8a\xd8" \ "\x9b\x45\x80\x8b\x9d\x8e\x56\xff\x5a\xe8\xc6\x54" \ "\x61\x06\xbd\x5a\xdc\x31\xe6\x23\x94\x9c\x41\x1c" \ "\xc8\xd8\xfc\x43\x27\x87\xe0\xd3\xeb\x56\x6c\x71" \ "\x9e\xb2\x49\xb8\x4b\x29\xbd\xe7\x86\xe7\xbe\x13" \ "\x7a\xb5\xc3\x42\xad\x93\x76\x23\xa4\xce\xa3\xb0" \ "\xb1\x83\x80\x7c\xb3\x42\x88\x08\x12\xf8\x34\x4e" \ "\xa4\x88\x0d\x04\x38\xa8\x1d\x96\x23\x1f\x2b\x7a" \ "\x99\xcc\x5a\x66\xf8\x84\xd9\x2a\xa1\xd3\xe0\xa7" \ "\xae\xa9\x10\x91\xcb\xa2\x54\x6e\x51\xc9\x46\xe6" \ "\x3f\x6a\x8f\x76\x5d\x9e\x04\x17\xcb\xeb\xad\x5d" \ "\x2c\xc0\xd9\x04\x84\x6a\x40\x58\x8e\x4a\x9e\x0e" \ "\x3b\xf7\xbc\xf7\xcf\x93\x09\x21\x94\x19\x4b\x56" \ "\x81\xe0\x8d\x40\x5d\x09\x80\xa4\xb8\xdf\x7b\x09" \ "\x07\x9e\x4c\x5a\x90\xfc\x0f\xfa\x7f\x17\xfc\x13" \ "\xc9\x2f\x4f\xb7\x6f\xfb\xe3\xe6\x00\x00\x00\x00" \ "\x49\x45\x4e\x44\xae\x42\x60\x82" image6_data = \ "\x89\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d" \ "\x49\x48\x44\x52\x00\x00\x00\x16\x00\x00\x00\x16" \ "\x08\x06\x00\x00\x00\xc4\xb4\x6c\x3b\x00\x00\x02" \ "\x9d\x49\x44\x41\x54\x78\x9c\xb5\x94\xcf\x4b\x54" \ "\x51\x14\xc7\x3f\xf7\xcd\xd3\x37\xe9\xcc\xbc\x71" \ "\x1c\x67\x74\x98\x07\x86\xab\xd2\x7d\x86\xa1\x08" \ "\x11\x45\x85\x4a\xb4\x70\x27\x4a\x8b\x76\x2d\xfc" \ "\x0b\x5a\x89\xc8\x20\x48\xb4\x10\x8c\x36\xc2\xa0" \ "\x50\x38\x20\x04\xa1\x6d\x45\xa8\xb4\x8d\x2e\x02" \ "\x09\xc2\x18\xc9\x19\xc7\x19\x66\x70\x7c\x9e\x16" \ "\xf9\x63\x74\x9c\x1f\x15\x1d\x38\x8b\x7b\xdf\xf9" \ "\x7e\x38\xef\x9e\xef\xbd\x4a\x44\xf8\x1f\xa1\x97" \ "\xfb\xa8\x94\x52\x40\x2b\xe0\x2e\xd8\xde\x01\x12" \ "\x22\x92\x2b\xab\x2d\xd5\xb1\x52\xea\xba\x89\xf9" \ "\x2c\x4f\x7e\xc0\x8b\x57\x74\x74\x01\x70\xe0\x38" \ "\xc8\x90\xd9\x03\xa2\x71\xe2\x33\x22\xf2\xbd\x6a" \ "\xb0\x4f\xf9\xee\x1d\x71\xf4\xca\x8f\xdf\x33\xc0" \ "\x80\xb3\x8b\x2e\x65\x60\x00\x90\x26\xcd\x0a\x2b" \ "\x32\xc7\x5c\x6e\x97\xdd\x6f\x69\xd2\x8f\x45\xe4" \ "\x4b\x45\xb0\xa1\x8c\x76\x27\xce\xf7\xbd\xf4\x06" \ "\x86\x19\xd6\x3c\x78\xd8\x67\x9f\xa7\x3c\x45\x47" \ "\x67\x8c\x31\x1a\x69\x24\x45\x8a\x69\xa6\x53\x2b" \ "\xac\xac\x27\x49\xde\x17\x91\xd4\x39\x90\x88\x9c" \ "\x26\xa0\x9a\x69\x7e\xdd\x41\x47\x2e\x46\x4c\xa2" \ "\x44\xa5\x8f\xbe\xbd\x20\xc1\x9d\x93\x1a\x13\x33" \ "\xd9\x49\x67\x36\x4a\x54\xe6\x99\x17\x0b\x6b\x3f" \ "\x4c\xf8\x49\x21\x47\x44\x8a\xc0\x2d\x6e\xdc\xdb" \ "\x43\x0c\xc9\x34\xd3\xd2\x45\x57\x36\x48\xf0\x03" \ "\xf0\x10\xb8\x0a\xb4\xe8\xe8\x77\x5c\xb8\x36\xfb" \ "\xe9\x4f\x2f\xb3\x2c\x23\x8c\xd8\x7e\xfc\x1f\x01" \ "\x67\x21\xeb\xa2\x2b\x04\x68\x3c\x5b\x48\x6d\x92" \ "\xe4\x88\x88\x7c\x2d\xa8\xd9\x76\x28\xc7\x8b\x55" \ "\x56\x9f\x67\xc9\x62\x61\x69\x1a\x5a\x0b\x50\x03" \ "\x9c\x3a\xe5\x1c\x58\x44\x7e\x78\x95\xf7\xd3\x02" \ "\x0b\xfe\x18\x31\x01\xf6\x72\x92\x2b\x84\xa2\x94" \ "\x6a\x08\x10\xb8\xdb\x46\x5b\xad\x81\xc1\x06\x1b" \ "\x08\x92\x00\xf2\x85\x75\x45\x3e\x4e\x4a\xf2\xc6" \ "\xc5\xbd\x93\xa8\x53\x75\x37\x03\x04\x5e\xd6\x50" \ "\x73\x6d\x90\xc1\xda\x35\xd6\x58\x62\xe9\x40\x47" \ "\x9f\x2d\xf2\xf5\xc5\x43\x2f\x95\x41\x82\x0f\x4c" \ "\xcc\x9d\x1e\x7a\xf2\x33\xcc\x48\x84\x88\x84\x08" \ "\x1d\x58\x58\x6f\x01\x77\xd9\xe1\x95\x4a\x13\xf3" \ "\xb6\x0f\x5f\xa2\x8f\xbe\xa3\x45\x16\x25\x42\x44" \ "\x82\x04\xb3\x16\xd6\x9b\xcb\xa0\x55\x81\x01\x67" \ "\x13\x4d\x9f\xfb\xe9\xcf\x1f\x43\xed\x30\xe1\xbd" \ "\x10\xa1\xf1\x52\xd0\xcb\x5c\x51\x14\x06\x86\x75" \ "\xc8\x61\x5b\x37\xdd\x7a\x8e\x1c\x93\x4c\xa6\x33" \ "\x64\xc6\x12\x24\xc6\x45\xc4\x2e\xa5\xab\x08\x76" \ "\xe1\xea\xb4\xb1\x6b\x6d\x6c\xd6\x59\x67\x97\x5d" \ "\x3d\x4d\x3a\x56\x0e\x0a\x65\x1e\xa1\xd3\x8e\x95" \ "\xd1\x5e\x4f\xfd\xac\x86\x76\x05\x50\x0e\x1c\x5b" \ "\x71\xe2\x8f\x8a\xae\xf0\x9f\x82\x01\x94\x52\xed" \ "\x80\xf7\x78\xf9\x53\x44\x36\x2a\x69\x2a\x1e\x85" \ "\x52\xaa\xd5\xc4\x7c\x67\x63\x37\x00\x38\x70\x24" \ "\x94\x52\xb7\x44\x64\xeb\x9f\xc0\x80\xc7\xc6\x6e" \ "\x18\x65\xb4\x0e\x60\x82\x09\x00\x4f\x25\x91\x56" \ "\x05\xf8\xaf\xa2\x9a\x8e\x53\x1a\xda\xe6\x14\x53" \ "\xee\xdf\x9d\x68\xfb\x40\xd9\xc1\x41\xf5\xc3\xab" \ "\xe7\xec\xef\x8e\x44\x24\x53\x49\xf3\x0b\xdf\x5b" \ "\xae\x1e\x85\x69\x65\x97\x00\x00\x00\x00\x49\x45" \ "\x4e\x44\xae\x42\x60\x82" image7_data = \ "\x89\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d" \ "\x49\x48\x44\x52\x00\x00\x00\x10\x00\x00\x00\x08" \ "\x08\x06\x00\x00\x00\xf0\x76\x7f\x97\x00\x00\x00" \ "\x43\x49\x44\x41\x54\x78\x9c\x63\x60\xa0\x10\x30" \ "\xc2\x18\x0e\x0e\x0e\xff\x49\xd5\x7c\xe0\xc0\x01" \ "\x46\x46\x64\x01\x52\x0c\x39\x70\xe0\x00\x23\x8a" \ "\x0b\x48\x31\x04\xa6\x19\xab\x01\x84\x0c\x41\xd6" \ "\x8c\xd3\x00\x5c\x86\xa0\x6b\xc6\x6b\x00\xba\x21" \ "\xd8\x34\x13\x05\x08\x85\x09\x00\x0d\xae\x19\xc6" \ "\xff\xdc\x33\xb6\x00\x00\x00\x00\x49\x45\x4e\x44" \ "\xae\x42\x60\x82" # end
NanoCAD-master
cad/src/command_support/generator_button_images.py
# Copyright 2008 Nanorex, Inc. See LICENSE file for details. """ DnaOrCnt_PropertyManager.py DnaOrCnt_PropertyManager class provides common functionality (e.g. groupboxes etc) to the subclasses that define various Dna and Cnt (Carbon nanotube) Property Managers. @author: Ninad @copyright: 2008 Nanorex, Inc. See LICENSE file for details. @version:$Id$ History: Created on 2008-05-20 TODO: - Need a better name for this class? - The Reference list widget and related code (added on 2008-06-24) supports the feature in insert dna/cnt commands, where you can specify a reference plane on which the structure will be placed. The ui elelment allows adding /deleting this plane. Implementing this is not straightforward. It needs specific code in PM, GM and command classes. Need some core internal features that allow easy creation and handling of such ui. (Similar issue can be seen in the MakeCrossOvers or MultipleDnaSegmentResize commands where special code is needed to add or remove segments from the list. [-- Ninad 2008-06-24 comment] """ from PyQt4.Qt import Qt, SIGNAL from PM.PM_CheckBox import PM_CheckBox from PM.PM_PrefsCheckBoxes import PM_PrefsCheckBoxes from PM.PM_SelectionListWidget import PM_SelectionListWidget from PM.PM_RadioButtonList import PM_RadioButtonList from utilities.constants import lightgreen_2 from command_support.EditCommand_PM import EditCommand_PM from PM.PM_ColorChooser import PM_ColorChooser from PM.PM_ColorComboBox import PM_ColorComboBox _superclass = EditCommand_PM class DnaOrCnt_PropertyManager(EditCommand_PM): """ DnaOrCnt_PropertyManager class provides common functionality (e.g. groupboxes etc) to the subclasses that define various Dna and Cnt (Carbon nanotube) Property Managers. @see: DnaSegment_PropertyManager (subclass) @see: InsertDna_PropertyManager (subclass) """ def __init__( self, command ): """ Constructor for the DNA Duplex property manager. """ self._cursorTextGroupBox = None self._colorChooser = None self.showCursorTextCheckBox = None self.referencePlaneListWidget = None #For model changed signal #@see: self.model_changed() and self._current_model_changed_params #for example use self._previous_model_changed_params = None #see self.connect_or_disconnect_signals for comment about this flag self.isAlreadyConnected = False self.isAlreadyDisconnected = False _superclass.__init__( self, command) def show(self): """ Show this PM """ _superclass.show(self) if isinstance(self.showCursorTextCheckBox, PM_CheckBox): self._update_state_of_cursorTextGroupBox( self.showCursorTextCheckBox.isChecked()) def _loadDisplayOptionsGroupBox(self, pmGroupBox): """ Load widgets in the Display Options GroupBox """ self._loadCursorTextGroupBox(pmGroupBox) def _loadColorChooser(self, pmGroupBox): self._colorChooser = PM_ColorComboBox(pmGroupBox) def _loadCursorTextGroupBox(self, pmGroupBox): """ Load various checkboxes within the cursor text groupbox. @see: self. _loadDisplayOptionsGroupBox() @see: self._connect_showCursorTextCheckBox() @see: self._params_for_creating_cursorTextCheckBoxes() """ self.showCursorTextCheckBox = \ PM_CheckBox( pmGroupBox, text = "Show cursor text", widgetColumn = 0, state = Qt.Checked) self._connect_showCursorTextCheckBox() paramsForCheckBoxes = self._params_for_creating_cursorTextCheckBoxes() self._cursorTextGroupBox = PM_PrefsCheckBoxes( pmGroupBox, paramsForCheckBoxes = paramsForCheckBoxes, title = 'Cursor text options:') def connect_or_disconnect_signals(self, isConnect): if isConnect: change_connect = self.win.connect else: change_connect = self.win.disconnect if self._colorChooser: change_connect(self._colorChooser, SIGNAL("editingFinished()"), self._changeStructureColor) pass def _connect_showCursorTextCheckBox(self): """ Connect the show cursor text checkbox with user prefs_key. Subclasses should override this method. The default implementation does nothing. """ pass def _params_for_creating_cursorTextCheckBoxes(self): """ Subclasses should override this method. The default implementation returns an empty list. Returns params needed to create various cursor text checkboxes connected to prefs_keys that allow custom cursor texts. @return: A list containing tuples in the following format: ('checkBoxTextString' , preference_key). PM_PrefsCheckBoxes uses this data to create checkboxes with the the given names and connects them to the provided preference keys. (Note that PM_PrefsCheckBoxes puts thes within a GroupBox) @rtype: list @see: PM_PrefsCheckBoxes @see: self._loadDisplayOptionsGroupBox where this list is used. #see: self._loadCursorTextGroupBox() @see: subclass method: DnaSegment_PropertyManager._params_for_creating_cursorTextCheckBoxes() """ params = [] #Format: (" checkbox text", prefs_key) return params def _update_state_of_cursorTextGroupBox(self, enable): """ """ if not isinstance(self._cursorTextGroupBox, PM_PrefsCheckBoxes): return if enable: self._cursorTextGroupBox.setEnabled(True) else: self._cursorTextGroupBox.setEnabled(False) def _loadReferencePlaneGroupBox(self, pmGroupBox): """ Load widgets in reference plane groupbox @see: InsertDna_PropertyManager._addGroupBoxes where this groupbox is added. """ # Placement Options radio button list to create radio button list. # Format: buttonId, buttonText, tooltip PLACEMENT_OPTIONS_BUTTON_LIST = [ \ ( 0, "Parallel to screen (default)", "Parallel to screen" ), ( 1, "On the specified plane:", "On specified plane" )] self._placementOptions = \ PM_RadioButtonList( pmGroupBox, ##label = "Duplex Placement Options:", buttonList = PLACEMENT_OPTIONS_BUTTON_LIST, checkedId = 0, spanWidth = True, borders = False) self._specifyReferencePlane_radioButton = self._placementOptions.getButtonById(1) self.referencePlaneListWidget = PM_SelectionListWidget( pmGroupBox, self.win, label = "", heightByRows = 2) def useSpecifiedDrawingPlane(self): """ Tells if the the command (rather the graphicsmode) should use the user specified drawing plane on which the structure (such as dna duplex or CNT) will be created. Returns True if a Palne is specified by the user AND 'use specified plane' radio button in the Property manager is checked. @see: InsertDna_GraphicsMode.getDrawingPlane() """ if self.referencePlaneListWidget is None: return False if self._specifyReferencePlane_radioButton.isChecked(): itemDict = self.referencePlaneListWidget.getItemDictonary() planeList = itemDict.values() if len(planeList) == 1: return True return False def activateSpecifyReferencePlaneTool(self, index): """ Slot method that changes the appearance of some ui elements, suggesting that the Specify reference plane tool is active. @see: self.isSpecifyPlaneToolActive() """ if self.referencePlaneListWidget is None: return if index == 0: self.referencePlaneListWidget.resetColor() else: itemDict = self.referencePlaneListWidget.getItemDictonary() planeList = itemDict.values() if len(planeList) == 0: self.referencePlaneListWidget.setColor(lightgreen_2) else: self.referencePlaneListWidget.resetColor() def isSpecifyPlaneToolActive(self): """ Returns True if the add segments tool (which adds the segments to the list of segments) is active @see: InsertDna_EditCommand.isSpecifyPlaneToolActive() @see: InsertDna_GraphicsMode.isSpecifyPlaneToolActive() @see: InsertDna_GraphicsMode.jigLeftUp() """ if self.referencePlaneListWidget is None: return False if self._specifyReferencePlane_radioButton.isChecked(): itemDict = self.referencePlaneListWidget.getItemDictonary() planeList = itemDict.values() if len(planeList) == 1: return False else: return True return False def removeListWidgetItems(self): """ Removes all the items in the list widget @TODO: At the moment the list widget means 'self.referencePlaneListWidget' the method name needs renaming if there are some more list widgets in the Property manager. """ if self.referencePlaneListWidget is None: return self.referencePlaneListWidget.insertItems( row = 0, items = ()) self.referencePlaneListWidget.setColor(lightgreen_2) def updateReferencePlaneListWidget(self, plane = None): """ Update the reference plane list widget by replacing the current item (if any) with the specified <plane >. This plane object (if not None) will be used as a referecne plane on which the structure will be constructed. @param plane: Plane object to be """ if self.referencePlaneListWidget is None: return planeList = [ ] if plane is not None: planeList = [plane] self.referencePlaneListWidget.insertItems( row = 0, items = planeList) def listWidgetHasFocus(self): """ Checks if the list widget that lists the referecne plane, on which the dna will be created, has the Qt focus. This is used to just remove items from the list widget (without actually 'deleting' the corresponding Plane in the GLPane) @see: InsertDna_GraphicsMode.keyPressEvent() where this is called """ if self.referencePlaneListWidget and \ self.referencePlaneListWidget.hasFocus(): return True return False def _changeStructureColor(self): """ """ if self._colorChooser is None: return if self.command and self.command.hasValidStructure(): color = self._colorChooser.getColor() if hasattr(self.command.struct, 'setColor'): self.command.struct.setColor(color) self.win.glpane.gl_update()
NanoCAD-master
cad/src/command_support/DnaOrCnt_PropertyManager.py
# Copyright 2007-2008 Nanorex, Inc. See LICENSE file for details. """ @author: Ninad @version: $Id$ @copyright: 2007-2008 Nanorex, Inc. See LICENSE file for details. This is a superclass for the property managers of various objects that use EditCommand for generating the object. e.g. PlanePropertyManager inherits from this class to use common methods such as ok_btn_cliked. """ import foundation.env as env from command_support.Command_PropertyManager import Command_PropertyManager _superclass = Command_PropertyManager class EditCommand_PM(Command_PropertyManager): """ This is a superclass for the property managers of various objects that use EditCommand for generating the object. e.g. PlanePropertyManager inherits from this class to use common methods """ def show(self): """ Shows the Property Manager. Extends superclass method. """ self._update_widgets_in_PM_before_show() _superclass.show(self) def _update_widgets_in_PM_before_show(self): """ Update various widgets in this Property manager. The default implementation does nothing. Overridden in subclasses. The various widgets , (e.g. spinboxes) will get values from the structure for which this propMgr is constructed for (seelf.command.struct) @see: RotaryMotorPropertyManager._update_widgets_in_PM_before_show @see: self.show where it is called. """ pass def update_props_if_needed_before_closing(self): """ This updates some cosmetic properties of the Rotary motor (e.g. opacity) before closing the Property Manager. This is the default implemetation. Subclasses may override this method @see: L{PlanePropertManager.update_props_if_needed_before_closing} where this method is overridden. """ #API method. See Plane.update_props_if_needed_before_closing for another #example. # Example: The Rotary Motor Property Manager is open and the user is # 'previewing' the motor. Now the user clicks on "Build > Atoms" # to invoke the next command (without clicking "Done"). # This calls self.open() which replaces the current PM # with the Build Atoms PM. Thus, it creates and inserts the motor # that was being previewed. Before the motor is permanently inserted # into the part, it needs to change some of its cosmetic properties # (e.g. opacity) which distinguishes it as # a previewed motor in the part. This function changes those properties. # [ninad 2007-10-09 comment] #called from updatePropertyManager in Ui_PartWindow.py (Partwindowclass) if self.command.struct and hasattr(self.command.struct, 'updateCosmeticProps'): self.command.struct.updateCosmeticProps() self.enable_or_disable_gui_actions(bool_enable = True) def preview_btn_clicked(self): """ Implements Preview button. """ self.command.preview_or_finalize_structure(previewing = True) env.history.message(self.command.logMessage) def restore_defaults_btn_clicked(self): """ Implements Restore defaults button """ pass
NanoCAD-master
cad/src/command_support/EditCommand_PM.py
# Copyright 2007-2008 Nanorex, Inc. See LICENSE file for details. """ EditCommand.py @author: Bruce Smith, Mark Sims, Ninad Sathaye, Will Ware @version: $Id$ @copyright: 2007-2008 Nanorex, Inc. See LICENSE file for details. History: - Originally created as 'GeometryGeneratorBaseClass'. It shared common code with GeneratorBaseClass but had some extra features to support creation and edition of a 'Plane' [June-Sept 2007]. It was split out of ReferenceGeometry.py - Before 2007-12-28, Editcommand was known as 'EditController' Ninad 2007-09-17: Code cleanup to split ui part out of this class. Ninad 2007-10-05: Major changes. Refactored GeometryGeneratorBaseClass and surrounding code. Also renamed GeometryGeneratorBaseClass to EditCommand, similar changes in surrounding code Ninad 2007-10-24: Changes to convert the old structure generators such as DnaGenerator / DnaDuplexGenerator to use the EditCommand class (and their PMs to use EditCommand_PM) Ninad 2007-12-26: Converted editControllers into Commands on commandSequencer TODO: - Need to cleanup docstrings. - In subclasses such as InsertDna_EditCommand, the method createStructure do nothing (user is not immediately creating a structure) . Need to clean this up a bit in this class and in the surrounding code - New subclass InsertDna_EditCommand adds the structure as a node in the MT in its _createStructure method. This should also be implemented for following sublasses: Plane_EditCommand, LineEditCommand, motor editcommand classes. """ import foundation.changes as changes from foundation.FeatureDescriptor import register_abstract_feature_class from utilities.Comparison import same_vals from utilities.constants import permit_gensym_to_reuse_name from utilities.exception_classes import AbstractMethod from commands.Select.Select_Command import Select_Command _superclass = Select_Command class EditCommand(Select_Command): """ EditCommand class that provides a editCommand object. The client can call three public methods defined in this class to acheive various things. 1. runCommand -- Used to run this editCommand . Depending upon the type of editCommand it is, it does various things. The most common thing it does is to create and show a property manager (PM) The PM is used by the editCommand to define the UI for the model which this editCommand creates/edits. See InsertDna_EditCommand.runCommand for an example 2. createStructure -- Used directly by the client when it already knows input parameters for the structure being generated. This facilitates imeediate preview of the model being created when you execute this command. See self.createStructure which is the default implementation used by many subclasses such as RotaryMotor_EditCommand etc. 3. editStructure -- Used directly by the client when it needs to edit an already created structure. See self.editStructure for details. TODO: NEED TO IMPROVE DOCSTRING FURTHER """ # see definition details in GeneratorBaseClass; # most of these should be overridden by each specific subclass cmd = "" cmdname = "" _gensym_data_for_reusing_name = None commandName = 'EditCommand' featurename = "Undocumented Edit Command" # default wiki help featurename from utilities.constants import CL_ABSTRACT command_level = CL_ABSTRACT __abstract_command_class = True flyoutToolbar = None def __init__(self, commandSequencer): """ Constructor for the class EditCommand. """ self.win = commandSequencer.win self.previousParams = None self.old_props = None self.logMessage = '' self.struct = None self.existingStructForEditing = False Select_Command.__init__(self, commandSequencer) return #=== START NEW COMMAND API methods ====================================== def command_enter_misc_actions(self): pass def command_exit_misc_actions(self): pass def command_will_exit(self): """ Overrides superclass method. @see: baseCommand.command_will_exit() for documentation """ if self.commandSequencer.exit_is_forced: pass elif self.commandSequencer.exit_is_cancel: self.cancelStructure() else: self.preview_or_finalize_structure(previewing = False) _superclass.command_will_exit(self) def runCommand(self): """ Used to run this editCommand . Depending upon the type of editCommand it is, it does various things. The most common thing it does is to create and show a property manager (PM) The PM is used by the editCommand to define the UI for the model which this editCommand creates/edits. See InsertDna_EditCommand.runCommand for an example Default implementation, subclasses should override this method. NEED TO DOCUMENT THIS FURTHER ? """ self.existingStructForEditing = False self.struct = None self.createStructure() def createStructure(self): """ Default implementation of createStructure method. Might be overridden in subclasses. Creates an instance (object) of the structure this editCommand wants to generate. This implements a topLevel command that the client can execute to create an object it wants. Example: If its a plane editCommand, this method will create an object of class Plane. @see: L{self.editStructure} (another top level command that facilitates editing an existing object (existing structure). """ assert not self.struct self.struct = self._createStructure() if not self.hasValidStructure(): return if self.struct: #When a structure is created first, set the self.previousParams #to the struture parameters. This makes sure that it doesn't # unnecessarily do self._modifyStructure in # self.preview_or_finalize_structure -- Ninad 2007-10-11 self.previousParams = self._gatherParameters() self.preview_or_finalize_structure(previewing = True) def editStructure(self, struct = None): """ Default implementation of editStructure method. Might be overridden in subclasses. It facilitates editing an existing object (existing structure). This implements a topLevel command that the client can execute to edit an existing object(i.e. self.struct) that it wants. Example: If its a plane edit controller, this method will be used to edit an object of class Plane. This method also creates a propMgr objects if it doesn't exist and shows this property manager @see: L{self.createStructure} (another top level command that facilitates creation of a model object created by this editCommand @see: L{Plane.edit} and L{Plane_EditCommand._createPropMgrObject} """ assert struct self.struct = struct self.existingStructForEditing = True self.old_props = self.struct.getProps() def hasValidStructure(self): """ Tells the caller if this edit command has a valid structure. This is the default implementation, overridden by the subclasses. Default implementation: This method checks for a few common things and by default, in the end returns True. A subclass can first call this superclass method, return False if superclass does so, if superclass returns True the subclass can then check the additional things @see: DnaSegment_EditCommand.hasValidStructure() """ if self.struct is None: return False structType = self._getStructureType() if not isinstance(self.struct, structType): return False #The following can happen. if hasattr(self.struct, 'killed') and self.struct.killed(): return False #Retrn True otherwise. Its now subclass's job to check additional things return True def _getStructureType(self): """ Subclasses must override this method to define their own structure type. Returns the type of the structure this editCommand supports. This is used in isinstance test. @see: self.hasValidStructure() """ print "bug: EditCommand._getStructureType not overridden in a subclass" raise AbstractMethod() def _createStructure(self): """ Create the model object which this edit controller creates) Abstract method. @see: L{Plane_EditCommand._createStructure} """ raise AbstractMethod() def _modifyStructure(self, params): """ Abstract method that modifies the current object being edited. @param params: The parameters used as an input to modify the structure (object created using this editCommand) @type params: tuple @see: L{Plane_EditCommand._modifyStructure} """ raise AbstractMethod() def _gatherParameters(self): """ Abstract method to be overridden by subclasses to return all the parameters needed to modify or (re)create the current structure. """ raise AbstractMethod() def preview_or_finalize_structure(self, previewing = False): """ Preview or finalize the structure based on the the previewing flag @param previewing: If true, the structure will use different cosmetic properties. @type previewing: boolean """ if previewing: self._previewStructure() else: self._finalizeStructure() return def _previewStructure(self): """ Preview the structure and update the previous parameters attr (self.previousParams) @see: self.preview_or_finalize_structure """ #For certain edit commands, it is possible that self.struct is #not created. If so simply return (don't use assert self.struct) ##This is a commented out stub code for the edit controllers ##such as DNAEditCommand which take input from the user before ##creating the struct. TO BE REVISED -- Ninad20071009 #The following code is now used. Need to improve comments and # some refactoring -- Ninad 2007-10-24 if not self.hasValidStructure(): self.struct = self._createStructure() self.previousParams = self._gatherParameters() self.win.assy.changed() self.win.win_update() return self.win.assy.current_command_info(cmdname = self.cmdname) params = self._gatherParameters() if not same_vals( params, self.previousParams): self._modifyStructure(params) self.logMessage = str(self.cmd + "Previewing " + self.struct.name) self.previousParams = params self.win.assy.changed() self.win.win_update() def _finalizeStructure(self): """ Finalize the structure. This is a step just before calling Done method. to exit out of this command. Subclasses may overide this method @see: EditCommand_PM.ok_btn_clicked @see: DnaSegment_EditCommand where this method is overridden. """ if self.struct is None: return self.win.assy.current_command_info(cmdname = self.cmdname) params = self._gatherParameters() if not same_vals( params, self.previousParams): self._modifyStructure(params) if hasattr(self.struct, 'updateCosmeticProps'): self.struct.updateCosmeticProps() self.logMessage = str(self.cmd + "Created " + self.struct.name) #Do we need to set the self.previousParams even when the structure #is finalized? I think this is unnecessary but harmless to do. self.previousParams = params self.win.assy.changed() self.win.win_update() def cancelStructure(self): """ Delete the old structure generated during preview if user modifies some parameters or hits cancel. Subclasses can override this method. @see: BuildDna_EditCommand.cancelStructure """ if self.struct is None: return self.win.assy.current_command_info(cmdname = self.cmdname + " (Cancel)") if self.existingStructForEditing: if self.old_props: self.struct.setProps(self.old_props) if hasattr(self.struct, 'updateCosmeticProps'): self.struct.updateCosmeticProps() self.win.glpane.gl_update() else: self._removeStructure() def _removeStructure(self): """ Remove this structure. @see: L{self.cancelStructure} """ if self.struct is not None: self.struct.kill_with_contents() self.struct = None self._revertNumber() self.win.win_update() def _revertNumber(self): """ Private method. Called internally when we discard the current structure and want to permit a number which was appended to its name to be reused. WARNING: the current implementation only works for classes which set self.create_name_from_prefix to cause our default _build_struct to set the private attr we use here, self._gensym_data_for_reusing_name, or which set it themselves in the same way (when they call gensym). This method is copied over from GeneratorBaseClass._revert_number """ if self._gensym_data_for_reusing_name: prefix, name = self._gensym_data_for_reusing_name # this came from our own call of gensym, or from a caller's if # it decides to set that attr itself when it calls gensym # itself. permit_gensym_to_reuse_name(prefix, name) self._gensym_data_for_reusing_name = None return pass # end of class EditCommand register_abstract_feature_class( EditCommand ) # this is so "export command table" lists it as a separate kind of feature # [bruce 080905] # end
NanoCAD-master
cad/src/command_support/EditCommand.py
# Copyright 2008 Nanorex, Inc. See LICENSE file for details. """ baseCommand.py - base class for command objects on a command sequencer stack @author: Bruce @version: $Id$ @copyright: 2008 Nanorex, Inc. See LICENSE file for details. """ from utilities.debug import print_compact_traceback _pct = print_compact_traceback # local abbreviation for readability from utilities.constants import CL_ABSTRACT from commandSequencer.command_levels import FIXED_PARENT_LEVELS from commandSequencer.command_levels import AFFECTS_FLYOUT_LEVELS DEBUG_USE_COMMAND_STACK = False # == class baseCommand(object): """ Abstract base class for command objects compatible with Command Sequencer. @note: all actual command objects are instances of subclasses of our subclass anyCommand. The intended division of methods is that those needed for CommandSequencer are defined here, whereas those needed only by other code in NE1 are defined in anyCommand or basicCommand. This is roughly followed but not completely. @note: In some cases, methods defined in baseCommand are overridden in anyCommand or basicCommand. """ __abstract_command_class = True # default values of command subclass constants # WARNING: presently some of these are overridden in anyCommand and/or # basicCommand; that will be cleaned up after the refactoring is complete. # [bruce 080815 comment] #Temporary attr 'command_porting_status'. Used ONLY to keep a track of #commands that are ported to the new command API. the default value is #'UNKNOWN'. This is overridden in subclasses. command_porting_status is set #to 'None' when the command is fully ported to USE_COMMAND_STACK command_porting_status = 'UNKNOWN' command_level = CL_ABSTRACT #doc command_level; see command_levels.py command_parent = None # TODO: rename this to command_parentName or ... ### # Subclasses should set this to the commandName of the parent command # they require, if any (and if that is not the default command). # (Whether they require a parent command at all is determined by # their command_level attribute.) # # For example, BreakStrands_Command requires parent command "Build Dna", # so it sets this to 'BUILD_DNA' == BuildDna_EditCommand.commandName. # internal name of command, e.g. 'DEPOSIT', # only seen by users in "debug" error messages; # might be used to create some prefs_keys and/or in some prefs values # [but I don't know if any such uses remain -- bruce 080727 comment] commandName = "(bug: missing commandName 1)" # default values of instance variables; properties; access methods # - related to parentCommand is_null = False # overridden only in nullCommand _parentCommand = None # parent command object, when self is on command stack def _get_parentCommand( self): return self._parentCommand parentCommand = property( _get_parentCommand ) # a read-only property def command_is_active(self): """ @return: whether self is presently on the command stack (whether or not it's on top (aka current)). @rtype: boolean """ # note: this is not as robust a definition as might be hoped. # iterating over the command stack and comparing the result # might catch more bugs. return self.parentCommand is not None # - related to flyout toolbar FlyoutToolbar_class = None #Ninad 2008-09-12 #Command subclasses can override this class attr with the appropriate #Flyout Toolbar class. This is used to create a FlyoutToolbar object #for the commands. this attr is also used to do flyout toolbar updates. #Example: if the value of this attr is None then it either implies the #command should use the flyout toolbar of the parent command and do #some more UI changes to it (example check an action) OR the command #shouldn't do anything with the flyout at all (this is decided using the #'command_level) #@see: self.command_update_flyout() #@see: self._command_entered_prepare_flyout() #@see: self._createFlyouttoolbarObject() flyoutToolbar = None # - related to a command's property manager (PM) command_has_its_own_PM = True # TODO: merge related code from our toplevel subclasses # REVIEW: can this be replaced by the condition (self.PM_class is not None)? # [bruce 081125 comments] propMgr = None # will be set to the PM to use with self (whether or not created by self); # some methods assume that object is a subclass of PM_Dialog, # or perhaps (more likely) of its subclass Command_PropertyManager. # [bruce 081125 comment] # == access methods def is_default_command(self): #bruce 080709 refactoring; moved to this file 080929 return self.commandName == self.commandSequencer.default_commandName() def get_featurename(self): """ [overridden in basicCommand, see there for doc] """ # revised, bruce 080727; moved to this class, bruce 080929 return "null command" # should never be seen def is_fixed_parent_command(cls): """ Is this command instance or class a "fixed-parent command", i.e. one which requires self.parentCommand to be an instance of a specific command? @note: it works to call this classmethod directly on the class, or on an instance """ return cls.command_level in FIXED_PARENT_LEVELS is_fixed_parent_command = classmethod(is_fixed_parent_command) def command_affects_flyout(cls): """ Does this command instance or class ever affect the flyout toolbar, either by replacing it, or by modifying its set of actions or their checked or enabled state? Used to decide when to call command_update_flyout, and when to restore the default flyout state for the current command if the user has temporarily modified it. @note: it works to call this classmethod directly on the class, or on an instance """ return cls.command_level in AFFECTS_FLYOUT_LEVELS command_affects_flyout = classmethod(command_affects_flyout) def command_that_supplies_PM(self): """ Return the innermost command (of self or its parent/grandparent/etc) which supplies the PM when self is current. Note that this command will supply a value of None for the PM, if self does. Self must be an active command (on the command stack). Print a warning if any PM encountered appears to have .command set incorrectly. """ # find innermost command whose .propMgr differs from its # parent's .propMgr. cseq = self.commandSequencer commands = cseq.all_active_commands( starting_from = self ) res = None for command in commands: if not command.parentCommand or \ command.parentCommand.propMgr is not command.propMgr: res = command break assert res # since outermost command has no parent assert res.propMgr is self.propMgr # sanity check on algorithm # check PM's command field if res.propMgr: ## assert res.propMgr.command is res, \ if not (res.propMgr.command is res): print "\n*** BUG: " \ "%r.PM %r has wrong .command %r, found from %r" % \ (res, res.propMgr, res.propMgr.command, self) return res # == exit-related methods (see also CommandSequencer.exit_all_commands) def command_Done(self, implicit = False): """ Exit this command, after also exiting any subcommands it may have, as if its Done button was pressed. @param implicit: this is occurring as a result of the user asking to enter some other command (not nestable under this command), rather than by an explicit exit request. @type implicit: boolean @note: subclasses should not override this method. Instead, if a subclass needs to add Done-specific code, it should override command_will_exit and condition its effects on one of the flags described in that method's docstring. """ self.commandSequencer._f_exit_active_command(self, implicit = implicit) return def command_Cancel(self): """ Exit this command, after also exiting any subcommands it may have, as if its Cancel button was pressed. @note: subclasses should not override this method. Instead, if a subclass needs to add Cancel-specific code, it should override command_will_exit and condition its effects on one of the flags described in that method's docstring. """ self.commandSequencer._f_exit_active_command(self, cancel = True) return def _f_command_do_exit_if_ok(self): # todo: args: anything needed to decide if ok or when asking user """ Exit this command (but not any other commands), when it's the current command, if possible or if self.commandSequencer.exit_is_forced is true, and return True. If not possible for some reason, emit messages as needed, and return False. @return: whether exit succeeded. @rtype: boolean @note: caller must only call this if this command *should* exit if possible, and if it's the current command (not merely an active command, even if it's the command which is supplying the PM). Deciding whether exit is needed, based on a desired next command, is up to the caller. @note: possible future change to return value: if we ask user about exiting, the answer might affect how or how much to exit, needed by caller for later stages of exiting multiple commands. In that case we'd need to return info about that, whenever exit succeeds. @note: certain attrs in self.commandSequencer (e.g. .exit_is_cancel) will tell self.command_will_exit which side effects to do. For documentation of those attrs, see CommandSequencer methods _f_exit_active_command and _exit_currentCommand_with_flags, and class CommandSequencer docstring. """ self.commandSequencer._f_lock_command_stack("preparing to exit a command") try: try: ok = self._command_ok_to_exit() # must explain to user if not except: _pct() ok = True if not ok and not self.commandSequencer.exit_is_forced: self._command_log("not exiting") return False try: self.command_will_exit() # args? except: _pct() finally: self.commandSequencer._f_unlock_command_stack() self._command_do_exit() return True def _command_ok_to_exit(self): # only in this file so far, 080826 ask = self.command_exit_should_ask_user() if ask: print "asking is nim" # put up dialog with 3 choices (or more?) # call method on self to put it up? or determine choices anyway? (yes) # also, if ok to exit but only after some side effects, do those side effects. # (especially likely if self.commandSequencer.exit_is_forced is true; ### TODO: put this in some docstring) return True def command_exit_should_ask_user(self): # only in this file so far, 080826 """ @return: whether user should be asked whether it's ok to exit self @rtype: boolean @warning: not yet properly implemented in caller @warning: overriding this method should be rare. @warning: if self.commandSequencer.exit_is_forced, the caller will still call this method but will always exit regardless of its return value. """ # note: someday this may call a new command API method # related to the old self.haveNontrivialState() method, # and if that returns true, check a user pref to decide what to do. # Initially it's ok if it always returns False. return False def command_will_exit(self): """ Perform side effects on self and the UI, needed when self is about to be exited for any reason. If the side effects need to depend on the manner of exit (e.g. command_Done vs command_Cancel vs exit_all_commands), or on the command being exited from or intended to be entered, this should be determined by testing an appropriate attribute of self.commandSequencer, e.g. exit_is_cancel, exit_is_forced, exit_is_implicit, exit_target, enter_target. For their meanings, see the docstring of class CommandSequencer. @note: when this is called, self is on top of the command stack, but it may or may not have been on top when the current user event handler started (e.g. some other command may have already exited during the same user event). @note: base class implementation calls self methods command_exit_misc_actions and command_exit_PM. [subclasses should extend this as needed, typically calling superclass implementation at the end] """ # note: we call these in the reverse order of how # command_entered calls the corresponding _enter_ methods. self.command_exit_misc_actions() self.command_exit_PM() return def command_exit_PM(self): """ Do whatever needs to be done to a command's PM when the command is about to exit. (Usually, nothing needs to be done.) [subclasses should override this as needed] """ return def command_exit_misc_actions(self): """ Undo whatever was done by self.command_enter_misc_actions() when this command was entered. [subclasses should override this as needed] """ return def _command_do_exit(self): """ [private] pop self from the top of the command stack """ if DEBUG_USE_COMMAND_STACK: print "_command_do_exit:", self assert self is self.commandSequencer._f_currentCommand, \ "can't pop %r since it's not currentCommand %r" % \ (self, self.commandSequencer._f_currentCommand) assert self._parentCommand is not None # would fail for default command self.commandSequencer._f_set_currentCommand( self._parentCommand ) self._parentCommand = None return # == enter-related methods def _command_do_enter_if_ok(self, args = None): """ #doc @return: whether enter succeeded. @rtype: boolean @note: caller must only call this if this command *should* enter if possible. @note: always called on an instance, even if a command class alone could (in principle) decide to refuse entry. """ self.commandSequencer._f_lock_command_stack("preparing to enter a command") try: try: ok = self.command_ok_to_enter() # must explain to user if not except: _pct() ok = True if not ok: self._command_log("not entering") return False try: self.command_prepare_to_enter() # get ready to receive events (usually a noop) # args? except: _pct() self._command_log("not entering due to exception") return False finally: self.commandSequencer._f_unlock_command_stack() self._command_do_enter() # push self on command stack self.commandSequencer._f_lock_command_stack("calling command_entered") try: self.command_entered() # update ui as needed # args? except: _pct() # but since we already entered it by then, # return True anyway # REVIEW: should caller continue entering subcommands # if it planned to? (for now, let it try) self.commandSequencer._f_unlock_command_stack() return True def command_ok_to_enter(self): """ Determine whether it's ok to enter self (assuming the user has explicitly asked to enter self), given the current state of the model and command stack. If not ok, explain to user why not (using redmsg or dialog) and return False. If ok, have no visible effect and return True. Should never have a side effect on the model. @return: True if ok to enter (usual case). @rtype: boolean @note: overriding this should be rare, and is always a UI design flaw. Instead, commands should enter, then help the user make it ok to use them (e.g. help them select an appropriate argument). [a few subclasses should override or extend, most don't need to] """ return True def command_prepare_to_enter(self): """ #doc [some subclasses should extend, most don't need to] """ return def _command_do_enter(self): """ [private] push self on command stack """ if DEBUG_USE_COMMAND_STACK: print "_command_do_enter:", self assert self._parentCommand is None self._parentCommand = self.commandSequencer._f_currentCommand self.commandSequencer._f_set_currentCommand( self) return def command_entered(self): """ Update self's command state and ui as needed, when self has just been pushed onto command stack. (But never modify the command stack. If that's necessary, do it in command_update_state.) @note: self may or may not still be the current command by the time the current user event is fully handled. It might be immediately "suspended upon entry" by a subcommand being pushed on top of it. @note: base class implementation calls other methods of self, including command_enter_misc_actions. @note: similar to old methods Enter and parts of init_gui. [subclasses should extend as needed, by calling superclass implementation at the start] @see: self._command_entered_prepare_flyout() @see: self.command_update_flyout() """ self.graphicsMode.Enter_GraphicsMode() if not self.command_has_its_own_PM: # note: that flag must be True (so this doesn't run) in the default # command, since it has no self.parentCommand self.propMgr = self.parentCommand.propMgr self.command_enter_PM() if self.flyoutToolbar is None: self._command_entered_prepare_flyout() self.command_enter_misc_actions() return def _command_entered_prepare_flyout(self): #Ninad 2008-09-12 """ Create flyout toolbar object for the command if needed. Whether to create it is decided using the class attr self.FlyoutToolbar_class. Example: if FlyoutToolbar_class is None, it means the command should use the flyout of the parent command if one exists. When FlyoutToolbar_class is defined by the command, it uses that to create one for the command. This method is called in self.command_entered(). Subclasses should NEVER override this method. @see: self.command_update_flyout() which actually does the updates to the flyout toolbar. @see: self.command_entered() which calls this method. """ if self.FlyoutToolbar_class is None: #The FlyoutToolbar_class is not define. This means either of the #following: A) the command is , for example, a subcommand, #which reuses the flyoutToolbar of the parent command and an action #representing this command is checked in the flyout toolbar. #B) The command is an internal request command and doesn't have #a specific action to be checked in the flyout. So all it does is #to not do any changes to the flyout and just continue using it. #The following line of code makes sure that the self.parentCommand #exists and if it does, it assigns self's flyout the value of #parentCommand's flyoutToolbar object. self.flyoutToolbar = self.parentCommand and self.parentCommand.flyoutToolbar else: #FlyoutToolbar_class is specified. So create a flyoutToolBarObject #if necessary if self.flyoutToolbar is None: self.flyoutToolbar = self._createFlyoutToolbarObject() def _createFlyoutToolbarObject(self): #Ninad 2008-09-12 """ Creates and returns a FlyoutToolbar object of the specified FlyoutToolbar_class. @see: self._command_entered_prepare_flyout() @see: self.command_update_flyout() @see: self._createPropMgrObject() """ if self.FlyoutToolbar_class is None: return None flyout = self.FlyoutToolbar_class(self) return flyout def command_enter_PM(self): """ Do whatever needs to be done to a command's PM object (self.propMgr) when a command has just been entered (but don't show that PM). For commands which use their parent command's PM, it has already been assigned to self.propMgr, assuming this method is called by the base class implementation of command_entered (as usual) and that self.command_has_its_own_PM is false. In that case, this method is allowed to perform side effects on that "parent PM" (and this is the best place to do them), but this is only safe if the parent command and PM are of the expected class and have been coded with this in mind. For commands which create their own PM, typically they either do it in __init__, or in this method (when their PM doesn't already exist). A created PM is conventionally stored in self.propMgr, and publicly accessed from there. It will persist there even when self is not on the command stack. For many commands, nothing needs to be done by this method. PM signal/slot connections should typically be created just once when the PM is first created. @note: base class implementation of command_entered calls this, after setting self.propMgr to PM from parent command if self.command_has_its_own_PM is false. @see: CommandSequencer._f_update_current_command() which calls PM.show() for the desired PM. [subclasses should override as needed] """ return def command_enter_misc_actions(self): """ incrementally modify the state of miscellaneous UI actions upon entry to this command. @note: Called by base class implementation of command_entered. [subclasses should override as needed] """ return # == update methods def command_post_event_ui_updater(self): """ Commands can extend this if they need to optimize by completely ignoring some updates under certain conditions. Note: this is called from MWsemantics.post_event_ui_updater. Note that this prevents *all* active commands, or the command sequencer, from doing any updates in response to this method (whose base class implem is indirectly the only caller of any command_update_* method), so it's safer to optimize one of the command_update_* methods instead. """ self.commandSequencer._f_update_current_command() return def command_update_state(self): """ At the end of any user event that may have changed system state which may need to cause changes to the command stack or to any active command's state or UI, the command sequencer will call this method on the current command, repeating that until the command stack doesn't change (but never calling it twice on the same command, during one user event, to prevent infinite recursion due to bugs in specific implems of this method). This method is responsible for: - optimizing for frequent calls (e.g. for every mouse drag event), by checking whether anything it cares about has actually changed (see below for how it can do this ### change counter; once per event means can set self._something_changed for other methods) - updating any "state machines" inside this command which can cause it to alter the command stack - exiting this command and/or entering other commands, if necessary due to its own state or system state If this method doesn't change the command stack (i.e. if self remains the current command), then after it returns, the command sequencer will call self.command_update_internal_state(), which should update internal state for all commands on the command stack, in bottom to top order (see its docstring for details ### superclass calls, base implem). The command sequencer will then call self.command_update_UI() (and, possibly, other update_UI methods on other UI objects ###doc). @note: For any command that has a "state machine", its logic should be implemented within this method. [many subclasses must override or extend this method; when extending, see the docstring for the specific superclass method being extended to decide when to call the superclass method within the new method] """ return def command_update_internal_state(self): """ Update the internal state of this command and all parent commands. Self is on the command stack, but might not be the current command. This must update all state that might be seen by other commands or UI elements, even if that state is stored in self.propMgr. It should not update UI elements themselves, unless they are used to store internal state. This must not change the command stack (error if it does). Any updates which might require exiting or entering commands must be done earlier, in a command_update method. @note: the base class implementation delegates to the parent command, so a typical subclass implementation of this method need only call its superclass method in order to accomplish the "all parent commands" part of its responsibility. Typically it should call its superclass method before doing its own updates. @see: command_update_state, for prior updates that might change the command stack; see its docstring for the context of this call @see: command_update_UI, for subsequent updates of UI elements only """ if self.parentCommand: assert self.parentCommand is not self self.parentCommand.command_update_internal_state() return def command_update_UI(self): """ Update UI elements owned by or displayed by this command (e.g. self.propMgr and/or self's flyout toolbar) (preferably by calling update_UI methods in those UI elements, rather than by hardcoding the update algorithms, since the UI elements themselves may be owned by parent commands rather than self). Self is always the current command. @see: command_update_state, for prior updates that might change the command stack; see its docstring for the context of this call @see: command_update_internal_state, for prior updates that change internal state variables in all active commands (even if those are stored in their property manager objects) @see: self.command_update_flyout() """ if self.propMgr: self.propMgr.update_UI() # must work when PM is shown or not shown, and should not show it # note: what shows self.propMgr (if it ought to be shown but isn't) # is the base implem of our indirect caller, # commandSequencer._f_update_current_command, # after we return. # Note: 2008-09-16: updating flyout toolbar is now done by #self.command_update_flyout() See that method for details. return def command_update_flyout(self): #bruce 080910; Ninad 2008-09-16 """ Subclasses should NEVER override this method. This method is only called for command stack changes involving commands that affect the flyout toolbar (according to their command_level). When this is called, self is the current command and all other update methods defined above have been called. @note: called only when command stack changed (counting only commands that affect flyout) since the last time this was called for any command @see: self.command_update_UI() where updates to PM are done @see: self._command_entered_prepare_flyout() which actually creates the flyout toolbar. @see: command_levels._IGNORE_FLYOUT_LEVELS @see: AbstractFlyout.resetStateOfActions() @see: AbstractFlyout.activateFlyoutToolbar() @see: CommandToolbar.resetToDefaultState() """ if self.flyoutToolbar: #activate the flyout toolbar. self.flyoutToolbar.activateFlyoutToolbar() if self.FlyoutToolbar_class is None: #@see:self._getFlyoutToolBarActionAndParentCommand() docstring #for a detailed documentation. flyoutActionToCheck, parentCommandString = self._getFlyoutToolBarActionAndParentCommand() #The following method needs to handle the empty action #string (flyoutActionToCheck) self._init_gui_flyout_action(flyoutActionToCheck, parentCommandName = parentCommandString) else: #Its not a subcommand that is using the flyout toolbar. So #make sure that no action is checked when this flyout is shown #(e.g. an action might be checked because the earlier command #was a subcommand using this flyout) self.flyoutToolbar.resetStateOfActions() else: #The flyout toolbar is None. NOTE: self.command_update_flyout is #only called for command stack changes involving commands that #affect flyout. Thus, this method is never called for commands whose #command_level is in 'ignore list' (such as CL_VIEW_CHANGE) #What this all means, is when this 'else' condition (i.e. flyoutToolbar #is None, is reached program needs to reset the flyout toolbar to its #default state. i.e. Check the Build Control button and show the #Build control button menu in the flyout toolbar. self.win.commandToolbar.resetToDefaultState() def _getFlyoutToolBarActionAndParentCommand(self): #Ninad 2008-09-15 """ Subclasses can override this method. Returns text of the action to check in the flyout toolbar and also in some cases, the name of the parentCommand (value is None or the command name string) Consider the following cases: A) The command is , for example, a subcommand, which reuses the flyoutToolbar of the parent command and an action representing this command is checked in the flyout toolbar. B) The command is an internal request command and doesn't have a specific action to be checked in the flyout. So all it does is to not do any changes to the flyout and just continue using it. For case (A) the 'flyoutActionToCheck' returns a string with action name for case (B), it returns 'None' (indicating that no modifications are necessary) The 'parentCommandName' string is usually empty. But some commands like OrderDna (global commands) need to specify this. @see: self.command_update_flyout() @see: self._init_gui_glyout_action() @see: DnaDuplex_Editcommand._getFlyoutToolBarActionAndParentCommand() """ flyoutActionToCheck = '' parentCommandName = None return flyoutActionToCheck, parentCommandName def _init_gui_flyout_action( self, action_attr, parentCommandName = None ): """ [helper method for command entry] If our direct parent command has the expected commandName, copy self.flyoutToolbar from it and call setChecked on the specified action in it (if it has that action) (setting self.flyoutToolbar = None if any of this fails by raising AttributeError, with no error message) and return the parent command. Otherwise return None. @param action_attr: attribute name of this command's action in this or parent command's flyout toolbar. Example: 'breakStrandAction' @type: string @param parentCommandName: commandName of expected parent command; if not provided or None, we use self.command_parent for this. Example: 'BUILD_DNA' @type: string @return: parent command, if it has expected commandName, otherwise None. @rtype: Command or None [helper method for use in init_gui implementations; might need refactoring] """ if not action_attr: return #bruce 080726 split this out of init_gui methods (by Ninad) # of several Commands; 080929 moved it into baseCommmand if parentCommandName is None: parentCommandName = self.command_parent assert self.command_parent, \ "_init_gui_flyout_action in %r requires " \ "self.command_parent assignment" % self # note: it's ok that we don't interpret command_parent = None # as the default commandName here, since the default command has no # flyout toolbar. This only works by accident; it might be more # principled to check self.is_fixed_parent_command() instead, once # that's always defined, and if it's true, interpret # command_parent = None as being the name of the default command. # [bruce 080814 comment] #bruce 080804 parentCommand = self.parentCommand assert parentCommand # should be already set by now (during command_entered) if parentCommand.commandName == parentCommandName: try: self.flyoutToolbar = parentCommand.flyoutToolbar #Need a better way to deal with changing state of the #corresponding action in the flyout toolbar. To be revised #during command toolbar cleanup action = getattr(self.flyoutToolbar, action_attr) action.setChecked(True) except AttributeError: # REVIEW: this could have several causes; would any of them # be bugs and deserve an error message? [bruce 080726 questions] self.flyoutToolbar = None return parentCommand else: print "fyi: _init_gui_flyout_action in %r found wrong kind " \ "of parent command" % self # not sure if this ever happens; might be a bug if so return None pass # == other methods def _command_log(self, msg): print msg pass # end
NanoCAD-master
cad/src/command_support/baseCommand.py
# Copyright 2004-2007 Nanorex, Inc. See LICENSE file for details. """ gpl_only.py This module contains code which is only distributed in the GPL version, since providing this code might violate the commercial-version licenses of Qt and/or PyQt. Specifically (as I understand it -- bruce 041217), those licenses require anyone who writes new code which uses the Qt or PyQt APIs (to link to the commercial versions of PyQt or Qt) to purchase a commercial license for those packages. This generally affects only developers, but if our product lets users run arbitrary Python code (which might include general use of Qt, via PyQt), it affects users too; so functions that permit users to run arbitrary Python code can't be distributed as part of the commercial version. In the future we might permit all users to run Python code provided it doesn't use any functions imported from PyQt; but it's hard to do that well enough, and for now these functions are only provided for debugging, so it's easiest to just leave them out of the commercial version. When we later add a scripting ability, we'll have to revisit this issue. Other modules which import functions from this one must deal with the absence of this module. Generally, for any function in this module, most other code should not call it directly, but call some wrapper function, in a module appropriate to the function's purpose, where the wrapper function's only job is to handle the case where this module gpl_only is not available. -- bruce 041217 $Id$ """ #bruce 070425: Qt4 is all-GPL, so (for Qt4) I'm removing the check for Windows # and/or the gpl_only_ok file. # Here are those functions we can't allow Qt3 Windows users to run: def _execfile_in_globals(filename, globals): execfile(filename, globals) def _exec_command_in_globals( command, globals): exec command in globals # end
NanoCAD-master
cad/src/platform_dependent/gpl_only.py
# Copyright 2008 Nanorex, Inc. See LICENSE file for details. """ Paths.py -- platform dependant filename paths @author: Bruce, Mark, maybe others @version: $Id$ @copyright: 2008 Nanorex, Inc. See LICENSE file for details. """ import sys import os def get_default_plugin_path(win32_path, darwin_path, linux_path): """ Returns the plugin (executable) path to the standard location for each platform (taken from the appropriate one of the three platform-specific arguments), but only if a file or dir exists there. Otherwise, returns an empty string. """ if sys.platform == "win32": # Windows plugin_path = win32_path elif sys.platform == "darwin": # MacOS plugin_path = darwin_path else: # Linux plugin_path = linux_path if not os.path.exists(plugin_path): return "" return plugin_path
NanoCAD-master
cad/src/platform_dependent/Paths.py
# Copyright 2004-2008 Nanorex, Inc. See LICENSE file for details. """ PlatformDependent.py -- module for platform-specific utilities and constants. Also includes various code that might conceivably vary by platform, but mainly is here since it had no better place to live. In fact, by 060106 most of its code is like that, and a lot of it has something to do with messages or the screen or files, that is, issues having to do with both the UI and the OS interface. @author: Bruce, Mark, maybe others @version: $Id$ @copyright: 2004-2008 Nanorex, Inc. See LICENSE file for details. Module classification: A mix of things. Some are platform dependent. Some are utilities (and of those, some would make sense within utilities.Log). Some are io. """ import sys, os, time from PyQt4.Qt import Qt, QDesktopWidget, QRect import foundation.env as env from utilities import debug_flags from utilities.debug import print_compact_traceback from utilities.debug import print_compact_stack from utilities.Log import redmsg # == constants (or variables settable by a debugger) read by code in other modules # == file utilities def mkdirs_in_filename(filename): """ Make all directories needed for the directory part of this filename, if nothing exists there. Never make the filename itself (even if it's intended to be a directory, which we have no way of knowing anyway). If something other than a directory exists at one of the dirs we might otherwise make, we don't change it, which will probably lead to errors in this function or in the caller, which is fine. """ dir, file = os.path.split(filename) if not os.path.exists(dir): mkdirs_in_filename(dir) os.mkdir(dir) if not os.path.exists(dir): print u"Directory not created: ", dir.encode("utf_8") return # == event code def is_macintosh(): #e we might need to update this, since I suspect some mac pythons # have a different value for sys.platform return sys.platform == 'darwin' def filter_key(key, debug_keys = 0): #bruce revised this 070517 to fix Mac-specific delete key bug which resurfaced in Qt4 """ Given a Qt keycode key, usually return it unchanged, but return a different keycode if that would help fix platform-specific bugs in Qt keycodes or in our use of them. """ if is_macintosh(): # Help fix Qt's Mac-specific Delete key bug, bug 93. if key == Qt.Key_Backspace: #bruce 070517 revised value; note: this is 16777219 == 0x1000003 # This was 4099 in Qt3 and worked for a long time. ##k will this 4099 be the same in other macs? other platforms? Does Qt define it anywhere?? # Now it's 16777219 in Qt4 (Mac OS 10.3.9, iMac G5 standard keyboard, Qt 4.2.2). # The Qt doc (4.2.2) says this is Qt.Key_Backspace, and that named constant works here to fix the bug. # Note: the other Del key (in a 6-key keypad) is 16777223 == 0x1000007 == Qt.Key_Delete. # (See also: comments in TreeWidget.keyPressEvent about how these two keys are handled # differently by Qt. Trying it now, Qt.Key_Delete gets into this method only once # per press/release, apparently only for release, whereas the regular delete key (Qt.Key_Backspace) gets into # this method once for press and once for release. It turns out that a keypress in the model tree # gets handled by MWsemantics and passed to the GLPane, so no fix is needed in modelTreeGui now; # if it's ever given its own keyPressEvent handler, one will be needed there as it was needed in # TreeWidget in Qt3. I added a comment about that in modelTreeGui. # [bruce 070517] if debug_keys: print "fyi: mac bugfix: remapping key %d (actual delete key) to key %d (Qt.Key_Delete)" % (key, Qt.Key_Delete) key = Qt.Key_Delete return key def wrap_key_event( qt_event): #bruce 070517 renamed this """ Return our own event object in place of (or wrapping) the given Qt event. Fix bugs in Qt events, and someday provide new features to help in history-tracking. So far [041220] this only handles key events, and does no more than fix the Mac-specific bug in the Delete key (bug 93). """ return _wrapped_KeyEvent(qt_event) class _wrapped_KeyEvent: #bruce 070517 renamed this """ Our own event type. API should be non-Qt-specific (but isn't really). """ # presently used only for GLPane key events; # not all methods work in Qt4, but the nonworking ones aren't used # [bruce 070517 comment] def __init__(self, qt_event): self._qt_event = qt_event # private def key(self): return filter_key( self._qt_event.key() ) def ascii(self): try: return filter_key( self._qt_event.ascii() ) #k (does filter_key matter here?) except: print_compact_stack( "bug: event.ascii() not available in Qt4, returning -1: ") return -1 ### BUG: need to fix in some better way [070811] def state(self): try: return self._qt_event.state() except: print_compact_stack( "bug: event.state() not available in Qt4, returning -1: ") return -1 ### BUG; need to fix in some better way [070811] def stateAfter(self): try: return self._qt_event.stateAfter() except: print_compact_stack( "bug: event.stateAfter() not available in Qt4, returning -1: ") return -1 ### BUG; need to fix in some better way [070811] def isAutoRepeat(self): return self._qt_event.isAutoRepeat() #e more methods might be needed here pass #e there might be other code mentioning "darwin" which should be # moved here... maybe also modifier keys in constants.py... # Use these names for our modifier keys and for how to get the context menu, # in messages visible to the user. def shift_name(): """ Return name of the Shift modifier key. """ return "Shift" def control_name(): """ Return name of the (so-called) Control modifier key. """ if is_macintosh(): return "Command" else: return "Control" pass def context_menu_prefix(): """ what to say instead of "context" in the phrase "context menu" """ if is_macintosh(): return "Control" else: return "Right" #k I think pass def middle_button_prefix(): """ what to say instead of "middle" as a prefix for press or click, for middle mouse button actions """ if is_macintosh(): return "Option" # name of Option/Alt modifier key else: return "Middle" # refers to middle mouse button pass # helpers for processing modifiers on mouse events # [moved here from GLPane.py -- bruce 050112] def fix_event_helper(self, event, when, target = None): #bruce 050913 new API; should merge them, use target, doc this one ## if when == 'press': ## but = event.stateAfter() ## else: ## but = event.state() but, mod = event.buttons(), event.modifiers() ## if when == 'press': ## print "in fix_event_helper: but/mod ints before fix_buttons_helper",int(but),int(mod)#bruce 070328 but, mod = fix_buttons_helper(self, but, mod, when) return but, mod def fix_buttons_helper(self, but, mod, when): """ Every mouse event's button and modifier key flags should be filtered through this method (actually just a "method helper function"). Arguments: - self can be the client object; we use it only for storing state between calls, namely, self._fix_buttons_saved_buttons. The caller need no longer init that to 0. - 'but' should be the flags from event.stateAfter() or event.state(), whichever ones would have the correct set of mousebuttons -- this depends on the type of event; see the usage in GLPane for an example. - 'when' should be 'press', 'move', or 'release', according to how this function should treat the buttons and modifier keys -- it will record them for press, and then maintain the same ones (in its return value) for move or release, regardless of what the real modifier keys and buttons did. Returns: a new version of 'but' which is simpler for client code to use correctly (as described below). Known bugs [as of 050113]: reportedly prints warnings, and perhaps has wrong results, when dialogs intercept some "release" events. (Or am I confusing these rumors with ones about key-releases?) Should be easy to fix given a repeatable example. More details: this function does two things: 1. Store all button and modifier-key flags from a mouse-press, and reuse them on the subsequent mouse-drag and mouse-release events (but not on pure mouse-moves), so the caller can just switch on the flags to process the event, and will always call properly paired begin/end routines (this matters if the user releases or presses a modifier key during the middle of a drag; it's common to release a modifier key then). 2. On the Mac, remap Option+Qt.LeftButton to middleButton, so that the Option key (also called the Alt key) simulates the middle mouse button. (Note that Qt/Mac, by default, lets Control key simulate right button and remaps Command key to the same flag we call Qt.ControlModifier; we like this and don't change it here. In Qt4.2.2/Mac, the Control key is no longer simulating right button -- in fact, right button is simulating control key! So we fix that here.) """ # [by bruce, 040917 (in GLPane.py). At time of commit, # tested only on Mac with one-button mouse.] if sys.platform in ['darwin']: #bruce 070328 Qt4/Mac bugfix: # work around a bug in Qt 4.2.2/Mac in which the control key is no longer mapped to the # right mouse button, and not only that, the right mouse button itself is no longer mapped # to the right mouse button, turning into control-LMB instead! (Undo that unwanted change here. # It caused GLPane context menus to not work at all, at least on my Mac OS 10.3.9 / Qt 4.2.2.) try: if (mod & Qt.MetaModifier) and (but & Qt.LeftButton): mod = mod & ~Qt.MetaModifier but = (but & ~Qt.LeftButton) | Qt.RightButton except: print "following exception concerns but = %r, mod = %r; btw Qt.MetaModifier = %r" % (but, mod, Qt.MetaModifier) raise pass allButtons = (Qt.LeftButton|Qt.MidButton|Qt.RightButton) allModifiers = (Qt.ShiftModifier|Qt.ControlModifier|Qt.AltModifier) #allFlags = (allButtons|allModKeys) _debug = 0 # set this to 1 to see some debugging messages if when == 'move' and (but & allButtons): when = 'drag' assert when in ['move','press','drag','release'] if not hasattr(self, '_fix_buttons_saved_buttons'): self._fix_buttons_saved_buttons = Qt.NoButton self._fix_buttons_saved_modifiers = Qt.NoModifier # 1. bugfix: make mod keys during drag and button-release the # same as on the initial button-press. Do the same with mouse # buttons, if they change during a single drag (though I hope # that will be rare). Do all this before remapping the # modkey/mousebutton combinations in part 2 below! if when == 'press': self._fix_buttons_saved_buttons = but & allButtons self._fix_buttons_saved_modifiers = mod & allModifiers # we'll reuse this button/modkey state during the same # drag and release if _debug and self._fix_buttons_saved_buttons != but: print "fyi, debug: fix_buttons: some event flags unsaved: %d - %d = 0x%x" % ( but, self._fix_buttons_saved_buttons, but - self._fix_buttons_saved_buttons) # fyi: on Mac I once got 2050 - 2 = 0x800 from this statement; # don't know what flag 0x800 means; shouldn't be a problem elif when in ['drag','release']: if ((self._fix_buttons_saved_buttons & allButtons) or (self._fix_buttons_saved_modifiers & allModifiers)): but0 = but but &= ~allButtons but |= self._fix_buttons_saved_buttons # restore the modkeys and mousebuttons from the mousepress if _debug and but0 != but: print "fyi, debug: fix_buttons rewrote but0 0x%x to but 0x%x" % (but0, but) #works mod0 = mod mod &= ~allModifiers mod |= self._fix_buttons_saved_modifiers # restore the modkeys and mousemodifiers from the mousepress if _debug and mod0 != mod: print "fyi, debug: fix_buttons rewrote mod0 0x%x to mod 0x%x" % (mod0, mod) #works else: # fyi: This case might happen in the following rare # and weird situation: - the user presses another # mousebutton during a drag, then releases the first # one, still in the drag; - Qt responds to this by # emitting two mouseReleases in a row, one for each # released button. (I don't know if it does this; # testing it requires a 3-button mouse, but the one I # own is unreliable.) # # In that case, this code might make some sense of # this, but it's not worth analyzing exactly what it # does for now. # # If Qt instead suppresses the first mouseRelease #until all buttons are up (as I hope), this case never #happens; instead the above code pretends the same #mouse button was down during the entire drag. print "warning: Qt gave us two mouseReleases without a mousePress;" print " ignoring this if we can, but it might cause bugs" pass # don't modify 'but' else: pass # pure move (no mouse buttons down): # don't revise the event flags if when == 'release': self._fix_buttons_saved_buttons = Qt.NoButton self._fix_buttons_saved_modifiers = Qt.NoModifier # 2. let the Mac's Alt/Option mod key simulate middle mouse button. if sys.platform in ['darwin']: ### please try adding your platform here, and tell me whether it ### breaks anything... see below. # As of 040916 this hasn't been tested on other platforms, # so I used sys.platform to limit it to the Mac. Note # that sys.platform is 'darwin' for my MacPython 2.3 and # Fink python 2.3 installs, but might be 'mac' or # 'macintosh' or so for some other Macintosh Pythons. When # we find out, we should add those to the above list. As # for non-Mac platforms, what I think this code would do # (if they were added to the above list) is either # nothing, or remap some other modifier key (different # than Shift or Control) to middleButton. If it does the # latter, maybe we'll decide that's good (for users with # less than 3 mouse buttons) and document it. # -- bruce 040916-17 ## qt4todo('Not sure this is what Bruce intended...') # nope, it crashed! Fixing it using & and ~. bruce 070328 try: if (mod & Qt.AltModifier) and (but & Qt.LeftButton): ## mod = mod - Qt.AltModifier ## TypeError: unsupported operand type(s) for -: 'KeyboardModifiers' and 'KeyboardModifier' ## but = but - Qt.LeftButton + Qt.MidButton mod = mod & ~Qt.AltModifier but = (but & ~Qt.LeftButton) | Qt.MidButton except: print "following exception concerns mod = %r; btw Qt.AltModifier = %r" % (mod, Qt.AltModifier) raise return but, mod # === # Finding or making special directories and files (e.g. in user's homedir): # code which contains hardcoded filenames in the user's homedir, etc # (moved into this module from MWsemantics.py by bruce 050104, # since not specific to one window, might be needed before main window init, # and the directory names might become platform-specific.) _tmpFilePath = None def find_or_make_Nanorex_directory(): """ Find or make the directory ~/Nanorex, in which we will store important subdirectories such as Preferences, temporary files, etc. If it doesn't exist and can't be made, try using /tmp. [#e Future: for Windows that backup dir should be something other than /tmp. And for all OSes, we should use a more conventional place to store prefs if there is one (certainly there is on Mac).] """ global _tmpFilePath if _tmpFilePath: return _tmpFilePath # already chosen, always return the same one _tmpFilePath = _find_or_make_nanorex_dir_0() assert _tmpFilePath return _tmpFilePath def _find_or_make_nanorex_dir_0(): """ private helper function for find_or_make_Nanorex_directory """ #Create the temporary file directory if not exist [by huaicai ~041201] # bruce 041202 comments about future changes to this code: # - we'll probably rename this, sometime before Alpha goes out, # since its purpose will become more user-visible and general. # - it might be good to create a README file in the directory # when we create it. And maybe to tell the user we created it, # in a dialog. # - If creating it fails, we might want to create it in /tmp # (or wherever some python function says is a good temp dir) # rather than leaving an ususable path in tmpFilePath. This # could affect someone giving a demo on a strange machine! # - If it exists already, we might want to test that it's a # directory and is writable. If we someday routinely create # a new file in it for each session, that will be a good- # enough test. tmpFilePath = os.path.normpath(os.path.expanduser("~/Nanorex/")) if not os.path.exists(tmpFilePath): try: os.mkdir(tmpFilePath) except: #bruce 041202 fixed minor bug in next line; removed return statement print_compact_traceback("exception in creating temporary directory: \"%s\"" % tmpFilePath) #bruce 050104 new feature [needs to be made portable so it works on Windows ###@@@] os_tempdir = "/tmp" print "warning: using \"%s\" for temporary directory, since \"%s\" didn't work" % (os_tempdir, tmpFilePath) tmpFilePath = os_tempdir #e now we should create or update a README file in there [bruce 050104] return tmpFilePath def path_of_Nanorex_subdir(subdir): #bruce 060614 """ Return the full pathname which should be used for the given ~/Nanorex subdirectory, without checking whether it exists. WARNING: as a kluge, the current implem may create ~/Nanorex itself. This might be necessary (rather than a kluge) if the name can only be determined by creating it (as the current code for creating it assumes, but whose true status is unknown). """ nanorex = find_or_make_Nanorex_directory() nanorex_subdir = os.path.join(nanorex, subdir) return nanorex_subdir def find_or_make_Nanorex_subdir(subdir, make = True): #bruce 060614 added make arg; revised implem (so subdir can be >1 level deep) """ Find or make a given subdirectory under ~/Nanorex/. It's allowed to be more than one level deep, using '/' separator. (This assumes '/' is an acceptable file separator on all platforms. I think it is, but haven't fully verified it. [bruce 060614]) (If make = False, never make it; return None if it's not there.) Return the full path of the Nanorex subdirectory, whether it already exists or was made here. """ subdir = path_of_Nanorex_subdir(subdir) errorcode, path_or_errortext = find_or_make_any_directory(subdir, make = make) if errorcode: if make: # this should not normally happen, since ~/Nanorex should be writable, but it's possible in theory print "bug: should not normally happen:", path_or_errortext return None return path_or_errortext def find_or_make_any_directory(dirname, make = True, make_higher_dirs = True): #bruce 060614 """ Find or make the given directory, making containing directories as needed unless make_higher_dirs is False. If <make> is False, don't make it, only find it, and make sure it's really a directory. Return (errorcode, message), where: - on success, return (0, the full and normalized path of <dirname>), or if <make> is False and <dirname> does not exist, return (0, None). - on error, return (1, errormsg). """ ###e once this works, redefine some other functions in terms of it, here and in callers of functions here. dirname = os.path.abspath(os.path.normpath(dirname)) #k might be redundant, in wrong order, etc if os.path.isdir(dirname): return 0, dirname if os.path.exists(dirname): return 1, "[%s] exists but is not a directory" % (dirname,) # not there if not make: return 0, None # This isn't an error since <make> is False and <dirname> does not exist. # try to make it; first make sure parent is there, only making it if make_higher_dirs is true. parent, basedir = os.path.split(dirname) if not parent or parent == dirname: # be sure to avoid infinite recursion; parent == dirname can happen for "/", # though presumably that never gets here since isdir is true for it, so this might never be reached. return 1, "[%s] does not exist" % (dirname,) assert basedir assert parent errorcode, path = find_or_make_any_directory(parent, make = make_higher_dirs, make_higher_dirs = make_higher_dirs) if errorcode: return errorcode, path # path is the errortext # now try to make the dir in question; this could fail for a variety of reasons # (like the parent not being writable, bad chars in basedir, disk being full...) try: os.mkdir(dirname) except: return 1, "can't create directory [%s]" % (dirname, ) ###e should grab exception text to say why not if not os.path.isdir(dirname): return 1, "bug: [%s] is not a directory, even though mkdir said it made it" % (dirname, ) # should never happen return 0, dirname # == def builtin_plugins_dir(): """ Return pathname of built-in plugins directory. Should work for either developers or end-users on all platforms. (Doesn't check whether it exists.) """ # filePath = the current directory NE-1 is running from. filePath = os.path.dirname(os.path.abspath(sys.argv[0])) return os.path.normpath(filePath + '/../plugins') def user_plugins_dir(): """ Return pathname of user custom plugins directory, or None if it doesn't exist. """ return find_or_make_Nanorex_subdir( 'Plugins', make = False) def find_plugin_dir(plugin_name): """ Return (True, dirname) or (False, errortext), with errortext wording chosen as if the requested plugin ought to exist. """ try: userdir = user_plugins_dir() if userdir and os.path.isdir(userdir): path = os.path.join(userdir, plugin_name) if os.path.isdir(path): return True, path except: print_compact_traceback("bug in looking for user-customized plugin %r; trying builtin plugins: ") pass try: appdir = builtin_plugins_dir() assert appdir if not os.path.isdir(appdir): return False, "error: can't find built-in plugins directory [%s] (or it's not a directory)" % (appdir,) path = os.path.join(appdir, plugin_name) if os.path.isdir(path): return True, path return False, "can't find plugin %r" % (plugin_name,) except: print_compact_traceback("bug in looking for built-in plugin %r: " % (plugin_name,)) return False, "can't find plugin %r" % (plugin_name,) pass # == _histfile = None _histfile_timestamp_string = None #bruce 060614 kluge -- record this for use in creating other per-session unique directory names # To clean this up, we should create this filename, and the file itself, # earlier during startup, and be 100% sure it's unique (include pid, use O_EXCL, or test in some manner). def make_history_filename(): """ [private method for history init code] Return a suitable name for a new history file (not an existing filename). Note: this does not actually create the file! It's assumed the caller will do that immediately (and we don't provide perfect protection against two callers doing this at the same time). The filename contains the current time, so this should be called once per history (probably once per process), not once per window when we have more than one. This filename could also someday be used as a "process name", valid forever, but relative to the local filesystem. """ prefsdir = find_or_make_Nanorex_directory() tried_already = None while 1: timestamp_string = time.strftime("%Y%m%d-%H%M%S") histfile = os.path.join( prefsdir, "Histories", "h%s.txt" % timestamp_string ) # e.g. ~/Nanorex/Histories/h20050104-160000.txt if not os.path.exists(histfile): if histfile == tried_already: # this is ok, but is so unlikely that it might indicate a bug, so report it print "fyi: using history file \"%s\" after all; someone removed it!" % histfile if "kluge": global _histfile, _histfile_timestamp_string _histfile = histfile _histfile_timestamp_string = timestamp_string # this lacks the 'h' and the '.txt' return histfile # caller should print this at some point # Another process which wants to use the same kind of history filename # (in the same Nanorex-specific prefs directory) must have started less # than one second before! Wait for this to be untrue. Print something, # in case this gets into an infloop from some sort of bug. This is rare # enough that it doesn't matter much what we print -- hardly anyone # should see it. if histfile != tried_already: print "fyi: history file \"%s\" already exists; will try again shortly..." % histfile tried_already = histfile # prevent printing another msg about the same filename time.sleep(0.35) continue pass _tempfiles_dir = None # this is assigned if and only if we ever create that dir, so we can move it when we quit. (Not a kluge.) _tempfiles_dir_has_moved = False def tempfiles_dir(make = True): #bruce 060614 """ Return (and by default, make if necessary) the pathname of the subdir for this process's temporary files. If make is false and this dir is not there, return None rather than its intended name. [All temporary files created by this process should go into the subdir we return, and upon normal exit it should be moved to a different location or name that marks it as "Old", e.g. from ~/Nanorex/TemporaryFiles into ~/Nanorex/OldTempFiles, and subsequent nE-1 startups should consider deleting it if it's both marked as old (meaning nE-1 didn't crash and can't be still running) and is too old in modtime of any file, or recorded quit-time (eg modtime of a logfile that records the quit). But all that is NIM as of 060614.] """ #bruce 060614; current implem is a kluge, but should be ok in practice # unless you start more than one nE-1 process in one second, and furthermore they # happen to both think they own the same history file name (unlikely but possible) global _tempfiles_dir if _tempfiles_dir_has_moved: print "bug: _tempfiles_dir_has_moved but we're calling tempfiles_dir after that; _tempfiles_dir == %r" % (_tempfiles_dir,) assert _histfile_timestamp_string, "too early to call tempfiles_dir" if _tempfiles_dir: return _tempfiles_dir _tempfiles_dir = find_or_make_Nanorex_subdir("TemporaryFiles/t%s" % _histfile_timestamp_string, make = make ) # that might be None if make is false, but that's ok since it already was None if we got this far # [don't reset _tempfiles_dir_has_moved to mitigate the bug of calling this when it's already set, # since the newly made dir might have the same name as the moved one so we don't want to try moving it again] return _tempfiles_dir def move_tempfiles_dir_when_quitting(): #bruce 060614 ###@@@ need to call this when nE-1 quits """ If tempfiles_dir actually created a directory during this session, move it to where old ones belong. (Also reset variables so that if some bug makes someone call tempfiles_dir again, it will complain, but then return the moved directory rather than a now-invalid pathname.) """ global _tempfiles_dir, _tempfiles_dir_has_moved if _tempfiles_dir_has_moved: print "bug: _tempfiles_dir_has_moved but we're calling move_tempfiles_dir_when_quitting again" #e print_compact_stack return _tempfiles_dir_has_moved = True # even if not _tempfiles_dir if not _tempfiles_dir: return if not os.path.isdir(_tempfiles_dir): print "bug: can't find _tempfiles_dir %r which we supposedly made earlier this session" % (_tempfiles_dir,) return assert _histfile_timestamp_string movetodir = find_or_make_Nanorex_subdir("OldTempFiles") moveto = os.path.join( movetodir, os.path.basename(_tempfiles_dir)) assert _tempfiles_dir != moveto os.rename(_tempfiles_dir, moveto) _tempfiles_dir = moveto return # === # user-message helpers: # here are some functions involving user messages, which don't really belong in # this file, but there is not yet a better place for them. [bruce 041018] def fix_plurals(text, between = 1): """ Fix plurals in text (a message for the user) by changing: 1 thing(s) -> 1 thing 2 thing(s) -> 2 things permitting at most 'between' extra words in between, e.g. by default 2 green thing(s) -> 2 green things. Also, if the subsequent word is (literally) were/was or was/were, replace it with the correct form. """ words = text.split(" ") numpos = -1 count = 0 didpos = -1 didnum = -1 for word,i in zip(words,range(len(words))): if word and word[-1].isdigit(): # if word ends with a digit, call it a number (e.g. "(1" ) numpos = i elif word.endswith("(s)") or \ word.endswith("(s),") or \ word.endswith("(s).") or \ word.endswith("(s)</span>"): # (that condition is a kluge, should be generalized [bruce 041217]) # (added "(s).", bruce 060615) # (added "(s)</span>" (bad kluge, very fragile, but works for now) # for when this is used at the end of input to redmsg etc [bruce 080201]) ## suflen = ( (not word.endswith("(s)")) and 1) or 0 # klugier and klugier suflen = len( word.split('(s)', 1)[1] ) # length of everything after '(s)' #bruce 080201 count += 1 if numpos >= 0 and (i-numpos) <= (between+1): # not too far back # fix word for whether number is 1 nw = words[numpos] assert nw and nw[-1].isdigit() # consider only the adjacent digits at the end num = "" for cc in nw: num += cc if not cc.isdigit(): num = "" if suflen: words[i], suffix = words[i][:-suflen], words[i][-suflen:] else: suffix = "" if num == "1": words[i] = words[i][:-3] + suffix else: words[i] = words[i][:-3] + "s" + suffix didpos = i didnum = num else: # error, but no change to words[i] print "fyi, cosmetic bug: fix_plurals(%r) found no number close enough to affect %r" % (text,word) numpos = -1 # don't permit "2 dog(s) cat(s)" -> "2 dogs cats" elif word == "was/were" or word == "were/was": #bruce 060615 new feature (#e probably should generalize to e.g. is/are) if didpos >= 0 and (i-didpos) <= 1: # not too far back # replace with whichever is correct of "was" or "were" if didnum == "1": words[i] = "was" else: words[i] = "were" didpos = -1 else: print "fyi, cosmetic bug: fix_plurals(%r) was unable to replace %r" % (text,word) continue if not count: print """fyi, possible cosmetic bug: fix_plurals(%r) got text with no "(s)" (or between option not big enough), has no effect""" % (text,) return " ".join(words) def th_st_nd_rd(val): # mark 060927 wrote this. bruce 060927 split it out of its caller & wrote docstring. """ Return the correct suffix (th, st, nd, or rd) to append to any nonnegative integer in decimal, to make an abbreviation such as 0th, 1st, 2nd, 3rd, or 4th. """ suffix = "th" ones = val % 10 tens = val % 100 if ones == 1: if tens == 1 or tens > 20: suffix = "st" elif ones == 2: if tens == 2 or tens > 20: suffix = "nd" elif ones == 3: if tens == 3 or tens > 20: suffix = "rd" return suffix def hhmmss_str(secs): """ Given the number of seconds, return the elapsed time as a string in hh:mm:ss format """ # [bruce 050415 comment: this is sometimes called from external code # after the progressbar is hidden and our launch method has returned.] # bruce 050415 revising this to use pure int computations (so bugs from # numeric roundoff can't occur) and to fix a bug when hours > 0 (commented below). secs = int(secs) hours = int(secs/3600) # use int divisor, not float # (btw, the int() wrapper has no effect until python int '/' operator changes to produce nonints) minutes = int(secs/60 - hours*60) seconds = int(secs - minutes*60 - hours*3600) #bruce 050415 fix bug 439: also subtract hours if hours: return '%02d:%02d:%02d' % (hours, minutes, seconds) else: return '%02d:%02d' % (minutes, seconds) # == # code for determining screen size (different for Mac due to menubar) #e (I should also pull in some more related code from main.py...) def screen_pos_size(): ###e this copies code in main.py -- main.py should call this """ Return (x,y),(w,h), where the main screen area (not including menubar, for Mac) is in a rect of size w,h, topleft at x,y. Note that x,y is 0,0 except for Mac. Current implementation guesses Mac menubar size since it doesn't know how to measure it. """ # Create desktop widget to obtain screen resolution dtop = QDesktopWidget() screensize = QRect (dtop.screenGeometry (0)) if is_macintosh(): # menubar_height = 44 was measured (approximately) on an iMac G5 20 inch # screen; I don't know if it's the same on all Macs (or whether it can # vary with OS or user settings). (Is there any way of getting this info # from Qt? #e) menubar_height = 44 else: menubar_height = 0 screen_w = screensize.width() screen_h = screensize.height() # of which menubar_height is in use at the top x,y = 0,0 w,h = screen_w, screen_h y += menubar_height h -= menubar_height return (x,y), (w,h) # == def open_file_in_editor(file, hflag = True): #bruce 050913 revised this """ Opens a file in a standard text editor. Error messages go to console and (unless hflag is false) to env.history. """ #bruce 050913 replaced history arg with hflag = True, since all callers passed env.history to history arg. file = os.path.normpath(file) if not os.path.exists(file): msg = "File does not exist: " + file print msg if hflag: env.history.message(redmsg(msg)) return editor_and_args = get_text_editor() # a list of editor name and 0 or more required initial arguments [bruce 050704 revised API] editor = editor_and_args[0] initial_args = list( editor_and_args[1:] ) if os.path.exists(editor): args = [editor] + initial_args + [file] if debug_flags.atom_debug: print "editor = ",editor print "Spawnv args are %r" % (args,) try: # Spawn the editor. kid = os.spawnv(os.P_NOWAIT, editor, args) except: # We had an exception. print_compact_traceback("Exception in editor; continuing: ") msg = "Cannot open file " + file + ". Trouble spawning editor " + editor print msg if hflag: env.history.message(redmsg(msg)) else: msg = "Cannot open file " + file + ". Editor " + editor + " not found." if hflag: env.history.message(redmsg(msg)) return def get_text_editor(): #bruce 050704 revised API """ Returns a list of the name and required initial shell-command-line arguments (if any) of a text editor for this platform. The editor can be caused to open a file by launching it using these args plus the filename. """ args = [] # might be modified below if sys.platform == 'win32': # Windows editor = "C:/WINDOWS/notepad.exe" elif sys.platform == 'darwin': # MacOSX editor = "/usr/bin/open" args = ['-e'] # /usr/bin/open needs -e argument to force treatment of file as text file. else: # Linux editor = "/usr/bin/kwrite" return [editor] + args def get_rootdir(): """ Returns the root directory for this platform. """ if sys.platform == 'win32': # Windows rootdir = "C:/" else: # Linux and MacOS rootdir = "/" return rootdir def get_gms_name(): """ Returns either GAMESS (Linux or MacOS) or PC GAMESS (Windows). """ if sys.platform == 'win32': # Windows gms_name = "PC GAMESS" else: # Linux and MacOS gms_name = "GAMESS" return gms_name def find_pyrexc(): import Pyrex # not a toplevel import -- module not present for most users if sys.platform == 'darwin': # MacOS x = os.path.dirname(Pyrex.__file__).split('/') y = '/'.join(x[:-4] + ['bin', 'pyrexc']) if os.path.exists(y): return y elif os.path.exists('/usr/local/bin/pyrexc'): return '/usr/local/bin/pyrexc' raise Exception('cannot find Mac pyrexc') elif sys.platform == 'linux2': if os.path.exists('/usr/bin/pyrexc'): return '/usr/bin/pyrexc' if os.path.exists('/usr/local/bin/pyrexc'): return '/usr/local/bin/pyrexc' raise Exception('cannot find pyrexc') else: # windows return 'python c:/Python' + sys.version[:3] + '/Scripts/pyrexc.py' # == test code if __name__ == '__main__': msg = "Dehydrogenate: removed 4 atom(s) from 1 molecule(s) (1 selected molecule(s) had no hydrogens)" msg2 = "Dehydrogenate: removed 4 atoms from 1 molecule (1 selected molecule had no hydrogens)" assert fix_plurals(msg) == msg2 print "test done" # end
NanoCAD-master
cad/src/platform_dependent/PlatformDependent.py
NanoCAD-master
cad/src/platform_dependent/__init__.py
# Copyright 2005-2008 Nanorex, Inc. See LICENSE file for details. """ bond_constants.py -- constants and simple functions for use with class Bond (which can be defined without importing that class). @author: Bruce @version: $Id$ @copyright: 2005-2008 Nanorex, Inc. See LICENSE file for details. History: 050429 - Started out as part of bonds.py. Gradually extended. 050707 - Split into separate file, largely to avoid recursive import problems (since these constants need to be imported by many bond-related modules). Many of them are still imported via bonds module, by code in other modules. 050920 - Full mmp support for Carbomeric bonds. [FYI: As of today, sim executable reportedly accepts them and uses same params as for bond2.] """ from math import floor, ceil from geometry.VQT import Q from utilities.debug import print_compact_traceback from utilities import debug_flags import foundation.env as env from simulation.PyrexSimulator import thePyrexSimulator # == # Bond valence constants -- exact ints, 6 times the numeric valence they represent. # If these need an order, their standard order is the same as the order of their numeric valences # (as in the constant list BOND_VALENCES). V_SINGLE = 6 * 1 # 6 V_GRAPHITE = 6 * 4/3 # 8 (this can't be written 6 * (1+1/3) or 6 * (1+1/3.0) - first one is wrong, second one is not an exact int) V_AROMATIC = 6 * 3/2 # 9 V_DOUBLE = 6 * 2 # 12 V_CARBOMERIC = 6 * 5/2 # 15 for the bonds in a carbomer of order 2.5 (which alternate with aromatic bonds); saved as bondc as of 050920 V_TRIPLE = 6 * 3 # 18 V_UNKNOWN = 6 * 7/6 # 7 not in most tables here, and not yet used; someday might be used internally by bond-type inference code BOND_VALENCES = [V_SINGLE, V_GRAPHITE, V_AROMATIC, V_DOUBLE, V_CARBOMERIC, V_TRIPLE] # when convenient (e.g. after A8), V_GRAPHITE should be renamed to V_GRAPHITIC [bruce 060629] BOND_MMPRECORDS = ['bond1', 'bondg', 'bonda', 'bond2', 'bondc', 'bond3'] # (Some code might assume these all start with "bond".) # (These mmp record names are also hardcoded into mmp-reading code in files_mmp.py.) bond_type_names = {V_SINGLE:'single', V_DOUBLE:'double', V_TRIPLE:'triple', V_AROMATIC:'aromatic', V_GRAPHITE:'graphitic', V_CARBOMERIC:'carbomeric'} BOND_VALENCES_HIGHEST_FIRST = list(BOND_VALENCES) BOND_VALENCES_HIGHEST_FIRST.reverse() V_ZERO_VALENCE = 0 # used as a temporary valence by some code BOND_LETTERS = ['?'] * (V_TRIPLE+1) # modified just below, to become a string; used in initial Bond.draw method via bond_letter_from_v6 for v6, mmprec in zip( BOND_VALENCES, BOND_MMPRECORDS ): BOND_LETTERS[v6] = mmprec[4] # '1','g',etc # for this it's useful to also have '?' for in-between values but not for negative or too-high values, # so a list or string is more useful than a dict assert BOND_LETTERS[V_CARBOMERIC] == 'c' # not 'a', not 'b' BOND_LETTERS[0] = '0' # see comment in bond_letter_from_v6 BOND_LETTERS = "".join(BOND_LETTERS) ## print "BOND_LETTERS:",BOND_LETTERS # 0?????1?ga??2?????3 BOND_MIN_VALENCES = [ 999.0] * (V_TRIPLE+1) #bruce 050806; will be modified below BOND_MAX_VALENCES = [-999.0] * (V_TRIPLE+1) bond_valence_epsilon = 1.0 / 64 # an exact float; arbitrary, but must be less than 1/(2n) where no atom has more than n bonds for v6 in BOND_VALENCES: if v6 % V_SINGLE == 0: # exact valence BOND_MIN_VALENCES[v6] = BOND_MAX_VALENCES[v6] = v6 / 6.0 else: # non-integral (and inexact) valence BOND_MIN_VALENCES[v6] = floor(v6 / 6.0) + bond_valence_epsilon BOND_MAX_VALENCES[v6] = ceil(v6 / 6.0) - bond_valence_epsilon pass BOND_MIN_VALENCES[V_UNKNOWN] = 1.0 # guess, not yet used BOND_MAX_VALENCES[V_UNKNOWN] = 3.0 # ditto # constants returned as statuscode by Atom.directional_bond_chain_status() # [bruce 071016] DIRBOND_CHAIN_MIDDLE = 'middle' DIRBOND_CHAIN_END = 'end' DIRBOND_NONE = None DIRBOND_ERROR = 'error' # == # [Note: the functions atoms_are_bonded and find_bond, were moved # from bonds.py to here (to remove an import cycle) by bruce 071216; # I also removed the old alias 'bonded' for atoms_are_bonded, # since 'bonded' is too generic to be searched for.] def atoms_are_bonded(a1, a2): """ Are these atoms (or singlets) already directly bonded? [AssertionError if they are the same atom.] """ #bruce 041119 #e optimized by bruce 050502 (which indirectly added "assert a1 is not a2") ## return a2 in a1.neighbors() return not not find_bond(a1, a2) def find_bond(a1, a2): """ If a1 and a2 are bonded, return their Bond object; if not, return None. [AssertionError if they are the same atom.] """ #bruce 050502; there might be an existing function in some other file, to merge this with assert a1 is not a2 for bond in a1.bonds: if bond.atom1 is a2 or bond.atom2 is a2: return bond return None def find_Pl_bonds(atom1, atom2): #bruce 080409 moved this here to clear up an import cycle """ return the two bonds in atom1-Pl5-atom2, or (None, None) if that structure is not found. """ for bond1 in atom1.bonds: Pl = bond1.other(atom1) if Pl.element.symbol == 'Pl5': # avoid import of model.elements bond2 = find_bond(Pl, atom2) if bond2: return bond1, bond2 return None, None # == def min_max_valences_from_v6(v6): """ Given a v6 value (an int representing a bond order times 6), return a range of acceptable floating point bond orders. V_SINGLE returns 1.0, 1.0. V_AROMATIC returns 1+delta, 2-delta, for small delta. etc... """ return BOND_MIN_VALENCES[v6], BOND_MAX_VALENCES[v6] def valence_to_v6(valence): #bruce 051215 """ Given a valence (int or float, single bond is 1 or 1.0), return it as a v6, being careful about rounding errors. """ return int(valence * V_SINGLE + 0.01) # kluge: 0.01 is based on knowledge of scale of V_SINGLE (must be > 0, < 1/V_SINGLE) def bond_letter_from_v6(v6): #bruce 050705 """ Return a bond letter summarizing the given v6, which for legal values is one of 1 2 3 a g b, and for illegal values is one of - 0 ? + """ try: ltr = BOND_LETTERS[v6] # includes special case of '0' for v6 == 0, # which should only show up for transient states that are never drawn, except in case of bugs except IndexError: # should only show up for transient states... if v6 < 0: ltr = '-' else: ltr = '+' return ltr def btype_from_v6(v6): #bruce 050705 """ Given a legal v6, return 'single', 'double', etc. For illegal values, return 'unknown'. For V_CARBOMERIC this returns 'carbomeric', not 'aromatic'. """ try: return bond_type_names[v6] except KeyError: if debug_flags.atom_debug: print "atom_debug: illegal bond v6 %r, calling it 'unknown'" % (v6,) return 'unknown' #e stub for this error return; should it be an error word like this, or single, or closest legal value?? pass def invert_dict(dict1): #bruce 050705 res = {} for key, val in dict1.items(): res[val] = key return res bond_type_names_inverted = invert_dict(bond_type_names) def v6_from_btype(btype): #bruce 050705 """ Return the v6 corresponding to the given bond-type name ('single', 'double', etc). Exception if name not legal. """ return bond_type_names_inverted[btype] _bond_arrows = { 0: "<- ->".split(), 1: "-- ->".split(), # from atom1 to atom2, i.e. to the right -1: "<- --".split(), } def bonded_atoms_summary(bond, quat = Q(1,0,0,0)): #bruce 050705; direction feature, bruce 070414. ###e SHOULD CALL bond_left_atom """ Given a bond, and an optional quat describing the orientation it's shown in, order the atoms left to right based on that quat, and return a text string summarizing the bond in the form C26(sp2) <-2-> C34(sp3) or so, leaving out the < or > if the bond has a direction. """ a1 = bond.atom1 a2 = bond.atom2 direction = bond._direction vec = a2.posn() - a1.posn() vec = quat.rot(vec) if vec[0] < 0.0: a1, a2 = a2, a1 direction = - direction a1s = describe_atom_and_atomtype(a1) a2s = describe_atom_and_atomtype(a2) bondletter = bond_letter_from_v6(bond.v6) if bondletter == '1': bondletter = '' arrows = _bond_arrows.get(direction, ("<-", " (invalid direction) ->")) return "%s %s%s%s %s" % (a1s, arrows[0], bondletter, arrows[1], a2s) def bond_left_atom(bond, quat = Q(1,0,0,0)): #bruce 070415, modified from bonded_atoms_summary, which ought to call this now ##e # TODO: make this method name clearer: bond_leftmost_atom? bond_get_atom_on_left? [bruce 080807 comment] """ Given a bond, and an optional quat describing the orientation it's shown in, order the atoms left to right based on that quat (i.e. as the bond would be shown on the screen using it), and return the leftmost atom. """ a1 = bond.atom1 a2 = bond.atom2 vec = a2.posn() - a1.posn() vec = quat.rot(vec) if vec[0] < 0.0: a1, a2 = a2, a1 return a1 def describe_atom_and_atomtype(atom): #bruce 050705, revised 050727 #e refile? """ If a standard atom, return a string like C26(sp2) with atom name and atom hybridization type, but only include the type if more than one is possible for the atom's element and the atom's type is not the default type for that element. If a PAM Ss or Sj atom, returns a string like Ss28(A) with atom name and dna base name. @deprecated: For some purposes use L{Atom.getInformationString()} instead. (But for others, that might not be suitable. Needs review.) """ res = str(atom) if atom.atomtype is not atom.element.atomtypes[0]: res += "(%s)" % atom.atomtype.name if atom.getDnaBaseName(): res += "(%s)" % atom.getDnaBaseName() return res # == _bond_params = {} # maps triple of atomtype codes and v6 to (rcov1, rcov2) pairs def bond_params(atomtype1, atomtype2, v6 = V_SINGLE): #bruce 060324 for bug 900; made v6 optional, 080405 """ Given two atomtypes and an optional bond order encoded as v6, look up or compute the parameters for that kind of bond. For now, the return value is just a pair of numbers, rcov1 and rcov2, for use as the covalent radii for atom1 and atom2 respectively for this kind of bond (with their sum adjusted to the equilibrium bond length if this is known). """ atcode1 = id(atomtype1) # maybe: add a small int code attr to atomtype, for efficiency atcode2 = id(atomtype2) try: return _bond_params[(atcode1, atcode2, v6)] except KeyError: res = _bond_params[(atcode1, atcode2, v6)] = \ _compute_bond_params(atomtype1, atomtype2, v6) return res pass def ideal_bond_length(atom1, atom2, v6 = V_SINGLE): #bruce 080404 """ Return the ideal bond length between atom1 and atom2 (using their current atomtypes) for a bond of the given order (default V_SINGLE). The atoms need not be bonded; if they are, that bond's current order is ignored. [review: revise that rule, to use it if they are bonded??] (Use bond_params, which uses getEquilibriumDistanceForBond if ND-1 is available.) """ rcov1, rcov2 = bond_params(atom1.atomtype, atom2.atomtype, v6) return rcov1 + rcov2 def _compute_bond_params(atomtype1, atomtype2, v6): #bruce 080405 revised this """ [private helper function for bond_params] """ # note: this needn't be fast, since its results for given arguments # are cached for the entire session by the caller. # (note: as of 041217 rcovalent is always a number; it's 0.0 for Helium, # etc, so for nonsense bonds like He-He the entire bond is drawn as if # "too long". [review: what should we do for a nonsense bond like C-He?]) rcov1 = atomtype1.rcovalent rcov2 = atomtype2.rcovalent rcovsum = rcov1 + rcov2 # ideal length according to our .rcovalent tables, # used as a fallback if we can't get a better length if not rcovsum: print "error: _compute_bond_params for nonsense bond:", \ atomtype1, atomtype2, v6 rcov1 = rcov2 = 0.5 # arbitrary rcovsum = rcov1 + rcov2 # now adjust rcov1 and rcov2 to make their sum the equilibrium bond length # [bruce 060324 re bug 900] eltnum1 = atomtype1.element.eltnum # note: both atoms and atomtypes have .element eltnum2 = atomtype2.element.eltnum ltr = bond_letter_from_v6(v6) # determine ideal bond length (special case for one element being Singlet) assert eltnum1 or eltnum2, "can't bond bondpoints to each other" if eltnum1 == 0 or eltnum2 == 0: # one of them is Singlet (bondpoint); getEquilibriumDistanceForBond # doesn't know about those, so work around this somehow nicelen = None if atomtype1.element.pam or atomtype2.element.pam: # in this case we prefer the native formula (see if this fixes bug 2944) [bruce 081210] nicelen = rcovsum if nicelen is None: # use half the distance for a bond from the non-Singlet atomtype to itself eltnum = eltnum1 or eltnum2 nicelen = _safely_call_getEquilibriumDistanceForBond( eltnum, eltnum, ltr) if nicelen: nicelen = nicelen / 2.0 pass pass else: nicelen = _safely_call_getEquilibriumDistanceForBond( eltnum1, eltnum2, ltr) if nicelen is None: # the call failed, use our best guess nicelen = rcovsum assert nicelen > 0.0 # now adjust rcov1 and rcov2 so their sum equals nicelen # (this works even if one of them is 0, presumably for a bondpoint) ratio = nicelen / float(rcovsum) rcov1 *= ratio rcov2 *= ratio return rcov1, rcov2 def _safely_call_getEquilibriumDistanceForBond( eltnum1, eltnum2, ltr): #bruce 080405 split this out """ #doc eg: args for C-C are (6, 6, '1') @return: ideal length in Angstroms (as a positive float), or None if the call of getEquilibriumDistanceForBond failed """ try: pm = thePyrexSimulator().getEquilibriumDistanceForBond(eltnum1, eltnum2, ltr) assert pm > 2.0, "too-low pm %r for getEquilibriumDistanceForBond%r" % \ (pm, (eltnum1, eltnum2, ltr)) # 1.0 means an error occurred; 2.0 is still ridiculously low # [not as of 070410]; btw what will happen for He-He?? # update 070410: it's 1.8 for (202, 0, '1'). # -- but a new sim-params.txt today changes the above to 170 nicelen = pm / 100.0 # convert picometers to Angstroms return nicelen except: # be fast when this happens a lot (not important now that our retval # is cached, actually; even so, don't print too much) if not env.seen_before("error in getEquilibriumDistanceForBond"): #e include env.redraw_counter to print more often? no. msg = "bug: ignoring exceptions when using " \ "getEquilibriumDistanceForBond, like this one: " print_compact_traceback(msg) return None pass # == # Here's an old long comment which is semi-obsolete now [050707], but which motivates the term "v6". # Note that I'm gradually replacing the term "bond valence" with whichever of "bond order" or "bond type" # (related but distinct concepts) is appropriate. Note also that all the bond orders we deal with in this code # are "structural bond orders" (used by chemists to talk about bonding structure), not "physical bond orders" # (real numbers related to estimates of occupancy of molecular orbitals by electrons). #bruce 050429: preliminary plan for higher-valence bonds (might need a better term for that): # # - Bond objects continue to compare equal when on same pair of atoms (even if they have a # different valence), and (partly by means of this -- probably it's a kluge) they continue # to allow only one Bond between any two atoms (two real atoms, or one real atom and one singlet). # # - I don't think we need to change anything basic about "internal vs external bonds", # coordinates, basic inval/draw schemes (except to properly draw new kinds of bonds), # etc. (Well, not due to bond valence -- we might change those things for other reasons.) # # - Each Bond object has a valence. Atoms often sum the valences of their bonds # and worry about this, but they no longer "count their bonds" -- at least not as a # substitute for summing the valences. (To prevent this from being done by accident, # we might even decide that their list of bonds is not really a list, at least temporarily # while this is being debugged. #?) # # This is the first time bonds have any state that needs to be saved, # except for their existence between their two atoms. This will affect mmpfile read/write, # copying of molecules (which needs rewriting anyway, to copy jigs/groups/atomsets too), # lots of things about depositMode, maybe more. # # - Any bond object can have its valence change over time (just as the coords, # elements, or even identities of its atoms can also change). This makes it a lot # easier to write code which modifies chemical structures in ways which preserve (some) # bonding but with altered valence on some bonds. # # - Atoms might decide they fit some "bonding pattern" and reorder # their list of bonds into a definite order to match that pattern (this is undecided #?). # This might mean that code which replaces one bond with a same-valence bond should do it # in the same place in the list of bonds (no idea if we even have any such code #k). # # - We might also need to "invalidate an atom's bonding pattern" when we change anything # it might care about, about its bonds or even its neighboring elements (two different flags). #? # # - We might need to permit atoms to have valence errors, either temporarily or permanently, # and keep track of this. We might distinguish between "user-permitted" or even "user-intended" # valence errors, vs "transient undesired" valence errors which we intend to automatically # quickly get rid of. If valence errors can be long-lasting, we'll want to draw them somehow. # # - Singlets still require exactly one bond (unless they've been killed), but it can have # any valence. This might affect how they're drawn, how they consider forming new bonds # (in extrude, fuse chunks, depositMode, etc), and how they're written into sim-input mmp files. # # - We represent the bond valence as an integer (6 times the actual valence), since we don't # want to worry about roundoff errors when summing and comparing valences. (Nor to pay the speed # penalty for using exactly summable python objects that pretend to have the correct numeric value.) # # An example of what we don't want to have to worry about: # # >>> 1/2.0 + 1/3.0 + 1/6.0 # 0.99999999999999989 # >>> _ >= 1.0 # False # # We do guarantee to all code using these bond-valence constants that they can be subtracted # and compared as numbers -- i.e. that they are "proportional" to the numeric valence. # Some operations transiently create bonds with unsupported values of valence, especially bonds # to singlets, and this is later cleaned up by the involved atoms when they update their bonding # patterns, before those bonds are ever drawn. Except for bugs or perhaps during debugging, # only standard-valence bonds will ever be drawn, or saved in files, or seen by most code. # == # end
NanoCAD-master
cad/src/model/bond_constants.py
# Copyright 2005-2007 Nanorex, Inc. See LICENSE file for details. """ pi_bond_sp_chain.py -- geometric info for individual pi bonds, or chains of them connected by sp atoms. @author: bruce @version: $Id$ @copyright: 2005-2007 Nanorex, Inc. See LICENSE file for details. Note, 070414: it turns out a lot of the same concepts and similar code ought to be useful for keeping track of chains of "directional bonds" (such as pseudo-atom DNA backbones) in which direction-inference and consistency checks should occur. Maybe I'll even create a general class for perceiving bond-chains (or rings), with subclasses which know about specific ways of recognizing bonds they apply to; or a class whose instances hold bond-classifiers and act as perceivers of chains of bonds of that type. (Once the chain is perceived, by generic code, it does need specific code for its chain-type to figure out what to do, though the basic fact of being destroyed when involved-atom-structure changes is probably common. In the bond direction case, unlike in PiBondSpChain, destroying the perceived strand will leave behind some persistent state, namely the per-bond directions themselves; the perceived strand's role is to help change those directions in an organized way.) """ import math from Numeric import dot from utilities import debug_flags from model.jigs import Jig from geometry.VQT import V, Q, A, cross, vlen, norm, twistor_angle from operations.bond_chains import grow_bond_chain from model.bond_constants import V_SINGLE from model.bond_constants import V_DOUBLE from model.bond_constants import V_TRIPLE from model.bond_constants import V_AROMATIC from model.bond_constants import V_GRAPHITE from model.bond_constants import V_CARBOMERIC DFLT_OUT = V(0.0, -0.6, 0.8) # these are rotated from standard out = V(0,0,1), up = V(0,1,0) but still orthonormal DFLT_UP = V(0.0, 0.8, 0.6) # _recompile_counter is useful for development, and is harmless otherwise try: _recompile_counter except: _recompile_counter = 1 else: # increment the counter only when the module got recompiled, not just when it got reloaded from the same .pyc file if __file__.endswith(".py"): _recompile_counter += 1 print "_recompile_counter incremented to", _recompile_counter else: pass ## print "_recompile_counter unchanged at", _recompile_counter pass def bond_get_pi_info(bond, **kws): """ #doc; **kws include out, up, abs_coords """ obj = bond.pi_bond_obj if obj is not None: # let the obj update itself and return the answer. # (I think this should always work, since it gets invalled and can remove itself as needed. # If not, it must resort to similar code to remainder of this routine, # since it can't return anything here to tell this routine to do that for it.) if obj._recompile_counter != _recompile_counter: # it would not be good to do this except when the module got recompiled due to being modified # (ie not merely when it got reloaded), since that would defeat persistence of these objects, which we need to debug print "destroying %r of obsolete class" % obj # happens when we reload this module at runtime, during development obj.destroy() obj = None # special case for triple bonds [bruce 050728 to fix bug 821]: they are always arbitrarily oriented and not twisted if bond.v6 == V_TRIPLE: return pi_vectors(bond, **kws) # not worth optimizing for single bonds, since we're never called for them for drawing, # and if we're called for them when depositing sp2-sp-sp2 to position singlets on last sp2, # it would not even be correct to exclude them here! if obj is not None: return obj.get_pi_info(bond, **kws) # no need to pass an index -- that method can find one on bond if it stored one # if the obj is not there, several situations are possible; we only store an obj if the pi bond chain length is >1. if not bond.potential_pi_bond(): return None # note, this does *not* happen for single bonds, if they could in principle be changed to higher bond types if pi_bond_alone_in_its_sp_chain_Q(bond): # optimize this common case, with simpler code and by not storing an object for it # (since too many atoms would need to invalidate it) return pi_vectors(bond, **kws) obj = bond.pi_bond_obj = make_pi_bond_obj(bond) # make an obj that updates itself as needed when atoms/bonds change or move return obj.get_pi_info(bond, **kws) class PerceivedStructureType(Jig): #e rename, not really a Type (eg not a pattern), more like a set or layer or record """ ... Subclasses are used for specific kinds of perceived structures (e.g. sp chains, pi systems, diamond or graphite rings). """ pass #bruce 060223: How will we (PiBondSpChain) deal with Undo? We could just store every attr in this object, but we don't want to bother. # We want to think of it as entirely derived from other state (as it in fact is). So if things change, we'd rather invalidate it # and start over. In theory that should be ok, provided Undo (when changing other atoms & bonds) invals them in all the same # ways their LL change methods would do, including telling this object they changed (which makes it destroy itself). # Since this is a Jig, it will at least participate in Jigs' scheme for having atom lists and being on atoms' jig lists, # and Undo ought to properly handle that... how does that interact with our own policy of destroying ourself as soon as some atom # we're interested in says it changed? Could that happen with atom->jig and jig->atom connections not yet corresponding? # Solution to that worry: first let Undo do all its setattrs (so atom->jig and jig->atom connections have all been changed), # then call all object updaters at once. Ours is our superclass's and does nothing (I think); the one on the first atom we # encounter will destroy us; this will remove us from an atom's jig list but that should not (I think) invalidate the atom, # since those are really just "back pointers" rather than properties of the atom (if it did inval it, that would be bad, I think -- # maybe not, since _undo_update is really an inval method and those can in general call other inval methods). # So if Atom & Bond _undo_updates are correct, we should be ok. If not, some bugs will be noticed at some point. # # One other thing: we're a Jig, but we're not in the node tree (which is why we don't get into mmp files). So Undo will not find us # as a child object. We'll still get an objkey (I think)... hmm, this might be a problem, since when restoring some atom->jig to us, # it won't restore our pointer to that atom. Can that ever happen (in light of our atomset being fixed)? I don't know. I think this # might indeed cause bugs, so we might need to get counted as a child, or be some new undo-kind of object that easily gets # invalidated by any _undo_update on atoms it touches (maybe we introduce "subscribe to another obj's _undo_update" or to their # specific attrs?). I think it's easiest to wait and see if bugs happen. If they do, that subscription idea sounds best to me. # CHANGED MY MIND, I'll just make us an S_CHILD of our bonds... then our atomset should be ok, and we could have _undo_update # notice it changing too, if we wanted to. Let's do that for safety (maybe we'll never know if it was needed). # ###@@@ class PiBondSpChain(PerceivedStructureType): """ Records one chain (or ring) of potential-pi-bonds connected by -sp- atoms; as a Jig, sits on all atoms whose structure or motion matters for the extent of this chain and the geometry of its pi orbitals (ie all atoms in the chain, and the immediate neighbor atoms of the ends). Main job is to calculate pi-orbital angles for drawing the pi bonds. Someday we might extend this to also infer bond types along the chain, etc. """ ringQ = False # class constant; in the Ring subclass, this is True have_geom = False # initial value of instance variable def _undo_update(self): #bruce 060223; see long comment above """ our atomset (a member of our superclass Jig) must have changed... """ self.destroy() PerceivedStructureType._undo_update(self) # might be pointless after that, but you never know... return def __init__(self, listb, lista): ### not like Jig init, might be a problem eg for copying it ###@@@ review whether that happens """ Make one, from lists of bonds and atoms (one more atom than bond, even for a ring, where 1st and last atoms are same) """ self._recompile_counter = _recompile_counter self.listb = listb self.lista = lista assert len(lista) == 1 + len(listb) assert len(listb) > 0 #e could assert each bond's atoms are same as prior and next corresponding atom in lista # now add ourselves into each bond, exclusively (for cleaner code, this should be a separate method, called by init caller #e) for i, bond in zip( range(len(listb)), listb ): if bond.pi_bond_obj is not None: if debug_flags.atom_debug: print "atom_debug: bug: obs pi_bond_obj found (and discarded) on %r" % (bond,) bond.pi_bond_obj.destroy() bond.pi_bond_obj = self bond.pi_obj_memo = i # now inval bond?? no, that would be wrong -- this func is part of updating it after smth else invalled it earlier. # figure out which atoms we need to monitor, for invalidating our geometric info or our structure. all_atoms = list(lista) # atoms in the chain, plus neighbor atoms whose posns matter assert len(lista) >= 2 end1 = lista[0] end2 = lista[-1] if end1 is not end2: # not a ring nn = end1.neighbors() nn.remove(lista[1]) all_atoms.extend(nn) # order doesn't matter nn = end2.neighbors() nn.remove(lista[-2]) all_atoms.extend(nn) assy = all_atoms[0].molecule.assy #e need to zap the need for assy from Node PerceivedStructureType.__init__(self, assy, all_atoms) return super = PerceivedStructureType # needed for this to work across reloads listb = () # permit repeated destroy [bruce 060322] _recompile_counter = None # ditto (not sure if needed) def destroy(self): super = self.super for bond in self.listb: self.listb = () #bruce 060322 to save RAM (might not be needed) if bond.pi_bond_obj is self: bond.pi_bond_obj = None bond.pi_obj_memo = None # only needed to cause an exception if something tries to misuse it elif bond.pi_bond_obj is not None: if debug_flags.atom_debug: print "atom_debug: bug: wrong pi_bond_obj %r found (not changed) on %r as we destroy %r" % (bond.pi_bond_obj, bond, self) super.destroy(self) def changed_structure(self, atom): # ideally this should react differently to neighbor atoms and others; but even neighbors might be brought in, eg C(sp3)-C#C; # so it's simplest for now to just forget about it and rescan for it when next needed. self.destroy() ###k need to make sure it's ok for jigs (Nodes) not in the model tree # no point in calling super.changed_structure after self.destroy! def moved_atom(self, atom): """ some atom I'm on moved; invalidate my geometric info """ # must be fast, so don't bother calling Jig.moved_atom, since it's a noop self.have_geom = False def changed_bond_type(self, bond): #bruce 050726 """ some bond I'm on changed type (perhaps due to user change or to bond inference code); invalidate my geometric info """ # there is no superclass method for this -- it's only called on bond.pi_bond_obj for our own bonds ###e it might be worth only invalidating if the bond type differs from what we last used when recomputing self.have_geom = False def get_pi_info(self, bond, out = DFLT_OUT, up = DFLT_UP, abs_coords = False): if len(self.listb) == 1: if debug_flags.atom_debug: print "atom_debug: should never happen (but should work if it does): optim for len1 PiBondSpChain object %r" % self return pi_vectors(self.listb[0], out = out, up = up, abs_coords = abs_coords) # optimization; should never happen since it's done instead of creating this object if not self.have_geom: self.recompute_geom(out = out, up = up) # always in abs coords self.have_geom = True ind = bond.pi_obj_memo # this was stored again whenever our structure changed (for now, only in init) assert type(ind) == type(1) assert 0 <= ind < len(self.listb) assert self.listb[ind] is bond biL_pvec, biR_pvec = self.pvecs_i( ind, abs_coords = True) #bruce 050727 -- abs_coords arg was used both here & below -- wrong, using True here is right (so I fixed it), # but I didn't yet see any effect from that presumed bug. It might be that the chunk quat is # always Q(1,0,0,0) whenever the pi_info gets updated. bond_axis = self.axes[ind] ## bond_axis = self.lista[ ind+1 ].posn() - self.lista[ ind ].posn() # order matters, i think if bond.atom1 is self.lista[ind]: assert bond.atom2 is self.lista[ind+1] else: # flipped assert bond.atom1 is self.lista[ind+1] assert bond.atom2 is self.lista[ind] bond_axis = - bond_axis biL_pvec, biR_pvec = biR_pvec, biL_pvec return pi_info_from_abs_pvecs( bond, bond_axis, biL_pvec, biR_pvec, abs_coords = abs_coords) def pvecs_i(self, i, abs_coords = False): """ Use last recomputed geom to get the 2 pvecs for bond i... in the coordsys of the bond, or always abs if flag is passed. WARNING: pvec order matches atom order in lista, maybe not in bond. """ biL_pvec = biR_pvec = self.quats_cum[i].rot(self.b0L_pvec) # not yet twisted axis = self.axes[i] ## if self.twist90 and i % 2 == 1: ## biL_pvec = norm(cross(biL_pvec, axis)) ## biR_pvec = norm(cross(biR_pvec, axis)) twist = self.twist # this is the twist angle (in radians), for each bond; or None or 0 or 0.0 for no twist if twist: # twist that much times i and i+1 for L and R, respectively, around axes[i] theta = twist quatL = Q(axis, theta * (i)) quatR = Q(axis, theta * (i+1)) biL_pvec = quatL.rot(biL_pvec) biR_pvec = quatR.rot(biR_pvec) if not abs_coords: # put into bond coords (which might be the same as abs coords) bond = self.listb[i] quat = bond.bond_to_abs_coords_quat() biL_pvec = quat.unrot(biL_pvec) biR_pvec = quat.unrot(biR_pvec) return biL_pvec, biR_pvec # warning: these two vectors might be the same object def recompute_geom(self, out = DFLT_OUT, up = DFLT_UP): """ Compute and store enough geometric info for pvecs_i to run (using submethods for various special cases): self.quats_cum, self.twist, self.b0L_pvec. """ # put coords on each bond axis, then link these (gauge transform)... start with first and propogate. # warning: each bond in turn might have a different coordinate system! # (if they alternate external/internal, different chunks) # and the geom we compute for each bond should be in that bond's system, to help draw it properly. # fortunately they're only linked by rotations... so we should be able to compensate for coord changes. # This also means -- when a bond is invalidated, it might be from changing its coord sys, even if no atom motion # or structure change. This needs to invalidate it here, too, or (more simply) inval this whole thing. # or we could let the pi info be in abs coords and rotate the vecs before use? # yes, this is effectively what we ended up doing, except even the abs coords get computed each time they're asked for # from the quats stored by this routine. self.twist = None # default value self.axes = self.quats_cum = self.chain_quat_cum = None # invalid values (for catching bugs) bonds = self.listb lista = self.lista ## # first, do we want that 90-deg offset? Only if double bonds, I think. ## # (It's just a kluge to avoid returning pi orders of (1,0) for some of them and (0,1) for the others. ## # We use it so we can return pi orders of (1,0) for all double bonds.) ## # ## # Let's assume bond inference was done, so if one bond is double, they all are. ## # BUT WAIT, are all the middle atoms C(sp), not some other element?? I think so... ###@@@ check this somewhere, ## # and if another is poss, probably don't even make it form a chain like this ## self.twist90 = ( bonds[0].v6 == V_DOUBLE ) posns = A( map( lambda atom: atom.posn(), lista ) ) self.axes = axes = posns[1:] - posns[:-1] # axes along bonds, all in consistent directions & abs coords quats_incr = map( lambda (axis1, axis2): Q(axis1, axis2), zip( axes[:-1], axes[1:] ) ) # how to transform vectors perp to one bond, to those perp to the next # cumulative quats (there might be a more compact python notation for this, and/or a way to do more of it in Numeric) qq = Q(1,0,0,0) quats_cum = [qq] # how to get from bonds[0] to each bonds[i] starting from i == 0, using only bend-projections at atoms for qi, i in zip( quats_incr, range(len(quats_incr)) ): # qi tells us how to map (perps to axes[i]) to (perps to axes[i+1]) qq = qq + qi # make a new quat, don't use += ###e ideally we'd now enforce qq turning axes[0] into axes[i], to compensate for cumulative small errors [nim] if self.adjacent_double_bonds( i, i+1 ): axis = axes[i+1] theta = math.pi / 2 # 90 degrees qq += Q(axis, theta) quats_cum.append(qq) assert len(quats_cum) == len(bonds) self.quats_cum = quats_cum self.chain_quat_cum = quats_cum[-1] if self.ringQ: # for rings we need to know how to get all the way around the ring, ie from bonds[-1] to bonds[0] # (but we won't add these quats to our lists) self.ringquat_incr = Q( axes[-1], axes[0] ) if self.adjacent_double_bonds( -1, 0 ): self.ringquat_incr += Q(axes[0], math.pi / 2) ## self.ringquat_cum = self.chain_quat_cum + self.ringquat_incr #k probably not used # now we know total twist, so we can use code similar to pi_vectors function to decide what to do at the ends. # BTW all this only mattered if we weren't alternating single-triple bonds... ideally we'd rule that out first. # but no harm if we don't. # BTW2, at what point should this code do any bond-type inference? and how -- should it take most recently user-changed # bond in it, or most recently inferred end-bond, and propogate that, in some cases? btw3, remember it might be a ring. # call subclass-specific funcs to do the rest -- compute the twist and start/end p orbital vectors, used later by pvecs_i... self.out = out self.up = up self.recompute_geom_from_quats() return # from recompute_geom def adjacent_double_bonds( self, i1, i2 ): # replaces self.twist90 code, 050726 """ #doc; i1 might be -1 """ bonds = self.listb v1 = bonds[i1].v6 # ok for negative indices i1 v2 = bonds[i2].v6 #bruce 050728 kluge bugfix: treat V_SINGLE as V_DOUBLE so this gives user benefit of the doubt if they # just haven't yet bothered to put in the correct bondtypes, and so this works from depositmode growing an sp chain # when it's making new singlets on an sp2 atom it deposits at the end of the sp chain. if v1 == V_SINGLE: v1 = V_DOUBLE if v2 == V_SINGLE: v2 = V_DOUBLE # if both are double, or one is double and one is aromatic or graphite (but not carbomeric) if v1 == V_DOUBLE and v2 in (V_DOUBLE, V_AROMATIC, V_GRAPHITE): return True if v2 == V_DOUBLE and v1 in (V_AROMATIC, V_GRAPHITE): return True return False def recompute_geom_from_quats(self): # non-ring class """ [not a ring; various possible end situations] """ out = self.out up = self.up atoms = self.lista bonds = self.listb # (I wish I could rename these attrs to "atoms" and "bonds", # but self.atoms conflicts with the Jig attr, and self.chain_atoms is too long.) # default values: self.bm1R_pvec = "not needed" # and bug if used, we hope, unless we later change this value self.twist = None # Figure out p vectors for atom[0]-end (left end) of bond[0], and atom[-1]-end (right end) of bond[-1]. # If both are determined from outside this chain (i.e. if the subrs here don't return None), # or if we are a ring (so they are forced to be the same, except for the projection due to bond bending at the ring-joining atom), # then [using self.recompute_geom_both_ends_constrained()] they must be made to match (up to an arbitrary sign), # using a combination of some twist (to be computed here) along each bond, # plus a projection and (in some cases, depending on bond types i think -- see self.twist90) # 90-degree turn at each bond-bond connection; # the projection part for all the bond-bond connections is already accumulated in self.chain_quat_cum. # note: the following p-vec retvals are in abs coords, as they should be #e rename the funcs, since they are not only for sp2, but for any atom that ends our chain of pi bonds pvec1 = p_vector_from_sp2_atom(atoms[0], bonds[0], out = out, up = up) # might be None pvec2 = p_vector_from_sp2_atom(atoms[-1], bonds[-1], out = out, up = up) # ideally, close to negative or positive of pvec1 ###@@@ handle neg # handle one being None (use other one to determine the twist) or both being None (use arb vectors) if pvec1 is None: if pvec2 is None: # use arbitrary vectors on left end of bonds[0], perp to bond and to out; compute differently if bond axis ~= out axis = self.axes[0] pvec = cross(out, axis) lenpvec = vlen(pvec) if lenpvec < 0.01: # bond axis is approx parallel to out pvec = cross(up, axis) lenpvec = vlen(pvec) # won't be too small -- bond can't be parallel to both up and out pvec /= lenpvec self.b0L_pvec = pvec else: # pvec2 is defined, pvec1 is not. Need to transport pvec2 back to coords of pvec1 # so our standard code (pvec_i, which wants pvec1, i.e. self.b0L_pvec) can be used. self.b0L_pvec = self.chain_quat_cum.unrot(pvec2) else: if pvec2 is None: self.b0L_pvec = pvec1 else: # both vectors not None -- use recompute_geom_both_ends_constrained self.b0L_pvec = pvec1 self.bm1R_pvec = pvec2 self.recompute_geom_both_ends_constrained() return # from non-ring recompute_geom_from_quats def recompute_geom_both_ends_constrained(self): """ Using self.b0L_pvec and self.chain_quat_cum and self.bm1R_pvec, figure out self.twist... [used for rings, and for linear chains with both ends constrained] """ bonds = self.listb # what pvec would we have on the right end of the chain, if there were no per-bond twist? bm1R_pvec_no_twist = self.chain_quat_cum.rot( self.b0L_pvec ) # note, this is a vector perp to bond[-1] axism1 = self.axes[-1] # what twist is needed to put that vector over the actual one (or its neg), perhaps with 90-deg offset? i = len(bonds) - 1 ## if self.twist90 and i % 2 == 1: ## bm1R_pvec_no_twist = norm(cross(axism1, bm1R_pvec_no_twist)) # use negative if that fits better if dot(bm1R_pvec_no_twist, self.bm1R_pvec) < 0: bm1R_pvec_no_twist = - bm1R_pvec_no_twist # total twist is shared over every bond # note: we care which direction we rotate around axism1 total_twist = twistor_angle( axism1, bm1R_pvec_no_twist, self.bm1R_pvec) # in radians; angular range is undefined, for now # [it's actually +- 2pi, twice what it would need to be in general], # so we need to coerce it into the range we want, +- pi/2 (90 degrees); here too we use the fact # that in this case, a twist of pi (180 degrees) is the same as 0 twist. while total_twist > math.pi/2: total_twist -= math.pi while total_twist <= - math.pi/2: total_twist += math.pi self.twist = total_twist / len(bonds) return pass # end of class PiBondSpChain class RingPiBondSpChain( PiBondSpChain): """ Class for a perceived ring of =C= or -C# atoms, or other 2-bond sp atoms if there are any (not sure if there can be) """ ringQ = True # Note: I've assumed a ring means no constraints on angles... what if other bonds? but sp2 atoms count as endpoints, # so it's ok, this is just ring of sp, so it's true. def recompute_geom_from_quats(self): # ring class # get arb p-vector for use at bond[-1] right end self.bm1R_pvec = arb_perp_unit_vector(self.axes[-1]) # then project that through ring-joining-atom to a pvec for use at bond[0] left end self.b0L_pvec = self.ringquat_incr.rot(self.bm1R_pvec) # then use same code as non-ring with constrained pvecs self.recompute_geom_both_ends_constrained( ) # fyi: one of several methods to finish up; chains can use this one or others return pass # end of class RingPiBondSpChain def make_pi_bond_obj(bond): # see also find_chain_or_ring_from_bond, which generalizes this [bruce 071126] """ #doc ... make one for a pi bond, extended over sp atoms in the middle... what if sp3-sp-sp3, no pi bonds? then no need for one! """ atom1 = bond.atom1 atom2 = bond.atom2 # more atoms to the right? what we need to grow: sp atom, exactly one other bond, it's a pi bond. (and no ring formed) ringQ, listb1, lista1 = grow_pi_sp_chain(bond, atom1) if ringQ: assert atom2 is lista1[-1] return RingPiBondSpChain( [bond] + listb1 , [atom2, atom1] + lista1 ) ringQ, listb2, lista2 = grow_pi_sp_chain(bond, atom2) assert not ringQ listb1.reverse() lista1.reverse() return PiBondSpChain( listb1 + [bond] + listb2, lista1 + [atom1, atom2] + lista2 ) # one more atom than bond def sp_atom_2bonds(atom): """ """ ## warning: this being true is *not* enough to know that a pi bond containing atom has an sp-chain length > 1. return atom.atomtype.is_linear() and len(atom.bonds) == 2 and atom.atomtype.numbonds == 2 def next_bond_in_sp_chain(bond, atom): """ Given a pi bond and one of its atoms, try to grow the chain beyond that atom... return next bond, or None. @note: This function not returning None (for either atom on the end of a potential pi bond) is the definitive condition for that bond not being the only one in its sp-chain. """ assert bond.potential_pi_bond() if not sp_atom_2bonds(atom): return None #k retval bonds = atom.bonds # len(bonds) == 2, known from subr conds above if bond is bonds[0]: obond = bonds[1] else: assert bond is bonds[1] obond = bonds[0] if obond.potential_pi_bond(): return obond return None def pi_bond_alone_in_its_sp_chain_Q(bond): return next_bond_in_sp_chain(bond, bond.atom1) is None and next_bond_in_sp_chain(bond, bond.atom2) is None def grow_pi_sp_chain(bond, atom): # WARNING: superceded by grow_pi_sp_chain_NEWER_BETTER, except that one is untested. see its comment. """ Given a potential pi bond and one of its atoms, grow the pi-sp-chain containing bond in the direction of atom, adding newly found bonds and atoms to respective lists (listb, lista) which we'll return, until you can't or until you notice that it came back to bond and formed a ring (in which case return as much as possible, but not another ref to bond or atom). Return value is the tuple (ringQ, listb, lista) where ringQ says whether a ring was detected and len(listb) == len(lista) == number of new (bond, atom) pairs found. """ listb, lista = [], [] origbond = bond # for detecting a ring while 1: nextbond = next_bond_in_sp_chain(bond, atom) # this is the main difference from grow_bond_chain if nextbond is None: return False, listb, lista if nextbond is origbond: return True, listb, lista nextatom = nextbond.other(atom) listb.append(nextbond) lista.append(nextatom) bond, atom = nextbond, nextatom pass def grow_pi_sp_chain_NEWER_BETTER(bond, atom): #bruce 070415 -- newer & better implem of grow_pi_sp_chain (equiv, # but uses general helper func), but untested. Switch to this one when there's time to test it. return grow_bond_chain(bond, atom, next_bond_in_sp_chain) # == def pi_vectors(bond, out = DFLT_OUT, up = DFLT_UP, abs_coords = False): # rename -- pi_info for pi bond in degen sp chain # see also PiBondSpChain.get_pi_info """ Given a bond involving some pi orbitals, return the 4-tuple ((a1py, a1pz), (a2py, a2pz), ord_pi_y, ord_pi_z), where a1py and a1pz are orthogonal vectors from atom1 giving the direction of its p orbitals for use in drawing this bond (for twisted bonds, the details of these might be determined more by graphic design issues than by the shapes of the real pi orbitals of the bond, though the goal is to approximate those); where a2py and a2pz are the same for atom2 (note that a2py might not be parallel to a1py for twisted bonds); and where ord_pi_y and ord_pi_z are order estimates (between 0.0 and 1.0 inclusive) for use in drawing the bond, for the pi_y and pi_z orbitals respectively. Note that the choice of how to name the two pi orbitals (pi_y, pi_z) is arbitrary and up to this function. All returned vectors are in the coordinate system of bond, unless abs_coords is true. This should not be called for pi bonds which are part of an "sp chain", but it should be equivalent to the code that would be used for a 1-bond sp-chain (i.e. it's an optimization of that code, PiBondSpChain.get_pi_info, for that case). """ atom1 = bond.atom1 atom2 = bond.atom2 bond_axis = atom2.posn() - atom1.posn() #k not always needed i think # following subrs should be renamed, since we routinely call them for sp atoms, # e.g. in -C#C- where outer bonds are not potential pi bonds pvec1 = p_vector_from_sp2_atom(atom1, bond, out = out, up = up) # might be None pvec2 = p_vector_from_sp2_atom(atom2, bond, out = out, up = up) # ideally, close to negative or positive of pvec1 # handle one being None (use other one in place of it) or both being None (use arb vectors) if pvec1 is None: if pvec2 is None: # use arbitrary vectors perp to the bond; compute differently if bond_axis ~= out [###@@@ make this a subr? dup code?] pvec = cross(out, bond_axis) lenpvec = vlen(pvec) if lenpvec < 0.01: pvec = up else: pvec /= lenpvec pvec1 = pvec2 = pvec else: pvec1 = pvec2 else: if pvec2 is None: pvec2 = pvec1 else: # both vectors not None -- use them, but negate pvec2 if this makes them more aligned if dot(pvec1, pvec2) < 0: pvec2 = - pvec2 return pi_info_from_abs_pvecs( bond, bond_axis, pvec1, pvec2, abs_coords = abs_coords) def pi_info_from_abs_pvecs( bond, bond_axis, pvec1, pvec2, abs_coords = False): """ #doc; bond_axis (passed only as an optim) and pvecs are in abs coords; retval is in bond coords unless abs_coords is true """ a1py = pvec1 a2py = pvec2 a1pz = norm(cross(bond_axis, pvec1)) a2pz = norm(cross(bond_axis, pvec2)) ord_pi_y, ord_pi_z = pi_orders(bond) if not abs_coords: # put into bond coords (which might be the same as abs coords) quat = bond.bond_to_abs_coords_quat() a1py = quat.unrot(a1py) a2py = quat.unrot(a2py) a1pz = quat.unrot(a1pz) a2pz = quat.unrot(a2pz) return ((a1py, a1pz), (a2py, a2pz), ord_pi_y, ord_pi_z) def pi_orders(bond): try: ord_pi_y, ord_pi_z = pi_order_table[bond.v6] except: if debug_flags.atom_debug: print "atom_debug: bug: pi_order_table[bond.v6] for unknown v6 %r in %r" % (bond.v6, bond) ord_pi_y, ord_pi_z = 0.5, 0.5 # this combo is not otherwise possible return ord_pi_y, ord_pi_z pi_order_table = { V_SINGLE: (0, 0), V_DOUBLE: (1, 0), # choice of 1,0 rather than 0,1 is just a convention, but we always use it even for =C=C=C= chains V_TRIPLE: (1, 1), V_AROMATIC: (0.5, 0), V_GRAPHITE: (0.33, 0), V_CARBOMERIC: (0.5, 1), # I think the 0.5 should actually be 1-x for adjacent bonds of order x, so it's wrong for graphite ###e } # == def p_vector_from_sp2_atom(atom, bond, out = DFLT_OUT, up = DFLT_UP): """ Given an sp2 atom and a possibly-pi bond to it, return its p orbital vector for use in thinking about that pi bond, or None if this atom (considering its other bonds) doesn't constrain that direction. """ if not atom.atomtype.is_planar(): return None # helps make initial stub code simpler nbonds = len(atom.bonds) if nbonds == 3: # we can determine atom's p vector (there is only one) from those bonds # (no need to check atomtype -- it can't be sp, and if it was sp3 we should not have been called; # and in case of errors or bugs, maybe the type is not sp2 as we hope, but this code will still "work".) return p_vector_from_3_bonds(atom, bond, out = out, up = up) elif nbonds == 2: return p_vector_from_sp2_2_bonds(atom, bond, out = out, up = up) ### revise to return None if it doesn't know? elif nbonds == 1: # might be O(sp2); if not for knowing it was sp2, might be open bond or N(sp)... but it won't tell us orientation return None else: assert bond in atom.bonds assert len(atom.bonds) <= 3 # will always fail pass def p_vector_from_3_bonds(atom, bond, out = DFLT_OUT, up = DFLT_UP): """ Given an sp2 atom with 3 bonds, and one of those bonds which we assume has pi orbitals in it, return a unit vector from atom along its p orbital, guaranteed perpendicular to bond, for purposes of drawing the pi orbital component of bond. Note that it's arbitrary whether we return a given vector or its opposite. [##e should we fix that, using out and up? I don't think we can in a continuous way, so don't bother.] We don't verify the atom is sp2, since we don't need to for this code to work, though our result would probably not make sense otherwise. """ others = map( lambda bond: bond.other(atom), atom.bonds) assert len(others) == 3 other1 = bond.other(atom) others.remove(other1) other2, other3 = others apos = atom.posn() v1 = other1.posn() - apos # if v1 has 0 length, we should return some default value here; this might sometimes happen so I better handle it. # actually i'm not sure the remaining code would fail in this case! If not, I might revise this. if vlen(v1) < 0.01: # in angstroms return + up v2 = other2.posn() - apos v3 = other3.posn() - apos # projecting along v1, we hope v2 and v3 are opposite, and then we return something perpendicular to them. # if one is zero, just be perp. to the other one alone. # (If both zero? Present code returns near-0. Should never happen, but fix. #e) # otherwise if they are not opposite, use perps to each one, "averaged", # which means (for normalized vectors), normalize the larger of the sum or difference # (equivalent to clustering them in the way (of choice of sign for each) that spans the smallest angle). # Optim: no need to project them before taking cross products to get the perps to use. ## v2 -= v1 * dot(v2,v1) ## v3 -= v1 * dot(v3,v1) v2p = cross(v2,v1) v3p = cross(v3,v1) lenv2p = vlen(v2p) if lenv2p < 0.01: return norm(v3p) v2p /= lenv2p lenv3p = vlen(v3p) if lenv3p < 0.01: return v2p # normalized above v3p /= lenv3p r1 = v2p + v3p r2 = v2p - v3p lenr1 = vlen(r1) lenr2 = vlen(r2) if lenr1 > lenr2: return r1/lenr1 else: return r2/lenr2 pass def p_vector_from_sp2_2_bonds(atom, bond, out = DFLT_OUT, up = DFLT_UP): others = map( lambda bond: bond.other(atom), atom.bonds) assert len(others) == 2 other1 = bond.other(atom) others.remove(other1) other2, = others apos = atom.posn() v1 = other1.posn() - apos if vlen(v1) < 0.01: # in angstroms return + up v2 = other2.posn() - apos v2p = cross(v2,v1) lenv2p = vlen(v2p) if lenv2p < 0.01: # this entire case happens rarely or hopefully never (only when 2 sp2 bonds are parallel) res = up - v1 * dot(up,v1) if vlen(res) >= 0.01: return norm(res) res = out - v1 * dot(out,v1) return norm(out) return v2p / lenv2p # == # pure geometry routines, should be refiled: def arb_non_parallel_vector(vec): """ Given a nonzero vector, return an arbitrary vector not close to being parallel to it. """ x,y,z = vec if abs(z) < abs(x) > abs(y): # x is biggest, use y return V(0,1,0) else: return V(1,0,0) pass def arb_perp_unit_vector(vec): """ Given a nonzero vector, return an arbitrary unit vector perpendicular to it. """ vec2 = arb_non_parallel_vector(vec) return norm(cross(vec, vec2)) def arb_ortho_pair(vec): #k not presently used # see also some related code in pi_vectors() """ Given a nonzero vector, return an arbitrary pair of unit vectors perpendicular to it and to each other. """ res1 = arb_perp_unit_vector(vec) res2 = norm(cross(vec, res1)) return res1, res2 # end
NanoCAD-master
cad/src/model/pi_bond_sp_chain.py
# Copyright 2004-2009 Nanorex, Inc. See LICENSE file for details. """ PovrayScene.py - The POV-Ray Scene class. @author: Mark @version: $Id$ @copyright: 2004-2009 Nanorex, Inc. See LICENSE file for details. History: mark 060601 - Created. """ import os from PyQt4.Qt import QDialog from PyQt4.Qt import QPixmap from PyQt4.Qt import QLabel from PyQt4.Qt import QRect from PyQt4.Qt import QSize from PyQt4.Qt import QApplication import foundation.env as env from foundation.Utility import SimpleCopyMixin, Node from utilities.icon_utilities import imagename_to_pixmap from graphics.rendering.povray.povray import decode_povray_prefs, write_povray_ini_file, launch_povray_or_megapov from graphics.rendering.povray.writepovfile import writepovfile from utilities.Log import redmsg, orangemsg, greenmsg, _graymsg from utilities import debug_flags from platform_dependent.PlatformDependent import find_or_make_Nanorex_subdir from utilities.debug import print_compact_traceback import re from files.mmp.files_mmp_registration import MMP_RecordParser from files.mmp.files_mmp_registration import register_MMP_RecordParser POVNum = 0 def generate_povrayscene_name(assy, prefix, ext): """ Returns a name for the POV-Ray Scene object. Make sure the filename that is derived from the new name does not already exist. """ global POVNum name = '' name_exists = True while name_exists: POVNum += 1 name = prefix + "-" + str(POVNum) + ext # (i.e. "POV-Ray Scene-1.pov") # TODO: use gensym, then no need for POVNum if not os.path.exists(get_povrayscene_filename_derived_from_name(assy, name)): name_exists = False return name def get_povrayscene_filename_derived_from_name(assy, name): """ Returns the full (absolute) path of the POV-Ray Scene filename for <assy> derived from <name>. """ errorcode, dir = assy.find_or_make_pov_files_directory() if errorcode: return "filename_does_not_exist" povrayscene_file = os.path.normpath(os.path.join(dir, name)) #print "get_povrayscene_filename_derived_from_name(): povrayscene_file=", povrayscene_file return povrayscene_file # == class PovrayScene(SimpleCopyMixin, Node): """ A POV-Ray Scene is a .pov file that can be used to render images, accessible from the Model Tree as a node. """ sym = "POV-Ray Scene" extension = ".pov" povrayscene_file = '' width = height = output_type = None #bruce 060620, might not be needed copyable_attrs = Node.copyable_attrs + ('width', 'height', 'output_type', 'povrayscene_file') def __init__(self, assy, name, params = None): #bruce 060620 removed name from params list, made that optional, made name a separate argument, # all to make this __init__ method compatible with that of other nodes (see above for one reason); # also revised this routine in other ways, e.g. to avoid redundant sets of self.assy and self.name # (which are set by Node.__init__). if not name: # [Note: this code might be superceded by code in Node.__init__ once nodename suffix numbers are revised.] # If this code is superceded, Node.__init__ must provide a way to verify that the filename (derived from the name) # doesn't exist, since this would be an invalid name. Mark 060702. name = generate_povrayscene_name(assy, self.sym, self.extension) self.const_pixmap = imagename_to_pixmap("modeltree/povrayscene.png") # note: this might be changed later; this value is not always correct; that may be a bug when this node is copied. # [bruce 060620 comment] Node.__init__(self, assy, name) if params: self.set_parameters(params) else: def_params = (assy.o.width, assy.o.height, 'png') self.set_parameters(def_params) return def set_parameters(self, params): #bruce 060620 removed name from params list """ Sets all parameters in the list <params> for this POV-Ray Scene. """ self.width, self.height, self.output_type = params self.povrayscene_file = get_povrayscene_filename_derived_from_name(self.assy, self.name) # Mark 060702. self.assy.changed() def get_parameters(self): #bruce 060620 removed name from params list """ Returns list of parameters for this POV-Ray Scene. """ return (self.width, self.height, self.output_type) def edit(self): """ Opens POV-Ray Scene properties dialog with current parameters. """ self.assy.w.povrayscenecntl.setup(self) def writemmp(self, mapping): mapping.write("povrayscene (" + mapping.encode_name(self.name) + ") %d %d %s\n" % \ (self.width, self.height, self.output_type)) # Write relative path of POV-Ray Scene file into info record. # For Alpha 8, the name and the basename are usually the same. # The only way I'm aware of that the name and the basename would be # different is if the user renamed the node in the Model Tree. # [Or they might move the file in the OS, and edit the node's mmp record, # in ways which ought to be legal according to the documentation. bruce 060707 comment] mapping.write("info povrayscene povrayscene_file = POV-Ray Scene Files/%s\n" % self.name) # Relative path. # Note: Users will assume when they rename an existing MMP file, all the POV-Ray Scene files will still be associated # with the MMP file. This is handled by separate code in Save As which copies those files, or warns when it can't. self.writemmp_info_leaf(mapping) return def readmmp_info_povrayscene_setitem( self, key, val, interp ): """ This is called when reading an mmp file, for each "info povrayscene" record which occurs right after this node is read and no other (povrayscene) node has been read. Key is a list of words, val a string; the entire record format is presently [060108] "info povrayscene <key> = <val>", and there is exactly one word in <key>, "povrayscene_file". <val> is the povrayscene filename. <interp> is not currently used. """ if len(key) != 1: if debug_flags.atom_debug: print "atom_debug: fyi: info povrayscene with unrecognized key %r (not an error)" % (key,) return if key[0] == 'povrayscene_file': if val: if val[0] == '/' or val[0] == '\\': # val is an absolute path. self.povrayscene_file = val else: # val is a relative path. Build the absolute path. errorcode, dir = self.assy.find_or_make_part_files_directory() self.povrayscene_file = os.path.normpath(os.path.join(dir, val)) self.update_icon( print_missing_file = True) pass return def update_icon(self, print_missing_file = False, found = None): """ Update our icon according to whether our file exists or not (or use the boolean passed as found, if one is passed). (Exception: icon looks normal if filename is not set yet. Otherwise it looks normal if file is there, not normal if file is missing.) If print_missing_file is true, print an error message if the filename is non-null but the file doesn't exist. Return "not found" in case callers want to print their own error messages (for example, if they use a different filename). """ #bruce 060620 split this out of readmmp_info_povrayscene_setitem for later use in copy_fixup_at_end (not yet done ###@@@). # But its dual function is a mess (some callers use their own filename) so it needs more cleanup. #e filename = self.povrayscene_file if found is None: found = not filename or os.path.exists(filename) # otherwise found should have been passed as True or False if found: self.const_pixmap = imagename_to_pixmap("modeltree/povrayscene.png") else: self.const_pixmap = imagename_to_pixmap("modeltree/povrayscene-notfound.png") if print_missing_file: msg = redmsg("POV-Ray Scene file [" + filename + "] does not exist.") #e some callers would prefer orangemsg, cmd, etc. env.history.message(msg) return not found def __str__(self): return "<povrayscene " + self.name + ">" def write_povrayscene_file(self): """ Writes a POV-Ray Scene file of the current scene in the GLPane to the POV-Ray Scene Files directory. If successful, returns errorcode=0 and the absolute path of povrayscene file. Otherwise, returns errorcode=1 with text describing the problem writing the file. """ ini, pov, out = self.get_povfile_trio() # pov includes the POV-Ray Scene Files directory in its path. if not ini: return 1, "Can't get POV-Ray Scene filename" #print "write_povrayscene_file(): povrayscene_file=", pov writepovfile(self.assy.part, self.assy.o, pov) return 0, pov def get_povfile_trio(self, tmpfile = False): """ Makes up and returns the trio of POV-Ray filenames (as absolute paths): POV-Ray INI file, POV-Ray Scene file, and output image filename. If there was any problem, returns None, None, None. <tmpfile> flag controls how we choose their directory. [WARNING: current code may call it more than once during the same operation, so it needs to be sure to return the same names each time! [bruce guess 060711]] """ # The ini, pov and out files must be in the same directory due to POV-Ray's I/O Restriction feature. Mark 060625. ini_filename = "povray.ini" # Critically important: POV-Ray uses the INI filename as an argument; it cannot have any whitespaces. # This is a POV-Ray bug on Windows only. For more information about this problem, see: # http://news.povray.org/povray.windows/thread/%3C3e28a17f%40news.povray.org%3E/?ttop=227783&toff=150 # Mark 060624. if tmpfile: pov_filename = "raytracescene.pov" dir = find_or_make_Nanorex_subdir("POV-Ray") if not dir: return None, None, None else: pov_filename = self.name errorcode, dir = self.assy.find_or_make_pov_files_directory() if errorcode: return None, None, None ###e ought to return something containing dir (errortext) instead # Build image output filename <out_filename>. # WARNING and BUG: this code is roughly duplicated in povray.py, and they need to match; # and .bmp is probably not properly supported for Mac in povray.py. [bruce 060711 comment] if self.output_type == 'bmp': output_ext = '.bmp' else: # default output_ext = '.png' base, ext = os.path.splitext(pov_filename) out_filename = base + output_ext ini = os.path.normpath(os.path.join(dir, ini_filename)) pov = os.path.normpath(os.path.join(dir, pov_filename)) out = os.path.normpath(os.path.join(dir, out_filename)) #print "get_povfile_trio():\n ini=", ini, "\n pov=", pov, "\n out=", out return ini, pov, out def raytrace_scene(self, tmpscene = False): """ Render scene. If tmpscene is False, the INI and pov files are written to the 'POV-Ray Scene Files' directory. If tmpscene is True, the INI and pov files are written to a temporary directory (~/Nanorex/POV-Ray). Callers should set <tmpscene> = True when they want to render the scene but don't need to save the files and create a POV-Ray Scene node in the MT (i.e. 'View > POV-Ray'). The caller is responsible for adding the POV-Ray Scene node (self) to the model tree, if desired. Prints any necessary error messages to history; returns nothing. """ #bruce 060710 corrected inaccuracies in docstring cmd = greenmsg("POV-Ray: ") if env.debug(): #bruce 060707 (after Windows A8, before Linux/Mac A8) # compromise with what's best, so it can be ok for A8 even if only on some platforms env.history.message(_graymsg("POV-Ray: ")) env.history.h_update() env.history.widget.update() ###@@@ will this help? is it safe? should h_update do it? ini, pov, out = self.get_povfile_trio(tmpscene) if not ini: ## return 1, "Problem getting POV-Ray filename trio." # [bruce 060710 replaced the above with the following, since it no longer matches the other return statements, or any calls] env.history.message(cmd + redmsg("Problem getting POV-Ray filename trio.")) ###e should fix this to improve the message, by including errortext from get_povfile_trio retval (which is nim) return if tmpscene or not os.path.isfile(self.povrayscene_file): # write a new .pov file and save its name in self # #bruce 060711 comment (about a bug, not yet reported): ###@@@ # If an existing pov file has unexpectedly gone missing, # this code (I think) rerenders the current model, without even informing the user of the apparent error. # That is extremely bad behavior, IMHO. What it ought to do is put up a dialog to inform the # user that the file is missing, and allow one of three actions: cancel, rerender current model, # or browse for the file to try to find it. If that browse is cancelled, it should offer the other # options, or if that finds the file but it's external, it should offer to copy it or make an # external link (or cancel), and then to continue or do no more. All this is desirable for any kind # of file node, not just PovrayScene. As it is, this won't be fixed for Mac A8; don't know about 8.1. self.povrayscene_file = pov writepovfile(self.assy.part, self.assy.o, self.povrayscene_file) # bruce 060711 question (possible bug): what sets self.width, self.height, self.output_type in this case, # if the ones used by writepovfile differ from last time they were set in this node? # Guess: nothing does (bug, not yet reported). ###@@@ # figure out renderer to use (POV-Ray or MegaPOV), its path, and its include_dir # (note: this contains most of the error checks that used to be inside launch_povray_or_megapov) # [bruce 060711 for Mac A8] win = self.assy.w ask_for_help = True # give user the chance to fix problems in the prefs dialog errorcode, errortext_or_info = decode_povray_prefs(win, ask_for_help, greencmd = cmd) if errorcode: errortext = errortext_or_info env.history.message(cmd + redmsg(errortext)) # redmsg in Mac A8, orangemsg in Windows A8 [bruce 060711] return info = errortext_or_info (program_nickname, program_path, include_dir) = info pov = self.povrayscene_file ###k btw, is this already true? #k is out equal to whatever in self might store it, if anything? maybe it's not stored in self. write_povray_ini_file(ini, pov, out, info, self.width, self.height, self.output_type) if tmpscene: msg = "Rendering scene. Please wait..." else: msg = "Rendering raytrace image from POV-Ray Scene file. Please wait..." env.history.message(cmd + msg) env.history.h_update() #bruce 060707 (after Windows A8, before Linux/Mac A8): try to make this message visible sooner # (doesn't work well enough, at least on Mac -- do we need to emit it before write_povray_ini_file?) env.history.widget.update() ###@@@ will this help? is it safe? should h_update do it? ###e these history widget updates fail to get it to print. Guess: we'd need qapp process events. Fix after Mac A8. # besides, we need this just before the launch call, not here. if os.path.exists(out): #bruce 060711 in Mac A8 not Windows A8 (probably all of Mac A8 code will also be in Linux A8) #e should perhaps first try moving the file to a constant name, so user could recover it manually if they wanted to #e (better yet, we should also try to avoid this situation when choosing the filename) msg = "Warning: image file already exists; removing it first [%s]" % out env.history.message(cmd + orangemsg(msg)) try: os.remove(out) except: # this code was tested with a fake exception [060712 1041am] msg1 = "Problem removing old image file" msg2a = " [%s]" % out msg2b = "-- will try to overwrite it, "\ "but undetected rendering errors might leave it unchanged [%s]" % out print_compact_traceback("%s: " % (msg1 + msg2a)) msg = redmsg(msg1) + msg2b #e should report the exception text in the history, too env.history.message(msg) pass # Launch raytrace program (POV-Ray or MegaPOV) errorcode, errortext = launch_povray_or_megapov(win, info, ini) if errorcode: env.history.message(cmd + redmsg(errortext)) # redmsg in Mac A8, orangemsg in Windows A8 [bruce 060711] return #bruce 060707 (after Windows A8, before Linux/Mac A8): make sure the image file exists. # (On Mac, on that date [not anymore, 060710], we get this far (no error return, or maybe another bug hid one), # but the file is not there.) if not os.path.exists(out): msg = "Error: %s program finished, but failed to produce expected image file [%s]" % (program_nickname, out) env.history.message(cmd + redmsg(msg)) return env.history.message(cmd + "Rendered image: " + out) # Display image in a window. imageviewer = ImageViewer(out, win) #bruce 060707 comment: if the file named <out> doesn't exist, on Mac, # this produces a visible and draggable tiny window, about 3 pixels wide and maybe 30 pixels high. imageviewer.display() return # from raytrace_scene out def kill(self, require_confirmation = True): """ Delete the POV-Ray Scene node and its associated .pov file if it exists. If <require_confirmation> is True, make the user confirm first [for deleting the file and the node both, as one op]. [WARNING: user confirmation is not yet implemented.] Otherwise, delete the file without user confirmation. """ if os.path.isfile(self.povrayscene_file): if 0: # Don't require confirmation for A8. Mark 060701. [but see comment below about why this is a bad bug] # if require_confirmation: msg = "Please confirm that you want to delete " + self.name from widgets.widget_helpers import PleaseConfirmMsgBox confirmed = PleaseConfirmMsgBox( msg) if not confirmed: return # warn the user that you are about to remove what might be an irreplaceable rendering of a prior version # of the main file, without asking, or even checking if other nodes in this assy still point to it # [this warning added by bruce 060711 for Mac A8, not present in Windows A8] env.history.message(orangemsg("Warning: deleting file [%s]" % self.povrayscene_file)) # do it os.remove(self.povrayscene_file) #bruce 060711 comment -- the above policy is a dangerous bug, since you can copy a node (not changing the filename) # and then delete one of the copies. This should not silently delete the file! # (Besides, even if you decide not to delete the file, .kill() should still delete the node.) # This behavior is so dangerous that I'm tempted to fix it for Mac A8 even though it's too late # to fix it for Windows A8. Certainly it ought to be reported and releasenoted. But I think I will refrain # from the temptation to fix it for Mac A8, since doing it well is not entirely trivial, and any big bug-difference # in A8 on different platforms might cause confusion. But at least I will add a history message, so the user knows # right away if it caused a problem. And it needs to be fixed decently well for A8.1. ###@@@ # As for a better behavior, it would be good (and not too hard) to find out if other nodes # in the same assy point to the same file, and not even ask (just don't delete the file) if they do. # If not, ask, but always delete the node itself. # But this is not trivial, since during a recursive kill of a Group, I'm not sure we can legally scan the tree. # (And if we did, it would then be quadratic time to delete a very large series of POV-Ray nodes.) # So we need a dictionary from filenames to lists or dicts of nodes that might refer to that filename. # Of course there should also (for any filenode) be CM commands to delete or rename the file, # or (if other nodes also point to it) to copy it so this node owns a unique one. Node.kill(self) # == Context menu item methods def __CM_Raytrace_Scene(self): """ Method for "Raytrace Scene" context menu. """ self.raytrace_scene() pass # end of class PovrayScene # == # ImageViewer class for displaying the image after it is rendered. Mark 060701. class ImageViewer(QDialog): """ ImageViewer displays the POV-Ray image <image_filename> after it has been rendered. """ def __init__(self,image_filename,parent = None,name = None,modal = 0,fl = 0): #QDialog.__init__(self,parent,name,modal,fl) QDialog.__init__(self,parent) self.image = QPixmap(image_filename) width = self.image.width() height = self.image.height() caption = image_filename + " (" + str(width) + " x " + str(height) + ")" self.setWindowTitle(caption) if name is None: name = "ImageViewer" self.setObjectName(name) self.pixmapLabel = QLabel(self) self.pixmapLabel.setGeometry(QRect(0, 0, width, height)) self.pixmapLabel.setPixmap(self.image) self.pixmapLabel.setScaledContents(1) self.resize(QSize(width, height).expandedTo(self.minimumSizeHint())) def display(self): """ Display the image in the ImageViewer, making sure it isn't larger than the desktop size. """ if QApplication.desktop().width() > self.image.width() + 10 and \ QApplication.desktop().height() > self.image.height() + 30: self.show() else: self.showMaximized() # No scrollbars provided with showMaximized. The image is clipped if it is larger than the screen. # Probably need to use a QScrollView for large images. Mark 060701. return pass # == # POV-Ray Scene record format: pvs_pat = re.compile("povrayscene \((.+)\) (\d+) (\d+) (.+)") class _MMP_RecordParser_for_PovrayScene( MMP_RecordParser): #bruce 071024 """ Read the MMP record for a POV-Ray Scene as: povrayscene (name) width height output_type """ def read_record(self, card): m = pvs_pat.match(card) name = m.group(1) name = self.decode_name(name) width = int(m.group(2)) height = int(m.group(3)) output_type = m.group(4) params = width, height, output_type pvs = PovrayScene(self.assy, name, params) self.addmember(pvs) # for interpreting "info povrayscene" records: self.set_info_object('povrayscene', pvs) return pass def register_MMP_RecordParser_for_PovrayScene(): """ [call this during init, before reading any mmp files] """ register_MMP_RecordParser( 'povrayscene', _MMP_RecordParser_for_PovrayScene ) return # end
NanoCAD-master
cad/src/model/PovrayScene.py
# Copyright 2004-2007 Nanorex, Inc. See LICENSE file for details. """ elements_data.py -- data for periodic table of elements (for chemical elements and Singlet -- see other files for PAM pseudoatoms) @author: Josh @version: $Id$ @copyright: 2004-2007 Nanorex, Inc. See LICENSE file for details. History: Initially by Josh as part of chem.py. Bruce 041221 split elements.py out of chem.py, and (around then) added support for alternate color/radius tables. Bruce 050510 made some changes for "atomtypes" with their own bonding patterns. Bruce 071101 split elements_data.py out of elements.py. Bruce 071105 revised init code, and split PAM3 and PAM5 data into separate files. """ from geometry.VQT import V, A, norm from utilities.constants import DIAMOND_BOND_LENGTH _DIRECTIONAL_BOND_ELEMENTS_chemical = ('X',) # mark 071014 # == # the formations of bonds -- standard offsets # (note: these are public symbols that can also be used in # element data files for pseudoatoms) uvec = norm(V(1,1,1)) tetra4 = uvec * A([[1,1,1], [-1,1,-1], [-1,-1,1], [1,-1,-1]]) tetra3 = uvec * A([[-1,1,-1], [-1,-1,1], [1,-1,-1]]) oxy2 = A([[-1,0,0], [0.2588, -0.9659, 0]]) tetra2 = A([[-1,0,0], [0.342, -0.9396, 0]]) straight = A([[-1,0,0], [1,0,0]]) flat = A([[-0.5,0.866,0], [-0.5,-0.866,0], [1,0,0]]) onebond = A([[1,0,0]]) # for use with valence-1 elements # mark 060129. New default colors for Alpha 7. _defaultRadiusAndColor = { "X": (1.1, [0.8, 0.0, 0.0]), "H" : (1.2, [0.78, 0.78, 0.78]), "He" : (1.4, [0.42, 0.45, 0.55]), "Li" : (4.0, [0.0, 0.5, 0.5]), "Be" : (3.0, [0.98, 0.67, 1.0]), "B" : (2.0, [0.2, 0.2, 0.59]), "C" : (1.84, [0.39, 0.39, 0.39]), "N" : (1.55, [0.12, 0.12, 0.39]), "O" : (1.74, [0.5, 0.0, 0.0]), "F" : (1.65, [0.0, 0.39, 0.2]), "Ne" : (1.82, [0.42, 0.45, 0.55]), "Na" : (4.0, [0.0, 0.4, 0.4]), "Mg" : (3.0, [0.88, 0.6, 0.9]), "Al" : (2.5, [0.5, 0.5, 1.0]), "Si" : (2.25, [0.16, 0.16, 0.16]), "P" : (2.11, [0.33, 0.08, 0.5]), "S" : (2.11, [0.86, 0.59, 0.0]), "Cl" : (2.03, [0.29, 0.39, 0.0]), "Ar" : (1.88, [0.42, 0.45, 0.55]), "K" : (5.0, [0.0, 0.3, 0.3]), "Ca" : (4.0, [0.79, 0.55, 0.8]), "Sc" : (3.7, [0.417, 0.417, 0.511]), "Ti" : (3.5, [0.417, 0.417, 0.511]), "V" : (3.3, [0.417, 0.417, 0.511]), "Cr" : (3.1, [0.417, 0.417, 0.511]), "Mn" : (3.0, [0.417, 0.417, 0.511]), "Fe" : (3.0, [0.417, 0.417, 0.511]), "Co" : (3.0, [0.417, 0.417, 0.511]), "Ni" : (3.0, [0.417, 0.417, 0.511]), "Cu" : (3.0, [0.417, 0.417, 0.511]), "Zn" : (2.9, [0.417, 0.417, 0.511]), "Ga" : (2.7, [0.6, 0.6, 0.8]), "Ge" : (2.5, [0.4, 0.45, 0.1]), "As" : (2.2, [0.6, 0.26, 0.7]), "Se" : (2.1, [0.78, 0.31, 0.0]), "Br" : (2.0, [0.0, 0.4, 0.3]), "Kr" : (1.9, [0.42, 0.45, 0.55]), "Sb" : (2.2, [0.6, 0.26, 0.7]), "Te" : (2.1, [0.9, 0.35, 0.0]), "I" : (2.0, [0.0, 0.5, 0.0]), "Xe" : (1.9, [0.4, 0.45, 0.55]), } _alternateRadiusAndColor = { "Al" : (2.050,), "As" : (2.050,), "B" : (1.461,), "Be" : (1.930,), "Br" : ( 1.832,), "C" : (1.431, [0.4588, 0.4588, 0.4588]), "Ca" : ( 1.274, ), "Cl" : ( 1.688,), "Co" : ( 1.970, ), "Cr" : ( 2.150,), "Cu" : ( 1.870,), "F" : ( 1.293,), "Fe" : ( 2.020,), "Ga" : ( 2.300,), "Ge" : (1.980,), "H" : (1.135, [1.0, 1.0, 1.0]), "I" : ( 1.967,), "K" : ( 1.592,), "Li" : ( 0.971,), "Mg" : ( 1.154,), "Mn" : (1.274,), "N" : ( 1.392,), "Na" : (1.287,), "Ni" : ( 1.920,), "O" : (1.322,), "P" : ( 1.784,), "S" : (1.741,), "Sb" : ( 2.200,), "Se" : ( 1.881,), "Si" : ( 1.825, [0.4353, 0.3647, 0.5216]), "Ti" : ( 2.300,) } # Format of _mendeleev: # Symbol, Element Name, NumberOfProtons, atomic mass in 10-27 kg, # then a list of atomtypes, each of which is described by # [ open bonds, covalent radius (pm), atomic geometry, hybridization ] # (bruce adds: not sure about cov rad units; table values are 100 times this comment's values) # covalent radii from Gamess FF [= means double bond, + means triple bond] # Biassed to make bonds involving carbon come out right ## Cl - 1.02 ## H -- 0.31 ## F -- 0.7 ## C -- 0.77 [compare to DIAMOND_BOND_LENGTH (1.544) in constants.py [bruce 051102 comment]] #### 1.544 is a bond length, double the covalent radius, so pretty consistent - wware 060518 ## B -- 0.8 ## S -- 1.07 ## P -- 1.08 ## Si - 1.11 ## O -- 0.69 ## N -- 0.73 ## C= - 0.66 ## O= - 0.6 ## N= - 0.61 ## C+ - 0.6 ## N+ - 0.56 # numbers changed below to match -- Josh 13Oct05 # [but this is problematic; see the following string-comment -- bruce 051014] """ [bruce 051014 revised the comments above, and adds:] Note that the covalent radii below are mainly used for two things: drawing bond stretch indicators, and depositing atoms. There is a basic logic bug for both uses: covalent radii ought to depend on bond type, but the table below is in terms of atom type, and the atomtype only tells you which combinations of bond types would be correct on an atom, not which bond is which. (And at the time an atom is deposited, which bond is which is often not known, especially by the current code which always makes single bonds.) This means that no value in the table below is really correct (except for atomtypes which imply all bonds should have the same type, i.e. for each element's first atomtype), and even if we just want to pick the best compromise value, it's not clear how best to do that. For example, a good choice for C(sp2) covalent radius (given that it's required to be the same for all bonds) might be one that would position the C between its neighbors (and position the neighbors themselves, if they are subsequently deposited) so that when its bond types are later changed to one of the legal combos (112, 1aa, or ggg), and assuming its position is then adjusted, that the neighbor atom positions need the least adjustment. This might be something like an average of the bond lengths... so it's good that 71 (in the table below) is between the single and double bond values of 77 and 66 (listed as 0.77 and 0.66 in the comment above), though I'm not aware of any specific formula having been used to get 71. Perhaps we should adjust this value to match graphite (or buckytubes if those are different), but this has probably not been done. The hardest case to accomodate is the triple bond radius (C+ in the table above), since this exists on C(sp) when one bond is single and one is triple (i.e. -C+), so the table entry for C(sp) could be a compromise between those values, but might as well instead just be the double bond value, since =C= is also a legal form for C(sp). The result is that there is no place in this table to put the C+ value. """ _mendeleev = [ ("X", "Singlet", 0, 0.001, [[1, 0, None, 'sp']]), #bruce 050630 made X have atomtype name 'sp'; might revise again later ("H", "Hydrogen", 1, 1.6737, [[1, 31, onebond]]), ("He", "Helium", 2, 6.646, None), ("Li", "Lithium", 3, 11.525, [[1, 152, None]]), ("Be", "Beryllium", 4, 14.964, [[2, 114, None]]), ("B", "Boron", 5, 17.949, [[3, 80, flat, 'sp2']]), #bruce 050706 added 'sp2' name, though all bonds are single ("C", "Carbon", 6, 19.925, [[4, DIAMOND_BOND_LENGTH / 2 * 100, tetra4, 'sp3'], #bruce 051102 replaced 77 with constant expr, which evals to 77.2 [3, 71, flat, 'sp2'], [2, 66, straight, 'sp'], # (this is correct for =C=, ie two double bonds) ## [1, 60, None] # what's this? I don't know how it could bond... removing it. [bruce 050510] ]), ("N", "Nitrogen", 7, 23.257, [[3, 73, tetra3, 'sp3'], [2, 61, flat[:2], 'sp2'], # bruce 050630 replaced tetra2 with flat[:2] # josh 0512013 made this radius 61, but this is only correct for a double bond, # whereas this will have one single and one double bond (or two aromatic bonds), # so 61 is probably not the best value here... 67 would be the average of single and double. # [bruce 051014] [1, 56, onebond, 'sp'], [3, 62, flat, 'sp2(graphitic)'], # this is just a guess! (for graphitic N, sp2(??) with 3 single bonds) (and the 62 is made up) ]), ("O", "Oxygen", 8, 26.565, [[2, 69, oxy2, 'sp3'], [1, 60, onebond, 'sp2']]), # sp2? ("F", "Fluorine", 9, 31.545, [[1, 70, onebond]]), ("Ne", "Neon", 10, 33.49, None), ("Na", "Sodium", 11, 38.1726, [[1, 186, None]]), ("Mg", "Magnesium", 12, 40.356, [[2, 160, None]]), ("Al", "Aluminum", 13, 44.7997, [[3, 143, flat]]), ("Si", "Silicon", 14, 46.6245, [[4, 111, tetra4]]), ("P", "Phosphorus", 15, 51.429, [[3, 108, tetra3, 'sp3'], [5, 100, tetra4, 'sp3(p)']]), # 100 is made up sp3(p) means sp3(phosphate) ("S", "Sulfur", 16, 53.233, [[2, 107, tetra2, 'sp3'], [1, 88, onebond, 'sp2']]), #bruce 050706 added this, and both names; length chgd by Josh ("Cl", "Chlorine", 17, 58.867, [[1, 102, onebond]]), ("Ar", "Argon", 18, 66.33, None), ("K", "Potassium", 19, 64.9256, [[1, 231, None]]), ("Ca", "Calcium", 20, 66.5495, [[2, 197, tetra2]]), ("Sc", "Scandium", 21, 74.646, [[3, 160, tetra3]]), ("Ti", "Titanium", 22, 79.534, [[4, 147, tetra4]]), ("V", "Vanadium", 23, 84.584, [[5, 132, None]]), ("Cr", "Chromium", 24, 86.335, [[6, 125, None]]), ("Mn", "Manganese", 25, 91.22, [[7, 112, None]]), ("Fe", "Iron", 26, 92.729, [[3, 124, None]]), ("Co", "Cobalt", 27, 97.854, [[3, 125, None]]), ("Ni", "Nickel", 28, 97.483, [[3, 125, None]]), ("Cu", "Copper", 29, 105.513, [[2, 128, None]]), ("Zn", "Zinc", 30, 108.541, [[2, 133, None]]), ("Ga", "Gallium", 31, 115.764, [[3, 135, None]]), ("Ge", "Germanium", 32, 120.53, [[4, 122, tetra4]]), ("As", "Arsenic", 33, 124.401, [[5, 119, tetra3]]), ("Se", "Selenium", 34, 131.106, [[6, 120, tetra2]]), ("Br", "Bromine", 35, 132.674, [[1, 119, onebond]]), ("Kr", "Krypton", 36, 134.429, None), ("Sb", "Antimony", 51, 124.401, [[3, 119, tetra3]]), ("Te", "Tellurium", 52, 131.106, [[2, 120, tetra2]]), ("I", "Iodine", 53, 132.674, [[1, 119, onebond]]), ("Xe", "Xenon", 54, 134.429, None), ] # How to add a new hybridization type for an element: # # First, add it to the table below (or one of the similar ones # wherever the element definition is found). If an element has more # than one hybridization, the hybridization name must be specified so # they can be distinguished. In general, hybridization names should # start with the string "sp", possibly followed by a digit 2 or 3. In # general, the formal charge plus the number of electrons provided # should equal the group number of the element. The total bond order # will be the electrons needed minus the electrons provided (this is # the number of electrons shared with other atoms). The number of # individual bonds to distinct atoms is specified by the length of the # geometry array. The geometry array specifies how these bonds are # arranged around the central atom. # # Next, check _init_permitted_v6_list() in class AtomType in # atomtypes.py. Make any adjustments necessary so that the correct # list of available bond types is generated for the new hybridization. # # Next, add the new hybridization to the UI in PM_ElementChooser.py. # See the comments there for how to do that. # symbol name # hybridization name # formal charge # number of electrons needed to fill shell # number of valence electrons provided # covalent radius (pm) # geometry (array of vectors, one for each available bond) # symb hybridization FC need prov c-rad geometry _chemicalAtomTypeData = [ ["X", 'sp', 0, 2, 1, 0.00, onebond], ["H", None, 0, 2, 1, 0.31, onebond], ["He", None, 0, 2, 2, 0.00, None], ["Li", None, 0, 2, 1, 1.52, None], ["Be", None, 0, 4, 2, 1.14, None], ["B", None, 0, 6, 3, 0.80, flat], ["C", 'sp3', 0, 8, 4, DIAMOND_BOND_LENGTH / 2, tetra4], ["C", 'sp2', 0, 8, 4, 0.71, flat], ["C", 'sp', 0, 8, 4, 0.66, straight], ["N", 'sp3', 0, 8, 5, 0.73, tetra3], ["N", 'sp2', 0, 8, 5, 0.61, flat[:2]], ["N", 'sp', 0, 8, 5, 0.56, onebond], ["N", 'sp2(graphitic)', 0, 8, 5, 0.62, flat], ["O", 'sp3', 0, 8, 6, 0.69, oxy2], ["O", 'sp2', 0, 8, 6, 0.60, onebond], ["O", 'sp2(-)', -1, 8, 7, 0.60, onebond], # bogus rcovalent ["O", 'sp2(-.5)', -0.5, 8,6.5, 0.60, onebond], # bogus rcovalent ["F", None, 0, 8, 7, 0.70, onebond], ["Ne", None, 0, 8, 8, 0.00, None], ["Na", None, 0, 2, 1, 1.86, None], ["Mg", None, 0, 4, 2, 1.60, None], ["Al", None, 0, 6, 3, 1.43, flat], ["Si", None, 0, 8, 4, 1.11, tetra4], ["P", 'sp3', 0, 8, 5, 1.08, tetra3], ["P", 'sp3(p)', 0, 10, 5, 1.00, tetra4], # bogus rcovalent. sp3(p)means sp3(phosphate) ["S", 'sp3', 0, 8, 6, 1.07, tetra2], ["S", 'sp2', 0, 8, 6, 0.88, onebond], ["Cl", None, 0, 8, 7, 1.02, onebond], ["Ar", None, 0, 8, 8, 0.00, None], ["K", None, 0, 2, 1, 2.31, None], ["Ca", None, 0, 4, 2, 1.97, tetra2], ["Sc", None, 0, 6, 3, 1.60, tetra3], ["Ti", None, 0, 8, 4, 1.47, tetra4], ["V", None, 0, 10, 5, 1.32, None], ["Cr", None, 0, 12, 6, 1.25, None], ["Mn", None, 0, 14, 7, 1.12, None], ["Fe", None, 0, 6, 3, 1.24, None], ["Co", None, 0, 6, 3, 1.25, None], ["Ni", None, 0, 6, 3, 1.25, None], ["Cu", None, 0, 4, 2, 1.28, None], ["Zn", None, 0, 4, 2, 1.33, None], ["Ga", None, 0, 6, 3, 1.35, None], ["Ge", None, 0, 8, 4, 1.22, tetra4], ["As", None, 0, 8, 5, 1.19, tetra3], ["Se", None, 0, 8, 6, 1.20, tetra2], ["Br", None, 0, 8, 7, 1.19, onebond], ["Kr", None, 0, 8, 8, 0.00, None], ["Sb", None, 0, 8, 5, 1.19, tetra3], ["Te", None, 0, 8, 6, 1.20, tetra2], ["I", None, 0, 8, 7, 1.19, onebond], ["Xe", None, 0, 8, 8, 0.00, None], ] # == def init_chemical_elements( periodicTable): periodicTable.addElements( _mendeleev, _defaultRadiusAndColor, _alternateRadiusAndColor, _chemicalAtomTypeData, _DIRECTIONAL_BOND_ELEMENTS_chemical ) return # end
NanoCAD-master
cad/src/model/elements_data.py
# Copyright 2004-2008 Nanorex, Inc. See LICENSE file for details. """ Comment.py - The Comment class. @version: $Id$ @copyright: 2004-2008 Nanorex, Inc. See LICENSE file for details. History: mark 060530 - Comment class moved here from Utility.py. bruce 071019 - moved mmp reading code for Comment into this file; registering it with files_mmp_registration instead of hardcoding it there """ from foundation.Utility import SimpleCopyMixin, Node from utilities.icon_utilities import imagename_to_pixmap from utilities.constants import gensym from files.mmp.files_mmp_registration import MMP_RecordParser from files.mmp.files_mmp_registration import register_MMP_RecordParser # == class Comment(SimpleCopyMixin, Node): """ A Comment stores a comment in the MMP file, accessible from the Model Tree as a node. """ # text representation: self.lines is a list of lines (str or unicode python strings). # This is the fundamental representation for use by mmp read/write, copy, and Undo. # For convenience, get_text() and set_text() are also available. sym = "Comment" lines = () copyable_attrs = Node.copyable_attrs + ('lines',) #bruce 060523 this fixes bug 1939 (undo) and apparently 1938 (file modified), # and together with SimpleCopyMixin it also fixes bug 1940 (copy) def __init__(self, assy, name, text=''): self.const_pixmap = imagename_to_pixmap("modeltree/comment.png") if not name: name = gensym("%s" % self.sym, assy) Node.__init__(self, assy, name) self.lines = [] # this makes set_text changed() test legal (result of test doesn't matter) self.set_text(text) return def assert_valid_line(self, line): #bruce 070502 assert type(line) in (type(""), type(u"")), "invalid type for line = %r, with str = %s" % (line, line) return def set_text(self, text): """ Set our text (represented in self.lines, a list of 1 or more str or unicode strings, no newlines) to the lines in the given str or unicode python string, or QString. """ oldlines = self.lines if type(text) in (type(""), type(u"")): # this (text.split) works for str or unicode text; # WARNING: in Qt4 it would also work for QString, but produces QStrings, # so we have to do the explicit type test rather than try/except like in Qt3. # (I didn't check whether we got away with try/except in Qt3 due to QString.split not working # or due to not being passed a QString in that case.) [bruce 070502 Qt4 bugfix] lines = text.split('\n') else: # it must be a QString text = unicode(text) ## self.text = text # see if edit still works after this -- it does lines = text.split('\n') # ok that they are unicode but needn't be? yes. map( self.assert_valid_line, lines) self.lines = lines if oldlines != lines: self.changed() return def get_text(self): """ return our text (perhaps as a unicode string, whether or not unicode is needed) """ return u'\n'.join(self.lines) #bruce 070502 bugfix: revert Qt4 porting error which broke this for unicode def _add_line(self, line, encoding = 'ascii'): """ [private method to support mmp reading (main record and info records)] Add the given line (which might be str or unicode, but is assumed to contain no \ns and not be a QString) to our text. """ if encoding == 'utf-8': line = line.decode(encoding) else: if encoding != 'ascii': print "Comment._add_line treating unknown encoding as if ascii:", encoding # no need to decode self.assert_valid_line(line) self.lines.append(line) self.changed() return def _init_line1(self, card): """ [private method] readmmp helper -- card is entire line of mmp record (perhaps including \n at end) """ # as of 060522 it does end with \n, but we won't assume it does; but we will assume it was written by our writemmp method if card[-1] == '\n': card = card[:-1] # comment (name) encoding1, line1 junk, rest = card.split(') ', 1) try: encoding1, line1 = rest.split(' ', 1) # assume ending blank has been preserved, if line was empty except: # assume ending blank got lost encoding1 = rest line1 = "" self.lines = [] # kluge self._add_line( line1, encoding1) return def readmmp_info_leaf_setitem( self, key, val, interp ): #bruce 060522 "[extends superclass method]" if key[0] == 'commentline' and len(key) == 2: # key[1] is the encoding, and val is one line in the comment self._add_line(val, key[1]) else: Node.readmmp_info_leaf_setitem( self, key, val, interp) return def edit(self): """ Opens Comment dialog with current text. """ self.assy.w.commentcntl.setup(self) def writemmp(self, mapping): lines = self.lines def encodeline(line): self.assert_valid_line(line) #k should be redundant, since done whenever we modify self.lines try: return 'ascii', line.encode('ascii') except: return 'utf-8', line.encode('utf-8') # needed if it contains unicode characters # in future we might have more possibilities, e.g. html or images or links... encodedlines = map( encodeline, lines) encoding1, line1 = encodedlines[0] # this works even if the comment is empty (1 line, length 0) mapping.write("comment (" + mapping.encode_name(self.name) + ") %s %s\n" % (encoding1, line1)) for encoding1, line1 in encodedlines[1:]: mapping.write("info leaf commentline %s = %s\n" % (encoding1, line1)) self.writemmp_info_leaf(mapping) return def __str__(self): return "<comment " + self.name + ">" pass # end of class Comment # == class _MMP_RecordParser_for_Comment( MMP_RecordParser): #bruce 071019 """ Read the first line of the MMP record for a Comment. """ def read_record(self, card): #bruce 060522 name = self.get_name(card, "Comment") name = self.decode_name(name) #bruce 050618 comment = Comment(self.assy, name) comment._init_line1(card) # card ends with a newline self.addmember(comment) # Note: subsequent lines of the Comment text (if any) # come from info leaf records following this record # in the mmp file. return pass def register_MMP_RecordParser_for_Comment(): """ [call this during init, before reading any mmp files] """ register_MMP_RecordParser( 'comment', _MMP_RecordParser_for_Comment ) return # end
NanoCAD-master
cad/src/model/Comment.py
# Copyright 2004-2008 Nanorex, Inc. See LICENSE file for details. """ Elem.py -- provides class Elem, which represents one element in NE1's periodic table. Note that some Elem instances are used only with "pseudoatoms" or bondpoints, whereas others correspond to actual chemical elements. @author: Josh @version: $Id$ @copyright: 2004-2008 Nanorex, Inc. See LICENSE file for details. History: Bruce 071101 split class Elem out of elements.py into its own module. TODO: In elements.py and Elem.py, modularize the creation of different kinds of elements, to help permit specialized modules and Elem/Atom subclasses for PAM3 and PAM5 (etc). (Should we define new Elem subclasses for them?) """ from foundation.state_utils import IdentityCopyMixin class Elem(IdentityCopyMixin): """ There is exactly one of these objects for each supported element in the periodic table. Its identity (as a python object) never changes during the run. Instead, if prefs changes are made in color, radius, or perhaps bonding pattern, this object's contents will be modified accordingly. """ # bruce 050510 renamed this from 'elem' # (not using 'Element' since too common in strings/comments) # default values of per-instance constants bonds_can_be_directional = False #bruce 071015 # attributes for classifying elements -- tentative in name, meaning, and value-encoding [bruce 071106] # (warning: these default values are never used, since __init__ always sets these attrs in self) pam = None # name of pseudo-atom model (e.g. MODEL_PAM3 == 'PAM3'), or None; # not sure if Singlet and regular elems have same .pam # REVIEW: it might be simplest if Singlet had None here, and all others had a true value, e.g. 'PAM3' or 'PAM5' or 'Chem'. # If we use that scheme, then we certainly need to rename this. It is an "element class"? "element model"?? role = None # element role in its pseudo-atom model; for DNA PAM atoms # this can be 'strand' or 'axis' or 'unpaired-base'; not sure about Singlet deprecated_to = None # symbol of an element to transmute this one to, when reading mmp files; or None, or 'remove' (??) # (used for deprecated elements, including simulation-only elements no longer needed when modeling) def __init__(self, eltnum, sym, name, mass, rvdw, color, bn, pam = None, role = None, deprecated_to = None ): """ Note: this should only be called by class _ElementPeriodicTable in elements.py. eltnum = atomic number (e.g. H is 1, C is 6); for Singlet this is 0 sym = (e.g.) "H" name = (e.g.) "Hydrogen" mass = atomic mass in e-27 kg rvdw = van der Waals radius [warning: vdw radius is used for display, and is changeable as a display preference! If we ever need to use it for chemical purposes, we'll need a separate unchanging copy for that!] color = color (RGB, 0-1) bn = bonding info: list of triples: # of bonds in this form covalent radius (units of 0.01 Angstrom) info about angle between bonds, as an array of vectors optional 4th item in the "triple": name of this bonding pattern, if it has one Note: self.bonds_can_be_directional is set for some elements by the caller. [In the future it may depend on the role option, or be its own option.] """ # bruce 041216 and 050510 modified the above docstring self.eltnum = eltnum self.symbol = sym self.symbol_for_printing = sym #bruce 071106 if sym[-1].isdigit(): # separate symbol digits from numeric key self.symbol_for_printing += '-' self.name = name self.color = color self.mass = mass self.rvdw = rvdw # option values self.pam = pam self.role = role self.deprecated_to = deprecated_to if not deprecated_to and deprecated_to is not None: print "WARNING: we don't yet know what element %r should be deprecated_to" % sym self.atomtypes = [] ## self.bonds = bn # not needed anymore, I hope # if not bn: # e.g. Helium # bn = [[0, 0, None]] # valence = bn[0][0] # assert type(valence) == type(1) # assert valence in [0,1,2,3,4,5,6,7] # in fact only up to 4 is properly supported # self.atomtypes = map( lambda bn_triple: AtomType( self, bn_triple, valence ), bn ) # creates cyclic refs, that's ok # # This is a public attr. Client code should not generally modify it! # # But if we someday have add_atomtype method, it can append or insert, # # as long as it remembers that client code treats index 0 as the default atomtype for this element. # # Client code is not allowed to assume a given atomtype's position in this list remains constant! return def addAtomType(self, aType): self.atomtypes += [aType] def find_atomtype(self, atomtype_name): #bruce 050511 """ Given an atomtype name or fullname (or an atomtype object itself) for this element, return the atomtype object. @param atomTypeName: The atomtype name or fullname (or an atomtype object itself) for this element. Given None, return this element's default atomtype object. @type atomTypeName: str or L{AtomType} @return: The atomtype object. @rtype: L{AtomType} @raise: Raise an exception (various exception types are possible) if no atomtype for this element matches the name (or equals the passed object). """ if not atomtype_name: # permit None or "" for now return self.atomtypes[0] for atomtype in self.atomtypes: # in order from [0], though this should not matter since at most one should match if atomtype.name == atomtype_name or atomtype.fullname == atomtype_name or atomtype == atomtype_name: return atomtype # we're not bothering to optimize for atomtype_name being the same obj we return assert 0, "%r is not a valid atomtype name or object for %s" % (atomtype_name, self.name) def findAtomType(self, atomTypeName): """ Given an atomtype name or fullname (or an atomtype object itself) for this element, return the atomtype object. Same as L{find_atomtype()}, provided for convenience. @param atomTypeName: The atomtype name or fullname (or an atomtype object itself) for this element. Given None, return this element's default atomtype object. @type atomTypeName: str or L{AtomType} @return: The atomtype object. @rtype: L{AtomType} @raise: Raise an exception (various exception types are possible) if no atomtype for this element matches the name (or equals the passed object). """ return self.find_atomtype(atomTypeName) def __repr__(self): return "<Element: " + self.symbol + "(" + self.name + ")>" pass # end
NanoCAD-master
cad/src/model/Elem.py
# Copyright 2006-2009 Nanorex, Inc. See LICENSE file for details. """ BorrowerChunk.py -- a chunk which temporarily borrows the atoms from another one, for an experimental optimization of display lists when moving subsets of the atoms of a chunk. Not used by default. Deprecated, since some more principled and more general loosening of the chunk <-> display list correspondence would be much better. @author: Bruce @version: $Id$ @copyright: 2006-2009 Nanorex, Inc. See LICENSE file for details. History: Bruce wrote this inside chunk.py Bruce 080314 split this into its own file. """ # note: this may not have been tested since it was split out of chunk.py. from utilities.debug import register_debug_menu_command from model.chunk import Chunk from model.global_model_changedicts import _changed_parent_Atoms import foundation.env as env from utilities.Log import orangemsg, redmsg, quote_html from utilities.debug import safe_repr # == # Some notes about BorrowerChunk [bruce 060411] ## If an undo checkpoint occurs while the atoms are stolen, ## it won't contain them (it will be as if they were deleted, I think). ## This might be tolerable for A7 (if tested for safety), since cp's during drag ## are rare -- or it might not, if problems are caused by bonds from existing to dead atoms! ## ## When we want to fix it, here are some possible ways: # - make the missing-atoms scheme work, by making the bonds from existing to dead atoms also seem to be missing, somehow. ## - let this chunk be scanned by Undo (ie make it a child of the assy, in a special place ## so not in the MT), and let it have an _undo_update method ## (or the like) which merges its atoms back into their homes. (It might turn out this is required ## anyway, if having it missing during a cp causes unforseen problems.) ## - disable cp's during drag. ## - merge undo diffs from the drag. # == class BorrowerChunk(Chunk): """ A temporary Chunk (mostly transparent to users and Undo, when not added to MT) whose atoms belong in other chunks. Useful for optimizing redraws, since it has one perhaps-small display list, and the other chunks' display lists won't be modified when our atoms change (except once when we first steal their atoms, and when we add them back). @warning: removing atoms from, or adding atoms to, this pseudo-chunk is not supported. Except for debugging purposes, it should never be added to the MT, or permitted to exist when arbitrary user-ops are possible. Its only known safe usage pattern is to be created, used, and destroyed, during one extended operation such as a mouse-drag. [If more uses are thought of, these limitations could all be removed. #e] update 060412: trying to make it fully safe for Undo cp, and in case it's accidently left alive (in GLPane or MT). But not trying to make results perfectly transparent or "correct" in those cases, since we'll try to prevent them. E.g. for mmp save, it'll save as a normal Chunk would. """ def __init__(self, assy, atomset = None, name = None): # revised 060413 """ #doc; for doc of atomset, see take_atomset """ Chunk.__init__(self, assy, self._name_when_empty(assy)) if atomset is not None: self.take_atomset(atomset, name = name) return def _name_when_empty(self, assy = None): if assy is None: assy = self.assy del assy # not yet used; might use id or repr someday return "(empty borrower id %#x)" % id(self) def take_atomset(self, atomset, name = None): """ #doc; atomset maps atom.key -> atom for some atoms we'll temporarily own @warning: if all of another chunk's atoms are in atomset, creating us will kill that chunk. @warning: it's up to the caller to make sure all singlet neighbors of atoms in atomset are also in atomset! Likely bugs if it doesn't. If you want to call this again on new atoms, call self.demolish first. """ if not name: name = "(borrower of %d atoms, id %#x)" % (len(atomset), id(self)) #e __repr__ also incls this info self.name = name # no use for prior value of self.name #k is there a set_name we should be using?? atoms = atomset.values() #e could optim this -- only use is to let us pick one arbitrary atom egatom = atoms[0] egmol = egatom.molecule # do this now, since we're going to change it in the loop del atoms, egatom assy = egmol.assy assert assy is self.assy # now steal the atoms, but remember their homes and don't add ourselves to assy.tree. # WARNING: if we steal *all* atoms from another chunk, that will cause trouble, # but preventing this is up to the caller! [#e put this into another method, so it can be called again later??] # We optimize this by lots of inlining, since we need it to be fast for lots of atoms. harmedmols = {} # id(mol) -> mol for all mols whose atoms we steal from origmols = {} # atom.key - original atom.molecule self.origmols = origmols self.harmedmols = harmedmols # self.atoms was initialized to {} in Chunk.__init__, or restored to that in self.demolish() for key, atom in atomset.iteritems(): mol = atom.molecule assert mol is not self if isinstance(mol, self.__class__): print "%r: borrowing %r from another borrowerchunk %r is not supported" % (self, atom, mol) # whether it might work, I have no idea harmedmols[id(mol)] = mol # inline part of mol.delatom(atom): #e do this later: mol.invalidate_atom_lists() _changed_parent_Atoms[key] = atom del mol.atoms[key] # callers can check for KeyError, always an error # don't do this (but i don't think it prevents all harm from stealing all mol's atoms): ## if not mol.atoms: ## mol.kill() # inline part of self.addatom(atom): atom.molecule = self atom.index = -1 # illegal value self.atoms[key] = atom #e do this later: self.invalidate_atom_lists() # remember where atom came from: origmols[key] = mol # do what we saved for later in the inlined delatom and addatom calls: for mol in harmedmols.itervalues(): natoms = len(mol.atoms) if not natoms: print "bug: BorrowerChunk stole all atoms from %r; potential for harm is not yet known" % mol mol.invalidate_atom_lists() self.invalidate_atom_lists() try: part = egmol.part part.add(self) ###e not 100% sure this is ok; need to call part.remove too (and we do) assert part is self.part # Part.add should do this (if it was not already done) except: print "data from following exception: egmol = %r, its part = %r, self.part = %r" % \ ( egmol, part, self.part ) raise return # from take_atomset # instead of overriding _draw_for_main_display_list # (now in ChunkDrawer rather than in our superclass Chunk, # so overriding it would require defining a custom _drawer_class), # it's enough to define _colorfunc and _dispfunc to help it: def _colorfunc(self, atm): """ Define this to use atm's home mol's color instead of self.color, and also so that self._dispfunc gets called [overrides self._colorfunc = None; this scheme will get messed up if self ever gets copied, since the copy code (two methods in Chunk) will set an instance attribute pointing to the bound method of the original] """ #e this has bugs if we removed atoms from self -- that's not supported (#e could override delatom to support it) return self.origmols[atm.key].drawing_color() def _dispfunc(self, atm): origmol = self.origmols[atm.key] glpane = origmol.glpane # set shortly before this call, in origmol.draw (kluge) disp = origmol.get_dispdef(glpane) return disp def restore_atoms_to_their_homes(self): """ put your atoms back where they belong (calling this multiple times should be ok) """ #e this has bugs if we added atoms to self -- that's not supported (#e could override addatom to support it) origmols = self.origmols for key, atom in self.atoms.iteritems(): _changed_parent_Atoms[key] = atom origmol = origmols[key] atom.molecule = origmol atom.index = -1 # illegal value origmol.atoms[key] = atom for mol in self.harmedmols.itervalues(): mol.invalidate_atom_lists() self.atoms = {} self.origmols = {} self.harmedmols = {} ## self.part = None self.invalidate_atom_lists() # might not matter anymore; hope it's ok when we have no atoms if self.part is not None: self.part.remove(self) return def demolish(self): """ Restore atoms, and make self reusable (but up to caller to remove self from any .dad it might have) """ self.restore_atoms_to_their_homes() self.name = self._name_when_empty() return def take_atoms_from_list(self, atomlist): """ We must be empty (ready for reuse). Divide atoms in atomlist by chunk; take the atoms we can (without taking all atoms from any chunk); return a pair of lists (other_chunks, other_atoms), where other_chunks are chunks whose atoms were all in atomlist, and other_atoms is a list of atoms we did not take for some other reason (presently always [] since there is no other reason we can't take an atom). """ # note: some recent selectMode code for setting up dragatoms is similar enough (in finding other_chunks) # that it might make sense to pull out a common helper routine other_chunks = [] other_atoms = [] # never changed our_atoms = [] chunks_and_atoms = divide_atomlist_by_chunk(atomlist) # list of pairs (chunk, atoms in it) for chunk, atlist in chunks_and_atoms: if len(chunk.atoms) == len(atlist): other_chunks.append(chunk) else: our_atoms.extend(atlist) atomset = dict([(a.key, a) for a in our_atoms]) self.take_atomset( atomset) return other_chunks, other_atoms def kill(self): self.restore_atoms_to_their_homes() # or should we delete them instead?? (this should never matter in our planned uses) # this includes self.part = None Chunk.kill(self) def destroy(self): self.kill() self.name = "(destroyed borrowerchunk)" # for testing, we might let one of these show up in the MT, and then we need these cmenu methods for it: def __CM_Restore_Atoms_To_Their_Homes(self): self.restore_atoms_to_their_homes() assy = self.assy self.kill() assy.w.win_update() # at least mt_update is needed #e we might need destroy and/or kill methods which call restore_atoms_to_their_homes pass # end of class BorrowerChunk # == def divide_atomlist_by_chunk(atomlist): # only used in this file as of 080314, but might be more generally useful # note: similar to some recent code for setting up dragatoms in selectMode, but not identical """ Given a list of atoms, return a list of pairs (chunk, atoms in that chunk from that list). Assume no atom appears twice. """ resdict = {} # id(chunk) -> list of one or more atoms from it for at in atomlist: chunk = at.molecule resdict.setdefault(id(chunk), []).append(at) return [(atlist[0].molecule, atlist) for atlist in resdict.itervalues()] def debug_make_BorrowerChunk(target): """ (for debugging only) """ debug_make_BorrowerChunk_raw(True) def debug_make_BorrowerChunk_no_addmol(target): """ (for debugging only) """ debug_make_BorrowerChunk_raw(False) def debug_make_BorrowerChunk_raw(do_addmol = True): win = env.mainwindow() atomset = win.assy.selatoms if not atomset: env.history.message(redmsg("Need selected atoms to make a BorrowerChunk (for debugging only)")) else: atomset = dict(atomset) # copy it, since we shouldn't really add singlets to assy.selatoms... for atom in atomset.values(): # not itervalues, we're changing it in the loop! # BTW Python is nicer about this than I expected: # exceptions.RuntimeError: dictionary changed size during iteration for bp in atom.singNeighbors(): # likely bugs if these are not added into the set! atomset[bp.key] = bp assy = atom.molecule.assy # these are all the same, and we do this at least once chunk = BorrowerChunk(assy, atomset) if do_addmol: win.assy.addmol(chunk) import __main__ __main__._bc = chunk env.history.message(orangemsg("__main__._bc = %s (for debugging only)" % quote_html(safe_repr(chunk)))) win.win_update() #k is this done by caller? return # == register_debug_menu_command("make BorrowerChunk", debug_make_BorrowerChunk) register_debug_menu_command("make BorrowerChunk (no addmol)", debug_make_BorrowerChunk_no_addmol) # end
NanoCAD-master
cad/src/model/BorrowerChunk.py
# Copyright 2008 Nanorex, Inc. See LICENSE file for details. """ elements_data_other.py -- data for miscellaneous kinds of elements which are neither chemical nor PAM pseudoatoms (for example, virtual site indicators) @author: Bruce @version: $Id$ @copyright: 2008 Nanorex, Inc. See LICENSE file for details. See also: the "handle" Ah5, which is defined as a PAM5 pseudoelement for code-convenience reasons. """ ## from model.elements_data import tetra4, flat, tetra2, onebond _DIRECTIONAL_BOND_ELEMENTS_OTHER = () # == _defaultRadiusAndColor = { "Vs0" : (1.0, [0.8, 0.8, 0.8]), #bruce 080515 guess, "very light gray" } _alternateRadiusAndColor = { } # Format of _mendeleev: see elements_data.py _mendeleev = [ # For indicators of virtual sites. # (We might add more, whose element names correspond to # virtual site pattern names, but which have the same role value.) ("Vs0", "virtual-site", 400, 1.0, None, dict(role = 'virtual-site')), ] # symb hybridization FC need prov c-rad geometry _otherAtomTypeData = [ ["Vs0", None, 0, 0, 0, 0.00, None], ] # == def init_other_elements( periodicTable): periodicTable.addElements( _mendeleev, _defaultRadiusAndColor, _alternateRadiusAndColor, _otherAtomTypeData, _DIRECTIONAL_BOND_ELEMENTS_OTHER, default_options = dict() ) return # end
NanoCAD-master
cad/src/model/elements_data_other.py
# Copyright 2004-2008 Nanorex, Inc. See LICENSE file for details. """ elements.py -- elements, periodic table, element display prefs @author: Josh @version: $Id$ @copyright: 2004-2008 Nanorex, Inc. See LICENSE file for details. History: Initially by Josh as part of chem.py. Bruce 041221 split this module out of chem.py, and (around then) added support for alternate color/radius tables. Huaicai circa 050309 revised outer levels of structure, added support for loading and saving color/radius tables into files, added preferences code. [This comment added by bruce 050509.] Bruce 050509 did some reformatting, corrected some out-of-date comments or docstrings, removed some obsolete commented-out code. (Committed 050510.) Bruce 050510 made some changes for "atomtypes" with their own bonding patterns. Bruce 071101 split class Elem into its own module, removed Singleton superclass, and split elements_data.py out of elements.py. Bruce 071105 modularized the creation of different kinds of elements, except for the central list of all the kinds in this file (implicit in the list of init_xxx_elements functions we call), so chemical, PAM3, and PAM5 elements are created by separate modules. Bruce 071106 removed a few useless and unused methods (one of which had a bug -- getElemBondCount didn't honor its atomtype argument). To access public attributes of elements, just use getElement() and then access the attribute directly. """ from foundation.preferences import prefs_context from model.Elem import Elem from model.atomtypes import AtomType from model.elements_data import init_chemical_elements from model.elements_data_other import init_other_elements from dna.model.elements_data_PAM3 import init_PAM3_elements from dna.model.elements_data_PAM5 import init_PAM5_elements # == class _ElementPeriodicTable(object): """ Represents a table of all possible elements (including pseudoelements) that can be used in Atoms. (Initially contains no elements; caller should add all the ones it needs before use, by calling addElements one or more times.) Normally used as a singleton, but I [bruce 071101] don't know whether that's obligatory. """ def __init__(self): self._periodicTable = {} # maps elem.eltnum to elem (an Elem) self._eltName2Num = {} # maps elem.name to elem.eltnum self._eltSym2Num = {} # maps elem.symbol to elem.eltnum #bruce 071105 added the color tables: self._defaultRadiusAndColor = {} # maps elem.symbol to (radius, color) pairs self._alternateRadiusAndColor = {} # alternate rad/color values (ok if incomplete) # bruce 050419 add public attributes to count changes # to any element's color or rvdw; the only requirement is that # each one changes at least once per user event which # changes their respective attributes for one or more elements. self.color_change_counter = 1 self.rvdw_change_counter = 1 return def addElements(self, elmTable, defaultRadiusAndColor, alternateRadiusAndColor, atomTypeData, directional_bond_elements = (), default_options = {} ): #bruce 071105 modified from def _createElements(self, elmTable): """ Create elements for all members of <elmTable> (list of tuples). (Ok to call this more than once for non-overlapping elmTables (unique element symbols). Use preference value for radius and color of each element, if available (using element symbol as prefs key); otherwise, use values from defaultRadiusAndColor dictionary, which must have values for all element symbols in elmTable. (Make sure it has the value, even if we don't need it due to prefs.) Also store all values in defaultRadiusAndColor, alternateRadiusAndColor tables for later use by loadDefaults or loadAlternates methods. @param elmTable: a list of elements to create, as tuples of a format documented in elements_data.py. @param defaultRadiusAndColor: a dictionary of radius, color pairs, indexed by element symbol. Must be complete. Used now when not overridden by prefs. Stored for optional later use by loadDefaults. @param alternateRadiusAndColor: an alternate dictionary of radius, color pairs. Need not be complete; missing entries are effectively taken from defaultRadiusAndColor. Stored for optional later use by loadAlternates. @param atomTypeData: array of initialization data for each AtomType. See description in elements_data.py. @param directional_bond_elements: a list of elements in elmTable which support directional bonds. """ prefs = prefs_context() symbols = {} for elm in elmTable: options = dict(default_options) assert len(elm) in (5, 6) if len(elm) >= 6: options.update(elm[5]) symbols[elm[0]] = 1 # record element symbols seen in this call rad_color = prefs.get(elm[0], defaultRadiusAndColor[elm[0]]) el = Elem(elm[2], elm[0], elm[1], elm[3], rad_color[0], rad_color[1], elm[4], ** options) assert not self._periodicTable.has_key(el.eltnum), \ "duplicate def of element number %r (prior: %r)" % \ (el.eltnum, self._periodicTable[el.eltnum] ) assert not self._eltName2Num.has_key(el.name), \ "duplicate def of element name %r" % (el.name,) assert not self._eltSym2Num.has_key(el.symbol), \ "duplicate def of element symbol %r" % (el.symbol,) self._periodicTable[el.eltnum] = el self._eltName2Num[el.name] = el.eltnum self._eltSym2Num[el.symbol] = el.eltnum if elm[0] in directional_bond_elements: #bruce 071015 # TODO: put this in the options field? or infer it from # pam and role? el.bonds_can_be_directional = True assert el.bonds_can_be_directional == (el.symbol == 'X' or el.role == 'strand') # once this works, we can clean up the code to not hardcode those list args # [bruce 080117] for key in defaultRadiusAndColor.iterkeys(): assert key in symbols for key in alternateRadiusAndColor.iterkeys(): assert key in symbols self._defaultRadiusAndColor.update(defaultRadiusAndColor) self._alternateRadiusAndColor.update(alternateRadiusAndColor) for aType in atomTypeData: at_symbol = aType[0] at_hybridizationName = aType[1] at_formalCharge = aType[2] at_electronsNeeded = aType[3] at_electronsProvided = aType[4] at_covalentRadius = aType[5] at_geometry = aType[6] elt = self.getElement(at_symbol) elt.addAtomType(AtomType(elt, at_hybridizationName, at_formalCharge, at_electronsNeeded, at_electronsProvided, at_covalentRadius, at_geometry)); return def _loadTableSettings(self, elSym2rad_color ): """ Load a table of element radius/color settings into self. @param elSym2rad_color: A dictionary of (eleSym : (rvdw, [r,g,b])). [r,g,b] can be None or missing, in which case use color from self._defaultRadiusAndColor; or the entire entry for eleSym can be missing, in which case use both color and radius from self._defaultRadiusAndColor. """ self.rvdw_change_counter += 1 self.color_change_counter += 1 for elm in self._periodicTable.values(): # TODO: recode this to not use try/except to test the table format try: e_symbol = elm.symbol rad_color = elSym2rad_color[e_symbol] elm.rvdw = rad_color[0] if len(rad_color) == 1: rad_color = self._defaultRadiusAndColor[e_symbol] elm.color = rad_color[1] # guess: this is what will routinely fail if [r,g,b] is None except: rad_color = self._defaultRadiusAndColor[e_symbol] elm.rvdw = rad_color[0] elm.color = rad_color[1] pass return def loadDefaults(self): """ Update the elements properties in self from self._defaultRadiusAndColor. """ self. _loadTableSettings( self._defaultRadiusAndColor) def loadAlternates(self): """ Update the elements properties in self from self._alternateRadiusAndColor; for missing or partly-missing values, use self._defaultRadiusAndColor. """ self. _loadTableSettings( self._alternateRadiusAndColor) def deepCopy(self): """ Deep copy the current settings of element rvdw/color, and return in a form that can be passed to resetElemTable. Typical use is in case user cancels modifications being done by an interactive caller which can edit this table. """ copyPTable = {} for elm in self._periodicTable.values(): if type(elm.color) != type([1, 1, 1]): print "Error: ", elm copyPTable[elm.symbol] = (elm.rvdw, elm.color[:]) return copyPTable def resetElemTable(self, elmTable): """ Set the current table of element settings to equal those in <elmTable> """ self._loadTableSettings(elmTable) def setElemColors(self, colTab): """ Set a list of element colors. @param colTab: A list of tuples in the form of <elNum, r, g, b> """ assert type(colTab) == type([1, 1, 1, 1]) self.color_change_counter += 1 for elm in colTab: self._periodicTable[elm[0]].color = [elm[1], elm[2], elm[3]] return def setElemColor(self, eleNum, c): """ Set element <eleNum> color as <c> """ assert type(eleNum) == type(1) assert eleNum >= 0 assert type(c) == type([1, 1, 1]) self.color_change_counter += 1 self._periodicTable[eleNum].color = c def getElemColor(self, eleNum): """ Return the element color as a triple list for <eleNum> """ assert type(eleNum) == type(1) assert eleNum >= 0 return self._periodicTable[eleNum].color def getPTsenil(self): """ Return a nested list of elements for use in Passivate, consisting of the reversed right ends of the top 4 rows (?) of the standard periodic table of the chemical elements. """ pTsenil = [ [self._periodicTable[2], self._periodicTable[1]], [self._periodicTable[10], self._periodicTable[9], self._periodicTable[8], self._periodicTable[7], self._periodicTable[6]], [self._periodicTable[18], self._periodicTable[17], self._periodicTable[16], self._periodicTable[15], self._periodicTable[14]], [self._periodicTable[36], self._periodicTable[35], self._periodicTable[34], self._periodicTable[33], self._periodicTable[32]] ] return pTsenil def getAllElements(self): """ Return the whole list of elements of periodic table as a dictionary. The caller should not modify this dictionary. """ return self._periodicTable def getElement(self, num_or_name_or_symbol): """ Return the element for <num_or_name_or_symbol>, which is either the index, name or symbol of the element. """ s = num_or_name_or_symbol if s in self._eltName2Num: s = self._eltName2Num[s] elif s in self._eltSym2Num: s = self._eltSym2Num[s] elif type(s) != type(1): assert 0, "don't recognize element name or symbol %r" % (s,) return self._periodicTable[s] def close(self): # The 'def __del__(self)' is not guaranteed to be called. # It is not called in my try on Windows. [Huaicai] """ Save color/radius preference before deleting """ prefs = prefs_context() elms = {} for elm in self._periodicTable.values(): elms[elm.symbol] = (elm.rvdw, elm.color) prefs.update(elms) #print "__del__() is called now." pass # end of class _ElementPeriodicTable # == # init code and global definitions PeriodicTable = _ElementPeriodicTable() # initially empty init_chemical_elements( PeriodicTable) # including Singlet == element 0 init_other_elements( PeriodicTable) init_PAM3_elements( PeriodicTable) init_PAM5_elements( PeriodicTable) Hydrogen = PeriodicTable.getElement(1) Carbon = PeriodicTable.getElement(6) Nitrogen = PeriodicTable.getElement(7) Oxygen = PeriodicTable.getElement(8) Singlet = PeriodicTable.getElement(0) Vs0 = PeriodicTable.getElement('Vs0') #bruce 080520 Pl5 = PeriodicTable.getElement('Pl5') #bruce 080312 for convertToPam3plus5 Ss5 = PeriodicTable.getElement('Ss5') Ax5 = PeriodicTable.getElement('Ax5') Gv5 = PeriodicTable.getElement('Gv5') Ss3 = PeriodicTable.getElement('Ss3') Ax3 = PeriodicTable.getElement('Ax3') # == test code if __name__ == '__main__': # UNTESTED since Singleton superclass removed or init code revised [071105] pt1 = _ElementPeriodicTable() init_chemical_elements( PeriodicTable) assert pt1.getElement('C') == pt1.getElement(6) assert pt1.getElement('Oxygen') == pt1.getElement(8) print pt1.getElement(6) print pt1.getElement(18) pt1.deepCopy() # end
NanoCAD-master
cad/src/model/elements.py
# Copyright 2004-2008 Nanorex, Inc. See LICENSE file for details. """ jigs_measurements.py -- Classes for measurement jigs. @version: $Id$ @copyright: 2004-2008 Nanorex, Inc. See LICENSE file for details. History: 060324 wware - with a debug pref, we can now get a drawing style for the distance measuring jig that looks like a dimension on a mechanical drawing. Future plans: similar drawing styles for angle and dihedral measurements, and switch drawing to OpenGL display lists for performance improvement. 05(later) wware - Simulator support was added, as well as MMP file records. 051104 wware - three measurement jigs (distance, angle, dihedral) written over the last few days. No simulator support yet, but they work fine in the CAD system, and the MMP file records should be acceptable when the time comes for sim support. """ import sys import Numeric from Numeric import dot import foundation.env as env from geometry.VQT import V, A, norm, cross, vlen, angleBetween from foundation.Utility import Node from utilities.Log import redmsg, greenmsg, orangemsg from utilities.debug import print_compact_stack, print_compact_traceback from model.jigs import Jig from graphics.drawing.dimensions import drawLinearDimension, drawAngleDimension, drawDihedralDimension from graphics.drawing.drawers import drawtext from utilities.constants import black from utilities.prefs_constants import dynamicToolTipAtomDistancePrecision_prefs_key from utilities.prefs_constants import dynamicToolTipBendAnglePrecision_prefs_key from OpenGL.GLU import gluUnProject def _constrainHandleToAngle(pos, p0, p1, p2): """ This works in two steps. (1) Project pos onto the plane defined by (p0, p1, p2). (2) Confine the projected point to lie within the angular arc. """ u = pos - p1 z0 = norm(p0 - p1) z2 = norm(p2 - p1) oop = norm(cross(z0, z2)) u = u - dot(oop, u) * oop # clip the point so it lies within the angle if dot(cross(z0, u), oop) < 0: # Clip on the z0 side of the angle. u = vlen(u) * z0 elif dot(cross(u, z2), oop) < 0: # Clip on the z2 side of the angle. u = vlen(u) * z2 return p1 + u # == Measurement Jigs # rename class for clarity, remove spurious methods, wware 051103 class MeasurementJig(Jig): """ superclass for Measurement jigs """ # constructor moved to base class, wware 051103 def __init__(self, assy, atomlist): Jig.__init__(self, assy, atomlist) self.font_name = "Helvetica" self.font_size = 10.0 # pt size self.color = black # This is the "draw" color. When selected, this will become highlighted red. self.normcolor = black # This is the normal (unselected) color. self.cancelled = True # We will assume the user will cancel self.handle_offset = V(0.0, 0.0, 0.0) # move some things to base class, wware 051103 copyable_attrs = Jig.copyable_attrs + ('font_name', 'font_size') def constrainedPosition(self): """ The jig maintains an unconstrained position. Constraining the position can mean projecting it onto a particular surface, and/or confining it to a particular region satisfying some linear inequalities in position. """ raise Exception('expected to be overloaded') def clickedOn(self, pos): self.handle_offset = pos - self.center() self.constrain() def constrain(self): self.handle_offset = self.constrainedPosition() - self.center() def move(self, offset): ###k NEEDS REVIEW: does this conform to the new Node API method 'move', or should it be renamed? [bruce 070501 question] self.handle_offset += offset self.constrain() def posn(self): return self.center() + self.handle_offset # move to base class, wware 051103 # Email from Bruce, 060327 <<<< # It's either a bug or a bad style error to directly call Node.kill, # skipping the superclass kill methods if any (and there is one, # at least Jig.kill). # In this case it might not be safe to call Jig.kill, since that might # recurse into this method, but (1) this needs a comment, (2) this is a # possible bug since removing the atoms is not happening when this jig # is killed, but perhaps needs to (otherwise the atoms will be listing # this jig as one of their jigs even after it's killed -- not sure what # harm this causes but it might be bad, e.g. a minor memory leak or # maybe some problem when copying them). # If you're not sure what to do about any of it, just commenting it # or filing a reminder bug is ok for now. It interacts with some code # I'm working on now in other files, so it might be just as well for me # to be the one to change the code. >>>> # For now, I think I'll go with Jig.kill, and let Bruce modify as needed. # [... but this is still Node.kill. Maybe Jig.kill caused a bug and someone # else changed it back and didn't comment it? Who knows. REVIEW sometime. # bruce 080311 comment.] def remove_atom(self, atom, **opts): # bruce 080311 added **opts to match superclass method signature """ Delete self if *any* of its atoms are deleted [overrides superclass method] """ Node.kill(self) # superclass is Jig, not Node; see long comment above # Set the properties for a Measure Distance jig read from a (MMP) file # include atomlist, wware 051103 def setProps(self, name, color, font_name, font_size, atomlist): self.name = name self.color = color self.font_name = font_name self.font_size = font_size self.setAtoms(atomlist) # simplified, wware 051103 # Following Postscript: font names NEVER have parentheses in them. # So we can use parentheses to delimit them. def mmp_record_jigspecific_midpart(self): return " (%s) %d" % (self.font_name, self.font_size) # unify text-drawing to base class, wware 051103 def _drawtext(self, text, color): # use atom positions to compute center, where text should go if self.picked: # move the text to the lower left corner, and make it big pos = A(gluUnProject(5, 5, 0)) drawtext(text, color, pos, 3 * self.font_size, self.assy.o) else: pos1 = self.atoms[0].posn() pos2 = self.atoms[-1].posn() pos = (pos1 + pos2) / 2 drawtext(text, color, pos, self.font_size, self.assy.o) # move into base class, wware 051103 def set_cntl(self): from command_support.JigProp import JigProp self.cntl = JigProp(self, self.assy.o) # move into base class, wware 051103 def writepov(self, file, dispdef): sys.stderr.write(self.__class__.__name__ + ".writepov() not implemented yet") def will_copy_if_selected(self, sel, realCopy): """ copy only if all my atoms are selected [overrides Jig.will_copy_if_selected] """ # for measurement jigs, copy only if all atoms selected, wware 051107 # [bruce 060329 adds: this doesn't prevent the copy if the jig is inside a Group, and that causes a bug] for atom in self.atoms: if not sel.picks_atom(atom): if realCopy: msg = "Can't copy a measurement jig [%s] unless all its atoms are selected." % (self.name,) env.history.message(orangemsg(msg)) return False return True def center(self): c = Numeric.array((0.0, 0.0, 0.0)) n = len(self.atoms) for a in self.atoms: c += a.posn() / n return c def writemmp_info_leaf(self, mapping): Node.writemmp_info_leaf(self, mapping) x, y, z = self.constrainedPosition() mapping.write("info leaf handle = %g %g %g\n" % (x, y, z)) def readmmp_info_leaf_setitem(self, key, val, interp): import string, Numeric if key == ['handle']: self.handle_offset = Numeric.array(map(string.atof, val.split())) - self.center() else: Jig.readmmp_info_leaf_setitem(self, key, val, interp) pass # end of class MeasurementJig # == Measure Distance class MeasureDistance(MeasurementJig): """ A Measure Distance jig has two atoms and draws a line with a distance label between them. """ sym = "Distance" icon_names = ["modeltree/Measure_Distance.png", "modeltree/Measure_Distance-hide.png"] featurename = "Measure Distance Jig" # added, wware 20051202 def constrainedPosition(self): a = self.atoms pos, p0, p1 = self.center() + self.handle_offset, a[0].posn(), a[1].posn() z = p1 - p0 nz = norm(z) dotprod = dot(pos - p0, nz) if dotprod < 0.0: return pos - dotprod * nz elif dotprod > vlen(z): return pos - (dotprod - vlen(z)) * nz else: return pos def _getinfo(self): return "[Object: Measure Distance] [Name: " + str(self.name) + "] " + \ "[Nuclei Distance = " + str(self.get_nuclei_distance()) + " ]" + \ "[VdW Distance = " + str(self.get_vdw_distance()) + " ]" def _getToolTipInfo(self): #ninad060825 """ Return a string for display in Dynamic Tool tip """ #honor user preferences for digit after decimal distPrecision = env.prefs[dynamicToolTipAtomDistancePrecision_prefs_key] nucleiDist = round(self.get_nuclei_distance(),distPrecision) vdwDist = round(self.get_vdw_distance(),distPrecision) attachedAtoms = str(self.atoms[0]) + "-" + str(self.atoms[1]) return str(self.name) + "<br>" + "<font color=\"#0000FF\"> Jig Type:</font>Measure Distance"\ + "<br>" + "<font color=\"#0000FF\">Atoms: </font>" + attachedAtoms+"<br>"\ +"<font color=\"#0000FF\">Nuclei Distance: </font>" + str(nucleiDist) + " A" \ + "<br>" + "<font color=\"#0000FF\">VdW Distance: </font> " + str(vdwDist) + " A" def getstatistics(self, stats): # Should be _getstatistics(). Mark stats.num_mdistance += 1 # Helper functions for the measurement jigs. Should these be general Atom functions? Mark 051030. def get_nuclei_distance(self): """ Returns the distance between two atoms (nuclei) """ return vlen (self.atoms[0].posn()-self.atoms[1].posn()) def get_vdw_distance(self): """ Returns the VdW distance between two atoms """ return self.get_nuclei_distance() - self.atoms[0].element.rvdw - self.atoms[1].element.rvdw # Measure Distance jig is drawn as a line between two atoms with a text label between them. # A wire cube is also drawn around each atom. def _draw_jig(self, glpane, color, highlighted=False): """ Draws a wire frame cube around two atoms and a line between them. A label displaying the VdW and nuclei distances (e.g. 1.4/3.5) is included. """ MeasurementJig._draw_jig(self, glpane, color, highlighted) text = "%.2f/%.2f" % (self.get_vdw_distance(), self.get_nuclei_distance()) # mechanical engineering style dimensions drawLinearDimension(color, self.assy.o.right, self.assy.o.up, self.constrainedPosition(), self.atoms[0].posn(), self.atoms[1].posn(), text, highlighted=highlighted) mmp_record_name = "mdistance" pass # end of class MeasureDistance # == Measure Angle class MeasureAngle(MeasurementJig): # new class. wware 051031 """ A Measure Angle jig has three atoms. """ sym = "Angle" icon_names = ["modeltree/Measure_Angle.png", "modeltree/Measure_Angle-hide.png"] featurename = "Measure Angle Jig" # added, wware 20051202 def constrainedPosition(self): import types a = self.atoms return _constrainHandleToAngle(self.center() + self.handle_offset, a[0].posn(), a[1].posn(), a[2].posn()) def _getinfo(self): # add atom list, wware 051101 return "[Object: Measure Angle] [Name: " + str(self.name) + "] " + \ ("[Atoms = %s %s %s]" % (self.atoms[0], self.atoms[1], self.atoms[2])) + \ "[Angle = " + str(self.get_angle()) + " ]" def _getToolTipInfo(self): #ninad060825 """ Return a string for display in Dynamic Tool tip """ #honor user preferences for digit after decimal anglePrecision = env.prefs[dynamicToolTipBendAnglePrecision_prefs_key] bendAngle = round(self.get_angle(),anglePrecision) attachedAtoms = str(self.atoms[0]) + "-" + str(self.atoms[1]) + "-" + str(self.atoms[2]) return str(self.name) + "<br>" + "<font color=\"#0000FF\"> Jig Type: </font>Measure Angle"\ + "<br>" + "<font color=\"#0000FF\">Atoms: </font>" + attachedAtoms + "<br>"\ + "<font color=\"#0000FF\">Angle </font> " + str(bendAngle) + " Degrees" def getstatistics(self, stats): # Should be _getstatistics(). Mark stats.num_mangle += 1 # Helper functions for the measurement jigs. Should these be general Atom functions? Mark 051030. def get_angle(self): """ Returns the angle between two atoms (nuclei) """ v01 = self.atoms[0].posn()-self.atoms[1].posn() v21 = self.atoms[2].posn()-self.atoms[1].posn() return angleBetween(v01, v21) # Measure Angle jig is drawn as a line between two atoms with a text label between them. # A wire cube is also drawn around each atom. def _draw_jig(self, glpane, color, highlighted=False): """ Draws a wire frame cube around two atoms and a line between them. A label displaying the angle is included. """ MeasurementJig._draw_jig(self, glpane, color, highlighted) # draw boxes around each of the jig's atoms. text = "%.2f" % self.get_angle() # mechanical engineering style dimensions drawAngleDimension(color, self.assy.o.right, self.assy.o.up, self.constrainedPosition(), self.atoms[0].posn(), self.atoms[1].posn(), self.atoms[2].posn(), text, highlighted=highlighted) mmp_record_name = "mangle" pass # end of class MeasureAngle # == Measure Dihedral class MeasureDihedral(MeasurementJig): # new class. wware 051031 """ A Measure Dihedral jig has four atoms. """ sym = "Dihedral" icon_names = ["modeltree/Measure_Dihedral.png", "modeltree/Measure_Dihedral-hide.png"] featurename = "Measure Dihedral Jig" # added, wware 20051202 def constrainedPosition(self): a = self.atoms p0, p1, p2, p3 = a[0].posn(), a[1].posn(), a[2].posn(), a[3].posn() axis = norm(p2 - p1) midpoint = 0.5 * (p1 + p2) return _constrainHandleToAngle(self.center() + self.handle_offset, p0 - dot(p0 - midpoint, axis) * axis, midpoint, p3 - dot(p3 - midpoint, axis) * axis) def _getinfo(self): # add atom list, wware 051101 return "[Object: Measure Dihedral] [Name: " + str(self.name) + "] " + \ ("[Atoms = %s %s %s %s]" % (self.atoms[0], self.atoms[1], self.atoms[2], self.atoms[3])) + \ "[Dihedral = " + str(self.get_dihedral()) + " ]" def _getToolTipInfo(self): #ninad060825 """ Return a string for display in Dynamic Tool tip """ #honor user preferences for digit after decimal anglePrecision = env.prefs[dynamicToolTipBendAnglePrecision_prefs_key] dihedral = round(self.get_dihedral(),anglePrecision) attachedAtoms = str(self.atoms[0]) + "-" + str(self.atoms[1]) + "-" + str(self.atoms[2]) + "-" + str(self.atoms[3]) return str(self.name) + "<br>" + "<font color=\"#0000FF\"> Jig Type: </font>Measure Dihedral"\ + "<br>" + "<font color=\"#0000FF\">Atoms: </font>" + attachedAtoms + "<br>"\ + "<font color=\"#0000FF\">Angle </font> " + str(dihedral) + " Degrees" def getstatistics(self, stats): # Should be _getstatistics(). Mark stats.num_mdihedral += 1 # Helper functions for the measurement jigs. Should these be general Atom functions? Mark 051030. def get_dihedral(self): """ Returns the dihedral between two atoms (nuclei) """ wx = self.atoms[0].posn()-self.atoms[1].posn() yx = self.atoms[2].posn()-self.atoms[1].posn() xy = -yx zy = self.atoms[3].posn()-self.atoms[2].posn() u = cross(wx, yx) v = cross(xy, zy) if dot(zy, u) < 0: # angles go from -180 to 180, wware 051101 return -angleBetween(u, v) # use new acos(dot) func, wware 051103 else: return angleBetween(u, v) # Measure Dihedral jig is drawn as a line between two atoms with a text label between them. # A wire cube is also drawn around each atom. def _draw_jig(self, glpane, color, highlighted=False): """ Draws a wire frame cube around two atoms and a line between them. A label displaying the dihedral is included. """ MeasurementJig._draw_jig(self, glpane, color, highlighted) # draw boxes around each of the jig's atoms. text = "%.2f" % self.get_dihedral() # mechanical engineering style dimensions drawDihedralDimension(color, self.assy.o.right, self.assy.o.up, self.constrainedPosition(), self.atoms[0].posn(), self.atoms[1].posn(), self.atoms[2].posn(), self.atoms[3].posn(), text, highlighted=highlighted) mmp_record_name = "mdihedral" pass # end of class MeasureDihedral # end of module jigs_measurements.py
NanoCAD-master
cad/src/model/jigs_measurements.py
# Copyright 2007 Nanorex, Inc. See LICENSE file for details. """ @author: Ninad @copyright: 2007 Nanorex, Inc. See LICENSE file for details. @version:$Id$ History: Ninad 20070703 : Created Ninad 20070706 : Added support for resizing a poly-line. """ import foundation.env as env from OpenGL.GL import glPushMatrix from OpenGL.GL import glPopMatrix from OpenGL.GLU import gluProject, gluUnProject from graphics.drawing.drawers import drawPolyLine from Numeric import dot from math import pi, cos from geometry.VQT import V, Q, cross, A, planeXline, vlen, norm, angleBetween from utilities.debug import print_compact_traceback from utilities.constants import blue from graphics.drawables.ResizeHandle import ResizeHandle from model.ReferenceGeometry import ReferenceGeometry class Line(ReferenceGeometry): """ """ sym = "Line" is_movable = True icon_names = ["modeltree/plane.png", "modeltree/plane-hide.png"] copyable_attrs = ReferenceGeometry.copyable_attrs mmp_record_name = "line" def __init__(self, win, plane = None, lst = None, pointList = None, READ_FROM_MMP = False): self.w = self.win = win ReferenceGeometry.__init__(self, win) self.plane = plane self.controlPoints = [] self.handles = [] self.quat = None self.center = None self.color = blue if lst: for a in lst: self.controlPoints.append(a.posn()) elif pointList: for a in pointList: self.controlPoints.append(a) self.win.assy.place_new_geometry(self) def _draw_geometry(self, glpane, color, highlighted=False): glPushMatrix() if not highlighted: color = self.color drawPolyLine(color, self.controlPoints) if self.picked: self._draw_handles(self.controlPoints) glPopMatrix() def _draw_handles(self, controlPoints): handleCenters = list(controlPoints) if len(self.handles) > 0: assert len(self.handles) == len(controlPoints) i = 0 for i in range(len(self.handles)): self.handles[i].draw(hCenter = handleCenters[i]) else: for hCenter in handleCenters: handle = ResizeHandle(self, self.glpane, hCenter) handle.draw() handle.setType('') if handle not in self.handles: self.handles.append(handle) def getHandlePoint(self, hdl, event): p1, p2 = self.glpane.mousepoints(event) rayPoint = p2 rayVector = norm(p2-p1) ptOnHandle = hdl.center handleNorm = hdl.glpane.lineOfSight hdl_intersection = planeXline(ptOnHandle, handleNorm, rayPoint, rayVector) handlePoint = hdl_intersection return handlePoint def resizeGeometry(self, hdl, evt): movedHandle = hdl event = evt handle_NewPt = self.getHandlePoint(movedHandle, event) ##if movedHandle in self.handles[1:-1]: movedHandle.center = handle_NewPt self.updateControlPoints(movedHandle, handle_NewPt) def updateControlPoints(self, hdl, hdl_NewPt): """ Update the control point list of the line. """ #@@TODO No need to clear all the list. Need to make sure that only #the changed point in the list is updated -- Ninad20070706 movedHandle = hdl handle_NewPt = hdl_NewPt if len(self.handles) > 1: self.controlPoints = [] for h in self.handles: self.controlPoints.append(h.center) def updateControlPoints_EXPERIMENTAL(self, hdl, hdl_NewPt): """ Experimental stuff in this method. Not used anywhere. Ignore """ movedHandle = hdl handle_NewPt = hdl_NewPt if len(self.handles) > 1: self.controlPoints = [] if movedHandle in self.handles[1:-1]: for h in self.handles: self.controlPoints.append(h.center) else: offsetVector = handle_NewPt - movedHandle.center movedHandle.center = handle_NewPt for h in self.handles[1:-1]: vect = movedHandle.center - h.center theta = angleBetween( vect, offsetVector) theta = theta*pi/180.0 offsetVecForHandle = offsetVector / cos(theta) ##offsetVecForHandle = offsetVector* len(vect)/len(offsetVector) h.center += offsetVecForHandle for h in self.handles: self.controlPoints.append(h.center) if 0: oldCenter = V(0.0, 0.0, 0.0) for h in self.handles: oldCenter += h.center oldCenter /= len(self.handles) movedHandle.center = handle_NewPt newCenter = V(0.0, 0.0, 0.0) for h in self.handles: newCenter += h.center newCenter /= len(self.handles) for h in self.handles: if h in self.handles[1:-1]: h.center += newCenter - oldCenter self.controlPoints.append(h.center)
NanoCAD-master
cad/src/model/Line.py
# Copyright 2007-2009 Nanorex, Inc. See LICENSE file for details. """ Chunk_Dna_methods.py -- dna-related methods for class Chunk @author: Bruce, Ninad @version: $Id$ @copyright: 2007-2009 Nanorex, Inc. See LICENSE file for details. History: Bruce 090115 split this out of class Chunk. (Not long or old enough for svn copy to be worthwhile, so see chunk.py for older svn history.) TODO: Refactoring: Some of the methods in this class are never used except on Dna-related subclasses of Chunk, and should be moved into those subclasses. Unfortunately it's not trivial to figure out for which ones that's guaranteed to be the case. There are some large hunks of duplicated code in this file (pylint can detect them). See also the REVIEW comments below, as always. """ from utilities.constants import noop from utilities.constants import MODEL_PAM3, MODEL_PAM5 class Chunk_Dna_methods: ## (NodeWithAtomContents): # Someday: inherit NodeWithAtomContents (Chunk's main superclass) to # mollify pylint? It does mollify it somewhat and seemed initially to be # ok... but Chunk (as all Nodes) is still an old-style class, so it has no # __mro__ attribute and follows different inheritance rules than new-style # classes. It turns out that the old rules mess up in this case, if we use # that superclass on more than one pre-mixin class split out of class # Chunk, e.g. Chunk_mmp_methods, since then whichever one comes first # pulls in NodeWithAtomContents methods ahead of the other mixin's # methods, which prevents the other mixin from overriding those methods. # (This is exactly the "diamond-shaped inheritance diagram" issue that the # new-style mro rules fix.) # # The upside of this is that we can't inherit Chunk's main superclass in # its special-method-mixin classes until we make Chunk a new-style class # (which has issues of its own, common to all Nodes, described elsewhere). # Hopefully, before that happens, we'll have refactored Chunk further to # use cooperating objects rather than mixin classes. [bruce 090123] """ Dna-related methods to be mixed in to class Chunk. """ # PAM3+5 attributes (these only affect PAM atoms in self, if any): # # ### REVIEW [bruce 090115]: can some of these be deprecated and removed? # # self.display_as_pam can be MODEL_PAM3 or MODEL_PAM5 to force conversion # on input # to the specified PAM model for display and editing of self, or can be # "" to use global preference settings. (There is no value which always # causes no conversion, but there may be preference settings which disable # ever doing conversion. But in practice, a PAM chunk will be all PAM3 or # all PAM5, so this can be set to the model the chunk uses to prevent # conversion for that chunk.) # # The value MODEL_PAM3 implies preservation of PAM5 data when present # (aka "pam3+5" or "pam3plus5"). # The allowed values are "", MODEL_PAM3, MODEL_PAM5. # # self.save_as_pam can be MODEL_PAM3 or MODEL_PAM5 to force conversion on save # to the specified PAM model. When not set, global settings or save # parameters determine which model to convert to, and whether to ever # convert. # # [bruce 080321 for PAM3+5] ### TODO: use for conversion, and prevent # ladder merge when different display_as_pam = "" # PAM model to use for displaying and editing PAM atoms in self (not # set means use user pref) save_as_pam = "" # PAM model to use for saving self (not normally set; not set means # use save-op params) # this mixin's contribution to Chunk.copyable_attrs _dna_copyable_attrs = ('display_as_pam', 'save_as_pam', ) def invalidate_ladder(self): #bruce 071203 """ Subclasses which have a .ladder attribute should call its ladder_invalidate_if_not_disabled method. """ return def invalidate_ladder_and_assert_permitted(self): #bruce 080413 """ Subclasses which have a .ladder attribute should call its ladder_invalidate_and_assert_permitted method. """ return def in_a_valid_ladder(self): #bruce 071203 """ Is this chunk a rail of a valid DnaLadder? [subclasses that might be should override] """ return False def _make_glpane_cmenu_items_Dna(self, contextMenuList): # by Ninad """ Private helper for Chunk.make_glpane_cmenu_items; does the dna-related part. """ #bruce 090115 split this out of Chunk.make_glpane_cmenu_items def _addDnaGroupMenuItems(dnaGroup): if dnaGroup is None: return item = (("DnaGroup: [%s]" % dnaGroup.name), noop, 'disabled') contextMenuList.append(item) item = (("Edit DnaGroup Properties..."), dnaGroup.edit) contextMenuList.append(item) return if self.isStrandChunk(): strandGroup = self.parent_node_of_class(self.assy.DnaStrand) if strandGroup is None: strand = self else: #dna_updater case which uses DnaStrand object for #internal DnaStrandChunks strand = strandGroup dnaGroup = strand.parent_node_of_class(self.assy.DnaGroup) if dnaGroup is None: #This is probably a bug. A strand should always be contained #within a Dnagroup. But we'll assume here that this is possible. item = (("%s" % strand.name), noop, 'disabled') else: item = (("%s of [%s]" % (strand.name, dnaGroup.name)), noop, 'disabled') contextMenuList.append(None) # adds a separator in the contextmenu contextMenuList.append(item) item = (("Edit DnaStrand Properties..."), strand.edit) contextMenuList.append(item) contextMenuList.append(None) # separator _addDnaGroupMenuItems(dnaGroup) # add menu commands from our DnaLadder [bruce 080407] # REVIEW: should these be added regardless of command? # [bruce 090115 question] # REVIEW: I think self.ladder is not valid except in dna-specific # subclasses of Chunk. Probably that means this code should be # moved there. [bruce 090115] if self.ladder: menu_spec = self.ladder.dnaladder_menu_spec(self) # note: this is empty when self (the arg) is a Chunk. # [bruce 080723 refactoring a recent Mark change] if menu_spec: # append separator?? ## contextMenuList.append(None) contextMenuList.extend(menu_spec) elif self.isAxisChunk(): segment = self.parent_node_of_class(self.assy.DnaSegment) dnaGroup = segment.parent_node_of_class(self.assy.DnaGroup) if segment is not None: contextMenuList.append(None) # separator if dnaGroup is not None: item = (("%s of [%s]" % (segment.name, dnaGroup.name)), noop, 'disabled') else: item = (("%s " % segment.name), noop, 'disabled') contextMenuList.append(item) item = (("Edit DnaSegment Properties..."), segment.edit) contextMenuList.append(item) contextMenuList.append(None) # separator # add menu commands from our DnaLadder [bruce 080407] # REVIEW: see comments for similar code above. [bruce 090115] if segment.picked: selectedDnaSegments = self.assy.getSelectedDnaSegments() if len(selectedDnaSegments) > 0: item = (("Resize Selected DnaSegments "\ "(%d)..." % len(selectedDnaSegments)), self.assy.win.resizeSelectedDnaSegments) contextMenuList.append(item) contextMenuList.append(None) if self.ladder: menu_spec = self.ladder.dnaladder_menu_spec(self) if menu_spec: contextMenuList.extend(menu_spec) _addDnaGroupMenuItems(dnaGroup) pass pass return # START of Dna-Strand-or-Axis chunk specific code ========================== # Note: some of these methods will be removed from class Chunk once the # dna data model is always active. [bruce 080205 comment] [some removed, 090121] def _editProperties_DnaStrandChunk(self): """ Private helper for Chunk.edit; does the dna-related part. """ # probably by Ninad; split out of Chunk.edit by Bruce 090115 commandSequencer = self.assy.w.commandSequencer commandSequencer.userEnterCommand('DNA_STRAND') assert commandSequencer.currentCommand.commandName == 'DNA_STRAND' commandSequencer.currentCommand.editStructure(self) return def isStrandChunk(self): # Ninad circa 080117, revised by Bruce 080117 """ Returns True if *all atoms* in this chunk are PAM 'strand' atoms or 'unpaired-base' atoms (or bondpoints), and at least one is a 'strand' atom. Also resets self.iconPath (based on self.hidden) if it returns True. This method is overridden in dna-specific subclasses of Chunk. It is likely that this implementation on Chunk itself could now be redefined to just return False, but this has not been analyzed closely. @see: BuildDna_PropertyManager.updateStrandListWidget where this is used to filter out strand chunks to put those into the strandList widget. """ # This is a temporary method that can be removed once dna_model is # fully functional. # bruce 090121 comment: REVIEW whether this can be redefined to return # False on this class, since it's implemented in our DnaStrandChunk # subclass. found_strand_atom = False for atom in self.atoms.itervalues(): if atom.element.role == 'strand': found_strand_atom = True # side effect: use strand icon [mark 080203] if self.hidden: self.iconPath = "ui/modeltree/Strand-hide.png" else: self.iconPath = "ui/modeltree/Strand.png" elif atom.is_singlet() or atom.element.role == 'unpaired-base': pass else: # other kinds of atoms are not allowed return False continue return found_strand_atom #END of Dna-Strand chunk specific code ================================== #START of Dna-Axis chunk specific code ================================== def isAxisChunk(self): """ Returns True if *all atoms* in this chunk are PAM 'axis' atoms or bondpoints, and at least one is an 'axis' atom. Overridden in some subclasses. @see: isStrandChunk """ # bruce 090121 comment: REVIEW whether this can be redefined to return # False on this class, since it's implemented in our DnaAxisChunk # subclass. found_axis_atom = False for atom in self.atoms.itervalues(): if atom.element.role == 'axis': found_axis_atom = True elif atom.is_singlet(): pass else: # other kinds of atoms are not allowed return False continue return found_axis_atom #END of Dna-Axis chunk specific code ==================================== #START of Dna-Strand-or-Axis chunk specific code ======================== def isDnaChunk(self): """ @return: whether self is a DNA chunk (strand or axis chunk) @rtype: boolean """ return self.isAxisChunk() or self.isStrandChunk() def getDnaGroup(self): # ninad 080205 """ Return the DnaGroup of this chunk if it has one. """ return self.parent_node_of_class(self.assy.DnaGroup) def getDnaStrand(self): """ Returns the DnaStrand(group) node to which this chunk belongs to. Returns None if there isn't a parent DnaStrand group. @see: Atom.getDnaStrand() """ if self.isNullChunk(): return None dnaStrand = self.parent_node_of_class(self.assy.DnaStrand) return dnaStrand def getDnaSegment(self): """ Returns the DnaStrand(group) node to which this chunk belongs to. Returns None if there isn't a parent DnaStrand group. @see: Atom.getDnaStrand() """ if self.isNullChunk(): return None dnaSegment = self.parent_node_of_class(self.assy.DnaSegment) return dnaSegment #END of Dna-Strand-or-Axis chunk specific code ======================== def _readmmp_info_chunk_setitem_Dna( self, key, val, interp ): """ Private helper for Chunk.readmmp_info_chunk_setitem. @return: whether we handled this info record (depends only on key, not on success vs error) @rtype: boolean """ if key == ['display_as_pam']: # val should be one of the strings "", MODEL_PAM3, MODEL_PAM5; # if not recognized, use "" if val not in ("", MODEL_PAM3, MODEL_PAM5): # maybe todo: use deferred_summary_message? print "fyi: info chunk display_as_pam with unrecognized value %r" % \ (val,) val = "" #bruce 080523: silently ignore this, until the bug 2842 dust fully # settles. This is #1 of 2 changes (in the same commit) which # eliminates all ways of setting this attribute, thus fixing # bug 2842 well enough for v1.1. (The same change is not needed # for save_as_pam below, since it never gets set, or ever did, # except when using non-default values of debug_prefs. This means # someone setting those prefs could save a file which causes a bug # only seen by whoever loads it, but I'll live with that for now.) ## self.display_as_pam = val pass elif key == ['save_as_pam']: # val should be one of the strings "", MODEL_PAM3, MODEL_PAM5; # if not recognized, use "" if val not in ("", MODEL_PAM3, MODEL_PAM5): # maybe todo: use deferred_summary_message? print "fyi: info chunk save_as_pam with unrecognized value %r" % \ (val,) val = "" self.save_as_pam = val else: return False return True def _writemmp_info_chunk_before_atoms_Dna(self, mapping): """ Private helper for Chunk.writemmp_info_chunk_before_atoms. @return: None """ if self.display_as_pam: # Note: not normally set on most chunks, even when PAM3+5 is in use. # Future optim (unimportant since not normally set): # we needn't write this is self contains no PAM atoms. # and if we failed to write it when dna updater was off, # that would be ok. # So we could assume we don't need it for ordinary chunks # (even though that means dna updater errors on atoms would discard it). mapping.write("info chunk display_as_pam = %s\n" % self.display_as_pam) if self.save_as_pam: # not normally set, even when PAM3+5 is in use mapping.write("info chunk save_as_pam = %s\n" % self.save_as_pam) return def _getToolTipInfo_Dna(self): """ Return the dna-related part of the tooltip string for this chunk """ # probably by Mark or Ninad # Note: As of 2008-11-09, this is only implemented for a DnaStrand. #bruce 090115 split this out of Chunk.getToolTipInfo strand = self.getDnaStrand() if strand: return strand.getDefaultToolTipInfo() segment = self.getDnaSegment() if segment: return segment.getDefaultToolTipInfo() return "" def _getAxis_of_self_or_eligible_parent_node_Dna(self, atomAtVectorOrigin = None): """ Private helper for Chunk.getAxis_of_self_or_eligible_parent_node; does the dna-related part. """ # by Ninad #bruce 090115 split this out of Chunk.getAxis_of_self_or_eligible_parent_node dnaSegment = self.parent_node_of_class(self.assy.DnaSegment) if dnaSegment and self.isAxisChunk(): axisVector = dnaSegment.getAxisVector( atomAtVectorOrigin = atomAtVectorOrigin ) if axisVector is not None: return axisVector, dnaSegment dnaStrand = self.parent_node_of_class(self.assy.DnaStrand) if dnaStrand and self.isStrandChunk(): arbitraryAtom = self.atlist[0] dnaSegment = dnaStrand.get_DnaSegment_with_content_atom( arbitraryAtom) if dnaSegment: axisVector = dnaSegment.getAxisVector( atomAtVectorOrigin = atomAtVectorOrigin ) if axisVector is not None: return axisVector, dnaSegment return None, None pass # end of class Chunk_Dna_methods # end
NanoCAD-master
cad/src/model/Chunk_Dna_methods.py
# Copyright 2007-2009 Nanorex, Inc. See LICENSE file for details. """ PAM_Atom_methods.py - methods for class Atom, which are only meant to be called on PAM Atoms. @author: Bruce, Mark, Ninad @version: $Id$ @copyright: 2007-2009 Nanorex, Inc. See LICENSE file for details. History: bruce 080327 split out of chem.py class Atom, in which these methods had been written TODO: REVIEW whether any of these methods are sometimes called on non-PAM atoms, always doing nothing or returning a null value, e.g. getDnaBaseName. also refactor some code that remains in chem.py but has PAM-element-specific sections, like the transmute context menu entries for PAM elements, and some bond_geometry_error_string things (which needs a separate refactoring first, for other reasons) """ # WARNING: this module is imported by chem.py and therefore indirectly by # chunk.py. Therefore its import dependence on other things needs to be # minimized. However, it seems ok at this point to import quite a bit of dna # updater code. Today I moved all imports to toplevel (including those with # old warnings that that didn't work when they were written) and experienced # no problems. # Even so, further refactoring (which among other things would mitigate this) # is desirable. (The ultimate issue is having PAM-specific methods on class # Atom, as opposed to on a PAM-specific subclass of class Atom; and having # that class Atom known directly to class Chunk.) [bruce 090119] from Numeric import dot from geometry.VQT import norm, V ##from foundation.state_constants import S_CHILDREN from utilities import debug_flags from utilities.debug import print_compact_stack from utilities.constants import Pl_STICKY_BOND_DIRECTION, MODEL_PAM5 from utilities.constants import average_value from model.bond_constants import DIRBOND_CHAIN_MIDDLE from model.bond_constants import DIRBOND_CHAIN_END from model.bond_constants import DIRBOND_NONE from model.bond_constants import DIRBOND_ERROR from model.bond_constants import find_bond from model.elements import Pl5 from model.global_model_changedicts import _changed_otherwise_Atoms from dna.model.pam3plus5_math import baseframe_abs_to_rel from dna.model.pam3plus5_math import baseframe_rel_to_abs from dna.model.pam3plus5_math import default_Pl_relative_position from dna.model.pam3plus5_math import default_Gv_relative_position from dna.model.pam3plus5_ops import Pl_pos_from_neighbor_PAM3plus5_data from dna.model.pam3plus5_ops import _f_baseframe_data_at_baseatom from dna.model.pam3plus5_ops import _f_find_new_ladder_location_of_baseatom from dna.model.pam3plus5_ops import kill_Pl_and_rebond_neighbors from dna.model.pam_conversion_mmp import Fake_Pl from dna.updater.dna_updater_prefs import legal_numbers_of_strand_neighbors_on_axis from dna.updater.fix_bond_directions import PROPOGATED_DNA_UPDATER_ERROR from dna.updater.fix_bond_directions import _f_detailed_dna_updater_error_string VALID_ELEMENTS_FOR_DNABASENAME = ('Ss5', 'Ss3', 'Sh5', 'Se3', 'Sj5', 'Sj3',) # TODO: use a boolean element attribute instead. # review: not the same as role == 'strand'... but is it if we exclude Pl? def make_vec_perp_to_vec(vec1, vec2): #bruce 080405 # todo: refile, or find an existing func the same """ return a modified copy of vec1 with its component parallel to vec2 subtracted out. """ remove_this_direction = norm(vec2) return vec1 - dot(vec1, remove_this_direction) * remove_this_direction #k _GV5_DATA_INDEX = 2 # == class PAM_Atom_methods: """ Intended only as a pre-mixin for class Atom. """ # Someday these methods will be refactored into subclasses of Atom. # Then those subclasses can be moved inside the dna package. # (Maybe this module could be moved there right now? Not easily, # regarding package import conventions/worries.) # === # # The Atom methods below this point might be moved into subclasses for # specific types of atoms. # # (Some of these methods might need trivial default defs on class Atom # until old code is fully revised to only call them on the subclasses.) # # Several general methods which remain in class Atom # also have special cases that might be # revised to be in subclass methods that extend them. These include: # # drawing_color # _draw_atom_style # draw_atom_sphere # draw_wirespheres # max_pixel_radius # writemmp # readmmp_info_atom_setitem # getInformationString # # (But some of these might be purely graphical, perhaps usable by more than # one subclass, and might thus remain in the superclass, or in a separately # refactored Atom drawing controller class.) # # [bruce 071113 comment, and reordered existing methods to move these here] # # === # default values of instance variables (some not needed): _dna_updater__error = "" # intentionally not undoable/copyable # this is now higher up, with an undo _s_attr decl: ## _dnaBaseName = "" #bruce 080319 revised # note: _dnaStrandId_for_generators is set when first demanded, or can be # explicitly set using setDnaStrandId_for_generators(). _fake_Pls = None # see comments where used _DnaLadder__ladder = None # for private use by class DnaLadder # note: not named with _f_, so I can use the pseudo-name-mangling # convention to indicate ownership by objects of a different class # [bruce 080413 added class definition, revised using code] # not: _s_attr__nonlive_Pls = S_CHILDREN # for default value assignments of _PAM3plus5_Pl_Gv_data and # _f_Pl_posn_is_definitive, and comments about them, see class Atom # (which inherits this class); they are only used by methods in this # class, except for a few foundational methods in class Atom # (for copy and soon for mmp save/load), but since it uses them # at all, we define them there. [bruce 080523] # # _PAM3plus5_Pl_Gv_data = ... # # _f_Pl_posn_is_definitive = ... # == methods for either strand or axis PAM atoms def dna_updater_error_string(self, include_propogated_error_details = True, newline = '\n' ): #bruce 080206; 080214 also covers check_bond_geometry ### REVIEW: integrate with bad_valence etc """ Return "" if self has no dna updater error (recorded by the dna updater in the private attribute self._dna_updater__error), or an error string if it does. By default, the error string is expanded to show the source of propogated errors from elsewhere in self's basepair (assuming the updater has gotten through the step of propogating them, which it does immediately after assigning/updating all the direct per-atom error strings). Any newlines in the error string (which only occur if it was expanded) are replaced with the optional newline argument (by default, left unchanged). @param include_propogated_error_details: see main docstring @type include_propogated_error_details: boolean @param newline: see main docstring @type newline: string @see: helper functions like _atom_set_dna_updater_error which should eventually become friend methods in a subclass of Atom. """ if self.check_bond_geometry(): # bruce 080214; initial kluge -- # if this happens, ignore the rest (non-ideal) return self.check_bond_geometry() # (redoing this is fast) if not self._dna_updater__error: # report errors from self's DnaLadder, if it has one ladder = getattr(self.molecule, 'ladder', None) # kluge for .ladder if ladder and ladder.error: return ladder.error return "" # otherwise report error from self res = self._dna_updater__error if include_propogated_error_details and \ res == PROPOGATED_DNA_UPDATER_ERROR: res = _f_detailed_dna_updater_error_string(self) res = res.replace('\n', newline) # probably only needed in then clause return res def _pam_atom_cmenu_entries(self): #bruce 080401 """ Return a menu_spec list of context menu entries specific to self being a PAM atom, or None. """ assert self.element.pam ladder = self.molecule.ladder res = [] if ladder: dnaladder_menu_spec = ladder.dnaladder_menu_spec(self) if dnaladder_menu_spec: if res: # never happens yet res.append(None) res.extend(dnaladder_menu_spec) # more? pass return res def reposition_baggage_using_DnaLadder(self, dont_use_ladder = False, only_bondpoints = False ): #bruce 080404; added options, bruce 080501 """ Reposition self's bondpoints (or other monovalent "baggage" atoms if any), making use of structural info from self.molecule.ladder. @note: as of late 080405, this doesn't yet actually make use of self.molecule.ladder. (Perhaps it could be optimized by making it do so?) @note: since we don't expect any baggage except bondpoints on PAM atoms, we don't bother checking for that, even though, if this did ever happen, it might be arbitrary which baggage element ended up at what position. This can easily be fixed if necessary. @warning: by default, it's only safe to call this when self.molecule.ladder is correct (including all its chunks and rails -- no need for its parent Group structure or markers), which if the dna updater is running means after self's new ladder's chunks were remade. @param dont_use_ladder: if true, don't assume self.molecule.ladder is correct. (As of 080501, this option has no effect, since the current implem doesn't use self.molecule.ladder or anything else fixed by the dna updater, except possibly bond directions on open bonds.) @type dont_use_ladder: boolean @param only_bondpoints: if true, only reposition bondpoints, not other baggage. @type only_bondpoints: boolean """ # And, if it turns out this ever needs to look inside # neighbor atom dnaladders (not in the same base pair), # we'll need to revise the dna updater's indirect caller # to call it in a separate loop over ladders than the one # that calls remake_chunks on all of the new ladders. # Note: I don't think there's any issue of the changes we do here # causing an infinite repeat (or even a single repeat) of the # dna updater -- we reset the flag that makes it call us, # and moving bondpoints (or real atoms) doesn't count as # changing the atoms for purposes of dna updater, and even # if it did, the updater ignores new changes from this step. # If we ever kill and remake bondpoints here, then we'll # need to also reset the flag at the end, but even if we forget, # it won't cause an immediate rerun of the dna updater # (due to its ignoring the changes from this step). self._f_dna_updater_should_reposition_baggage = False # even in case of exceptions (also simplifies early return) del dont_use_ladder # correct, since present implem never uses it baggage, others = self.baggage_and_other_neighbors() if only_bondpoints: # bruce 080501 for n in baggage[:]: if not n.is_singlet(): baggage.remove(n) others.append(n) continue pass if not baggage: return # optimization and for safety; might simplify following code # Notes: # # - If baggage might not be all bondpoints, we might want to filter # it here and only look at the bondpoints. (See docstring.) # [Now this is done by the only_bondpoints option. [bruce 080501]] # # - I'm assuming that Ax, Pl, Ss neighbors can never be baggage. # This depends on their having correct valence, since the test # used by baggage_and_other_neighbors is len(bonds), not valence. # how to do it depends on type of PAM element: if self.element.role == 'axis': # Ax3, Ax5, or Gv5 # which real neighbors do we have? # (depends on ladder len1, single strand or duplex) # ... # short term important case: we have one bondpoint # along axis, make it opposite the other axis bond, # and maybe we also have another "strand bondpoint". strand_neighbors = [] axis_neighbors = [] for other in others: # would also work if baggage was in this loop role = other.element.role if role == 'strand': strand_neighbors += [other] elif role == 'axis': axis_neighbors += [other] # other roles are possible too, but we can ignore them for now # (unpaired-base(?), None) # (in future we'll need to count unpaired-bases to understand # how many axis bondpoints are missing) ### TODO continue if len(axis_neighbors) == 1: # move a bondpoint to the opposite position from this one # (for now, just move the already-closest one) selfpos = self.posn() axisvec = axis_neighbors[0].posn() - selfpos newpos = selfpos - axisvec # correct only in direction, not distance moved_this_one = self.move_closest_baggage_to( newpos, baggage, remove = True, min_bond_length = 3.180 / 2 ) # this first corrects newpos for distance (since no option # prevents that) (an option does set the minimum distance # -- after 080405 fix in _compute_bond_params this is no # longer needed, but remains as a precaution) # (doing it first is best for finding closest one) # (someday we might pass bond order or direction to help # choose? then bond order would affect distance, perhaps) # passing baggage means only consider moving something # in that list; # remove = True means remove the moved one from that list; # return value is the one moved, or None if none was found # to move. if not moved_this_one: return # optim? pass ### todo: also fix bondpoints meant to go to strand atoms pass elif self.element.role == 'strand': # might be Pl5 or Ss5 or Ss3 if self.element.symbol == 'Ss3': ### TODO: split this section into its own method # if we have one real strand bond, make the open directional # bond opposite it (assume we have correct structure of # directional bonds with direction set -- one in, one out) strand_neighbors = [] axis_neighbors = [] for other in others: role = other.element.role if role == 'strand': strand_neighbors += [other] elif role == 'axis': axis_neighbors += [other] continue honorary_strand_neighbor = None # might be set below reference_strand_neighbor = None # might be set below if len(strand_neighbors) == 1: reference_strand_neighbor = strand_neighbors[0] elif not strand_neighbors and not axis_neighbors: # totally bare (e.g. just deposited) reference_strand_neighbor = self.next_atom_in_bond_direction(1) # should exist, but no need to check here if reference_strand_neighbor is not None: direction_to_it = find_bond(self, reference_strand_neighbor).bond_direction_from(self) moveme = self.next_atom_in_bond_direction( - direction_to_it ) if moveme is not None and moveme in baggage: honorary_strand_neighbor = moveme selfpos = self.posn() strandvec = reference_strand_neighbor.posn() - selfpos newpos = selfpos - strandvec # correct only in direction, not distance moved_this_one = self.move_closest_baggage_to( newpos, [moveme] ) if moved_this_one is not moveme: # should never happen print "error: moved_this_one %r is not moveme %r" % \ (moved_this_one, moveme) pass pass if len(axis_neighbors) == 0: # see if we can figure out which baggage should point towards axis candidates = list(baggage) if honorary_strand_neighbor is not None: # it's in baggage, by construction above candidates.remove(honorary_strand_neighbor) if reference_strand_neighbor is not None \ and reference_strand_neighbor in candidates: candidates.remove(reference_strand_neighbor) if len(candidates) != 1: # I don't know if this ever happens (didn't see it in test, # can't recall if I thought it should be possible) ## print " for %r: candidates empty or ambiguous:" % self, candidates pass else: # this is the honorary axis neighbor; we'll repoint it. honorary_axis_neighbor = candidates[0] # but which way should it point? just "not along the strand"? # parallel to the next strand atom's? that makes sense... # we'll start with that if we have it (otherwise with # whatever it already is), # then correct it to be perp to our strand. axisvecs_from_strand_neighbors = [] for sn in strand_neighbors: # real ones only its_axisbond = None # might be set below its_rung_bonds = [b for b in sn.bonds if b.is_rung_bond() ] if len(its_rung_bonds) == 1: its_axisbond = its_rung_bonds[0] elif not its_rung_bonds: its_runglike_bonds = \ [b for b in sn.bonds if not b.bond_direction_from(sn) ] # might be rung bonds, might be open bonds with # no direction set if len(its_runglike_bonds) == 1: its_axisbond = its_runglike_bonds[0] if its_axisbond is not None: # that gives us the direction to start with axisvec_sn = its_axisbond.spatial_direction_from(sn) # but correct it to be perpendicular to our bond to sn axisvec_sn = make_vec_perp_to_vec( axisvec_sn, sn.posn() - self.posn() ) axisvecs_from_strand_neighbors += [axisvec_sn] continue axisvec = None # might be set below if axisvecs_from_strand_neighbors: axisvec = average_value(axisvecs_from_strand_neighbors) if axisvec is None: # i.e. no strand_neighbors axisvec = honorary_axis_neighbor.posn() - self.posn() # this value (which it has now) would not change it # print " for %r: axisvec %r starts as" % (self, axisvec,) # now remove the component parallel to the presumed # strand bonds' average direction presumed_strand_baggage = filter( None, [reference_strand_neighbor, honorary_strand_neighbor] ) vecs = [norm(find_bond(self, sn).bond_direction_vector()) for sn in presumed_strand_baggage] if vecs: strand_direction = average_value(vecs) axisvec = make_vec_perp_to_vec( axisvec, strand_direction ) pass assert axisvec is not None self.move_closest_baggage_to( self.posn() + axisvec, [honorary_axis_neighbor] ) # assume it worked (since all candidates were in baggage) pass pass pass pass # (no other cases are possible yet, at least when called by dna updater) # (flag was reset above, so we're done) return # == end of methods for either strand or axis PAM atoms # == PAM Pl atom methods def Pl_preferred_Ss_neighbor(self): # bruce 080118, revised 080401 """ For self a Pl atom (PAM5), return the Ss neighbor it prefers to be grouped with (e.g. in the same chunk, or when one of its bonds is broken) if it has a choice. (If it has no Ss atom, print bug warning and return None.) @warning: the bond direction constant hardcoded into this method is an ARBITRARY GUESS as of 080118. Also it ought to be defined in some dna-related constants file (once this method is moved to a dna-related subclass of Atom). """ assert self.element is Pl5 candidates = [ # note: these might be None, or conceivably a non-Ss atom self.next_atom_in_bond_direction( Pl_STICKY_BOND_DIRECTION), self.next_atom_in_bond_direction( - Pl_STICKY_BOND_DIRECTION) ] candidates = [c for c in candidates if c is not None and \ c.element.symbol.startswith("Ss") # KLUGE, matches Ss3 or Ss5 ] # note: this cond excludes X (good), Pl (bug if happens, but good). # It also excludes Sj and Hp (bad), but is only used from dna updater # so that won't be an issue. Non-kluge variant would test for # "a strand base atom". ## if debug_pref("DNA: Pl5 stick with PAM5 over PAM3 chunk, " \ ## "regardless of bond direction?", ...): if 0: # see if this caused my last bridging Pl bug, bruce 080413 330pm PT: candidates_PAM5 = [c for c in candidates if c.element.pam == MODEL_PAM5] # Try these first, so we prefer Ss5 over Ss3 if both are present, # regardless of bond direction. [bruce 080401] candidates = candidates_PAM5 + candidates ## for candidate in candidates: ## if ...: ## return candidate # all necessary tests were done above -- just return first one, # if any are there if candidates: return candidates[0] print "bug: Pl with no Ss: %r" % self # only a true statement (that this is a bug) when dna updater # is enabled, but that's ok since we're only used then return None def _f_Pl_finish_converting_if_needed(self): """ [friend method for dna updater] Assume self is a Pl5 atom between two Ss3 or Ss5 atoms (or between one such atom and a bondpoint), in the same or different DnaLadders, WHICH MAY NOT HAVE YET REMADE THEIR CHUNKS (i.e. which may differ from atom.molecule.ladder for their atoms, if that even exists), which have finished doing a pam conversion or decided not to or didn't need to (i.e. which are in their proper post-conversion choice of model), and that self has proper directional bonds. Figure out whether self should continue to exist. (This is true iff either neighbor is a PAM5 atom, presumably Ss5.) If not, kill self and directly bond its neighbors, also recording its position on the neighbors which are Ss3 or Ss5 if its position is definitive (if it's not, it means this already happened -- maybe not possible, not sure). (This won't be called twice on self; assert that by asserting self is not killed.) If so, ensure self's position is definitive, which means, if it's not, make it so by setting it from the "+5 data" on self's Ss neighbors intended for self, and removing that data. (This method can be called twice on self in this case; self's position would typically be non-definitive the first time and (due to our side effect that time) definitive the second time.) """ assert not self.killed() sn = self.strand_neighbors() # doesn't include bondpoints pam5_neighbors = [n for n in sn if n.element.pam == MODEL_PAM5] should_exist = not not pam5_neighbors if not should_exist: # make sure it's not due to being called when we have no strand # neighbors (bare Pl) (this method is not legal to call then) assert sn, "error: %r._f_Pl_finish_converting_if_needed() " \ "illegal since no strand neighbors" % self if self._f_Pl_posn_is_definitive: self._f_Pl_store_position_into_Ss3plus5_data() # sets flag to false if debug_flags.DEBUG_DNA_UPDATER_VERBOSE: # 080413 print "fyi: stored pos of %r, "\ "will kill it and rebond neighbors" % self kill_Pl_and_rebond_neighbors(self) ###REVIEW: does killing self mess up its chain or its DnaLadderRailChunk? # (when called from dna updater, those are already invalid, they're # not the new ones we worry about -- UNLESS self was old and untouched # except by this corner Pl. That issue is a predicted unresolved bug # as of 080412 11:54pm PT. #### @@@@) else: if not self._f_Pl_posn_is_definitive: self._f_Pl_set_position_from_Ss3plus5_data() # sets flag to true if debug_flags.DEBUG_DNA_UPDATER_VERBOSE: # 080413 print "fyi: fixed pos of %r, keeping it" % self return def _f_Pl_set_position_from_Ss3plus5_data(self): #bruce 080402 """ [friend method for dna updater] Assume self is a Pl5 atom between two Ss3 or Ss5 atoms, in the same or different DnaLadders, WHICH MAY NOT HAVE YET REMADE THEIR CHUNKS (i.e. which may differ from atom.molecule.ladder for their atoms, if that even exists), and that self has proper directional bonds, and that self's current position is meaningless or out of date (and should be ignored). Set self's position using the "PAM3plus5 Pl-position data" (if any) stored on its neighbors, and remove that data from its neighbors. (If that data is not present, use reasonable defaults.) (Note that the analogous method on class Fake_Pl would *not* remove that data from its neighbors.) Assume that self's neighbors' DnaLadders (which, like self's, may not yet have remade their chunks) have up-to-date stored PAM basepair baseframe data to help do the necessary coordinate conversions. (This might not be checked. Using out of date data would cause hard-to-notice bugs.) No effect on other "PAM3plus5 data" (if any) on those neighbors (e.g. Gv-position data). """ assert not self._f_Pl_posn_is_definitive # note: the following function is also called by class Fake_Pl abspos = Pl_pos_from_neighbor_PAM3plus5_data( self.bond_directions_to_neighbors(), remove_data_from_neighbors = True ) # print "_f_Pl_set_position_from_Ss3plus5_data will set %r " \ # "on %r, now at %r" % (abspos, self, self.posn()) if abspos is None: print "bug: _f_Pl_set_position_from_Ss3plus5_data " \ "can't set %r on %r, now at %r" % \ (abspos, self, self.posn()) else: self.setposn(abspos) del self._f_Pl_posn_is_definitive # like doing self._f_Pl_posn_is_definitive = True, # but expose class default value to save RAM return def _f_Pl_store_position_into_Ss3plus5_data(self): #bruce 080402 """ [friend method for dna updater] Assume self is a Pl5 atom between two Ss3 or Ss5 atoms, in the same or different newly made DnaLadders -- WHICH MAY NOT HAVE YET REMADE THEIR CHUNKS (i.e. which may differ from atom. molecule.ladder for their atoms, if that even exists) -- and that self has proper directional bonds, and that self's current position is definitive (i.e. that any "PAM3plus5 Pl-position data" on self's neighbors should be ignored, and can be entirely replaced). Set the "PAM3plus5 Pl-position data" on self's Ss3 or Ss5 neighbors to correspond to self's current position. (This means that self will soon be killed, with its neighbors rebonded, and transmuted to Ss3 if necessary, but all that is up to the caller.) Assume that self's neighbors' DnaLadders have up-to-date stored PAM basepair baseframe data to help do the necessary coordinate conversions. (This might not be checked. Using out of date data would cause hard-to-notice bugs. Note that the global formerly called ladders_dict only assures that the baseframes are set at the ends.) No effect on other "PAM3plus5 data" (if any) on those neighbors (e.g. Gv-position data). @see: _f_Gv_store_position_into_Ss3plus5_data """ assert self.element is Pl5 assert self._f_Pl_posn_is_definitive # note: unlike with _f_Pl_set_position_from_Ss3plus5_data, # this method has no analogous method used during writemmp-only # PAM conversion -- either we're saving as PAM5 (moving data # onto Pl, not off of it), or as pure PAM3 (no Pl data at all). # PAM3+5 itself has no mmp format. pos = self.posn() for direction_to, ss in self.bond_directions_to_neighbors(): if ss.element.role == 'strand': # (avoid bondpoints or (erroneous) non-PAM or axis atoms) ss._f_store_PAM3plus5_Pl_abs_position( - direction_to, pos) continue self._f_Pl_posn_is_definitive = False return def _f_Gv_store_position_into_Ss3plus5_data(self): # todo: refile within class #bruce 080409, modified from _f_Pl_store_position_into_Ss3plus5_data """ [friend method for dna updater] Assume self is (or very recently was transmuted from??) a Gv5 atom axially between two Ss3 or Ss5 atoms (connected by rung bonds, in the same base pair), in the same DnaLadder (valid and error-free), and that self's current position is definitive (i.e. that any "PAM3plus5 Gv-position data" on self's neighbors should be ignored, and can be entirely replaced), as is true for all live Gv's except *very* transiently when they are created or removed during PAM conversion. Set the "PAM3plus5 Gv-position data" on self's Ss3 or Ss5 neighbors to correspond to self's current position. (This means that self will soon be moved or transmuted (or perhaps just has been??), with its neighbors also transmuted to Ss3 if necessary, but all that is up to the caller.) Assume that self's DnaLadder -- WHICH MAY NOT HAVE YET REMADE ITS CHUNKS (i.e. which may differ from atom.molecule.ladder for its atoms, if that even exists) -- has up-to-date stored PAM basepair baseframe data to help do the necessary coordinate conversions. (This might not be checked. Using out of date data would cause hard-to-notice bugs. Note that the global formerly called ladders_dict only assures that the baseframes are set for the basepairs at the ends of a ladder.) No effect on other "PAM3plus5 data" (if any) on self's neighbors (e.g. Pl-position data). @see: _f_Pl_store_position_into_Ss3plus5_data """ assert self.element.role == 'axis' pos = self.posn() sn = self.strand_neighbors() if len(sn) != 2: print "bug? %r has unexpected number of strand_neighbors %r" % (self, sn) # since ghost bases should be added to bring this up to 2 for ss in sn: assert ss.element.role == 'strand' # (avoid bondpoints or (erroneous) non-PAM or axis atoms) ss._f_store_PAM3plus5_Gv_abs_position( pos) continue return # == end of PAM Pl atom methods # == PAM strand atom methods (some are more specific than that, # e.g. not on Pl or only on Pl, but these are not yet divided up # except that some methods or attrs have Pl or Ss in their names, # and some of those have been moved into the Pl atom methods section above) def _writemmp_PAM3plus5_Pl_Gv_data( self, mapping): #bruce 080523 """ Write the mmp info record (or similar extra data) which represents a non-default value of self._PAM3plus5_Pl_Gv_data. """ vecs = self._PAM3plus5_Pl_Gv_data assert vecs is not None # should be a list of 3 standard "atom position vectors" # (they are relative rather than absolute, but can still # be written in the same manner as atom positions) record = "info atom +5data =" # will be extended below for vec in vecs: if vec is None: vecstring = " ()" # (guessing this is easier to read than None) else: xs, ys, zs = mapping.encode_atom_coordinates( vec ) vecstring = " (%s, %s, %s)" % (xs, ys, zs) # note: 4 of these chars could be left out if we wanted to # optimize the format record += vecstring record += "\n" mapping.write( record) return def _readmmp_3plus5_data(self, key, val, interp): #bruce 080523 """ Read the value part of the mmp info record which represents a non-default value of self._PAM3plus5_Pl_Gv_data. Raise exceptions on errors. @param val: @type val: string """ del key val = val.replace("()", "(None, None, None)") # kluge, for convenience for ignore in "(),": val = val.replace(ignore, " ") # ditto val = val.strip() coord_strings = val.split() assert len(coord_strings) == 9, "wrong length: %r" % (coord_strings,) def decode(coord_string): if coord_string == "None": return None return interp.decode_atom_coordinate(coord_string) coords = map( decode, coord_strings) # each element is a float or None def decode_coords( x, y, z ): if x is None or y is None or z is None: return None return V(x, y, z) x1, y1, z1, x2, y2, z2, x3, y3, z3 = coords d1 = decode_coords(x1, y1, z1) d2 = decode_coords(x2, y2, z2) d3 = decode_coords(x3, y3, z3) self._PAM3plus5_Pl_Gv_data = [d1, d2, d3] return def setDnaBaseName(self, dnaBaseName): # Mark 2007-08-16 #bruce 080319 revised, mainly to support undo/copy """ Set the Dna base letter. This is only valid for PAM atoms in the list VALID_ELEMENTS_FOR_DNABASENAME, i.e. strand sugar atoms, presently defined as ('Ss5', 'Ss3', 'Sh5', 'Se3', 'Sj5', 'Sj3'). @param dnaBaseName: The DNA base letter. This must be "" or one letter (this requirement is only partially enforced here). @type dnaBaseName: str @raise: AssertionError, if self is not a strand sugar atom or if we notice the value is not permitted. """ assert type(dnaBaseName) == type("") #bruce 080326 assert self.element.symbol in VALID_ELEMENTS_FOR_DNABASENAME, \ "Can only assign dnaBaseNames to PAM strand sugar atoms. " \ "Attempting to assign dnaBaseName %r to %r of element %r." \ % (dnaBaseName, self, self.element.name) if dnaBaseName == 'X': dnaBaseName = "" assert len(dnaBaseName) <= 1, \ "dnaBaseName must be empty or a single letter, not %r" % \ (dnaBaseName,) #bruce 080326 # todo: check that it's a letter # maybe: canonicalize the case; if not, make sure it doesn't matter if self._dnaBaseName != dnaBaseName: self._dnaBaseName = dnaBaseName _changed_otherwise_Atoms[self.key] = self #bruce 080319 # todo: in certain display styles (which display dna base letters), # call self.molecule.changeapp(0) self.changed() # bruce 080319 return def getDnaBaseName(self): """ Returns the value of attr I{_dnaBaseName}. @return: The DNA base name, or None if the attr I{_dnaBaseName} does not exist. @rtype: str """ # Note: bruce 080311 revised all direct accesses of atom._dnaBaseName # to go through this method, and renamed it to be private. # (I also stopped storing it in mmp file when value is X, unassigned. # This is desirable to save space and speed up save and load. # If some users of this method want the value on certain atoms # to always exist, this method should be revised to look at # the element type and return 'X' instead of "" for appropriate # elements.) #UPDATE: The following is now revised per above comment. i.e. if it #can't find a baseName for a valid element symbol (see list below) #it makes the dnaBaseName as 'X' (unassigned base). This is useful #while reading in the strand sequence. # See DnaStrand.getStrandSequence() for an example. --Ninad 2008-03-12 valid_element_symbols = VALID_ELEMENTS_FOR_DNABASENAME allowed_on_this_element = (self.element.symbol in valid_element_symbols) baseNameString = self.__dict__.get('_dnaBaseName', "") # modified below if not allowed_on_this_element: #bruce 080319 change: enforce this never existing on disallowed # element (probably just a clarification, since setting code was # probably already enforcing this) baseNameString = "" else: if not baseNameString: baseNameString = 'X' # unassigned base pass if len(baseNameString) > 1: #bruce 080326 precaution, should never happen baseNameString = "" return baseNameString def get_strand_atom_mate(self): """ Returns the 'mate' of this dna pseudo atom (the atom on another strand to which this atom is "base-paired"), or None if it has no mate. @return: B{Atom} (PAM atom) """ #Note: This method was created to support assignment of strand sequence #to strand chunks. This should be moved to dna_model and #can be revised further. -- Ninad 2008-01-14 # (I revised it slightly, to support all kinds of single stranded # regions. -- Bruce 080117) if self.element.role != 'strand': # REVIEW: return None, or raise exception? [bruce 080117 Q] return None #First find the connected axis neighbor axisAtom = self.axis_neighbor() if axisAtom is None: # single stranded region without Ax; no mate return None #Now find the strand atoms connected to this axis atom strandAtoms = axisAtom.strand_neighbors() #... and we want the mate atom of self for atm in strandAtoms: if atm is not self: return atm # if we didn't return above, there is no mate # (single stranded region with Ax) return None def setDnaStrandId_for_generators(self, dnaStrandId_for_generators): # Mark 070904 """ Set the Dna strand name. This is only valid for PAM atoms in the list 'Se3', 'Pe5', 'Pl5' (all deprecated when the dna updater is active). @param dnaStrandId_for_generators: The DNA strand id used by the dna generator @type dnaStrandId_for_generators: str @raise: AssertionError if self is not a Se3 or Pe5 or Pl5 atom. @see: self.getDnaStrandId_for_generators() for more comments. """ # Note: this (and probably its calls) needs revision # for the dna data model. Ultimately its only use will be # to help when reading pre-data-model mmp files. Presently # it's only called when reading "info atom dnaStrandName" # records. Those might be saved on the wrong atomtypes # by current dna updater code, but the caller tolerates # exceptions here (but complains using a history summary). # [bruce 080225/080311 comment] assert self.element.symbol in ('Se3', 'Pe5', 'Pl5'), \ "Can only assign dnaStrandNames to Se3, Pe5, or Pl5 (PAM) atoms. " \ "Attempting to assign dnaStrandName %r to %r of element %r." \ % (dnaStrandId_for_generators, self, self.element.name) # Make sure dnaStrandId_for_generators has all valid characters. #@ Need to allow digits and letters. Mark 2007-09-04 # ## for c in dnaStrandId_for_generators: ## if not c in string.letters: ## assert 0, "Strand id for generatos %r has an invalid " \ ## "character (%r)." % \ ## (dnaStrandId_for_generators, c) self._dnaStrandId_for_generators = dnaStrandId_for_generators def getDnaStrand(self): """ Returns the DnaStrand(group) node to which this atom belongs to. Returns None if there isn't a parent DnaStrand group. @see: Chunk.getDnaStrand() which is used here. """ chunk = self.molecule if chunk and not chunk.isNullChunk(): return chunk.getDnaStrand() return None def getDnaSegment(self): """ Returns the DnaSegment(group) node to which this atom belongs to. Returns None if there isn't a parent DnaSegment group. @see: Chunk.getDnaSegment() which is used here. """ chunk = self.molecule if chunk and not chunk.isNullChunk(): return chunk.getDnaSegment() return None def getDnaStrandId_for_generators(self): """ Returns the value of attr I{_dnaStrandId_for_generators}, or "" if it doesn't exist. @return: The DNA strand id used by dna generator, or "" if the attr I{_dnaStrandId_for_generators} does not exist. @rtype: str """ # Note: this (and probably its calls) need revision for the # dna data model. [bruce 080225/080311 comment] # Note: bruce 080311 revised all direct accesses of # atom._dnaStrandId_for_generators to go through this method, and # renamed it to make it private. #UPDATE renamed previous attr dnastrandName to # dnaStrandId_for_generators based on a discussion with Bruce. #It was renamed to this new name #in order to avoid confusion with the dna strand name which can #be acceesed as node.name. The new name 'dnaStrandId_for_generators' #and this comment makes it clear enough that this will only be used #by generators ... i.e. while creating a duplex from scratch by reading #in the standard mmp files in cad/plugins/PAM*/*.mmp. See #DnaDuplex._regroup to see how this is used. -- Ninad 2008-03-12 return self.__dict__.get('_dnaStrandId_for_generators', "") def directional_bond_chain_status(self): # bruce 071016, revised 080212 """ Return a tuple (statuscode, bond1, bond2) indicating the status of self's bonds with respect to chains of directional bonds. The possible return values are: DIRBOND_CHAIN_MIDDLE, bond1, bond2 -- inside a chain involving these two bonds (note: there might be other directional bonds (open bonds) which should be ignored) DIRBOND_CHAIN_END, bond1, None -- at the end of a chain, which ends with this bond DIRBOND_NONE, None, None -- not in a chain DIRBOND_ERROR, None, None -- local error in directional bond structure, so caller should treat this as not being in a chain Note that all we consider is whether a bond is directional, not whether a direction is actually set (except for atoms with more than one open bond, to disambiguate bare chain ends). Similarly, when two bonds have directions set, we don't consider whether their directions are consistent. (One reason is that we need to grow a chain that covers both bonds so the user can set the entire chain's direction. REVIEW: better to stop at such errors, so only a consistent part of the chain would be changed at once??) But if self is monovalent (e.g. a bondpoint) and its neighbor is not, we consider its neighbor's status in determining its own. Note that when drawing a bond, each of its atoms can have an almost-independent directional_bond_chain_status (due to the possibility of erroneous structures), so both of its atoms need their directional_bond_chain_status checked for errors. """ # note: I think this implem is correct with or without open bonds # being directional [bruce 071016] [revised 080212 to make more true] if not self.element.bonds_can_be_directional: # optimization return DIRBOND_NONE, None, None if len(self.bonds) == 1: # Special cases. This then-clause covers all situations for # self being monovalent, except a few that I think never happen. # (But if they do, fall through to general case below.) bond = self.bonds[0] neighbor = bond.other(self) if len(neighbor.bonds) > 1: # Monovalents defer to non-monovalent neighbors # (note: this applies to bondpoints (after mark 071014 changes) # or to "strand termination atoms".) # Those neighbors may decide bond is not in their chain due # to their other bonds. statuscode, bond1, bond2 = neighbor.directional_bond_chain_status() if statuscode == DIRBOND_NONE or statuscode == DIRBOND_ERROR: return statuscode, None, None elif statuscode == DIRBOND_CHAIN_MIDDLE: # it matters whether we're in the neighbor's chain if bond is bond1 or bond is bond2: return DIRBOND_CHAIN_END, bond, None else: # we're attached to the chain but not in it. # REVIEW: return DIRBOND_ERROR in some cases?? # (For example, when an atom has ._dna_updater__error # set on it?) Note that for open bonds on bare # strands, this happens routinely. return DIRBOND_NONE, None, None # DIRBOND_ERROR? pass elif statuscode == DIRBOND_CHAIN_END: # it matters whether the neighbor's chain includes us. # (for bare strand ends with two open bonds, this is up # to that neighbor even if arbitrary, as of 080212) if bond is bond1: return DIRBOND_CHAIN_END, bond, None else: return DIRBOND_NONE, None, None # DIRBOND_ERROR? pass else: assert 0, "%r got unrecognized statuscode %r from " \ "%r.directional_bond_chain_status" % \ (self, statuscode, neighbor) return DIRBOND_ERROR, None, None pass else: # two connected monovalent atoms, one maybe-directional # bond... for now, proceed with no special case. If this ever # happens, review it. (e.g. we might consider it an error.) pass pass dirbonds = self.directional_bonds() num = len(dirbonds) if num == 2: # it doesn't matter how many of them are open bonds, in this case return DIRBOND_CHAIN_MIDDLE, dirbonds[0], dirbonds[1] elif num == 1: # whether or not it's an open bond return DIRBOND_CHAIN_END, dirbonds[0], None elif num == 0: return DIRBOND_NONE, None, None else: # more than 2 -- see if some of them can be ignored # [behavior at ends of bare strands was revised 080212] real_dirbonds = filter( lambda bond: not bond.is_open_bond(), dirbonds ) num_real = len(real_dirbonds) if num_real == 2: # This works around the situation in which a single strand # (not at the end) has open bonds where axis atoms ought to # be, by ignoring those open bonds. (Note that they count as # directional, even though if they became real they would not # be directional since one atom would be Ax.) # POSSIBLE BUG: the propogate caller can reach this, if it can # start on an ignored open bond. Maybe we should require that # it is not offered in the UI in this case, by having it check # this method before deciding. ### REVIEW return DIRBOND_CHAIN_MIDDLE, real_dirbonds[0], real_dirbonds[1] else: # we need to look at bond directions actually set # (on open bonds anyway), to decide what to do. # # WARNING: this happens routinely at the end of a "bare strand" # (no axis atoms), since it has one real and two open bonds, # all directional. # # We might fix this by: # - making that situation never occur [unlikely] # - making bonds know whether they're directional even if # they're open (bond subclass) # - atom subclass for bondpoints # - notice whether a direction is set on just one open bond # [done below, 080212]; # - construct open bonds on directional elements so the right # number are set [dna updater does that now, but a user bond # dir change can make it false before calling us] # - (or preferably, marked as directional bonds without a # direction being set) # REVIEW: return an error message string? # [bruce 071112, 080212 updated comment] if num_real < 2: # new code (bugfix), bruce 080212 -- look at bonds with # direction set (assume dna updater has made the local # structure make sense) (only works if cmenu won't set dir # on open bond to make 3 dirs set ### FIX) # kluge (bug): assume all real bonds have dir set. # Easily fixable in the lambda if necessary. dirbonds_set = filter( lambda bond: bond._direction, dirbonds ) #k non-private method? if len(dirbonds_set) == 2: return DIRBOND_CHAIN_MIDDLE, dirbonds_set[0], dirbonds_set[1] if debug_flags.atom_debug: print "DIRBOND_ERROR noticed on", self return DIRBOND_ERROR, None, None pass def isThreePrimeEndAtom(self): """ Returns True if self is a three prime end atom of a DnaStrand. (This means the last non-bondpoint atom in the 5'->3' direction.) """ if self.is_singlet(): return False if not self.element.bonds_can_be_directional: return False # optimization nextatom = self.next_atom_in_bond_direction(1) if nextatom is None or nextatom.is_singlet(): return True # self is an end atom return False def isFivePrimeEndAtom(self): """ Returns True if self is a five prime end atom of a DnaStrand. (This means the last non-bondpoint atom in the 3'->5' direction.) """ if self.is_singlet(): return False if not self.element.bonds_can_be_directional: return False # optimization nextatom = self.next_atom_in_bond_direction(-1) if nextatom is None or nextatom.is_singlet(): return True # self is an end atom return False def strand_end_bond(self): #bruce 070415, revised 071016 ### REVIEW: rename? """ For purposes of possibly drawing self as an arrowhead, determine whether self is on the end of a chain of directional bonds (regardless of whether they have an assigned direction). But if self is a bondpoint attached to a chain of directional real bonds, treat it as not part of a bond chain, even if it's directional. [REVIEW: is that wise, if it has a direction set (which is probably an error)?] @return: None, or the sole directional bond on self (if it might be correct to use that for drawing self as an arrowhead). TODO: need a more principled separation of responsibilities between self and caller re "whether it might be correct to draw self as an arrowhead" -- what exactly is it our job to determine? REVIEW: also return an error code, for drawing red arrowheads in the case of certain errors? """ if not self.element.bonds_can_be_directional: return None # optimization statuscode, bond1, bond2 = self.directional_bond_chain_status() if statuscode == DIRBOND_CHAIN_END: assert bond1 assert bond2 is None return bond1 else: return None pass def directional_bonds(self): #bruce 070415 """ Return a list of our directional bonds. Its length might be 0, 1, or 2, or in the case of erroneous structures [or some legal ones as of mark 071014 changes], 3 or more. """ ### REVIEW: should this remain as a separate method, now that its result # can't be used naively? return filter(lambda bond: bond.is_directional(), self.bonds) def bond_directions_are_set_and_consistent(self): #bruce 071204 # REVIEW uses - replace with self._dna_updater__error?? """ Does self (a strand atom, base or base linker) have exactly two bond directions set, not inconsistently? @note: still used, but in some ways superceded by dna updater and the error code it can set. """ count_plus, count_minus = 0, 0 # for all bonds for bond in self.bonds: dir = bond.bond_direction_from(self) if dir == 1: count_plus += 1 elif dir == -1: count_minus += 1 return (count_plus, count_minus) == (1, 1) def desired_new_real_bond_direction(self): #bruce 080213 """ Something is planning to make a new real directional bond involving self, and will modify self's open bonds and/or their bond directions, but not self's existing real bonds or their bond directions. What bond direction (away from self) should it give the new real bond? """ count_plus, count_minus = 0, 0 # for real bonds only for bond in self.bonds: if not bond.is_open_bond(): # (could optim, doesn't matter) dir = bond.bond_direction_from(self) if dir == 1: count_plus += 1 elif dir == -1: count_minus += 1 counts = (count_plus, count_minus) if counts == (1, 0): return -1 elif counts == (0, 1): return 1 else: # Usually or always an error given how we are called, # but let the caller worry about this. # (Non-error cases are conceivable, e.g. within a dna generator, # or if isolated single bases are being bonded by the user.) return 0 pass def fix_open_bond_directions(self, bondpoint, want_dir): #bruce 080213 """ Something is planning to make a new real directional bond involving self, and will give it the bond direction want_dir (measured away from self). If bondpoint is not None, it plans to make this bond using that bondpoint (usually removing it). Otherwise... which bondpoint will it remove, if any?? ###REVIEW CALLERS If possible and advisable, fix all our open bond directions to best fit this situation -- i.e.: * make the direction from self to bondpoint equal want_dir (if bondpoint is not None); * if want_dir is not 0, remove equal directions from other open bonds of self to make the resulting situation consistent (do this even if you have to pick one arbitrarily? yes for now); * if want_dir is 0, do nothing (don't move any direction set on bondpoint to some other open bond of self, because this only happens on error (due to how we are called) and we should do as little as possible here, letting dna updater and/or user see and fix the error). @note: it's ok for this method to be slow. """ debug = debug_flags.atom_debug if debug: print "debug fyi: fix_open_bond_directions%r" % \ ((self, bondpoint, want_dir),) if bondpoint: bondpoint_bond = bondpoint.bonds[0] # redundant: assert bond.other(bondpoint) is self bondpoint_bond.set_bond_direction_from( self, want_dir) else: bondpoint_bond = None # print this until I see whether & how this happens: msg = "not sure what fix_open_bond_directions%r " \ "should do since bondpoint is None" % \ ((self, bondpoint, want_dir),) # not sure, because we might want to deduct want_dir from the # desired total direction we need to achieve on the other # bonds, depending on what caller will do. (If caller will # pick one arbitrarily, we need to know which one that is # now!) if debug_flags.atom_debug: print_compact_stack(msg + ": ") else: print msg + " (set debug flag to see stack)" if not self.bond_directions_are_set_and_consistent(): if debug: print "debug fyi: fix_open_bond_directions%r " \ "needs to fix other open bonds" % \ ((self, bondpoint, want_dir),) # Note: not doing the following would cause undesirable messages, # including history messages from the dna updater, but AFAIK would # cause no other harm when the dna updater is turned on (since the # updater would fix the errors itself if this could have fixed # them). if want_dir: num_fixed = [0] fixable_open_bonds = filter( lambda bond: bond.is_open_bond() and bond is not bondpoint_bond and bond.bond_direction_from(self) != 0 , self.bonds ) def number_with_direction( bonds, dir1 ): """ return the number of bonds in bonds which have the given direction from self """ return len( filter( lambda bond: bond.bond_direction_from(self) == dir1, bonds )) def fix_one( bonds, dir1): "fix one of those bonds (by clearing its direction)" bond_to_fix = filter( lambda bond: bond.bond_direction_from(self) == dir1, bonds )[0] if debug: print "debug fyi: fix_open_bond_directions(%r) " \ "clearing %r of direction %r" % \ (self, bond_to_fix, dir1) bond_to_fix.clear_bond_direction() num_fixed[0] += 1 assert num_fixed[0] <= len(self.bonds) # protect against infloop for dir_to_fix in (1, -1): # or, only fix bonds of direction want_dir? while ( number_with_direction( self.bonds, dir_to_fix ) > 1 and number_with_direction( fixable_open_bonds, dir_to_fix ) > 0 ): fix_one( fixable_open_bonds, dir_to_fix ) continue # if this didn't fix everything, let the dna updater complain # (i.e. we don't need to ourselves) pass return # from fix_open_bond_directions def next_atom_in_bond_direction(self, bond_direction): #bruce 071204 """ Assuming self is in a chain of directional bonds with consistently set directions, return the next atom (of any kind, including bondpoints) in that chain, in the given bond_direction. If the chain does not continue in the given direction, return None. If the assumptions are false, no error is detected, and no exception is raised, but either None or some neighbor atom might be returned. @note: does not verify that bond directions are consistent. Result is not deterministic if two bonds from self have same direction from self (depends on order of self.bonds). """ assert bond_direction in (-1, 1) for bond in self.bonds: dir = bond.bond_direction_from(self) if dir == bond_direction: return bond.other(self) # todo: could assert self is a termination atom or bondpoint, # or if not, that self.bond_directions_are_set_and_consistent() # (if we do, revise docstring) return None def bond_directions_to_neighbors(self): #bruce 080402 """ @return: a list of pairs (bond direction to neighbor, neighbor) for all neighbor atoms to which our bonds are directional (including bondpoints, strand sugar atoms, or Pl atoms). """ res = [] for bond in self.bonds: dir = bond.bond_direction_from(self) if dir: res.append( (dir, bond.other(self)) ) return res def axis_neighbor(self): #bruce 071203; bugfix 080117 for single strand """ Assume self is a PAM strand sugar atom; return the single neighbor of self which is a PAM axis atom, or None if there isn't one (indicating that self is part of a single stranded region). @note: before the dna updater is turned on by default, this may or may not return None for the single-stranded case, since there is no enforcement of one way of representing single strands. After it is turned on, it is likely that it will always return None for free- floating single strands, but this is not fully decided. For "sticky ends" it will return an axis atom, since they will be represented internally as double strands with one strand marked as unreal. """ axis_neighbors = filter( lambda atom: atom.element.role == 'axis', self.neighbors()) if axis_neighbors: assert len(axis_neighbors) == 1, \ "%r.axis_neighbor() finds more than one: %r" % \ (self, axis_neighbors) # stub, since the updater checks needed to ensure this # are NIM as of 071203 return axis_neighbors[0] return None def Pl_neighbors(self): #bruce 080122 """ Assume self is a PAM strand sugar atom; return the neighbors of self which are PAM Pl (pseudo-phosphate) atoms (or any variant thereof, which sometimes interposes between strand base sugar pseudoatoms). """ res = filter( lambda atom: atom.element is Pl5, self.neighbors()) return res def strand_base_neighbors(self): #bruce 071204 (nim, not yet needed; rename?) """ Assume self is a PAM strand sugar atom; return a list of the neighboring PAM strand sugar atoms (even if PAM5 linker atoms separate them from self). """ # review: should the return value also say in which direction each one lies, # whether in terms of bond_direction or base_index_direction? assert 0, "nim" def strand_next_baseatom(self, bond_direction = None): #bruce 071204 """ Assume self is a PAM strand sugar atom, and bond_direction is -1 or 1. Find the next PAM strand sugar atom (i.e. base atom) in the given bond direction, or None if it is missing (since the strand ends), or if any bond directions are unset or inconsistent, or if any other structural error causes difficulty, or if ._dna_updater__error is set in either self or in the atom we might otherwise return (even if that error was propogated from elsewhere in that atom's basepair, rather than being a problem with that atom itself). """ # note: API might be extended to permit passing a baseindex direction # instead, and working on either strand or axis baseatoms. assert bond_direction in (-1, 1) if self._dna_updater__error: #bruce 080131 new feature (part 1 of 3) return None atom1 = self.next_atom_in_bond_direction(bond_direction) # might be None or a bondpoint if atom1 is None: return None if atom1._dna_updater__error: #bruce 080131 new feature (part 2 of 3) return None # REVIEW: the following should probably test element.role == 'strand', # but that includes Se3 and Sh3 end-atoms, unlike this list. # Not an issue when dna updater is on and working, # but if it's disabled to work with an old file, that change # might cause bugs. But I don't feel fully comfortable with # making this depend at runtime on dna_updater_is_enabled() # (not sure why). So leave it alone for now. [bruce 080320] symbol = atom1.element.symbol # KLUGE -- should use another element attr, or maybe Atom subclass if symbol[0:2] not in ('Ss', 'Sj', 'Hp', 'Pl'): # base or base linker atoms (#todo: verify or de-kluge) return None if symbol.startswith('Pl'): # base linker atom # move one more atom to find the one to return atom1 = atom1.next_atom_in_bond_direction(bond_direction) # might be None or a bondpoint assert atom1 is not self # (false would imply one bond had two directions, # or two bonds between same two atoms) if atom1 is None: return None if atom1._dna_updater__error: #bruce 080131 new feature (part 3 of 3) return None if atom1.element.symbol[0:2] not in ('Ss', 'Sj', 'Hp'): return None pass return atom1 def _f_get_fake_Pl(self, direction): #bruce 080327 """ [friend method for PAM3+5 -> PAM5 conversion code] Assume self is a PAM3 or PAM5 strand sugar atom (either PAM model is possible, at least transiently, during PAM3+5 conversion). Find or make, and return, a cached fake Pl5 atom with a properly allocated and unchanging atom.key, to be used in the PAM5 form of self if self does not have a real Pl atom in the given bond_direction. The atom we return might be used only for mmp writing of a converted form, without making any changes in the model, or it might become a live atom and get used in the model. To make it a live atom, special methods must be called [nim] which remove it from being able to be returned by this method. If self does have a real such Pl atom, the atom we might otherwise return might still exist, but this method won't be called to ask for it. It may or may not detect that case. If it detects it, it will treat it as an error. However, it's not an error for the cached atom to survive during the time a live Pl atom takes it place, and to be reused if that live Pl atom ever dies. OTOH, the cached Pl atom might have formerly been a live Pl atom in the same place (i.e. bonded to self in the given bond_direction), killed when self was converted to PAM3. The 3d position (atom.posn()) of the returned atom is arbitrary, and can be changed by the caller for its own purposes. Absent structure changes to self, the identity, key, and 3d position of the returned atom won't be changed between calls of this method by the code that implements the service of which this method is part of the interface. """ fake_Pls = self._fake_Pls # None, or a 2-element list # Note: this list is NOT part of the undoable state, nor are the # fake atoms within it. # # REVIEW: should these have anything to do with storing Pl-posn # "+5" data? is that data in the undoable state? I think it is, # and these are not, so they probably don't help store it. if not fake_Pls: fake_Pls = self._fake_Pls = [None, None] assert direction in (1, -1) direction_index = (direction == 1) # arbitrary map from direction to [0,1] ### clean up dup code when we have some # review: change this to data_index, store a Fake_Gv in the same # array?? (don't know yet if writemmp pam5 conversion will need # one -- maybe not, or if it does it can probably be a flyweight, # but not yet known) Pl = fake_Pls[direction_index] if Pl is None: Pl = fake_Pls[direction_index] = Fake_Pl(self, direction) ## not: self.__class__(Pl5, V(0,0,0)) # obs cmt: maybe: let Pl be live, and if so, verify its bonding with self?? assert isinstance(Pl, Fake_Pl) # nonsense: ## assert Pl.killed() # for now return Pl # methods related to storing PAM3+5 Pl data on Ss # (Gv and Pl data share private helper methods) def _f_store_PAM3plus5_Pl_abs_position(self, direction, abspos, **opts): #bruce 080402, split 080409 """ [friend method for PAM3plus5 code, called from dna updater] If self is a PAM3 or PAM5 strand sugar atom, store "PAM3+5 Pl-position data" on self, for a hypothetical (or actual) Pl in the given bond direction from self, at absolute position abspos, converting this to a relative position using the baseframe info corresponding to self stored in self's DnaLadder, which must exist and be up to date (assumed, not checked). @warning: slow for non-end atoms of very long ladders, due to a linear search for self within the ladder. Could be optimized by passing an index hint if necessary. @note: this method might be inlined, when called by Pls between basepairs in the same DnaLadder, since much of it could be optimized in a loop over basepairs in order (in that case). """ assert direction in (1, -1) data_index = (direction == 1) self._store_PAM3plus5_abspos(data_index, abspos, **opts) # both Pl and Gv use this, with different data_index return def _store_PAM3plus5_abspos(self, data_index, abspos): """ [private helper, used for Pl and Gv methods] """ #bruce 080402, split 080409 if not self.element.symbol.startswith('Ss'): # kluge? needs to match Ss3 and Ss5, and not Pl. # not necessarily an error print "fyi: _store_PAM3plus5_abspos%r is a noop for this element" % \ (self, data_index, abspos) # remove when works if routine; leave in if never seen, to # notice bugs; current caller tries not to call in this case, # so this should not happen return if not self.can_make_up_Pl_abs_position(data_index and 1 or -1): # kluge: can store is the same as can make up, for now; # needed to fix bugs in pam conversion killing Pls next to # single strands [bruce 080413] return origin, rel_to_abs_quat, y_m_junk = _f_baseframe_data_at_baseatom(self) relpos = baseframe_abs_to_rel(origin, rel_to_abs_quat, abspos) if not self._PAM3plus5_Pl_Gv_data: self._PAM3plus5_Pl_Gv_data = [None, None, None] self._PAM3plus5_Pl_Gv_data[data_index] = relpos if debug_flags.DEBUG_DNA_UPDATER_VERBOSE: print "fyi, on %r for data_index %r stored relpos %r" % \ (self, data_index, relpos) # todo: use these prints to get constants for # default_Pl_relative_position (and Gv) [review: done now?] return def _f_recommend_PAM3plus5_Pl_abs_position(self, direction, make_up_position_if_necessary = True, **opts ): """ #doc; return None or a position @warning: this can return None even if make_up_position_if_necessary is passed, since some Ss atoms *can't* make up a position (e.g. those in DnaSingleStrandDomains, at least for now) """ #bruce 080402, split 080409 assert direction in (1, -1) data_index = (direction == 1) res = self._recommend_PAM3plus5_abspos(data_index, **opts) # both Pl and Gv use this, with different data_index if res is None and make_up_position_if_necessary: res = self._make_up_Pl_abs_position(direction) # might be None! # note: don't store this, even if not remove_data # (even though save in PAM5, then reload file, # *will* effectively store it, since in the file we don't # mark it as "made up, should be ignored"; if we did, # we'd want to erase that as soon as anything moved it, # and it'd be a kind of hidden info with mysterious effects, # so it's not a good idea to mark it that way) return res def _recommend_PAM3plus5_abspos(self, data_index, remove_data = False ): """ [private helper, used for Pl and Gv methods] #doc; return None or a position; never make up a position """ #bruce 080402, split 080409 data = None if self._PAM3plus5_Pl_Gv_data: data = self._PAM3plus5_Pl_Gv_data[data_index] # might be None if remove_data: self._PAM3plus5_Pl_Gv_data[data_index] = None # don't bother removing the [None, None, ...] list itself # (optim: should we remove it to conserve RAM??) # data is None or a relative Pl or Gv position if data is None: return None else: relpos = data origin, rel_to_abs_quat, y_m_junk = _f_baseframe_data_at_baseatom(self) return baseframe_rel_to_abs(origin, rel_to_abs_quat, relpos) pass # end of _recommend_PAM3plus5_abspos def _make_up_Pl_abs_position(self, direction): #bruce 080402 """ """ if not self.can_make_up_Pl_abs_position(direction): return None relpos = default_Pl_relative_position(direction) origin, rel_to_abs_quat, y_m_junk = _f_baseframe_data_at_baseatom(self) return baseframe_rel_to_abs(origin, rel_to_abs_quat, relpos) def can_make_up_Pl_abs_position(self, direction): #bruce 080413 try: ladder, whichrail, index = _f_find_new_ladder_location_of_baseatom(self) # not self.molecule.ladder, it finds the old invalid ladder instead except: print "bug? can_make_up_Pl_abs_position can't find new ladder of %r" % \ (self,) return True # should be False, but return True to mitigate new bugs caused # by this feature if not ladder: # probably can't happen print "bug? can_make_up_Pl_abs_position sees ladder of None for %r" % \ (self,) return True # should be False (see comment above) return ladder.can_make_up_Pl_abs_position_for(self, direction) # methods related to storing PAM3+5 Gv data on Ss # (Gv and Pl data share private helper methods) def _f_store_PAM3plus5_Gv_abs_position(self, abspos): #bruce 080409 """ [friend method for PAM3plus5 code, called from dna updater] If self is a PAM3 or PAM5 strand sugar atom, store "PAM3+5 Gv-position data" on self, for a hypothetical (or actual) Gv attached to self, at absolute position abspos, converting this to a relative position using the baseframe info corresponding to self stored in self's DnaLadder, which must exist and be up to date (assumed, not checked), BUT WHICH MAY NOT HAVE YET REMADE ITS CHUNKS (i.e. which may differ from atom. molecule.ladder for its atoms, if that even exists). @warning: slow for non-end atoms of very long ladders, due to a linear search for self within the ladder. Could be optimized by passing an index hint if necessary. @note: this method might be inlined, since much of it could be optimized in a loop over basepairs in order (in that case); or it might be passed a baseindex hint, or baseframe info. """ self._store_PAM3plus5_abspos( _GV5_DATA_INDEX, abspos) # both Pl and Gv use this, with different data_index return def _f_recommend_PAM3plus5_Gv_abs_position(self, make_up_position_if_necessary = True, **opts # e.g. remove_data = False ): """ #doc; return None or a position """ #bruce 080409 res = self._recommend_PAM3plus5_abspos( _GV5_DATA_INDEX, **opts) # both Pl and Gv use this, with different data_index if res is None and make_up_position_if_necessary: res = self._make_up_Gv_abs_position() return res def _make_up_Gv_abs_position(self): #bruce 080409 """ @note: self should be a strand sugar atom """ relpos = default_Gv_relative_position() # (a constant) # following code is the same as for the Pl version origin, rel_to_abs_quat, y_m_junk = _f_baseframe_data_at_baseatom(self) return baseframe_rel_to_abs(origin, rel_to_abs_quat, relpos) # == end of PAM strand atom methods # == PAM axis atom methods def strand_neighbors(self): #bruce 071203 """ Assume self is a PAM axis atom; return the neighbors of self which are PAM strand sugar atoms. There are always exactly one or two of these [NIM] after the dna updater has run. """ # [stub -- need more error checks in following (don't return Pl). # but this is correct if structures have no errors.] res = filter( lambda atom: atom.element.role == 'strand', self.neighbors()) ##assert len(res) in (1, 2), \ ## "error: axis atom %r has %d strand_neighbors (should be 1 or 2)"\ ## % (self, len(res)) # happens in mmkit - leave it as just a print at least until # we implem "delete bare atoms" - legal_nums = legal_numbers_of_strand_neighbors_on_axis() if not ( len(res) in legal_nums ): print "error: axis atom %r has %d strand_neighbors (should be %s)" % \ (self, len(res), " or ".join(map(str, legal_nums))) return res def axis_neighbors(self): #bruce 071204 # (used on axis atoms, not sure if used on strand atoms) return filter( lambda atom: atom.element.role == 'axis', self.neighbors()) # == end of PAM axis atom methods pass # end of class PAM_Atom_methods # end
NanoCAD-master
cad/src/model/PAM_Atom_methods.py
NanoCAD-master
cad/src/model/__init__.py
# Copyright 2004-2009 Nanorex, Inc. See LICENSE file for details. """ chunk.py -- provides class Chunk [formerly known as class molecule], for a bunch of atoms (not necessarily bonded together) which can be moved and selected as a unit. @author: Josh, Bruce, others @version: $Id$ @copyright: 2004-2009 Nanorex, Inc. See LICENSE file for details. History: originally by Josh lots of changes, by various developers split out of chem.py by bruce circa 041118 bruce 050513 optimized some things, including using 'is' and 'is not' rather than '==', '!=' for atoms, molecules, elements, parts, assys in many places (not all commented individually) bruce 060308 rewriting Atom and Chunk so that atom positions are always stored in the atom (eliminating Atom.xyz and Chunk.curpos, adding Atom._posn, eliminating incremental update of atpos/basepos). Motivation is to make it simpler to rewrite high-frequency methods in Pyrex. bruce 060313 splitting _recompute_atlist out of _recompute_atpos, and planning to remove atom.index from undoable state. Rules for atom.index (old, reviewed now and reconfirmed): owned by atom.molecule; value doesn't matter unless atom.molecule and its .atlist exist (but is set to -1 otherwise when this is convenient, to help catch bugs); must be correct whenever atom.molecule.atlist exists (and is reset when it's made); correct means it's an index for that atom into .atlist, .atpos, .basepos, whichever of those exist at the time (atlist always does). This means a chunk's addatom, delatom, and _undo_update need to invalidate its .atlist, and means there's no need to store atom.index as undoable state (making diffs more compact), or to update a chunk's .atpos (or even .atlist) when making an undo checkpoint. (It would be nice for Undo to not store copies of changed .atoms dicts of chunks too, but that's harder. ###e) [update, bruce 060411: I did remove atom.index from undoable state, as well as chunk.atoms, and I made atoms always store their own absposns. I forgot to summarize the new rules here -- maybe I did somewhere else. Looking at the code now, atoms still try to get baseposns from their chunk, which still computes that before drawing them; moving a chunk probably invalidates atpos and basepos (guess, but _recompute_atpos inval decl code would seem wrong otherwise) and drawing it then recomputes them -- or maybe not, since it's only when remaking display list that it should need to. Sometime I should review this and see if there is some obvious optimization needed.] bruce 080305 changed superclass from Node to NodeWithAtomContents bruce 090115 split Chunk_Dna_methods from here into a new mixin class bruce 090100 split Chunk_mmp_methods from here into a new mixin class bruce 090100 split Chunk_drawing_methods from here into a new mixin class (which on 090212 was turned into a cooperating separate class, ChunkDrawer) bruce 090211 making compatible with TransformNode, though that is unfinished and not yet actually used; places to fix for this are marked ####. (Update: as of 090225 TransformNode is abandoned. However, I'm leaving some comments that refer to TransformNode in place (in still-active files), since they also help point out the code which any other attempt to optimize rigid drags would need to modify. In those comments, dt and st refer to dynamic transform and static transform, as used in scratch/TransformNode.py.) """ import Numeric # for sqrt import math # only used for pi, everything else is from Numeric [as of before 071113] from Numeric import array from Numeric import add from Numeric import dot from Numeric import PyObject from Numeric import argsort from Numeric import compress from Numeric import nonzero from Numeric import take from Numeric import argmax from OpenGL.GL import glPushMatrix from OpenGL.GL import glTranslatef from OpenGL.GL import glRotatef from OpenGL.GL import glPopMatrix from utilities.Comparison import same_vals from utilities.constants import gensym, genKey from utilities.constants import diDEFAULT from utilities.constants import diINVISIBLE from utilities.constants import diDNACYLINDER from utilities.constants import diPROTEIN from utilities.constants import ATOM_CONTENT_FOR_DISPLAY_STYLE from utilities.constants import noop from utilities.constants import MAX_ATOM_SPHERE_RADIUS from utilities.constants import BBOX_MIN_RADIUS from utilities.prefs_constants import hoverHighlightingColor_prefs_key from utilities.debug import print_compact_stack ## from utilities.debug import compact_stack from utilities.debug import print_compact_traceback from utilities.debug import safe_repr from utilities import debug_flags from utilities.GlobalPreferences import pref_show_node_color_in_MT from utilities.icon_utilities import imagename_to_pixmap from geometry.BoundingBox import BBox from geometry.VQT import V, Q, A, vlen import foundation.env as env from foundation.NodeWithAtomContents import NodeWithAtomContents from foundation.inval import InvalMixin from foundation.state_constants import S_REF, S_CHILDREN_NOT_DATA from foundation.undo_archive import set_undo_nullMol from graphics.display_styles.displaymodes import get_display_mode_handler from graphics.drawables.Selobj import Selobj_API from model.bonds import bond_copied_atoms from model.chem import Atom # for making bondpoints, and a prefs function from model.elements import PeriodicTable from model.elements import Singlet from model.ExternalBondSet import ExternalBondSet from model.global_model_changedicts import _changed_parent_Atoms from model.Chunk_Dna_methods import Chunk_Dna_methods from graphics.model_drawing.ChunkDrawer import ChunkDrawer from model.Chunk_mmp_methods import Chunk_mmp_methods from commands.ChunkProperties.ChunkProp import ChunkProp # == _inval_all_bonds_counter = 1 # private global counter [bruce 050516] # == some debug code is near end of file # == Molecule (i.e. Chunk) # Historical note: # # (Josh wrote:) # I use "molecule" and "part" interchangeably throughout the program. # this is the class intended to represent rigid collections of # atoms bonded together, but it's quite possible to make a molecule # object with unbonded atoms, and with bonds to atoms in other # molecules # # [bruce 050315 adds: I've seen "part" used for the assembly, but not for "chunk" # (which is the current term for instances of class molecule aka Chunk). # Now, however, each assy has one or more Parts, each with its own # physical space, containing perhaps many bonded chunks. So any use of # "part" to mean "chunk" would be misleading.] # Note: we immediately kill any Chunk which loses all its atoms after having # had some. If this ever causes problems (unlikely -- it's been done since # 041116), we should instead do it when we update the model tree or glpane, # since we need to ensure it's always done by the end of any user event. _superclass = NodeWithAtomContents #bruce 080305 revised this class Chunk(Chunk_Dna_methods, Chunk_mmp_methods, NodeWithAtomContents, InvalMixin, Selobj_API ): """ A set of atoms treated as a unit. """ #bruce 071114 renamed this from class molecule -> class Chunk # subclass-specific constants _selobj_colorsorter_safe = True #bruce 090311 _drawer_class = ChunkDrawer # subclasses can set this to a subclass of that # class constants to serve as default values of attributes, and _s_attr # decls for some of them _hotspot = None _s_attr_hotspot = S_REF #bruce 060404 revised this in several ways; # bug 1633 (incl. all subbugs) will need retesting. # Note that this declares hotspot, not _hotspot, so that undo state # never contains dead atoms. This is only ok because we provide # _undo_setattr_hotspot as well. # # Note that we don't put this (or Jig.atoms) into the 'atoms' # _s_attrlayer, since we still need to scan them as data. # # Here are some old comments from when this declared _hotspot, still # relevant: todo: warn somehow if you hit a StateMixin object in S_REF # but didn't store state for it (as could happen when we declared # _hotspot as data, not child, and it could be a dead atom); ideally # we'd add debug code to detect the original error (declaring # hotspot), due to presence of a _get_hotspot method; maybe we'd have # an optional method (implemented by InvalMixin) to say whether an # attr is legal for an undoable state decl. But (060404) there needs # to be an exception, e.g. when _undo_setattr_hotspot exists, like # now. _colorfunc = None _dispfunc = None is_movable = True #mark 060120 # [no need for _s_attr decl, since constant for this class -- bruce guess 060308] # Undoable/copyable attrs: # (no need for _s_attr decls since copyable_attrs provides them) # self.display overrides global display (GLPane.display) # but is overriden by atom value if not default display = diDEFAULT # this overrides atom colors if set color = None # user_specified_center -- as of 050526 it's sometimes used # [but only in commented-out code as of 090113], but it's always None. # # note: if we implement self.user_specified_center as user-settable, # it also needs to be moved/rotated with the mol, like a datum point # rigidly attached to the mol (or like an atom) ## user_specified_center = None # never changed for now, so not in copyable_attrs copyable_attrs = _superclass.copyable_attrs + \ ('display', 'color', 'protein') + \ Chunk_Dna_methods._dna_copyable_attrs # this extends the copyable_attrs tuple from Node # (could add _colorfunc, but better to handle it separately in case this # gets used for mmp writing someday. as of 051003 _colorfunc would # anyway not be permitted since state_utils.copy_val doesn't know # how to copy it.) #e should add user_specified_center once that's in active use #bruce 060313 no longer need to store diffs of our .atoms dict! # But still need to scan them as children (for now -- maybe not for much longer). # Do we implement _s_scan_children, or declare .atoms as S_CHILDREN_NOT_DATA?? # I think the latter is simpler, so I'll try it. ## _s_attr_atoms = S_CHILDREN _s_attr_atoms = S_CHILDREN_NOT_DATA _s_attrlayer_atoms = 'atoms' #bruce 060404 # The iconPath specifies path(string) of an icon that represents the # objects of this class (in this case its gives the path of an 'chunk icon') # see PM.PM_SelectionListWidget.insertItems for an example use of this # attribute. iconPath = "ui/modeltree/Chunk.png" # no need to _s_attr_ decl basecenter and quat -- they're officially # arbitrary, and get replaced when things get recomputed # [that's the theory, anyway... bruce 060223] # flags to tell us that our ExternalBondSets need updating # (they might have lost or gained external bonds between specific # chunk pairs, of self and some other chunk). Note that this can happen # even if self.externs remains unchanged, if one of it's bonds' other atoms # changes parent. Here are the reasons these need to be set, and where we do that: # - changes inside a bond: # - make it: Bond.__init__ # - delete it or change one of its atoms: each caller of Atom.unbond # - change atoms by Undo/Redo: Atom._undo_update (since its list of bonds # changes); note that Bond._undo_udpate doesn't have enough info to do # this, since it doesn't know the old atom if one got replaced # - changes to an atom's parent chunk (.molecule): # Chunk.invalidate_atom_lists (also called by Chunk._undo_update) # [bruce 080702] _f_lost_externs = False _f_gained_externs = False # Set this to True if any of the atoms in this chunk have their # overlayText set to anything other than None. This keeps us from # having to test that for every single atom in every single chunk # each time the screen is rerendered. It is not reset to False # except when no atoms happen to have overlayText when self is rendered -- # in other words, it's only a hint -- false positives are permitted. chunkHasOverlayText = False showOverlayText = False # whether the user wishes to see the overlay text on this chunk # (used in ChunkDrawer) protein = None # this is set to an object of class Protein in some chunks glpane = None #bruce 050804 ### TODO: RENAME (last glpane we displayed on??) # (warning: same-named attr is also used/set in ChunkDrawer; # see comment therein for discussion) # == # note: def __init__ occurs below a few undo-related methods. TODO: move them below it. def _undo_update(self): #bruce 060223 (initial super-conservative overkill version -- i hope) """ [guess at API, might be revised/renamed] This is called when Undo has set some of our attributes, using setattr, in case we need to invalidate or update anything due to that. Note: it is only called if we are now alive (reachable in the model state). See also _f_invalidate_atom_lists_and_maybe_deallocate_displist, which is called (later) whether we are now alive or dead. """ assert self.assy is not None #bruce 080227 guess (from docstring) # [can fail, 080325, tom bug when updater turned on after separate @@@] # One thing we know is required: if self.atoms changes, invalidate self.atlist. # This permits us to not store atom.index as undoable state, and to not update # self.atpos before undo checkpoints. [bruce 060313] self.invalidate_everything() # this is probably overkill, but its call # of self.invalidate_atom_lists() is certainly needed self._colorfunc = None del self._colorfunc #bruce 060308 precaution; might fix (or # cause?) some "Undo in Extrude" bugs self._dispfunc = None del self._dispfunc _superclass._undo_update(self) # (Q: what's the general rule for whether to call our superclass # implem before or after running our own code in this method? # A: guess: this method is more like destroy than create, so do # high-level (subclass) code first. If it turns out this method # has some elements of both destroy and create, perhaps do only # the destroy-like elements before the superclass implem.) return def _undo_setattr_hotspot(self, hotspot, archive): """ [undo API method] Undo is mashing changed state into lots of objects' attrs at once; this lets us handle that specially, just for self.hotspot, but in unknown order (for now) relative either to our attrs or other objects. """ #bruce 060404; 060410 use store_if_invalid to fix new bug 1829 self.set_hotspot( hotspot, store_if_invalid = True) # == def __init__(self, assy, name = None): self._invalidate_all_bonds() # bruce 050516 -- needed in __init__ to make sure # the counter it sets is always set, and always unique # Note [bruce 041116]: # new chunks are NOT automatically added to assy. # This has to be done separately (if desired) by assy.addmol # (or the equivalent). # addendum [bruce 050206 -- describing the situation, not endorsing it!]: # (and for clipboard chunks it should not be done at all! # also not for chunks "created in a Group", if any; for those, # probably best to do addmol/moveto like [some code] does.) if not self.mticon: self.init_icons() self.init_InvalMixin() ## dad = None #bruce 050216 removed dad from __init__ args, since no calls # pass it and callers need to do more to worry about the # location anyway (see comments above) _superclass.__init__(self, assy, name or gensym("Chunk", assy)) # atoms in a dictionary, indexed by atom.key self.atoms = {} # note: Jigs are stored on atoms, not directly in Chunk; # so are bonds, but we have a list of external bonds, self.externs, # which is computed by __getattr__ and _recompute_externs; we have # several other attributes computed by _get_ or _recompute_ methods # using InvalMixin.__getattr__, e.g. center, bbox, basepos, atpos. # [bruce 041112] # Chunk-relative coordinate system, used internally to speed up # redrawing after mol is moved or rotated: self.basecenter = V(0,0,0) # origin, for basepos, used for redrawing self.quat = Q(1, 0, 0, 0) # attitude in space, for basepos # note: as of bruce 041112, the old self.center is split into several # attributes which are not always the same: # - self.center (public, the center for use by UI operations on the mol, # defined by _recompute_center); # - self.basecenter (private, for the mol-relative coordinate system, # often equal to self.center but not always); # - self.user_specified_center (None or a user-defined center; mostly # not yet implemented; would need to be transformed like an atom posn); # - self.average_position (average posn of atoms or singlets; default # value for self.center). self.haveradii = 0 # note: haveradii is not handled by InvalMixin # hotspot: default place to bond this Chunk when pasted; # should be a singlet in this Chunk, or None. ## old code: self.hotspot = None # (As of bruce 050217 (to fix bug 312) # this is computed by getattr each time it's needed, # using self._hotspot iff it's still valid, forgetting it otherwise. # This is needed since code which removes or kills singlets, or transmutes # them, does not generally invalidate the hotspot explicitly, # but it does copy or keep it # (e.g. in mol.copy or merge) even when doing so is questionable.) # BTW, we don't presently save the hotspot in the mmp file, # which is a reported bug which we hope to fix soon. # note: see comments in ChunkDrawer about future refactoring # re our _memo_dict, glpane attributes. [bruce 090123 comment] self._memo_dict = {} # for use by anything that wants to store its own memo data on us, # using a key it's sure is unique [bruce 060608] # [now private and has an accessor method, bruce 090213] # (when we eventually have a real destroy method, it should zap # this; maybe this will belong on class Node #e) #glname is needed for highlighting the chunk as an independent object #NOTE: See a comment in self.highlight_color_for_modkeys() for more info. if not self.isNullChunk(): self.glname = self.assy.alloc_my_glselect_name(self) #bruce 080917 revised ### REVIEW: is this ok or fixed if this chunk is moved to a new assy # (if that's possible)? [bruce 080917 Q] # keep track of other chunks we're bonded to; lazily updated # [bruce 080702] self._bonded_chunks = {} self._drawer = self._drawer_class(self) ### todo: refactor when we have GraphicsRules ### todo: optim: do this on demand, since some chunks are never drawn, # e.g. the ones named 'BasePairChunk' created internally by the dna # generator, and perhaps all dna chunks read from mmp files # (since the dna updater remakes them before they're drawn) return # from Chunk.__init__ # == unsorted methods, new as of bruce 090211 or so def set_assy(self, assy): #bruce 090225 precaution """ [override superclass method] """ if self._drawer: self._drawer.invalidate_display_lists() _superclass.set_assy(self, assy) return def invalidate_display_lists_for_style(self, style): #bruce 090211 """ Invalidate any of our display lists used with the given style (whose appearance might contain anything specific to that style), since the caller has changed something which sometimes affects appearances in that style but which is not change/usage-tracked in the standard way. @see: DnaStrand.setStrandSequence, which calls this with style = diDNACYLINDER when it changes dna sequence information, since that style sometimes visually indicates sequence. """ # review: add to Node API? might be better to just add enough # change tracking to never need it. self._drawer.invalidate_display_lists_for_style(style) for ebset in self._bonded_chunks.itervalues(): ebset.invalidate_display_lists_for_style(style) # note: doing this in our ExternalBondSets is needed in # principle, but might not be needed in practice for the # current calls or for certain styles. See the similar # comment in ExternalBondSetDrawer. [bruce 090217] return def invalidate_internal_bonds_display(self): #bruce 090211 """ """ #### TODO: refactor #### todo: optim: only in styles which show bonds! # but, that's only a correct optim if no atoms have individual styles # or if those that do are in their own displists. self._drawer.invalidate_display_lists() # might be overkill (eventually) return def invalidate_ExternalBondSet_display_for(self, other): #bruce 090211 ebset = self._bonded_chunks.get(other) # might be None if ebset is not None: ebset.invalidate_display_lists() # review: call invalidate_distortion, or merge invalidate_distortion with invalidate_display_lists? # justification: when this is called there is a real distortion, i think... return def draw(self, glpane, dispdef): #### won't be needed once we have GraphicsRules """ #doc @note: extended in DnaLadderRailChunk """ self.glpane = glpane # self.glpane is needed, but needs review anyway; see comment after # similar assignment in ChunkDrawer.draw [bruce 090212 comment] self._drawer.draw(glpane) def draw_highlighted(self, glpane, color): #### won't be needed once we have GraphicsRules, I hope """ """ #### note: should probably be merged with draw_in_abs_coords; see comments elsewhere self._drawer.draw_highlighted(glpane, color) # == bruce 090212 moved the following methods back to class Chunk # from ChunkDrawer ### todo: refile into original location in this class? def drawing_color(self): #bruce 080210 split this out, used in Atom.drawing_color """ Return the color tuple to use for drawing self, or None if per-atom colors should be used. """ color = self.color # None or a color color = self.modify_color_for_error(color) # (no change in color if no error) return color def modify_color_for_error(self, color): """ [overridden in some subclasses] """ return color def highlight_color_for_modkeys(self, modkeys): """ This is used to return a highlight color for the chunk highlighting. See code comment for more info. @note: this method is part of the Selobj_API. """ #NOTE: before 2008-03-13, the chunk highlighting was achieved by using #the atoms and bonds within the chunk. The Atom and Bond classes have #their own glselect name, so the code was able to recognize them as #highlightable objects and then depending upon the graphics mode the #user was in, it used to highlight the whole chunk by accessing the #chunk using, for instance, atom.molecule. although this is still #implemented, for certain display styles such as DnaCylinderChunks, #the atoms and bonds are never drawn. So there is no way to access the #chunk! To fix this, we need to make chunk a highlightable object. #This is done by making sure that the chunk gets a glselect name #(glname) and by defining this API method - Ninad 2008-03-13 return env.prefs[hoverHighlightingColor_prefs_key] #### REVIEW: does the return value matter, except for not being None? # Is this value ever None? [bruce 090212 questions] # == def find_or_recompute_memo( self, address, memo_validity_data, compute_memo_func ): """ #doc """ #bruce 090213 factored this out of its caller; # needs cleanup and maybe further refactoring memoplace = self._memo_dict.setdefault(address, {}) # memoplace is our caller's own persistent mutable dict on self # (kept unique by the client passing in a unique address), which # lasts as long as self does # todo: optimize the following -- could use single _memo_dict from address to (data, memo) if memoplace.get('memo_validity_data') != memo_validity_data: # same_vals? # need to compute or recompute memo, and save it memo = compute_memo_func(self) # review: also pass our other args? memoplace['memo_validity_data'] = memo_validity_data memoplace['memo'] = memo return memoplace['memo'] def changeapp_counter(self): """ #doc @warning: current implem is not correct unless called during self.draw! """ #bruce 090213 factored this out of its caller return self._drawer._havelist_inval_counter #### needs further refactoring # == drawing-helper methods applicable to any TransformNode # [bruce 090212 moved all these back to class Chunk; # they're often called externally] def pushMatrix(self, glpane): """ Do glPushMatrix(), then transform from (presumed) world coordinates to self's private coordinates. Also tell glpane this was done (for more info and requirements see docstring of applyMatrix). @see: self.applyMatrix() @see: self.popMatrix() """ glPushMatrix() self.applyMatrix(glpane) return def applyMatrix(self, glpane): """ Without doing glPushMatrix(), transform the current GL matrix state from (presumed) world coordinates to self's private coordinates. This is only permitted in 1-1 correspondence with a call (just done by caller) of either self.pushMatrix(glpane) or glPushMatrix(). I.e. two calls in a row of self.applyMatrix are illegal. This is not checked; errors in this will cause some things to be drawn in the wrong place. glpane must correspond to the current GL context. Also tell glpane that a push/apply of self's coordinate system has just been done, in case deferred drawing done after this call wants to know how to reproduce the current GL matrix state later (or more precisely, the current *symbolic* state -- i.e. which local coordinate systems are pushed, even if their value when used later differs from their current value). (This is why we require 1-1 correspondence between push and apply.) @see: self.pushMatrix() """ self.applyTransform() glpane.transforms += [self] return def applyTransform(self): #bruce 090223 """ @note: part of the TransformControl API """ #### REVIEW: when we have separate dt/st (see TransformNode), # will this apply both or only st? Same Q for applyMatrix. origin = self.basecenter glTranslatef(origin[0], origin[1], origin[2]) q = self.quat glRotatef(q.angle * 180.0 / math.pi, q.x, q.y, q.z) return def popMatrix(self, glpane): """ Undo the effect of self.pushMatrix(glpane). Also tell glpane this was done (for more info and requirements see docstring of applyMatrix). """ glPopMatrix() assert glpane.transforms[-1] is self glpane.transforms.pop() return # == def isNullChunk(self): # by Ninad """ @return: whether chunk is a "null object" (used as atom.molecule for some killed atoms). @rtype: boolean This is overridden in subclass _nullMol_Chunk ONLY. @see: _nullMol_Chunk.isNullChunk() """ return False def make_glpane_cmenu_items(self, contextMenuList, command): # by Ninad """ Make glpane context menu items for this chunk (and append them to contextMenuList), some of which may be specific to the given command (presumably the current command) based on its having a commandName for which we have special-case code. """ # Note: See make_selobj_cmenu_items in other classes. This method is very # similar to that method. But it's not named the same because the chunk # may not be a glpane.selobj (as it may get highlighted in SelectChunks # mode even when, for example, the cursor is over one of its atoms # (i.e. selobj = an Atom). So ideally, that method and this one should be # unified somehow. This method exists only in class Chunk and is called # only by certain commands. [comment originally by Ninad, revised by Bruce] assert command is not None #Start Standard context menu items rename and delete [by Ninad] parent_node_classes = (self.assy.DnaStrandOrSegment, self.assy.NanotubeSegment) ### TODO: refactor to not hardcode these classes, # but to have a uniform way to find the innermost node # visible in the MT, which is the node to be renamed. ### Also REVIEW whether what this finds (node_to_rename) is always # the same as the unit of hover highlighting, and if not, whether # it should be, and if so, whether the same code can be used to # determine the highlighted object and the object to rename or # delete. [bruce 081210 comments] parent_node = None for cls in parent_node_classes: parent_node = self.parent_node_of_class(cls) if parent_node: break node_to_rename = parent_node or self del parent_node name = node_to_rename.name item = (("Rename %s..." % name), node_to_rename.rename_using_dialog ) contextMenuList.append(item) def delnode_cmd(node_to_rename = node_to_rename): node_to_rename.assy.changed() #bruce 081210 bugfix, not sure if needed node_to_rename.assy.win.win_update() #bruce 081210 bugfix node_to_rename.kill_with_contents() return del node_to_rename item = (("Delete %s" % name), delnode_cmd ) contextMenuList.append(item) #End Standard context menu items rename and delete # Protein-related items #Urmi 20080730: edit properties for protein for context menu in glpane if command.commandName in ('SELECTMOLS', 'BUILD_PROTEIN'): if self.isProteinChunk(): try: protein = self.protein except: print_compact_traceback("exception in protein class") return ### REVIEW: is this early return appropriate? [bruce 090115 comment] if protein is not None: item = (("%s" % (self.name)), noop, 'disabled') contextMenuList.append(item) item = (("Edit Protein Properties..."), (lambda _arg = self.assy.w, protein = protein: protein.edit(_arg)) ) contextMenuList.append(item) pass pass pass # Nanotube-related items if command.commandName in ('SELECTMOLS', 'BUILD_NANOTUBE', 'EDIT_NANOTUBE'): if self.isNanotubeChunk(): try: segment = self.parent_node_of_class(self.assy.NanotubeSegment) except: # A graphene sheet or a simple chunk that thinks it's a nanotube. # REVIEW: the above comment (and this code) must be wrong, # because parent_node_of_class never has exceptions unless # it has bugs. So I'm adding this debug print. The return # statement below was already there. If the intent # was to return when segment is None, that was not there # and is not there now, and needs adding separately. # [bruce 080723 comment and debug print] print_compact_traceback("exception in %r.parent_node_of_class: " % self) return ### REVIEW: is this early return appropriate? [bruce 090115 comment] if segment is not None: # Self is a member of a Nanotube group, so add this # info to a disabled menu item in the context menu. item = (("%s" % (segment.name)), noop, 'disabled') contextMenuList.append(item) item = (("Edit Nanotube Properties..."), segment.edit) contextMenuList.append(item) pass pass pass # Dna-related items if command.commandName in ('SELECTMOLS', 'BUILD_DNA', 'DNA_SEGMENT', 'DNA_STRAND'): self._make_glpane_cmenu_items_Dna(contextMenuList) return # from make_glpane_cmenu_items def nodes_containing_selobj(self): #bruce 080508 bugfix """ @see: interface class Selobj_API for documentation """ # safety check in case of calls on out of date selobj: if self.killed(): return [] return self.containing_nodes() def _update_bonded_chunks(self): #bruce 080702 """ Make sure our map from (other chunk -> ExternalBondSet for self and it) (stored in self._bonded_chunks) is up to date, and that those ExternalBondSets have the correct subsets of our external bonds. Use the flags self._f_lost_externs and self._f_gained_externs to know what needs checking, and reset them. """ maybe_empty = [] if self._f_lost_externs: for ebset in self._bonded_chunks.itervalues(): ebset.remove_incorrect_bonds() if ebset.empty(): maybe_empty.append(ebset) # but don't yet remove it from self._bonded_chunks -- # we might still add bonds below self._f_lost_externs = False if self._f_gained_externs: for bond in self.externs: # this might recompute self.externs otherchunk = bond.other_chunk(self) ebset = self._bonded_chunks.get(otherchunk) # might be None if ebset is None: ebset = otherchunk._bonded_chunks.get( self) # might be None if ebset is None: ebset = ExternalBondSet( self, otherchunk) otherchunk._bonded_chunks[ self] = ebset else: # ebset was memoized in otherchunk but not in self -- # this should never happen # (since the only way to make one is the above case, # which ends up storing it in both otherchunk and self, # and the only way to remove one removes it from both) print "likely bug: ebset %r was in %r but not in %r" % \ (ebset, otherchunk, self) self._bonded_chunks[ otherchunk] = ebset pass ebset.add_bond( bond) # ok if bond is already there self._f_gained_externs = False # if some of our ExternalBondSets are now empty, destroy them # (this removes them from *both* their chunks, not only from self) for ebset in maybe_empty: if ebset.empty(): ebset.destroy() return def _destroy_bonded_chunks(self): for ebset in self._bonded_chunks.values(): ebset.destroy() self._bonded_chunks = {} # precaution (should be already true) return def _f_remove_ExternalBondSet(self, ebset): otherchunk = ebset.other_chunk(self) del self._bonded_chunks[otherchunk] def potential_bridging_objects(self): return self._bonded_chunks.values() # == def edit(self): ### REVIEW: model tree has a special case for isProteinChunk; # should we pull that in here too? Guess yes. # (Note, there are several other uses of isProteinChunk # that might also be worth refactoring.) [bruce 090106 comment] if self.isStrandChunk(): self._editProperties_DnaStrandChunk() else: cntl = ChunkProp(self) cntl.exec_() self.assy.mt.mt_update() ### REVIEW [bruce 041109]: don't we want to repaint the glpane, too? def getProps(self): # probably by Ninad """ To be revised post dna data model. Used in EditCommand class and its subclasses. """ return () def setProps(self, params): # probably by Ninad """ To be revised post dna data model. """ del params #START of Nanotube chunk specific code ======================== def isNanotubeChunk(self): # probably by Mark """ Returns True if *all atoms* in this chunk are either: - carbon (sp2) and either all hydrogen or nitrogen atoms or bondpoints - boron and either all hydrogen or nitrogen atoms or bondpoints @warning: This is a very loose test. It will return True if self is a graphene sheet, benzene ring, etc. Use at your own risk. """ found_carbon_atom = False # CNT found_boron_atom = False # BNNT for atom in self.atoms.itervalues(): if atom.element.symbol == 'C': if atom.atomtype.is_planar(): found_carbon_atom = True else: return False elif atom.element.symbol == 'B': found_boron_atom = True elif atom.element.symbol == 'N': pass elif atom.element.symbol == 'H': pass elif atom.is_singlet(): pass else: # other kinds of atoms are not allowed return False if found_carbon_atom and found_boron_atom: return False continue return True def getNanotubeSegment(self): # ninad 080205 """ Return the NanotubeSegment of this chunk if it has one. """ return self.parent_node_of_class(self.assy.NanotubeSegment) #END of Nanotube chunk specific code ======================== def _f_invalidate_atom_lists_and_maybe_deallocate_displist(self): #e rename, see below """ [friend method to be called by _fix_all_chunk_atomsets_differential in undo_archive; called at least whenever Undo makes a chunk dead w/o calling self.kill, which it does when undoing chunk creation or redoing chunk deletion; also called on many other changes by undo or redo, for either alive or dead chunks.] """ self.invalidate_atom_lists() #bruce 071105 created this method and made undo call it # instead of just calling invalidate_atom_lists directly, # so the code below is new. It's needed to make sure that # undo of chunk creation, or redo of chunk kill, deallocates # its display list. See comment next to call about a more # general mechanism (nim) that would be better in the undo # interface to us than this friend method. # REVIEW: would a better name and more general description be something # like "undo has modified your atoms dict, do necessary invals and # deallocates"? I think it would; so I'll split it into two methods, # one to keep here and one to move into ChunkDrawer for now. # [bruce 090123] self._drawer.deallocate_displist_if_needed() return # == def contains_atom(self, atom): #bruce 070514 """ Does self contain the given atom (a real atom or bondpoint)? """ #e the same-named method would be useful in Node, Selection, etc, someday return atom.molecule is self def break_interpart_bonds(self): #bruce 050308-16 to help fix bug 371; revised 050513 """ [overrides Node method] """ assert self.part is not None # check atom-atom bonds for b in self.externs[:]: #e should this loop body be a bond method?? m1 = b.atom1.molecule # one of m1, m2 is self but we won't bother finding out which m2 = b.atom2.molecule try: bad = (m1.part is not m2.part) except: # bruce 060411 bug-safety if m1 is None: m1 = b.atom1.molecule = _get_nullMol() print "bug: %r.atom1.molecule was None (changing it to _nullMol)" % b if m2 is None: m2 = b.atom2.molecule = _get_nullMol() print "bug: %r.atom2.molecule was None (changing it to _nullMol)" % b bad = True if bad: # bruce 060412 print -> print_compact_stack # e.g. this will happen if above code sets a mol to _nullMol #bruce 080227 revised following debug prints; maybe untested #bruce 080410 making them print, not print_compact_stack, temporarily; # they are reported to happen with paste chunk with hotspot onto open bond if m1.part is None: msg = "possible bug: %r .atom1 == %r .mol == %r .part is None" % \ ( b, b.atom1, m1 ) if debug_flags.atom_debug: print_compact_stack( "\n" + msg + ": " ) else: print msg if m2.part is None: msg = "possible bug: %r .atom2 == %r .mol == %r .part is None" % \ ( b, b.atom2, m2 ) if debug_flags.atom_debug: print_compact_stack( "\n" + msg + ": " ) else: print msg b.bust() # someday, maybe: check atom-jig bonds ... but callers need to handle # some jigs specially first, which this would destroy... # actually this would be inefficient from this side (it would scan # all atoms), so let's let the jigs handle it... though that won't work # when we can later apply this to a subtree... so review it then. return def set_hotspot(self, hotspot, silently_fix_if_invalid = False, store_if_invalid = False): #bruce 050217; 050524 added keyword arg; 060410 renamed it & more # first make sure no other code forgot to call us and set it directly assert not 'hotspot' in self.__dict__.keys(), "bug in some unknown other code" if self._hotspot is not hotspot: self.changed() #bruce 060324 fix bug 1532, and an unreported bug where this #didn't mark file as modified self._hotspot = hotspot if not store_if_invalid: # (when that's true, it's important not to recompute self.hotspot, # even in an assertion) # now recompute self.hotspot from the new self._hotspot (to check # whether it's valid) self.hotspot # note: this has side effects we depend on! assert self.hotspot is hotspot or silently_fix_if_invalid, \ "getattr bug, or specified hotspot %s is invalid" % \ safe_repr(hotspot) assert not 'hotspot' in self.__dict__.keys(), \ "bug in getattr for hotspot or in set_hotspot" return def _get_hotspot(self): #bruce 050217; used by getattr hs = self._hotspot if hs is None: return None if hs.is_singlet() and hs.molecule is self: # hs should be a valid hotspot; if you see no bug, return it if hs.killed_with_debug_checks(): # this also checks whether its key is in self.atoms # bug detected if debug_flags.atom_debug: print "_get_hotspot sees killed singlet still claiming to be in this Chunk" # fall thru else: # return a valid hotspot. # (Note: if there is no hotspot but exactly one singlet, # some callers treat that singlet as the hotspot, # but others don't want that feature, so it would be # wrong to do that here.) return hs # hs is not valid (this is often not a bug); forget about it and return None self._hotspot = None return None # bruce 041202/050109 revised the icon code; see longer comment about # Jig.init_icons for explanation; this might be moved into class Node later # Lists of icon basenames (relative to cad/src/ui/modeltree) # in same order as dispNames / dispLabel. Each list has an entry # for each atom display style. One list is for normal use, # one for hidden chunks. # # Note: these lists should *not* include icons for ChunkDisplayMode # subclasses such as DnaCylinderChunks. See 'def node_icon' below # for the code that handles those. [bruce comment 080213] mticon_names = [ "Default.png", "Invisible.png", "CPK.png", "Lines.png", "Ball_and_Stick.png", "Tubes.png"] hideicon_names = [ "Default-hide.png", "Invisible-hide.png", "CPK-hide.png", "Lines-hide.png", "Ball_and_Stick-hide.png", "Tubes-hide.png"] mticon = [] hideicon = [] def init_icons(self): # see also the same-named, related method in class Jig. """ each subclass must define mticon = [] and hideicon = [] as class constants... but Chunk is the only subclass, for now. """ if self.mticon or self.hideicon: return # the following runs once per NE1 session. for name in self.mticon_names: self.mticon.append( imagename_to_pixmap( "modeltree/" + name)) for name in self.hideicon_names: self.hideicon.append( imagename_to_pixmap( "modeltree/" + name)) return def node_icon(self, display_prefs): if self.isProteinChunk(): # Special case for protein icon (for MT only). # (For PM_SelectionListWidget, the attr iconPath was modified in # isProteinChunk() in separate code.) --Mark 2008-12-16. hd = get_display_mode_handler(diPROTEIN) if hd: return hd.get_icon(self.hidden) try: if self.hidden: return self.hideicon[self.display] else: return self.mticon[self.display] except IndexError: # KLUGE: detect self.display being a ChunkDisplayMode [bruce 060608] hd = get_display_mode_handler(self.display) if hd: return hd.get_icon(self.hidden) # else, some sort of bug return imagename_to_pixmap("modeltree/junk.png") pass # lowest-level structure-changing methods def addatom(self, atom): """ Private method; should be the only way new atoms can be added to a Chunk (except for optimized callers like Chunk.merge, and others with comments saying they inline it). Add an existing atom (with no current Chunk, and with a valid literal .xyz field) to the Chunk self, doing necessary invals in self, but not yet giving the new atom an index in our curpos, basepos, etc (which will not yet include the new atom at all). Details of invalidations: Curpos must be left alone (so as not to forget the positions of other atoms); the other atom-position arrays (atpos, basepos) and atom lists (atlist) are defined to be complete, so they're invalidated, and so are whatever other attrs depend on them. In the future we might change this function to incrementally grow those arrays. This will be transparent to callers since they are now recomputed as needed by __getattr__. (It's not worth tracking changes to the set of singlets in the mol, so instead we recompute self.singlets and self.singlpos as needed.) """ ## atom.invalidate_bonds() # might not be needed ## [definitely not after bruce 050516, since changing atom.molecule is enough; # if this is not changing it, then atom was in _nullMol and we don't care # whether its bonds are valid.] # make atom know self as its .molecule assert atom.molecule is None or atom.molecule is _nullMol #bruce 080220 new feature -- but now being done elsewhere (more efficient, # and useless here unless also done in all inlined versions, which is hard): ## if atom._f_assy is not self.assy: ## atom._f_set_assy(self.assy) atom.molecule = self _changed_parent_Atoms[atom.key] = atom #bruce 060322 atom.index = -1 # illegal value # make Chunk self have atom self.atoms[atom.key] = atom self.invalidate_atom_lists() return def delatom(self, atom): """ Private method; should be the only way atoms can be removed from a Chunk (except for optimized callers like Chunk.merge). Remove atom from the Chunk self, preparing atom for being destroyed or for later addition to some other mol, doing necessary invals in self, and (for safety and possibly to break cycles of python refs) removing all connections from atom back to self. """ ## atom.invalidate_bonds() # not needed after bruce 050516; see comment in addatom self.invalidate_atom_lists() # do this first, in case exceptions below # make atom independent of self assert atom.molecule is self atom.index = -1 # illegal value # inlined _get_nullMol: global _nullMol if _nullMol is None: # this caused a bus error when done right after class Chunk # defined; don't know why (class Node not yet ok??) [bruce 041116] ## _nullMol = Chunk("<not an assembly>", 'name-of-_nullMol') # this newer method might or might not have that problem _nullMol = _make_nullMol() atom.molecule = _nullMol # not a real mol; absorbs invals without harm _changed_parent_Atoms[atom.key] = atom #bruce 060322 # (note, we *don't* add atom to _nullMol.atoms, or do invals on it here; # see comment about _nullMol where it's defined) # make self forget about atom del self.atoms[atom.key] # callers can check for KeyError, always an error if not self.atoms: self.kill() # new feature, bruce 041116, experimental return # some invalidation methods def invalidate_atom_lists(self, invalidate_atom_content = True): """ [private method (but also called directly from undo_archive)] some atom is joining or leaving self; do all needed invalidations @note: ok to call just once, if many atoms are joining and/or leaving """ # Note: as of 060409 I think Undo/Redo can call this on newly dead Chunks # (from _fix_all_chunk_atomsets_differential, as of 071105 via the new # method _f_invalidate_atom_lists_and_maybe_deallocate_displist); # I'm not 100% sure that's ok, but I can't see a problem in the method # and I didn't find a bug in testing. [bruce 060409] self._drawer.invalidate_display_lists() self.haveradii = 0 self._f_lost_externs = True self._f_gained_externs = True if invalidate_atom_content: self.invalidate_atom_content() #bruce 080306 # the following is just an optimization [bruce 050513] of: ## self.invalidate_attrs(['externs', 'atlist']) # (since it's 25% of time to read atom records from mmp file, # 1 sec for 8k atoms) # note: invalidating externs is usually needed, so simplest to # do it always need = False try: del self.externs except: pass else: need = True try: del self.atlist # this is what makes it ok for atom indices to be invalid, as # they are when self.atoms changes, until self.atlist is next # recomputed [bruce 060313 comment] except: pass else: need = True if need: # this causes trouble, not yet sure why: ## self.changed_attrs(['externs', 'atlist']) ## AssertionError: validate_attr finds no attr 'externs' was saved, ## in <Chunk 'Ring Gear' (5167 atoms) at 0xd967440> # so do this instead: self.externs = self.atlist = -1 self.invalidate_attrs(['externs', 'atlist']) return def _ac_recompute_atom_content(self): #bruce 080306 """ Recompute and return (but do not record) our atom content, optimizing this if it's exactly known on any node-subtrees. @see: Atom.setDisplayStyle, Atom.revise_atom_content [Overrides superclass method. Subclasses whose atoms are stored differently may need to override this further.] """ atom_content = 0 for atom in self.atoms.itervalues(): ## atom_content |= (atom._f_updated_atom_content()) # IMPLEM that method on class Atom (look up from self.display)? # no, probably best to inline it here instead: atom_content |= ATOM_CONTENT_FOR_DISPLAY_STYLE[atom.display] # possible optimizations, if needed: # - could use 1<<(atom.display) and then postprocess # to add AC_HAS_INDIVIDUAL_DISPLAY_STYLE, if we wanted to inline # the definition of ATOM_CONTENT_FOR_DISPLAY_STYLE # - could skip bondpoints # - could skip all diDEFAULT atoms [###doit] return atom_content def invalidate_everything(self): """ Invalidate all invalidatable attrs of self. (Used in _undo_update and in some debugging methods.) """ self._invalidate_all_bonds() self.invalidate_atom_lists() # _undo_update depends on us calling this attrs = self.invalidatable_attrs() # now this is done in that method: ## attrs.sort() # be deterministic even if it hides bugs for some orders for attr in attrs: self.invalidate_attr(attr) # (these might be sufficient: ['externs', 'atlist', 'atpos']) return # debugging methods (not fully tested, use at your own risk) def update_everything(self): attrs = self.invalidatable_attrs() # now this is done in that method: ## attrs.sort() # be deterministic even if it hides bugs for some orders for attr in attrs: junk = getattr(self, attr) # don't actually remake display lists, but next redraw will do that; # don't invalidate them, since our semantics are to only update. return # some more invalidation methods def changed_atom_posn(self): #bruce 060308 """ One of self's atoms changed position; invalidate whatever we might own that depends on that (other than our ExternalBondSets, whose appearance the caller must invalidate if needed). """ # initial implem might be too conservative; should optimize, perhaps # recode in a new Pyrex ChunkBase. Some code is copied from # now-obsolete setatomposn; some of its comments might apply here as # well. self.changed() self._drawer.invalidate_display_lists() self.invalidate_attr('atpos') #e should optim this ##k verify this also invals basepos, or add that to the arg of this call return # for __getattr__, validate_attr, invalidate_attr, etc, see InvalMixin # [bruce 041111 says:] # These singlet-list and singlet-array attributes are not worth much trouble, # since they are never used in ways that need to be very fast, # but we do memoize self.singlets, so that findSinglets et. al. needn't # recompute it more than once (per call) or worry whether its order is the # same each time they recompute it. (I might or might not memoize singlpos # too... for now I do, since it's easy and low-cost to do so, but it's # not worth incrementally maintaining it in setatomposn or mol.move/rot # as was done before.) # # I am tempted to depend on self.atoms rather than self.atlist in the # recomputation method for self.singlets, # so I don't force self.atlist to be recomputed in it. # This would require changing the convention for what's invalidated by # addatom and delatom (they'd call changed_attr('atoms')). But I am # slightly worried that some uses of self.singlets might assume every # atom in there has a valid .index (into curpos or basepos), so I won't. # # Note that it would be illegal to pretend we're dependent on self.atlist # in _inputs_for_singlets, but to use self.atoms.values() in this code, since # this could lead to self.singlets existing while self.atlist did not, # making invals of self.atlist, which see it missing so think they needn't # invalidate self.singlets, to be wrong. [##e I should make sure to document # this problem in general, since it affects all recompute methods that don't # always access (and thus force recompute of) all their declared inputs.] # [addendum, 050219: not only that, but self.atoms.values() has indeterminate # order, which for all we know might be different each time it's constructed.] _inputs_for_singlets = ['atlist'] def _recompute_singlets(self): """ Recompute self.singlets, a list of self's bondpoints. """ # (Filter always returns a python list, even if atlist is a Numeric.array # [bruce 041207, by separate experiment]. Some callers test the boolean # value we compute for self.singlets. Since the elements are pyobjs, # this would probably work even if filter returned an array.) return filter( lambda atom: atom.element is Singlet, self.atlist ) _inputs_for_singlpos = ['singlets', 'atpos'] def _recompute_singlpos(self): """ Recompute self.singlpos, a Numeric array of self's bondpoint positions (in absolute coordinates). """ self.atpos # we must access self.atpos, since we depend on it in our inval rules # (if that's too slow, then anyone invalling atpos must inval this too #e) if len(self.singlets): return A( map( lambda atom: atom.posn(), self.singlets ) ) else: return [] pass # These 4 attrs are stored in one tuple, so they can be invalidated # quickly as a group. def _get_polyhedron(self): # self.polyhedron return self.poly_evals_evecs_axis[0] #bruce 060119 commenting these out since they are not used, # though if we want them it's fine to add them back. #bruce 060608 renamed them with plural 's'. ## def _get_evals(self): # self.evals ## return self.poly_evals_evecs_axis[1] ## def _get_evecs(self): # self.evecs ## return self.poly_evals_evecs_axis[2] def _get_axis(self): # self.axis return self.poly_evals_evecs_axis[3] _inputs_for_poly_evals_evecs_axis = ['basepos'] def _recompute_poly_evals_evecs_axis(self): return shakedown_poly_evals_evecs_axis( self.basepos) def full_inval_and_update(self): # bruce 041112-17 """ Public method (but should not usually be needed): invalidate and then recompute everything about a mol. Some old callers of shakedown might need to call this now, if there are bugs in the inval/update system for mols. And extrude calls it since it uses the deprecated method set_basecenter_and_quat. """ # full inval (has some common code with invalidate_atom_lists): self._drawer.invalidate_display_lists() self._f_lost_externs = self._f_gained_externs = True self.haveradii = 0 self.invalidate_attrs(['atlist', 'externs']) # invalidates everything, I think assert not self.valid_attrs(), \ "full_inval_and_update forgot to invalidate something: %r" % self.valid_attrs() # full update (but invals bonds): self.atpos # this invals all internal bonds (since it revises basecenter); we depend on that # self.atpos also recomputes some other things, but not the following -- do them all: self.bbox self.singlpos self.externs self.axis self.get_sel_radii_squared() assert not self.invalid_attrs(), \ "full_inval_and_update forgot to update something: %r" % self.invalid_attrs() return # Primitive modifier methods will (more or less by convention) # invalidate atlist if they add or remove atoms (or singlets), # and atpos if they move existing atoms (or singlets). # # (We will not bother to have them check whether they # are working with singlets, and if not, avoid invalidating # variables related to singlets. To add this, we would modify # the rules here so that invalidating atlist did not automatically # invalidate singlets (the list), etc... doing this right would # require a bit of thought, but is easy enough if we need it... # note that it would require checking elements when atoms are transmuted, # as well as checks for singlets in addatom/delatom/setatomposn.) _inputs_for_atlist = [] # only invalidated directly, by addatom/delatom def _recompute_atlist(self): #bruce 060313 split out of _recompute_atpos """ Recompute self.atlist, a list or Numeric array of this chunk's atoms (including bondpoints), ordered by atom.key. Also set atom.index on each atom in the list, to its index in the list. """ atomitems = self.atoms.items() atomitems.sort() # in order of atom keys; probably doesn't yet matter, but makes order deterministic atlist = [atom for (key, atom) in atomitems] self.atlist = array(atlist, PyObject) #review: untested whether making it an array is good or bad for atom, i in zip(atlist, range(len(atlist))): atom.index = i return _inputs_for_atpos = ['atlist'] # also incrementally modified by setatomposn [not anymore, 060308] # (Atpos could be invalidated directly, but maybe it never is (not sure); # anyway we don't optim for that.) _inputs_for_basepos = ['atpos'] # also invalidated directly, but not often def _recompute_atpos(self): """ recompute self.atpos and self.basepos and more; also change self's local coordinate system (used for basepos) [#doc more] """ #bruce 060308 major rewrite #bruce 060313 splitting _recompute_atlist out of _recompute_atpos # Something must have been invalid to call us, so basepos must be # invalid. So we needn't call changed_attr on it. assert not self.__dict__.has_key('basepos') if self.assy is None: if debug_flags.atom_debug: # [bruce comment 050702: this happens if you delete the chunk # while dragging it by selatom in build mode] msg = "atom_debug: fyi, recompute atpos called on killed mol %r" % self print_compact_stack(msg + ": ") # Optional debug code: # This might be called if basepos doesn't exist but atpos does. # I don't think that can happen, but if it can, I need to know. # So find out which of the attrs we recompute already exist: ## print "_recompute_atpos on %r" % self ## for attr in ['atpos', 'average_position', 'basepos']: ## ## vq = self.validQ(attr) ## if self.__dict__.has_key(attr): ## print "fyi: _recompute_atpos sees %r already existing" % attr atlist = self.atlist # might call _recompute_atlist atpos = map( lambda atom: atom.posn(), atlist ) # atpos, basepos, and atlist must be in same order atpos = A(atpos) # we must invalidate or fix self.atpos when any of our atoms' positions is changed! self.atpos = atpos assert len(atpos) == len(atlist) self._recompute_average_position() # sets self.average_position from self.atpos self.basecenter = + self.average_position # not an invalidatable attribute # unary '+' prevents mods to basecenter from affecting # average_position; it might not be needed (that depends on # Numeric.array += semantics). # Note: basecenter is arbitrary, but should be somewhere near the # atoms... except see set_basecenter_and_quat, used in extrudeMode -- # it may be that it's not really arbitrary due to kluges in how that's # used [still active as of 070411]. if debug_messup_basecenter: # ... so this flag lets us try some other value to test that!! blorp = messupKey.next() self.basecenter += V(blorp, blorp, blorp) self.quat = Q(1,0,0,0) # arbitrary value, except we assume it has this specific value to # simplify/optimize the next line if self.atoms: self.basepos = atpos - self.basecenter # set now (rather than when next needed) so it's still safe to # assume self.quat == Q(1,0,0,0) else: self.basepos = [] # this has wrong type, so requires special code in mol.move etc ###k Could we fix that by just assigning atpos to it (no elements, # so should be correct)?? [bruce 060119 question] assert len(self.basepos) == len(atlist) # note: basepos must be a separate (unshared) array object # (except when mol is frozen [which is no longer supported as of 060308]); # as of 060308 atpos (when defined) is a separate array object, # since curpos no longer exists. self._changed_basecenter_or_quat_while_atoms_fixed() # (that includes self.changed_attr('basepos'), though an assert above # says that that would not be needed in this case.) # validate the attrs we set, except for the non-invalidatable ones, # which are curpos, basecenter, quat. self.validate_attrs(['atpos', 'average_position', 'basepos']) return # from _recompute_atpos # aliases, in case someone needs one of the other things we compute # (but not average_position, that has its own recompute method): _recompute_basepos = _recompute_atpos def _changed_basecenter_or_quat_while_atoms_fixed(self): """ [private method] If you change self.basecenter or self.quat while intending self's atoms to remain fixed in absolute space (rather than moving along with those changes), first recompute self.basepos to be correct in the new local coordinates (or perhaps just invalidate self.basepos -- that use is unanalyzed and untried), then call this method to do necessary invals. This method invals other things (besides self.basepos) which depend on self's local coordinate system -- i.e. self's internal bonds and self's OpenGL display lists; and it calls changed_attr('basepos'). """ self._invalidate_internal_bonds() self.changed_attr('basepos') self._drawer.invalidate_display_lists() #### REVIEW: can we transform them instead? Not sure there's much # reason, since this usually happens due to changes that # invalidate_display_lists anyway. #### REVIEW: do we need to invalidate ExternalBondSet DLs? #### Is this called when we remove a dynamic_transform from self #### (once our super of TransformNode is implemented)? def _invalidate_internal_bonds(self): self._invalidate_all_bonds() # easiest to just do this def _invalidate_all_bonds(self): #bruce 050516 optimized this global _inval_all_bonds_counter _inval_all_bonds_counter += 1 # note: it's convenient that individual values of this global # counter are not used on more than one chunk, since that way # there's no need to worry about whether the bond inval/update # code, which should be the only code to look at this counter, # needs to worry that its data looks right but is for the wrong # chunks. self._f_bond_inval_count = _inval_all_bonds_counter return _inputs_for_average_position = ['atpos'] def _recompute_average_position(self): """ Compute or recompute self.average_position, the average position of the atoms (including singlets); store it, so _recompute_atpos can also call it since it needs the same value; not sure if it's useful to have a separate recompute method for this attribute; but probably yes, so it can run after incremental mods to atpos. """ if self.atoms: self.average_position = add.reduce(self.atpos)/len(self.atoms) else: self.atpos # recompute methods must always use all their inputs self.average_position = V(0,0,0) return def _get_center_weight(self):#bruce 070411 """ Compute self.center_weight, the weight that should be given to self.center for making group centers as weighted averages of chunk centers. """ return len(self.atoms) _inputs_for_bbox = ['atpos'] def _recompute_bbox(self): """ Recompute self.bbox, an axis-aligned bounding box (in absolute coordinates) made from all of self's atom positions (including bondpoints), plus a fudge factor to account for atom radii. """ self.bbox = BBox(self.atpos) # Center. def _get_center(self): # _get_center seems better than _recompute_center since this attr # is only needed by the UI and this method is fast """ Compute self.center on demand, which is the center to use for rotations and stretches and perhaps some other purposes. Presently, this is always the average position of all atoms in self (including bondpoints). """ ## if self.user_specified_center is not None: ## return self.user_specified_center return self.average_position # What used to be called self.center, used mainly to relate basepos and curpos, # is now called self.basecenter and is not a recomputed attribute, # though it is chosen and stored by the _recompute_atpos method. # See also a comment about this in Chunk.__init__. [bruce 041112] # Externs _inputs_for_externs = [] # only invalidated by hand def _recompute_externs(self): """ Recompute self.externs, the list of external bonds of self. """ externs = [] for atom in self.atoms.itervalues(): for bond in atom.bonds: if bond.atom1.molecule is not self or \ bond.atom2.molecule is not self: externs.append(bond) return externs # == def get_dispdef(self, glpane = None): """ @return: display style we'd use to draw self on the given glpane (or on self.assy.o if glpane is not provided) @see: getDisplayStyle """ # REVIEW: how should it be refactored so each type of chunk # (protein, dna, etc) has its own drawing code, including its own way # of interpreting display style settings (which themselves need a lot # of refactoring and generalization)? # [bruce 090123 comment] if self.display != diDEFAULT: disp = self.display else: if glpane is None: glpane = self.assy.o disp = glpane.displayMode if disp == diDNACYLINDER and not self.isDnaChunk(): # piotr 080409 fix bug 2785, revised by piotr 080709 if self.isProteinChunk(): disp = diPROTEIN else: disp = glpane.lastNonReducedDisplayMode if disp == diPROTEIN and not self.isProteinChunk(): # piotr 080709 if self.isDnaChunk(): disp = diDNACYLINDER else: disp = glpane.lastNonReducedDisplayMode return disp # == def writepov(self, file, disp): """ Draw self (if visible) into an open povray file (which already has whatever headers & macros it needs), using the given display mode unless self overrides it. """ if self.hidden: return if self.display != diDEFAULT: disp = self.display drawn = self.part.drawing_frame.repeated_bonds_dict # bruce 070928 bugfix: use repeated_bonds_dict # instead of a per-chunk dict, so we don't # draw external bonds twice if drawn is None: # bug, but we can work around it locally; # I'd add a debug print except I might never test this # before the release and it might be verbose [bruce 090218] drawn = {} for atom in self.atoms.values(): atom.writepov(file, disp, self.color) for bond in atom.bonds: if id(bond) not in drawn: drawn[id(bond)] = bond bond.writepov(file, disp, self.color) # piotr 080521 # write POV-Ray file for the ChunkDisplayMode hd = get_display_mode_handler(disp) if hd: hd._writepov(self, file) def writemdl(self, alist, f, disp): if self.display != diDEFAULT: disp = self.display if self.hidden or disp == diINVISIBLE: return # review: use self.color somehow? for a in self.atoms.values(): a.writemdl(alist, f, disp, self.color) # == def move(self, offset): """ Public method: translate self (a Chunk) by offset; do all necessary invalidations, but optimize those based on self's relative structure not having changed or reoriented. """ # code and doc rewritten by bruce 041109. # The method is public but its implem is pretty private! # First make sure self.basepos is up to date! Otherwise # self._changed_basecenter_or_quat_to_move_atoms() might not be able to reconstruct it. # I don't think this should affect self.bbox, but in case I'm wrong, # do this before looking at bbox. self.basepos # Now, update bbox iff it's already present. if self.__dict__.has_key('bbox'): # bbox already present -- moving it is faster than recomputing it #e (though it might be faster to just delete it, if many moves # will happen before we need it again) # TODO: refactor this to use a move method in bbox. if self.bbox.data: self.bbox.data += offset # Now, do the move. Note that this might destructively modify the object # self.basecenter rather than replacing it with a new one. self.basecenter += offset # (note that if we did "self.bbox.data += off" at this point, and # self.bbox was not present, it might be recomputed from inconsistent # data (depending on details of _recompute_bbox) and then moved; # so don't do it here!) # Do all necessary invalidations and/or recomputations (except for bbox), # treating basepos as definitive and recomputing curpos from it. self._changed_basecenter_or_quat_to_move_atoms() def pivot(self, point, q): """ Public method: pivot the Chunk self around point by quaternion q; do all necessary invalidations, but optimize those based on self's relative structure not having changed. See also self.rot(). """ # First make sure self.basepos is up to date! Otherwise # self._changed_basecenter_or_quat_to_move_atoms() might not be able to reconstruct it. self.basepos # Do the motion (might destructively modify basecenter and quat objects) r = point - self.basecenter self.basecenter += r - q.rot(r) self.quat += q # No good way to rotate a bbox, so just invalidate it. self.invalidate_attr('bbox') # Do all necessary invalidations and/or recomputations (except bbox), # treating basepos as definitive and recomputing curpos from it. self._changed_basecenter_or_quat_to_move_atoms() def rot(self, q): """ Public method: rotate self around its center by quaternion q; do all necessary invalidations, but optimize those based on self's relative structure not having changed. See also self.pivot(). """ # bruce 041109: the center of rotation is not always self.basecenter, # so in general we need to pivot around self.center. self.pivot(self.center, q) # not basecenter! return def stretch(self, factor, point = None): """ Public method: expand self by the given factor (keeping point fixed -- by default, point is self.center). Do all necessary invalidations, optimized for this operation. """ self.basepos # recompute if necessary # note: use len(), since A([[0.0,0.0,0.0]]) is false! if not len(self.basepos): # precaution (probably never occurs): # special case for no atoms, since # remaining code won't work for it, # since self.basepos has the wrong type then (it's []). # Note that no changes or invals are needed in this case. return factor = float(factor) if point is None: point = self.center # not basecenter! # without moving self in space, change self.basecenter to point # and change self.basepos to match (so the stretch around point # can be done in a simple way, lower down) self.basepos += (self.basecenter - point) self.basecenter = point # i.e. self.basecenter = self.basecenter - self.basecenter + point, # or self.basecenter -= (self.basecenter - point) # stretch self around the new self.basecenter self.basepos *= factor # (warning: the above += and *= might destructively modify basepos -- I'm not sure) # do necessary recomputes from the new definitive basepos, # and invals (including bbox, internal bonds) self._changed_basepos_basecenter_or_quat_to_move_atoms() def _changed_basepos_basecenter_or_quat_to_move_atoms(self): """ like _changed_basecenter_or_quat_to_move_atoms, but we also might have changed basepos """ # Do the needed invals, and recomputation of curpos from basepos # (I'm not sure if the order would need review if we revise inval rules): self._drawer.invalidate_display_lists() # (not needed for mov or rot, so not done by _changed_basecenter_or_quat_to_move_atoms) self.changed_attr('basepos') # invalidate whatever depends on basepos ... self._invalidate_internal_bonds() # ... including the internal bonds, handled separately self.invalidate_attr('bbox') # since not handled by following routine self._changed_basecenter_or_quat_to_move_atoms() # (misnamed -- in this case we changed basepos too) def _changed_basecenter_or_quat_to_move_atoms(self): #bruce 041104-041112 """ Call this whenever you have just changed self.basecenter and/or self.quat (and/or self.basepos if you call changed_attr on it yourself), and you want to move the Chunk self (in 3d model space) by changing curpos to match, assuming that basepos is still correct in the new local coords basecenter and quat. Note that basepos must already exist, since this method can't recompute it from curpos in the standard way, since curpos is wrong and basepos is correct (not a legal state except within the callers of this method). Also do the proper invalidations and/or incremental recomputations, except for self.bbox, which the caller must fix or invalidate (either before or after calling us). Our invalidations assume that only basecenter and/or quat were changed; some callers (which modify basepos) must do additional invalidations. @see: _changed_basecenter_or_quat_while_atoms_fixed (quite different) """ assert self.__dict__.has_key('basepos'), \ "internal error in _changed_basecenter_or_quat_to_move_atoms for %r" % (self,) if not len(self.basepos): #bruce 041119 bugfix -- use len() # we need this 0 atoms case (though it probably never occurs) # since the remaining code won't work for it, # since self.basepos has the wrong type then (in fact it's []); # note that no changes or invals are needed for 0 atoms. return # record the fact that the model will have changed by the time we return # [bruce 071102 -- fixes bug 2576 and perhaps analogous bugs; # note that traditionally these calls have been left up to the # user event handlers, so most of the Node changing methods that # ought to do them probably don't do them.] self.changed() # Node method # imitate the recomputes done by _recompute_atpos self.atpos = self.basecenter + self.quat.rot(self.basepos) # inlines base_to_abs self._set_atom_posns_from_atpos( self.atpos) #bruce 060308 # no change in atlist; no change needed in our atoms' .index attributes # no change here in basepos or bbox (if caller changed them, it should # call changed_attr itself, or it should invalidate bbox itself); # but changes here in whatever depends on atpos, aside from those. self.changed_attr('atpos', skip = ('bbox', 'basepos')) # we've moved one end of each external bond, so invalidate them... # [bruce 050516 comment (95% sure it's right): # note that we don't, and need not, inval internal bonds] for bond in self.externs: bond.setup_invalidate() return def _set_atom_posns_from_atpos(self, atpos): #bruce 060308; revised 060313 """ Set our atom's positions en masse from the given array, doing no chunk or bond invals (caller must do whichever invals are needed, which depends on how the positions changed). The array must be in the same order as self.atpos (its typical value, but we won't depend on that and won't access or modify self.atpos) and self.atlist (which must already exist). """ assert self.__dict__.has_key('atlist') atlist = self.atlist assert len(atlist) == len(atpos) for i in xrange(len(atlist)): atlist[i]._f_setposn_no_chunk_or_bond_invals( atpos[i] ) return def applyToPoint(self, point): #bruce 090223 """ Considering self as a transform (namely, the transform used to map relative to absolute coordinates), apply that transform to the given point. @return: transformed point @note: part of the TransformControl API """ # review: should we pick single name, and merge methods applyToPoint and base_to_abs? # or do they have different contracts (point vs anything)? return self.base_to_abs(point) def base_to_abs(self, anything): # bruce 041115, docstring revised 090223 """ map anything (which is accepted by quat.rot() and Numeric.array's '+' method, and which is semantically equivalent to a point or array of points -- not a vector!) from Chunk-relative coordinates to absolute coordinates. @note: guaranteed to never recompute basepos/atpos or modify the chunk-relative coordinate system state it uses. @see: Inverse of abs_to_base. Used to implement applyToPoint. """ return self.basecenter + self.quat.rot( anything) def abs_to_base(self, anything): # bruce 041201, docstring revised 090223 """ map anything (which is accepted by quat.unrot() and Numeric.array's '-' method, and which is semantically equivalent to a point or array of points -- not a vector!) from absolute coordinates to chunk-relative coordinates. @note: guaranteed to never recompute basepos/atpos or modify the chunk-relative coordinate system state it uses. @see: Inverse of base_to_abs. """ return self.quat.unrot( anything - self.basecenter) def set_basecenter_and_quat(self, basecenter, quat): """ Deprecated public method: Change self's basecenter and quat to the specified values, as a way of moving self's atoms. It's deprecated since basecenter and quat are replaced by in-principle-arbitrary values every time certain recomputations are done after self's geometry might have changed, but this method is only useful if the caller knows what they are, and computes the new ones it wants relative to what they are, which in practice means the caller must be able to prevent modifications to self during an entire period when it wants to be able to call this method repeatedly on self. So it's much better to use self.pivot instead (or some combo of move, rot, and pivot methods). """ # [written by bruce for extrude; moved into class Chunk by bruce 041104] # modified from mol.move and mol.rot as of 041015 night self.basepos # recompute basepos if it's currently invalid # make sure mol owns its new basecenter and quat, # since it might destructively modify them later! self.basecenter = V(0,0,0) + basecenter self.quat = Q(1,0,0,0) + quat # review: +quat might be correct and faster... don't know; doesn't matter much self.bbox = None del self.bbox #e could optimize if quat is not changing self._changed_basecenter_or_quat_to_move_atoms() def getaxis(self): """ Return self's axis, in absolute coordinates. @note: several Nodes have this method, but it's not (yet) formally a Node API method. @see: self.axis (in self-relative coordinates) """ return self.quat.rot(self.axis) def setcolor(self, color, repaint_in_MT = True): """ Change self's color to the specified color. A color of None means self's atoms will be drawn with their element colors. @param color: None, or a standard color 3-tuple. @param repaint_in_MT: True by default; callers can optimize by passing False if they know self is too new to have ever been drawn into any model tree widget. """ #bruce 080507 added repaint_in_MT option # color is None or a 3-tuple; it matters that the 3-tuple is never boolean False, # so don't use a Numeric array! As a precaution, enforce this now. [bruce 050505] if color is not None: r,g,b = color color = r,g,b self.color = color # warning: some callers (ChunkProp.py) first replace self.color, # then call us to bless the new value. Therefore the following is # needed even if self.color didn't change here. [bruce 050505 comment] self._drawer.invalidate_display_lists() #### TODO: optim -- draw self when colored with nocolor_dl, # so no need to inval here [bruce comment 090211] self.changed() if repaint_in_MT and pref_show_node_color_in_MT(): #bruce 080507, mainly for testing new method repaint_some_nodes self.assy.win.mt.repaint_some_nodes([self]) return def setDisplayStyle(self, disp): #bruce 080910 renamed from setDisplay """ Set self's display style. """ if self.display == disp: #bruce 080305 optimization; looks safe after review of all calls; # important (due to avoiding inlined changeapp and display list # remake) if user selects several chunks and changes them all # at once, and some are already set to disp. Also done in class Atom. return self.display = disp # part of inlined self.changeapp(1) (not all is needed): self._drawer.invalidate_display_lists() #### TODO: optim: cache DLs for at least one old display style, # to speed up changing back to prior style self.haveradii = 0 self.changed() return def getDisplayStyle(self): """ Return the display style setting on self. Note that this might be diDEFAULT -- that setting makes self get drawn as if it had a display style inherited from self's graphical environment (for now, its glpane), but an inherited style is never returned from this method (unless it also happens to be explicitly set on self). (Use get_dispdef to obtain the display style that will be used to draw self, which might be set on self or inherited from self's environment.) @note: the display style used to draw self can differ from self.display not only if that's diDEFAULT, but due to some special cases in get_dispdef based on what kind of chunk self is. @see: L{get_dispdef()} """ return self.display def show_invisible_atoms(self): # by Mark ### TODO: RENAME """ Reset the display style of each invisible (diINVISIBLE) atom in self to diDEFAULT, thus making it visible again. @return: number of invisible atoms in self (which are all made visible) """ n = 0 for a in self.atoms.itervalues(): if a.display == diINVISIBLE: a.setDisplayStyle(diDEFAULT) n += 1 return n def set_atoms_display(self, display): """ Change the display style setting for all atoms in self to the one specified by 'display'. @param display: display style setting to apply to all atoms in self (can be diDEFAULT or diINVISIBLE or various other values) @return: number of atoms in self whose display style setting changed """ n = 0 for a in self.atoms.itervalues(): if a.display != display: a.setDisplayStyle(display) # REVIEW: does this always succeed? # If not, should we increment n then? [bruce 090108 questions] n += 1 return n def changeapp(self, atoms): """ Call this when you've changed the graphical appearance of self. (But there is no need to call it if only self's external bonds look different, or (at present) just for a change to self.picked.) @param atoms: (required) True means that not only the graphical appearance of self, but also specifically the set of atoms of self or their atomic radii (for purposes of hover-highlighting(?) or selection), have changed. @type atoms: boolean @note: changeapp does not itself call self.assy.changed(), since that is not always correct to do (e.g., selecting an atom should call changeapp(), but not assy.changed(), on atom.molecule). @see: changed_selected_atoms """ #### REVIEW and document: need this be called when changing self's color? #### TODO: classify external calls, figure out which ones must also invalidate EBSets #### self._drawer.invalidate_display_lists() if atoms: #bruce 041207 added this arg and its effect self.haveradii = 0 # invalidate self.sel_radii_squared # (using self.invalidate_attr would be too slow) ### REVIEW my removal of the following code (now that invalidate_display_lists does track_inval): # the best test would be, does something that calls changeapp and nothing else # do a gl_update? I'm not sure what op does that, so leave this here until # that's definitively tested. [bruce 090212/090217] # ## #bruce 050804 new feature ## # (related to graphics prefs updating, ## # probably more generally useful): ## # REVIEW: do some inlines of changeapp need to do this too? ## # If they did, would that catch the redraws that currently ## # only Qt knows we need to do? [bruce 080305 question] ## glpane = self.glpane ## # the last glpane that drew this chunk, or None if it was never ## # drawn (if more than one can ever draw it at once, this code ## # needs to be revised to scan them all ##k) ## if glpane is not None: ## try: ## flag = glpane.wants_gl_update ## except AttributeError: ## # this will happen for ThumbViews, until they are fixed to use ## # this system so they get updated when graphics prefs change ## pass ## else: ## if flag: ## glpane.wants_gl_update_was_True() # sets it False and does gl_update ## pass return def invalidate_distortion(self): #bruce 090211; note, NOT YET CALLED as of 090213 (awaiting use of superclass TransformNode) #### TODO: refile into superclass TransformNode, when we have it #### TODO: call where needed, eg some changeapp calls; also make sib method for external atoms display changes """ Called when any of our atoms' relative coordinates move (thus changing our shape, and presumably that of all our transform-bridging objects such as ExternalBondSets). """ for bo in self.bridging_objects(): #### note: this method is only defined in TransformNode bo.invalidate_distortion() return def changed_selected_atoms(self): #bruce 090119 """ Invalidate whatever is needed due to something having changed the selectness of some of self's atoms. @note: this is a low-level method, called by Atom.pick/unpick etc, so most new code need never call this. """ self.changeapp(1) # * for atom appearance (since selected atom wireframes are part of # the main chunk display list) # * for selatom radius (affected by selectedness for invisible atoms) self.changed_selection() # reports an undoable change to selection def natoms(self): #bruce 060215 """ Return number of atoms (real atoms or bondpoints) in self. """ return len(self.atoms) def getToolTipInfo(self): """ Return the tooltip string for this chunk """ info = self._getToolTipInfo_Dna() if info: return info # in future, we might combine it with other info return "" def getinfo(self): # mark 2004-10-14 """ Return information about the selected chunk for the msgbar """ if self is self.assy.ppm: return ele2Num = {} # Determine the number of element types in this Chunk. for a in self.atoms.values(): if not ele2Num.has_key(a.element.symbol): ele2Num[a.element.symbol] = 1 # New element found else: ele2Num[a.element.symbol] += 1 # Increment element # String construction for each element to be displayed. natoms = self.natoms() # number of atoms in the chunk nsinglets = 0 einfo = "" for item in ele2Num.iteritems(): if item[0] == "X": # Singlet nsinglets = int(item[1]) continue else: eleStr = "[" + item[0] + ": " + str(item[1]) + "] " einfo += eleStr if nsinglets: eleStr = "[Open bonds: " + str(nsinglets) + "]" einfo += eleStr natoms -= nsinglets # compute number of real atoms in this chunk minfo = "Chunk Name: [" + str (self.name) + "] Total Atoms: " + str(natoms) + " " + einfo # set ppm to self for next mol picked. self.assy.ppm = self return minfo def getstatistics(self, stats): """ Adds the current chunk, including number of atoms and singlets, to part stats. """ stats.nchunks += 1 stats.natoms += self.natoms() for a in self.atoms.itervalues(): if a.element.symbol == "X": stats.nsinglets += 1 def pickatoms(self): # mark 060211. """ Pick the atoms of self not already picked (selected). Return the number of newly picked atoms. [overrides Node method] """ # todo: Could use a complementary unpickatoms() method. [mark 060211] # [fyi, that doesn't refer to the one in ops_select --bruce] self.assy.permit_pick_atoms() npicked = 0 for a in self.atoms.itervalues(): if not a.is_singlet(): if not a.picked: a.pick() if a.picked: # in case not picked due to selection filter npicked += 1 return npicked def pick(self): """ select self [extends Node method] """ if not self.picked: if self.assy is not None: self.assy.permit_pick_parts() #bruce 050125 added this... hope it's ok! ###k ###@@@ # (might not be needed for other kinds of leaf nodes... # not sure. [bruce 050131]) _superclass.pick(self) #bruce 050308 comment: _superclass.pick (Node.pick) has ensured #that we're in the current selection group, so it's correct to #append to selmols, *unless* we recompute it now and get a version #which already contains self. So, we'll maintain it iff it already #exists. Let the Part figure out how best to do this. # [bruce 060130 cleaned this up, should be equivalent] if self.part: self.part.selmols_append(self) self._drawer._f_kluge_set_selectedness_for_drawing(True) pass return def unpick(self): """ unselect self [extends Node method] """ if self.picked: _superclass.unpick(self) if self.part: self.part.selmols_remove(self) self._drawer._f_kluge_set_selectedness_for_drawing(False) pass return def getAxis_of_self_or_eligible_parent_node(self, atomAtVectorOrigin = None): """ Return the axis of a parent node such as a DnaSegment or a Nanotube Segment or the dna segment of a DnaStrand. If one doesn't exist, return self's axis. Also return the node from which the returned axis was found. @param atomAtVectorOrigin: If the atom at vector origin is specified, the method will try to return the axis vector with the vector start point at this atom's center. [REVIEW: What does this mean??] @type atomAtVectorOrigin: B{Atom} @return: (axis, node used to get that axis) """ #@TODO: refactor this. Method written just before FNANO08 for a critical #NFR. (this code is not a part of Rattlesnake rc2) #- Ninad 2008-04-17 #bruce 090115 partly refactored it, but more would be better. # REVIEW: I don't understand any meaning in what the docstring says about # atomAtVectorOrigin. What does it actually do? [bruce 090115 comment] axis, node = self._getAxis_of_self_or_eligible_parent_node_Dna( atomAtVectorOrigin = atomAtVectorOrigin ) if axis is not None: return axis, node nanotube = self.parent_node_of_class(self.assy.NanotubeSegment) if nanotube: axisVector = nanotube.getAxisVector(atomAtVectorOrigin = atomAtVectorOrigin) if axisVector is not None: return axisVector, nanotube #If no eligible parent node with an axis is found, return self's axis. return self.getaxis(), self def is_glpane_content_itself(self): #bruce 080319 """ @see: For documentation, see Node method docstring. @rtype: boolean [overrides Node method] """ # Note: this method is misnamed, since it's not about graphics drawing # or the GLPane as an implementation of that; it's a selection- # semantics method. (See comment on Node def for more info.) So it # should not be moved to ChunkDrawer. [bruce 090123 comment] return True def kill(self): """ (Public method) Kill a Chunk: unpick it, break its external bonds, kill its atoms (which should kill any jigs attached only to this mol), remove it from its group (if any) and from its assembly (if any); make it forget its group and assembly. It's legal to kill a mol twice, and common now that emptying a mol of all atoms kills it automatically; redundant kills have no effect. It's probably legal to reuse a killed mol (if it's added to a new assy -- there's no method for this), but this has never been tested. [extends Node method] """ self._destroy_bonded_chunks() ## print "fyi debug: mol.kill on %r" % self # Bruce 041116 revised docstring, made redundant kills noticed # and fully legal, and made kill forget about dad and assy. # Note that _nullMol might be killed every so often. # (caller no longer needs to set externs to [] when there are no atoms) if self is _nullMol: return # all the following must be ok for an already-killed Chunk! self._f_prekill() #bruce 060327, needed here even though _superclass.kill might do it too ## self.unpick() #bruce 050214 comment [superseded, see below]: keep doing unpick # here, even though _superclass.kill now does it too. #update, bruce 080310: doing this here looks like a bug if self.dad # is selected but not being killed -- a situation that never arises # from a user op of "kill selection", but that might happen when the # dna updater kills a chunk, e.g. due to merging it. So, don't do it # here. Superclass method avoids the issue by doing it only after # self.dad becomes None. If this doesn't work, we'll need to define # and call here self._unpick_during_kill rather than just self.kill. for b in self.externs[:]: #bruce 050214 copy list as a precaution b.bust() self.externs = [] #bruce 041029 precaution against repeated kills #10/28/04, delete all atoms, so jigs attached can be deleted when no atoms # attaching the jig . Huaicai for a in self.atoms.values(): a.kill() # WARNING: this will recursively kill self (when its last atom is # killed as this loop ends, or perhaps earlier if a bondpoint comes # last in the values list)! Should be ok, # though I ought to rewrite it so that if that does happen here, # I don't redo everything and have to worry whether that's safe. # [bruce 050214 comment] # [this would also serve to bust the extern bonds, but it seems safer # to do that explicitly and to do it first -- bruce 041109 comment] #bruce 041029 precautions: if self.atoms: print "fyi: bug (ignored): %r mol.kill retains killed atoms %r" % (self, self.atoms) self.atoms = {} self.invalidate_attr('atlist') # probably not needed; covers atpos # and basepos too, due to rules; externs were correctly set to [] if self.assy: # bruce 050308 for assy/part split: [bruce 051227 removing obsolete code] # let the Part handle it if self.part: self.part.remove(self) assert self.part is None _superclass.kill(self) #bruce 050214 moved this here, made it unconditional self._drawer._f_kill_displists() return # from Chunk.kill def _f_set_will_kill(self, val): #bruce 060327 in Chunk """ [extends private superclass method; see its docstring for details] """ _superclass._f_set_will_kill( self, val) for a in self.atoms.itervalues(): a._f_will_kill = val # inlined a._f_prekill(val), for speed ##e want to do it on their bonds too?? return # New method for finding atoms or singlets under mouse. Helps fix bug 235 # and many other bugs (mostly never reported). [bruce 041214] # (We should use this in extrude, too! #e) def findAtomUnderMouse( self, point, matrix, **kws): """ [Public method, but for a more convenient interface see its caller:] For each visible atom or singlet (using current display modes and radii, but not self.hidden), determine whether its front surface hits the given line (encoded in point and matrix), within the optional near and far cutoffs (clipping or water planes, parallel to screen) given in **kws. Return a list of pairs (z, atom), where z is the z coordinate where the line hits the atom's front surface (treating the surface as a sphere) after transformation by matrix (closer atoms must have higher z); this list always contains either 0 or 1 pair (but in the future we might add options to let it contain more pairs). Note that a line might hit an atom on the front and/or back of the atom's surface (perhaps only on the back, if a cutoff occurs inside the atom!). This implem never includes back-surface hits (though it would be easy to add them), since the current drawing code doesn't draw them. Someday this implem will be obsolete, replaced by OpenGL-based hit tests. (Then atom hits will be obscured by bonds, as they should be, since they are already visually obscured by them. #e) We have a special kluge for selatom -- see the code. As of 041214, it's checked twice, at both the radii it's drawn at. We have no option to exclude singlets, since that would be wrong to do for individual molecules (it would make them fail to obscure atoms in other molecules for selection, even when they are drawn over them). See our caller in assembly for that. """ if not self.atoms: return [] #e Someday also check self.bbox as a speedup -- but that might be slower # when there are only a few atoms. atpos = self.atpos # a Numeric array; might be recomputed here # assume line of sight hits water surface (parallel to screen) at point # (though the docstring doesn't mention this assumption since it is # probably not required as long as z direction == glpane.out); # transform array of atom centers (xy parallel to water, z towards user). v = dot( atpos - point, matrix) # compute xy distances-squared between line of sight and atom centers r_xy_2 = v[:,0]**2 + v[:,1]**2 ## r_xy = sqrt(r_xy_2) # not needed # Select atoms which are hit by the line of sight (as array of indices). # See comments in _findAtomUnderMouse_Numeric_stuff for more details. # (Optimize for the slowest case: lots of atoms, most fail lineofsight # test, but a lot still pass it since we have a thick Chunk; do # "slab" test separately on smaller remaining set of atoms.) # self.sel_radii_squared (not a real attribute, just the way we refer to # the value of its get method, in comments like this one) # is array over atoms of squares of radii to be # used for selection (perhaps equal to display radii, or a bit larger) # (using mol's and glpane's current display modes), or -1 for invisible # atoms (whether directly diINVISIBLE or by inheriting that from the mol # or glpane). # For atoms with more than one radius (currently just selatom), # we patch this to include the largest radius, then tell # the subroutine how to also notice the smaller radii. (This avoids # flicker of selatom when only its larger radius hits near clipping plane.) # (This won't be needed once we switch to OpenGL-based hit detection. #e) radii_2 = self.get_sel_radii_squared() # might be recomputed now assert len(radii_2) == len(self.atoms) selatom = self.assy.o.selatom unpatched_seli_radius2 = None if selatom is not None and selatom.molecule is self: # need to patch for selatom, and warn subr of its smaller radii too seli = selatom.index unpatched_seli_radius2 = radii_2[seli] radii_2[seli] = selatom.highlighting_radius() ** 2 # (note: selatom is drawn even if "invisible") if unpatched_seli_radius2 > 0.0: kws['alt_radii'] = [(seli, unpatched_seli_radius2)] try: # note: kws here might include alt_radii as produced above res = self._findAtomUnderMouse_Numeric_stuff( v, r_xy_2, radii_2, **kws) except: print_compact_traceback("bug in _findAtomUnderMouse_Numeric_stuff: ") res = [] if unpatched_seli_radius2 is not None: radii_2[seli] = unpatched_seli_radius2 return res # from findAtomUnderMouse def _findAtomUnderMouse_Numeric_stuff(self, v, r_xy_2, radii_2, far_cutoff = None, near_cutoff = None, alt_radii = () ): """ private helper routine for findAtomUnderMouse """ ## removed support for backs_ok, since atom backs are not drawn p1 = (r_xy_2 <= radii_2) # indices of candidate atoms if not p1: # i.e. if p1 is an array of all false/0 values [bruce 050516 guess/comment] # no atoms hit by line of sight (common when several mols shown) return [] p1inds = nonzero(p1) # indices of the nonzero elements of p1 # note: now compress(p1, arr, dim) == take(arr, p1inds, dim) vp1 = take( v, p1inds, 0) # transformed positions of atoms hit by line of sight vp1z = vp1[:,2] # depths (above water = positive) of atoms in p1 # i guess i'll do fewer steps -- no slab test until i get actual hit depths. # this is suboptimal if the slab test becomes a good one (likely, in the future). # atom half-thicknesses at places they're hit r_xy_2_p1 = take( r_xy_2, p1inds) radii_2_p1 = take( radii_2, p1inds) thicks_p1 = Numeric.sqrt( radii_2_p1 - r_xy_2_p1 ) # now front surfaces are at vp1z + thicks_p1, backs at vp1z - thicks_p1 fronts = vp1z + thicks_p1 # arbitrary order (same as vp1) ## if backs_ok: backs = vp1z - thicks_p1 # Note that due to varying radii, the sort orders of atom centers, # front surface hits, and back surface hits might all be different. # We want the closest hit (front or back) that's not too close # (or too far, but we can ignore that until we find the closest one); # so in terms of distance from the near_cutoff, we want the smallest one # that's still positive, from either array. Since one or both arrays might # have no positive elements, it's easiest to just form a list of candidates. # This helps handle our selatom kluge (i.e our alt_radii option) too. pairs = [] # list of 0 to 2 (z, mainindex) pairs which pass near_cutoff if near_cutoff is not None: # returned index will be None if there was no positive elt; checked below closest_front_p1i = index_of_smallest_positive_elt(near_cutoff - fronts) ## if backs_ok: closest_back_p1i = index_of_smallest_positive_elt(near_cutoff - backs) else: closest_front_p1i = index_of_largest_elt(fronts) ## if backs_ok: closest_back_p1i = index_of_largest_elt(backs) ## if not backs_ok: ## closest_back_p1i = None if closest_front_p1i is not None: pairs.append( (fronts[closest_front_p1i], p1inds[closest_front_p1i] ) ) ## if closest_back_p1i is not None: ## pairs.append( (backs[closest_back_p1i], closest_back_p1i) ) # add selatom if necessary: # add in alt_radii (at most one; ok to assume that for now if we have to) # (ignore if not near_cutoff, since larger radii obscure smaller ones) if alt_radii and near_cutoff: for ind, rad2 in alt_radii: if p1[ind]: # big radius was hit, need to worry about smaller ones # redo above Numeric steps, just for this atom r_xy_2_0 = r_xy_2[ind] radii_2_0 = rad2 if r_xy_2_0 <= radii_2_0: thick_0 = Numeric.sqrt( radii_2_0 - r_xy_2_0 ) zz = v[ind][2] + thick_0 if zz < near_cutoff: pairs.append( (zz, ind) ) if not pairs: return [] pairs.sort() # the one we want is at the end (highest z == closest) (closest_z, closest_z_ind) = pairs[-1] # We've narrowed it down to a single candidate, which passes near_cutoff! # Does it pass far_cutoff? if far_cutoff is not None: if closest_z < far_cutoff: return [] atom = self.atlist[ closest_z_ind ] return [(closest_z, atom)] # from _findAtomUnderMouse_Numeric_stuff # self.sel_radii_squared is not a real attribute, since invalling it # would be too slow. Instead we have these methods: def get_sel_radii_squared(self): #bruce 050419 fix bug 550 by fancifying haveradii # in the same way as for havelist (see 'bruce 050415'). # Note: this must also be invalidated when one atom's display mode changes, # and it is, by atom.setDisplayStyle calling changeapp(1) on its chunk. disp = self.get_dispdef() ##e should caller pass this instead? eltprefs = PeriodicTable.rvdw_change_counter # (color changes don't matter for this, unlike for display lists) radiusprefs = Atom.selradius_prefs_values() #bruce 060317 -- include this in the tuple below, to fix bug 1639 if self.haveradii != (disp, eltprefs, radiusprefs): # value must agree with set, below # don't have them, or have them for wrong display mode, or for # wrong element-radius prefs try: res = self.compute_sel_radii_squared() except: print_compact_traceback("bug in %r.compute_sel_radii_squared(), using []: " % self) res = [] #e len(self.atoms) copies of something would be better self.sel_radii_squared_private = res self.haveradii = (disp, eltprefs, radiusprefs) return self.sel_radii_squared_private def compute_sel_radii_squared(self): lis = map( lambda atom: atom.selradius_squared(), self.atlist ) if not lis: return lis else: return A( lis ) pass def nearSinglets(self, point, radius): # todo: rename """ return the bondpoints in the given sphere (point, radius), sorted by increasing distance from point """ # note: only used in AtomTypeDepositionTool (Build Atoms mode) # (note: findHandles_exact in handles.py may be related code) if not self.singlets: return [] singlpos = self.singlpos # do this in advance, to help with debugging v = singlpos - point try: #bruce 051129 add try/except and printout to help debug bug 829 r = Numeric.sqrt(v[:,0]**2 + v[:,1]**2 + v[:,2]**2) # this line had OverflowError in bug 829 p = (r <= radius) i = argsort(compress(p, r)) return take(compress(p, self.singlets), i) except: print_compact_traceback("exception in nearSinglets (data printed below): ") print "if that was bug 829, this data (point, singlpos, v) might be relevant:" print "point =", point print "singlpos =", singlpos print "v =", v return [] # safe value for caller # == copy methods (extended/revised by bruce 050524-26) def will_copy_if_selected(self, sel, realCopy): return True def will_partly_copy_due_to_selatoms(self, sel): assert 0, "should never be called, since a chunk does not " \ "*refer* to selatoms, or appear in atom.jigs" return True # but if it ever is called, answer should be true def _copy_optional_attrs_to(self, numol): #bruce 090112 split this out of two methods. # Note: we don't put these in copyable_attrs, since # copy_copyable_attrs_to wasted RAM when they have their # default values (and perhaps for other reasons??). # Review: add a method like this to Node API, to be called # inside default def of copy_copyable_attrs_to?? if self.chunkHasOverlayText: numol.chunkHasOverlayText = True if self.showOverlayText: numol.showOverlayText = True if self._colorfunc is not None: #bruce 060411 added condition numol._colorfunc = self._colorfunc if self._dispfunc is not None: numol._dispfunc = self._dispfunc # future: also copy user-specified axis, center, etc, if we have those # (but see existing copy code for self.user_specified_center) return def _copy_empty_shell_in_mapping(self, mapping): """ [private method to help the public copy methods, all of which start with this except the deprecated mol.copy] Copy this chunk's name (w/o change), properties, etc, but not any of its atoms (caller will presumably copy some or all of them separately). Don't copy hotspot. New chunk is in mapping.assy (NOT necessarily the same as self.assy) but not in any Group or Part. #doc: invalidation status of resulting chunk? Update orig->copy correspondence in mapping (for self, and in future for any copyable subobject which gets copied by this method, if any does). Never refuses. Returns copy (a new chunk with no atoms). Ok to assume self has never yet been copied. """ #bruce 070430 revised to honor mapping.assy numol = self.__class__(mapping.assy, self.name) #bruce 080316 Chunk -> self.__class__ (part of fixing this for Extrude of DnaGroup) self.copy_copyable_attrs_to(numol) # copies .name (redundantly), .hidden, .display, .color... self._copy_optional_attrs_to(numol) mapping.record_copy(self, numol) return numol def copy_full_in_mapping(self, mapping): # in class Chunk """ #doc; overrides Node method; only some atom copies get recorded in mapping (if we think it might need them) """ # bruce 050526; 060308 major rewrite numol = self._copy_empty_shell_in_mapping( mapping) # now copy the atoms, all at once (including all their existing # singlets, even though those might get revised) # note: the following code is very similar to # copy_in_mapping_with_specified_atoms, but not identical. pairlis = [] ndix = {} # maps old-atom key to corresponding new atom nuatoms = {} for a in self.atlist: # note: self.atlist is now in order of atom.key; # it might get recomputed right now (along with atpos & basepos if so) na = a.copy() # inlined addatom, optimized (maybe put this in a new variant of obs copy_for_mol_copy?) na.molecule = numol # no need for _changed_parent_Atoms[na.key] = na #bruce 060322 nuatoms[na.key] = na pairlis.append((a, na)) ndix[a.key] = na numol.invalidate_atom_lists() numol.atoms = nuatoms # note: we don't bother copying atlist, atpos, basepos, # since it's hard to do correctly (e.g. not copying everything # which depends on them would cause inval bugs), and it's wasted work # for callers which plan to move all the atoms after # the copy self._copy_atoms_handle_bonds_jigs( pairlis, ndix, mapping) # note: no way to handle hotspot yet, since how to do that might depend on whether # extern bonds are broken... so let's copy an explicit one, and tell the mapping # if we have an implicit one... or, register a cleanup function with the mapping. copied_hotspot = self.hotspot # might be None (this uses __getattr__ to ensure the stored one is valid) if copied_hotspot is not None: numol.set_hotspot( ndix[copied_hotspot.key]) elif len(self.singlets) == 1: #e someday it might also work if there are two singlets on the same base atom! # we have an implicit but unambiguous hotspot: # might need to make it explicit in the copy [bruce 041123, revised 050524] copy_of_hotspot = ndix[self.singlets[0].key] mapping.do_at_end( lambda ch = copy_of_hotspot, numol = numol: numol._f_preserve_implicit_hotspot(ch) ) return numol # from copy_full_in_mapping def _copy_atoms_handle_bonds_jigs(self, pairlis, ndix, mapping): """ [private helper for some copy methods] Given some copied atoms (in a private format in pairlis and ndix), ensure their bonds and jigs will be taken care of. """ del self # doesn't use self origid_to_copy = mapping.origid_to_copy extern_atoms_bonds = mapping.extern_atoms_bonds # maybe: could be integrated with mapping.do_at_end, # but it's probably better not to, so as to specialize it for speed; # even so, could clean this up to bond externs as soon as 2nd atom seen # (which might be more efficient, though that doesn't matter much # since externs should not be too frequent); # could do all this in a Bond method for (a, na) in pairlis: if a.jigs: # a->na mapping might be needed if those jigs are copied, # or confer properties on atom a origid_to_copy[id(a)] = na # inlines mapping.record_copy for speed for b in a.bonds: a2key = b.other(a).key if a2key in ndix: # internal bond - make the analogous one # [this should include all bonds to singlets] #bruce 050524 changes: don't do it twice for the same bond; # and use bond_copied_atoms to copy bond state (e.g. # bond-order policy and estimate) from old bond. # [note: also done in copy_single_chunk] if a.key < a2key: # arbitrary condition which is true for exactly one # ordering of the atoms; note both keys are for # original atoms (it would also work if both were from # copied atoms, but not if they were mixed) bond_copied_atoms(na, ndix[a2key], b, a) else: # external bond [or at least outside of atoms in # pairlis/ndix] -- caller will handle it when all chunks # and individual atoms have been copied (copy it if it # appears here twice, or break it if once) # [note: similar code will be in atom.copy_in_mapping] extern_atoms_bonds.append( (a,b) ) # it's ok if this list has several entries for one 'a' origid_to_copy[id(a)] = na # a->na mapping will be needed outside this method, # to copy or break this bond pass pass return # from _copy_atoms_handle_bonds_jigs def copy_in_mapping_with_specified_atoms(self, mapping, atoms): #bruce 050524-050526 """ Copy yourself in this mapping (for the first and only time), but with only some of your atoms (and all their singlets). [#e hotspot? fix later if needed, hopefully by replacing that concept with a jig (see comment below for ideas).] """ numol = self._copy_empty_shell_in_mapping( mapping) all = list(atoms) for a in atoms: all.extend(a.singNeighbors()) items = [(atom.key, atom) for atom in all] items.sort() pairlis = [] ndix = {} if len(items) < len(self.atoms) and not numol.name.endswith('-frag'): # rename to indicate that this copy has fewer atoms, in the same way Separate does numol.name += '-frag' #e want to add a serno to -frag, e.g. -frag1, -frag2? # If so, see -copy for how, and need to fix endswith tests for -frag. for key, a in items: na = a.copy() numol.addatom(na) pairlis.append((a, na)) ndix[key] = na self._copy_atoms_handle_bonds_jigs( pairlis, ndix, mapping) ##e do anything about hotspot? easiest: if we copy it (explicit or # implicit) or its base atom, put them in mapping, # and register some other func (than the one copy_in_mapping does) # to fix it up at the end. # Could do this uniformly in _copy_empty_shell_in_mapping, # and here just be sure to tell mapping.record_copy. # # (##e But really we ought to simplify all this code by just # replacing the hotspot concept with a "bonding-point jig" # or perhaps a bond property. That might be less work! And more useful! # And then one chunk could have several hotspots with different # pastable names and paster-jigs! # And the paster-jig could refer to real atoms to be merged # with what you paste it on, not only singlets! # Or to terminating groups (like H) to pop off if you use # that pasting point (but not if you use some other one). # Maybe even to terminating groups connected to base at more # than one place, so you could make multiple bonds at once! # Or instead of a terminating group, it could include a pattern # of what it should suggest adding itself to! # Even for one bond, this could help it orient # the addition as intended, spatially!) return numol def _f_preserve_implicit_hotspot( self, hotspot): #bruce 050524 #e could also take base-atom arg to use as last resort if len(self.singlets) > 1 and self.hotspot is None: self.set_hotspot( hotspot, silently_fix_if_invalid = True) # this checks everything before setting it; if invalid, silent noop # == ## def copy(self, dad = None, offset = V(0,0,0), cauterize = 1): #bruce 080314 ## """ ## Public method. DEPRECATED, see code comments for details. ## Deprecated alias for copy_single_chunk (also deprecated but still in use). ## """ ## cs = compact_stack("\n*** print once: called deprecated Chunk.copy from: ") ## if not env.seen_before(cs): ## print cs ## return self.copy_single_chunk( dad, offset, cauterize) def copy_single_chunk(self, dad = None, offset = V(0,0,0), cauterize = 1): """ Public method. DEPRECATED, see code comments for details. Copy the Chunk self to a new Chunk. Offset tells where it will go relative to the original. Unless cauterize = 0, replace bonds out of self (to atoms in other Chunks) with singlets in the copy [though that's not very nice when we're copying a group of mols all at once ###@@@ bruce 050206 comment], and if this causes the hotspot in the copy to become ambiguous, set one explicitly. (This has no effect on the original mol's hotspot.) If cauterize == 0, the copy has atoms with lower valence instead, wherever the original had outgoing bonds (not recommended). Note that the copy has the same assembly as self, but is not added to that assembly (e.g. to its .molecules list); caller should call assy.addmol if desired. Warning: addmol would not notice if the dad (passed as an arg) was some Group in that assembly, and might blindly reset it to assy.tree! Also, tho we set dad in the copy as asked, we don't add the copied mol to dad.members! Bruce 050202-050206 thinks we should deprecate passing dad for now, just pass None, and caller should use one of addmol or addchild or addsibling to place the mol somewhere. Not sure what happens now; so I made addchild notice the setting of dad but lack of being in dad's members list, and tolerate it but complain when atom_debug. This should all be cleaned up sometime soon. ###@@@ """ #bruce 080314 renamed, added even more deprecated alias method under # the prior name (copy) (see also Node.copy, NamedView.copy), fixed all uses # to call the new name. The uses are mainly in pasting and setHotSpot. # It's almost certain that Extrude no longer calls this. # The new name includes "single" to emphasize the reason this method is # inherently defective and therefore deprecated -- that in copying only # one chunk, unaware of a larger set of things being copied, it can't # help but break its inter-chunk bonds. # # older comments: # # This is the old copy method -- should remove ASAP but might still be needed # for awhile (as of 050526)... actually we'll keep it for awhile, # since it's used in many places and ways in depositMode and # extrudeMode... it'd be nice to rewrite it to call general copier... # # NOTE: to copy several chunks and not break interchunk bonds, don't use this -- # use either copied_nodes_for_DND or copy_nodes_in_order as appropriate # (or other related routines we might add near them in the future), # then do a few more things to fix up their output -- see their existing calls # for details. [bruce 070412/070525 comment] # #bruce 060308 major rewrite, and no longer permit args to vary from defaults assert cauterize == 1 assert same_vals( offset, V(0,0,0) ) assert dad is None # bruce added cauterize feature 041116, and its hotspot behavior 041123. # Without hotspot feature, Build mode pasting could have an exception. ##print "fyi debug: mol.copy on %r" % self # bruce 041116: note: callers seem to be mainly in model tree copy ops # and in depositMode. # [where do they call addmol? why did extrude's copies break on 041116?] pairlis = [] ndix = {} newname = mol_copy_name(self.name, self.assy) #bruce 041124 added "-copy<n>" (or renumbered it, if already in name), # similar to Ninad's suggestion for improving bug 163's status message # by making it less misleading. numol = Chunk(self.assy, "fakename") # name is set below #bruce 050531 kluges to fix bug 660, until we replace or rewrite this method # using one of the newer "copy" methods self.copy_copyable_attrs_to(numol) # copies .name (redundantly), .hidden, .display, .color... # and sets .prior_part, which is what should fix bug 660 self._copy_optional_attrs_to(numol) numol.name = newname #end 050531 kluges nuatoms = {} for a in self.atlist: # 060308 changed similarly to copy_full_in_mapping (shares some code with it) na = a.copy() na.molecule = numol # no need for _changed_parent_Atoms[na.key] = na #bruce 060322 nuatoms[na.key] = na pairlis.append((a, na)) ndix[a.key] = na numol.invalidate_atom_lists() numol.atoms = nuatoms extern_atoms_bonds = [] for (a, na) in pairlis: for b in a.bonds: a2key = b.other(a).key if a2key in ndix: # internal bond - make the analogous one # (this should include all preexisting bonds to singlets) #bruce 050715 bugfix (copied from 050524 changes to another # routine; also done below for extern_atoms_bonds): # don't do it twice for the same bond # (needed by new faster bonding methods), # and use bond_copied_atoms to copy bond state # (e.g. bond-order policy and estimate) from old bond. if a.key < a2key: # arbitrary condition which is true for exactly # one ordering of the atoms; # note both keys are for original atoms # (it would also work if both were from # copied atoms, but not if they were mixed) bond_copied_atoms(na, ndix[a2key], b, a) else: # external bond - after loop done, make a singlet in the copy extern_atoms_bonds.append( (a,b) ) # ok if several times for one 'a' ## if extern_atoms_bonds: ## print "fyi: mol.copy didn't copy %d extern bonds..." % len(extern_atoms_bonds) copied_hotspot = self.hotspot # might be None if cauterize: # do something about non-copied bonds (might be useful for extrude) # [experimental code, bruce 041112] if extern_atoms_bonds: ## print "... but it will make them into singlets" # don't make our hotspot ambiguous, if it wasn't already if self.hotspot is None and len(self.singlets) == 1: # we have an implicit but unambiguous hotspot: # make it explicit in the copy [bruce 041123] copied_hotspot = self.singlets[0] for a, b in extern_atoms_bonds: # compare to code in Bond.unbond(): x = Atom('X', b.ubp(a) + offset, numol) na = ndix[a.key] #bruce 050715 bugfix: also copy the bond-type (two places in this routine) bond_copied_atoms( na, x, b, a) if copied_hotspot is not None: numol.set_hotspot( ndix[copied_hotspot.key]) # future: also copy (but translate by offset) user-specified # axis, center, etc, if we ever have those ## if self.user_specified_center is not None: #bruce 050516 bugfix: 'is not None' ## numol.user_specified_center = self.user_specified_center + offset numol.setDisplayStyle(self.display) # REVIEW: why is this not redundant? (or is it?) [bruce 090112 question] numol.dad = dad if dad and debug_flags.atom_debug: #bruce 050215 print "atom_debug: mol.copy got an explicit dad (this is deprecated):", dad return numol # == def Passivate(self, p = False): """ [Public method, does all needed invalidations:] Passivate the selected atoms in this chunk, or all its atoms if p = True. This transmutes real atoms to match their number of real bonds, and (whether or not that succeeds) removes all their open bonds. """ # todo: move this into the operations code for its caller for a in self.atoms.values(): if p or a.picked: a.Passivate() def Hydrogenate(self): """ [Public method, does all needed invalidations:] Add hydrogen to all unfilled bond sites on carbon atoms assuming they are in a diamond lattice. For hilariously incorrect results, use on graphite. @warning: can create overlapping H atoms on diamond. """ # review: probably docstring is wrong in implying this # only affects Carbon # todo: move this into the operations code for its caller count = 0 for a in self.atoms.values(): count += a.Hydrogenate() return count def Dehydrogenate(self): """ [Public method, does all needed invalidations:] Remove hydrogen atoms from this chunk. @return: number of atoms removed. """ # todo: move this into the operations code for its caller count = 0 for a in self.atoms.values(): count += a.Dehydrogenate() # review: bug if done to H-H? return count # == def __str__(self): # bruce 041124 revised this; again, 060411 # (can I just zap it so __repr__ is used?? Try this after A7. ##e) return "<%s %r>" % (self.__class__.__name__, self.name) def __repr__(self): #bruce 041117, revised 051011 # Note: if you extend this, make sure it doesn't recompute anything # (like len(self.singlets) would do) or that will confuse debugging # by making debug-prints trigger recomputes. if self is _nullMol: return "<_nullMol>" try: name = "%r" % self.name except: name = "(exception in self.name repr)" try: self.assy except: return "<Chunk %s at %#x with self.assy not set>" % (name, id(self)) #bruce 051011 classname = self.__class__.__name__ # not always Chunk! if self.assy is not None: return "<%s %s (%d atoms) at %#x>" % (classname, name, len(self.atoms), id(self)) else: return "<%s %s, KILLED (no assy), at %#x of %d atoms>" % \ (classname, name, id(self), len(self.atoms)) # note other order pass def merge(self, mol): """ merge the given Chunk into this one. """ if mol is self: # Can't merge self. Mark 2007-10-21 return # rewritten by bruce 041117 for speed (removing invals and asserts); # effectively inlines hopmol and its delatom and addatom; # no need to find and hop singlet neighbors of atoms in mol # since they were already in mol anyway. for atom in mol.atoms.values(): # should be a method in atom: atom.index = -1 atom.molecule = self _changed_parent_Atoms[atom.key] = atom #bruce 060322 #bruce 050516: changing atom.molecule is now enough in itself # to invalidate atom's bonds, since their validity now depends on # a counter stored in (and unique to) atom.molecule having # a specific stored value; in the new Chunk (self) this will # have a different value. So I can remove the following code: ## for bond in atom.bonds: ## bond.setup_invalidate() self.atoms.update(mol.atoms) self.invalidate_atom_lists() # be safe, since we just stole all mol's atoms: mol.atoms = {} mol.invalidate_atom_lists() mol.kill() return # from merge def overlapping_chunk(self, chunk, tol = 0.0): """ Returns True if any atom of chunk is within the bounding sphere of this chunk's bbox. Otherwise, returns False. @param tol: (optional) an additional distance to be added to the radius of the bounding sphere in the check. @type tol: float """ if vlen (self.bbox.center() - chunk.bbox.center()) > \ self.bbox.scale() + chunk.bbox.scale() + tol: return False else: return True def overlapping_atom(self, atom, tol = 0.0): """ Returns True if atom is within the bounding sphere of this chunk's bbox. Otherwise, returns False. @param tol: (optional) an additional distance to be added to the radius of the bounding sphere in the check. @type tol: float """ if vlen (atom.posn() - self.bbox.center()) > self.bbox.scale() + tol: return False else: return True def bounding_sphere(self, tol = (MAX_ATOM_SPHERE_RADIUS - BBOX_MIN_RADIUS + 0.5) ): """ @return: a (loose) bounding sphere for self for purposes of drawing, accounting for maximum possible atom/bond radius. @param tol: a radius increment, whose default value accounts for the maximum possible atom/bond radius. If this is passed as 0, we only try to bound the centers of self's atoms. @note: logically, atom/bond drawing radius are only known to self.drawer rather than self, but for now it's more convenient to define this here so ExternalBondSet can easily call it to get its own bounding volume. @see: overlapping_chunk, overlapping_atom, ChunkDrawer.is_visible (which calls us) """ # bbox test by piotr 080331; bruce 090212 split into separate method # in ChunkDrawer; bruce 090306 split most of that into this method. # piotr 080402: Added a correction for the true maximum # DNA CPK atom radius. # Maximum VdW atom radius in PAM3/5 = 5.0 * 1.25 + 0.2 = 6.2 # = MAX_ATOM_SPHERE_RADIUS # The default radius used by BBox is equal to sqrt(3*(1.8)^2) = # = 3.11 A, so the difference = approx. 3.1 A = BBOX_MIN_RADIUS # The '0.5' is another 'fuzzy' safety margin, added here just # to be sure that all objects are within the sphere. # piotr 080403: moved the correction here from GLPane.py bbox = self.bbox center = bbox.center() radius = bbox.scale() + tol return center, radius def isProteinChunk(self): """ Returns True if the chunk is a protein object. """ if self.protein is None: return False else: # This only adds the icon to the PM_SelectionListWidget. # To add the protein icon for the model tree, the node_icon() # method was modified. --Mark 2008-12-16. if self.hidden: self.iconPath = "ui/modeltree/Protein-hide.png" else: self.iconPath = "ui/modeltree/Protein.png" return True pass # end of class Chunk # == # The chunk _nullMol is never part of an assembly, but serves as the chunk # for atoms removed from other chunks (when killed, or before being added to new # chunks), so it can absorb invalidations which certain dubious code # (like depositMode via selatom) sends to killed atoms, by operating on them # (or invalidating bonds containing them) even after they're killed. # Initing _nullMol here caused a bus error; don't know why (class Node not ready??) # So we do it when first needed, in delatom, instead. [bruce 041116] ## _nullMol = Chunk("<not an assembly>") def _get_nullMol(): """ return _nullMol, after making sure it's initialized """ # inlined into delatom global _nullMol if _nullMol is None: _nullMol = _make_nullMol() return _nullMol _nullMol = None def _make_nullMol(): #bruce 060331 split out and revised this, to mitigate bugs similar to bug 1796 """ [private] Make and return (what the caller should store as) the single _nullMol object. """ ## return Chunk("<not an assembly>", 'name-of-_nullMol') null_mol = _nullMol_Chunk("<not an assembly>", 'name-of-_nullMol') set_undo_nullMol(null_mol) return null_mol class _nullMol_Chunk(Chunk): """ [private] subclass for _nullMol """ def changed_selection(self): # in class _nullMol_Chunk msg = "bug: _nullMol.changed_selection() should never be called" if env.debug(): print_compact_stack(msg + ": ") else: print msg return def isNullChunk(self): # by Ninad, implementing old suggestion by Bruce for is_nullMol """ @return: whether chunk is a "null object" (used as atom.molecule for some killed atoms). Overrides Chunk method. This method helps replace comparisons to _nullMol (helps with imports, replaces set_undo_nullMol, permits per-assy _nullMol if desired) """ return True pass # end of class _nullMol # == from geometry.geometryUtilities import selection_polyhedron, inertia_eigenvectors, compute_heuristic_axis def shakedown_poly_evals_evecs_axis(basepos): """ Given basepos (an array of atom positions), compute and return (as the elements of a tuple) the bounding polyhedron we should draw around these atoms to designate that their Chunk is selected, the eigenvalues and eigenvectors of the inertia tensor (computed as if all atoms had the same mass), and the (heuristically defined) principal axis. """ #bruce 041106 split this out of the old Chunk.shakedown() method, # replaced Chunk attrs with simple variables (the ones we return), # and renamed self.eval to evals (just in this function) to avoid # confusion with python's built-in function eval. #bruce 060119 split it into smaller routines in new file geometry.py. polyhedron = selection_polyhedron(basepos) evals, evecs = inertia_eigenvectors(basepos) # These are no longer saved as chunk attrs (since they were not used), # but compute_heuristic_axis would compute this anyway, # so there's no cost to doing it here and remaining compatible # with the pre-060119 version of this routine. This would also permit # a future optimization in computing other kinds of axes for the same # chunk (by passing different options to compute_heuristic_axis), # as we may want to do in viewParallelTo and viewNormalTo # (see also the comments about those in compute_heuristic_axis). axis = compute_heuristic_axis( basepos, 'chunk', evals_evecs = (evals, evecs), aspect_threshhold = 0.95, near1 = V(1,0,0), near2 = V(0,1,0), dflt = V(1,0,0) # prefer axes parallel to screen in default view ) assert axis is not None axis = A(axis) ##k if this is in fact needed, we should probably # do it inside compute_heuristic_axis for sake of other callers assert type(axis) is type(V(0.1, 0.1, 0.1)) # this probably doesn't check element types (that's probably ok) return polyhedron, evals, evecs, axis # from shakedown_poly_evals_evecs_axis # == def mol_copy_name(name, assy = None): """ turn xxx or xxx-copy or xxx-copy<n> into xxx-copy<m> for a new number <m> """ # bruce 041124; added assy arg, 080407; rewrote/bugfixed, 080723 # if name looks like xxx-copy or xxx-copy<nnn>, remove the -copy<nnn> part parts = name.split("-copy") if len(parts) > 1: nnn = parts[-1] if not nnn or nnn.isdigit(): name = "-copy".join(parts[:-1]) # everything but -copy<nnn> # (note: this doesn't contain '-copy' unless original name # contained it twice) pass return gensym(name + "-copy", assy) # (in mol_copy_name) # note: we assume this adds a number to the end # == Numeric.array utilities [bruce 041207/041213] def index_of_smallest_positive_elt(arr, retval_if_none = None): # use same kluge value as findatoms (an assumption of max model depth) res = argmax( - arr - 100000.0*(arr < 0) ) if arr[res] > 0.0: return res else: return retval_if_none def index_of_largest_elt(arr): return argmax(arr) #e inline it? # == debug code debug_messup_basecenter = 0 # set this to 1 to change basecenter gratuitously, # if you want to verify that this has no visible effect # (or find bugs when it does, like in Extrude as of 041118) # messupKey is only used when debug_messup_basecenter, but it's always set, # so it's ok to set debug_messup_basecenter at runtime messupKey = genKey() # end
NanoCAD-master
cad/src/model/chunk.py
# Copyright 2008-2009 Nanorex, Inc. See LICENSE file for details. """ virtual_site_indicators.py - graphical indicators related to virtual sites (as used in the current GROMACS implementation of the PAM5 force field); presently used only to visualize such sites for debugging, not as part of their implementation for minimize. @author: Bruce @version: $Id$ @copyright: 2008-2009 Nanorex, Inc. See LICENSE file for details. """ import foundation.env as env from utilities.prefs_constants import hoverHighlightingColor_prefs_key from utilities.prefs_constants import selectionColor_prefs_key from utilities.constants import red, orange, yellow, average_value, ave_colors, blue, gray from utilities.Log import quote_html from geometry.VQT import V, vlen from graphics.drawing.drawers import drawwirecube from graphics.drawing.CS_draw_primitives import drawline from graphics.drawing.CS_draw_primitives import drawcylinder from graphics.drawing.patterned_drawing import isPatternedDrawing from graphics.drawing.patterned_drawing import startPatternedDrawing from graphics.drawing.patterned_drawing import endPatternedDrawing from model.chunk import Chunk from model.jigs import Jig # == class VisualFeedbackJig(Jig): """ A superclass for Jigs for internal or in-MT use in implementing visual feedback related to ND-1 pattern matching, virtual sites, and struts. """ # Jig or Node API class constants: copyable_attrs = Jig.copyable_attrs + ('_props', ) # default values of instance variables _props = None # == Jig or Node API methods def remove_atom(self, atom, **opts): """ [extends superclass method] """ if getattr(self, '_being_killed', False): return # prevent infinite recursion (I hope #k) self._being_killed = True # only used in this file as of 080520 self.kill() # Note: should be ok, because in pi_bond_sp_chain, # this calls destroy which calls super.destroy which calls kill. # (I don't know why that doesn't have the same recursion problem # that this does, as used in VirtualSiteJig.) return def changed_structure(self, atom): # review: should we disable self by user choice?? # make the site_atom color more gray [in some subclasses]??? # not unless we confirm it's a change that really matters! # (note: this is called at least once during or shortly after # construction of the VirtualSiteJig, not sure why.) return # == other methods def setProps(self, props): """ Set the parameters which define the virtual site position as a function of the parent atom positions, and other properties. @param props: the new property values, in a certain order (see code) @type props: tuple """ self._props = props self._update_props() return def _update_props(self): """ Subclasses can use this to set private attributes from self._props and to check for errors in that process. Methods in self (this class or subclasses) should call this in setProps to check for errors, and before every use of private attrs this sets from self._props, to make sure they are up to date in case self._props has changed somehow. (Though it may be that it can't change once set, in current code.) """ # note: if we didn't want to call this before every use, # we'd at least need to call it after copy (in the copy) # and in undo_update. return def _any_atom_is_hidden(self): """ """ for atom in self.atoms: if atom.is_hidden(): return True return False pass # end of class VisualFeedbackJig # == class VirtualSiteJig( VisualFeedbackJig): """ A Jig for internal use (also may appear in the MT for purpose of letting self.picked control drawing of extra info, but doesn't appear there in present implementation of external code), for maintaining the relationship between some atoms which define a virtual site (the "parent atoms" or "defining atoms"), and an atom which represents the site itself (all of which are passed to this jig in its atomlist). Keeps the "site atom" positioned in the correct place. When picked (or when the site atom's chunk is picked), draws an indication of how the site atom position came from the parent atom positions. """ # Jig or Node API class constants: sym = "VirtualSiteJig" icon_names = ('border/dna.png', 'border/dna.png') # stubs, not correct # == Jig or Node API methods, and other methods def __init__(self, assy, atomlist): """ """ assert len(atomlist) >= 2 # at least one parent atom, exactly one site atom (the last one) VisualFeedbackJig.__init__(self, assy, atomlist) return def _getToolTipInfo(self): # VirtualSiteJig # untested, since some ###BUG prevents this from being shown """ Return a string for display in self's Dynamic Tool tip. (Appears when user highlights this jig's drawing, but unrelated to tooltip on our site_atom itself.) [overridden from class Jig] """ self._update_props() # doesn't yet matter in this method msg = "%s: %s" % (self.sym, quote_html(self.name)) + \ "<br><font color=\"#0000FF\">" \ "%s</font>" % (self._props,) return msg def site_atom(self): return self.atoms[-1] def parent_atoms(self): return self.atoms[:-1] def _draw_jig(self, glpane, color, highlighted = False): """ [overrides superclass method] """ # note: kluge: called directly from a specialized Chunk, not from self.draw! if self._should_draw(): sitepos = self.site_position() # or, should we assume the atom pos is up to date? yes, use that. ### FIX colors = [red, orange, yellow] for a in self.parent_atoms(): chunk = a.molecule dispdef = chunk.get_dispdef(glpane) disp, rad = a.howdraw(dispdef) if self.picked: rad *= 1.01 color = colors[0] drawwirecube(color, a.posn(), rad) # useful?? drawline( color, a.posn(), sitepos) # draw each atom in a different color (at least if there are no more than 3) colors = colors[1:] + [color] continue return def _should_draw(self): # note: this is not about whether to draw the site_atom # (which is done by a different object), # but about whether to draw connections from it to its parent atoms. return self.picked or self.site_atom().molecule.picked # so self needn't appear in MT if that chunk does def _update_props(self): """ [overrides superclass method] """ props = self._props self._function_id = props[0] if self._function_id == 1: self._x, self._y = props[1:] else: print "%r.setProps: don't recognize those props" % self, props return def site_position(self): ## return average_value( [a.posn() for a in self.parent_atoms()] ) ## # STUB, actually use self._function_id and _x and _y, or self._props self._update_props() if self._function_id == 1 and len(self.parent_atoms()) == 3: # the only supported kind so far parentID1, parentID2, parentID3 = self.parent_atoms() A = self._x B = self._y # Multiply the vector (parentID2 - parentID1) * A # Multiply the vector (parentID3 - parentID1) * B # Add the above two vectors to parentID1 pos1 = parentID1.posn() pos2 = parentID2.posn() pos3 = parentID3.posn() return pos1 + (pos2 - pos1) * A + (pos3 - pos1) * B else: print "bug: unsupported kind of virtual site:", self._props return average_value( [a.posn() for a in self.parent_atoms()] ) pass def moved_atom(self, atom): """ [extends Jig method] """ if atom is not self.site_atom(): self._update_site_atom_position() return def _update_site_atom_position(self): self.site_atom().setposn( self.site_position() ) pass # end of class VirtualSiteJig # == class VirtualBondJig( VisualFeedbackJig): """ For virtual bonds, including PAM5 FF "struts". """ # Jig or Node API class constants: sym = "VirtualBondJig" icon_names = ('border/dna.png', 'border/dna.png') # stubs, not correct # == Jig or Node API methods, and other methods def __init__(self, assy, atomlist): """ """ assert len(atomlist) == 2 VisualFeedbackJig.__init__(self, assy, atomlist) return def _getToolTipInfo(self): # VirtualBondJig """ Return a string for display in self's Dynamic Tool tip. [overridden from class Jig] """ self._update_props() ks = self._ks # N/m r0 = self._r0 # pm length = self._getLength() # pm force = ks * (length - r0) # pN msg = "%s: %s" % (self.sym, quote_html(self.name)) + \ "<br><font color=\"#0000FF\">" \ "ks = %f N/m<br>" \ "r0 = %f pm<br>" \ "len = %f pm<br>" \ "len/r0 = %f<br>" \ "force = %f pN</font>" % (ks, r0, length, length/r0, force) return msg def _draw_jig(self, glpane, color, highlighted = False): """ [overrides superclass method] """ del color self._update_props() if not self._should_draw(): return drawrad = 0.1 posns = [a.posn() for a in self.atoms] normcolor = self._drawing_color() # russ 080530: Support for patterned highlighting drawing modes. selected = self.picked patterned = isPatternedDrawing(select = selected, highlight = highlighted) if patterned: # Patterned selection drawing needs the normal drawing first. drawcylinder( normcolor, posns[0], posns[1], drawrad) startPatternedDrawing(select = selected, highlight = highlighted) pass # Draw solid color, or overlay pattern in highlight or selection color. drawcylinder( (highlighted and env.prefs[hoverHighlightingColor_prefs_key] or selected and env.prefs[selectionColor_prefs_key] or normcolor), posns[0], posns[1], drawrad) if patterned: # Reset from patterned drawing mode. endPatternedDrawing(select = selected, highlight = highlighted) pass return def _should_draw(self): return not self._any_atom_is_hidden() #080520 new feature def _should_draw_thicker(self): # not yet used return self.picked or \ self.atoms[0].molecule.picked or \ self.atoms[1].molecule.picked def _update_props(self): """ [overrides superclass method] """ props = self._props self._ks, self._r0 = props # TODO: use in draw, tooltip return def _getLength(self): length_in_Angstroms = vlen( self.atoms[0].posn() - self.atoms[1].posn() ) length = 100.0 * length_in_Angstroms # in pm == picometers return length def _drawing_color(self): r0 = self._r0 # pm ks = self._ks # N/m length = self._getLength() # pm frac = 1 - 1 / (0.08 * ks * abs(r0 - length) + 1) if length < r0: # compressed: blue (gray if not at all, blue if a lot; should use ks somehow to get energy or force...) # limit = r0 * 0.5 #frac = (r0 - length) / (r0 * 0.5) # if > 1, we'll use 1 below limit_color = blue else: # stretched # limit = r0 * 1.5 #frac = (length - r0) / (r0 * 0.5) limit_color = red ## neutral_color = gray neutral_color = (0.8, 0.8, 0.8) # "very light gray" if frac > 1.0: frac = 1.0 color = ave_colors( frac, limit_color, neutral_color ) return color pass # end of class VirtualBondJig # == class VirtualSiteChunkDrawer( Chunk._drawer_class ): #bruce 090212 split this out (###UNTESTED) def _draw_outside_local_coords(self, glpane, disp, drawLevel, is_chunk_visible): Chunk._drawer_class._draw_outside_local_coords(self, glpane, disp, drawLevel, is_chunk_visible) for atom in self._chunk.atoms.itervalues(): if hasattr(atom, '_site_atom_jig'): color = 'not used' atom._site_atom_jig._draw_jig(glpane, color) # note: needs to be in abs coords ## print "called %r._draw_jig" % atom # works pass continue return pass class VirtualSiteChunk(Chunk): """ A chunk that (initially) has only a virtual site atom, and represents it in the MT. This atom will also have a VirtualSiteJig (and be its site_atom), which cooperates with us in some sense, and which we can find via that atom. Nothing prevents a user from merging several of these chunks into one. Its jig-drawing code will still work then. Nothing prevents merging it into a regular chunk, but doing that would break that code (i.e. stop drawing the VirtualSiteJigs), so users shouldn't do that. """ # someday: custom icon for MT? # note: mmp save/reload would not preserve this chunk subclass # maybe someday: hide our atom if some or all of our parent atoms # are hidden. Do this by self.hidden = True so it's noticed by # any VirtualBondJigs on our atom. Not simple, since it needs to be # done before drawing, not during it, since it's a model change # (doing that during drawing can cause bugs); but hidden state # can't yet be subscribed to. Maybe an update_parts hook could do it? # Not sure if even that would be safe (in terms of changing the model # then), though I guess it probably is since updaters change it quite a bit. # Anyway, for now, this feature is not needed. _drawer_class = VirtualSiteChunkDrawer pass # == def make_virtual_site( assy, parent_atoms, site_params, MT_name = None): """ @return: ( object to assign to site_atom_id, list of nodes to add to MT ) """ from model.elements import Vs0 site_atom = assy.make_Atom_and_bondpoints(Vs0, V(0,0,0), Chunk_class = VirtualSiteChunk) jig = VirtualSiteJig(assy, parent_atoms + [site_atom]) jig.setProps(site_params) # so it knows how to compute site_position jig._update_site_atom_position() # also put them into the model somewhere? just the chunk. store the jig on the atom... ## return [ site_atom.molecule, jig ] # list of nodes for MT ### hmm, could let the jig draw if the atom chunk is picked... site_atom._site_atom_jig = jig # used (for drawing the jig) only if this atom is in a VirtualSiteChunk # todo: put something useful into the tooltip and the chunk name if MT_name: jig.name = "%s" % (MT_name,) # not presently user-visible, I think # (except maybe in statusbar when self is selobj?) site_atom.molecule.name = "%s" % (MT_name,) return site_atom, [ site_atom.molecule ] # == def add_virtual_site(assy, parent_atoms, site_params, MT_name = None): """ @return: object to assign to site_atom_id @warning: caller must call assy.w.win_update() """ site_atom, nodes = make_virtual_site( assy, parent_atoms, site_params, MT_name = MT_name) for node in nodes: assy.addnode(node) # todo: add them in a better place? # review: redundant with make_Atom_and_bondpoints? return site_atom # == def make_virtual_bond( assy, atoms, bond_params, MT_name = None ): """ @return: liat of objects to add to model """ jig = VirtualBondJig( assy, atoms ) jig.setProps( bond_params) # also put them into the model somewhere? not for now. just make it findable/drawable from its atoms. NIM #### PROBLEM: how will two chemical atoms draw one of these? # - could put it in the model # - only needed if both atoms are chem, since VirtualSiteChunk could draw it itself # (best implem?: ask each atom's chunk if it has a special property that says it'll draw it) # - could add features to Atom.draw # - could reimplement it as a Bond subclass (bond order zero??); # but worry about bugs in Bond selobj code in various modes needed_in_model = True # STUB -- see above for a better rule! if MT_name: jig.name = "%s" % (MT_name,) res = [] if needed_in_model: res.append(jig) return res # == def add_virtual_bond( assy, atoms, bond_params, MT_name = None ): """ @return: None """ nodes = make_virtual_bond( assy, atoms, bond_params, MT_name = MT_name) for node in nodes: assy.addnode(node) # todo: add them in a better place? return # == test code from utilities.debug import register_debug_menu_command def virtual_site_from_selatoms_command(glpane): assy = glpane.assy atoms = assy.selatoms.values() # arbitrary order, nevermind if len(atoms) != 3: errormsg = "select exactly 3 atoms to make a test virtual site" env.history.redmsg( errormsg) pass else: parent_atoms = list(atoms) site_params = ( 1, 0.5, 0.5 ) # stub site_atom, nodes = make_virtual_site( assy, parent_atoms, site_params) for node in nodes: assy.addnode(node) pass assy.w.win_update() return def initialize(): """ [called during startup] """ register_debug_menu_command( "Test: virtual site from selatoms", virtual_site_from_selatoms_command ) return # end
NanoCAD-master
cad/src/model/virtual_site_indicators.py
# Copyright 2005-2008 Nanorex, Inc. See LICENSE file for details. """ global_model_changedicts.py - global changedicts needed by master_model_updater or the specific update functions it calls. These are public for access and modification by those update functions, and for additions by all low-level model-modification code. @author: Bruce @version: $Id$ @copyright: 2005-2008 Nanorex, Inc. See LICENSE file for details. TODO: Maybe make their global names (here) and localvar names (in specific update functions) differ. Maybe let them be created by changedict objects, from which we'll assign them to these same globals? This would also facilitate their use in ways that are protected from undetected changes during their use, related to how Undo uses its changedicts, but swapping in new subscribing dicts each time an old one needs to be looked at. Maybe let them be attributes of one singleton object? Related -- integrate these with the Undo changedicts and in some cases reuse the same ones (subscribe to them in master_model_updater or its update functions). (For what to do to be clear, we need to see the details of how higher-level updaters ever need to repeat lower-level ones.) History: bruce 050627 started this as part of supporting higher-order bonds. bruce 071108 split this out of bond_updater.py (which also got split into itself and master_model_updater.py). """ # == # dict for atoms or singlets whose element, atomtype, or set of bonds (or neighbors) gets changed [bruce 050627] #e (doesn't yet include all killed atoms or singlets, but maybe it ought to) [that comment might be obs!] # (changing an atom's bond type does *not* itself update this dict -- see changed_bond_types for that) changed_structure_atoms = {} # maps atom.key to atom, for atoms or singlets # WARNING: there is also a related but different global dict lower down in this file, # whose spelling differs only in 'A' vs 'a' in Atoms, and initial '_'. # See the comment there for more info. [bruce 060322] # == # changedicts for class Atom, used by Undo and by dna updater # [moved from chem.py (near class Atom) to this file, bruce 080510; # for comments and registrations, see chem.py] # TODO: rename these to not appear to be private. They're all used in chem.py, # and several of them are used in other files. _changed_parent_Atoms = {} _changed_structure_Atoms = {} # WARNING: there is also a related but different global dict earlier in this file, # whose spelling differs only in 'A' vs 'a' in Atoms, and in having no initial underscore, # namely, changed_structure_atoms. For more info, see the comment under the import # of this dict in chem.py. _changed_posn_Atoms = {} _changed_picked_Atoms = {} _changed_otherwise_Atoms = {} # == # dict for bonds whose bond-type gets changed # (need not include newly created bonds) changed_bond_types = {} # == # status codes for updater runs of all kinds # (not yet used for all updaters, though). LAST_RUN_DIDNT_HAPPEN = 9 # due to all updaters skipped, or that updater disabled, or program just started LAST_RUN_IS_ONGOING = 10 LAST_RUN_FAILED = 11 # i.e. raised an exception and ended early LAST_RUN_SUCCEEDED = 12 status_of_last_dna_updater_run = LAST_RUN_DIDNT_HAPPEN # end
NanoCAD-master
cad/src/model/global_model_changedicts.py
# Copyright 2009 Nanorex, Inc. See LICENSE file for details. """ Part_drawing_frame.py -- classes for use as a Part's drawing_frame @author: Bruce @version: $Id$ @copyright: 2009 Nanorex, Inc. See LICENSE file for details. History: Bruce 090218 wrote this in part.py, then split into its own file, then added features related to DrawingSets. Bruce 090219 moved everything related to DrawingSets elsewhere. """ # (todo: better name?) # WARNING: The present scheme for Part._drawing_frame would not work # if multiple threads could draw one Part, or if complex objects in # a part (e.g. chunks) might be drawn twice in one frame. See comments # near its use in Chunk.draw for ways we might need to generalize it. # [bruce 070928/090218] from utilities.debug import print_compact_stack from utilities.prefs_constants import indicateOverlappingAtoms_prefs_key from geometry.NeighborhoodGenerator import NeighborhoodGenerator import foundation.env as env # == class _Part_drawing_frame_superclass: """ """ # repeated_bonds_dict lets bonds (or ExternalBondSets) avoid being # drawn twice. It maps id(bond) to bond (for any Bond or ExternalBondSet) # for all bonds that might otherwise be drawn twice. It is public # for use and modification by anything that draws bonds, but only # during a single draw call (or a single draw of a subset of the model). # # Note that OpenGL drawing (draw methods) uses it only for external # bonds, but POV-Ray drawing (writepov methods) uses it for all # bonds; this is ok even if some writepov methods someday call some # draw methods. repeated_bonds_dict = None # These are for implementing optional indicators about overlapping atoms. _f_state_for_indicate_overlapping_atoms = None indicate_overlapping_atoms = False pass # == class Part_drawing_frame(_Part_drawing_frame_superclass): """ One of these is created whenever drawing all or part of a Part, provided Part.before_drawing_model is called as it should be. It holds attributes needed during a single draw of one Part (or, a draw of a portion of the model for one Part). See superclass code comments for documentation of attributes. For more info, see docstring of Part.before_drawing_model. """ def __init__(self): self.repeated_bonds_dict = {} # Note: this env reference may cause undesirable usage tracking, # depending on when it occurs. This should cause no harm -- # only a needless display list remake when the pref is changed. self.indicate_overlapping_atoms = \ env.prefs[indicateOverlappingAtoms_prefs_key] if self.indicate_overlapping_atoms: TOO_CLOSE = 0.3 # stub, guess; needs to not be true even for # bonded atoms, or atoms and their bondpoints, # but big enough to catch "visually hard to separate" atoms. # (1.0 is far too large; 0.1 is ok but too small to be best.) # It would be much better to let this depend on the elements # and whether they're bonded, and not hard to implement # (each atom could be asked whether it's too close to each # other one, and take all this into account). If we do that, # this value should be the largest tolerance for any pair # of atoms, and the code that uses this NeighborhoodGenerator # should do more filtering on the results. [bruce 080411] self._f_state_for_indicate_overlapping_atoms = \ NeighborhoodGenerator( [], TOO_CLOSE, include_singlets = True ) pass return pass # == class fake_Part_drawing_frame(_Part_drawing_frame_superclass): """ Use one of these "between draws" to avoid or mitigate bugs. """ def __init__(self): print_compact_stack( "warning: fake_Part_drawing_frame is being instantiated: " ) # done in superclass: self.repeated_bonds_dict = None # This is necessary to remove any chance of self surviving # for more than one draw of one object (since using an actual # dict then would make bonds sometimes fail to be drawn). # Client code must tolerate this value. return pass # end
NanoCAD-master
cad/src/model/Part_drawing_frame.py
# Copyright 2007-2008 Nanorex, Inc. See LICENSE file for details. """ ReferenceGeometry.py - Jig subclass used as superclass for Plane, Line, etc @author: Ninad @version: $Id$ @copyright: 2007-2008 Nanorex, Inc. See LICENSE file for details. History: ninad 20070521 : Created ninad 20070601: Implemented DragHandler and selobj interface for the class Handles. (and for ReferenceGeoemtry which is a superclass of Plane) ninad 20070604: Changed the superclass from Node to Jig based on a discussion with Bruce. This allows us to use code for jig selection deletion in some select modes. (note that it continues to use drag handler, selobj interfaces.). This might CHANGE in future. After making jig a superclass of ReferenceGeometry some methods in this file have become overdefined. This needs cleanup """ #@NOTE:This file is subjected to major changes. #@TODO: Ninad20070604 : #- Needs documentation and code cleanup / organization post Alpha-9. #-After making jig a superclass of ReferenceGeometry #some methods in this file have become overdefined. This needs cleanup. import foundation.env as env from utilities import debug_flags from utilities.debug import print_compact_traceback from utilities.prefs_constants import selectionColor_prefs_key from utilities.prefs_constants import hoverHighlightingColor_prefs_key from utilities.constants import orange, yellow from OpenGL.GL import glPushName from OpenGL.GL import glPopName from foundation.Utility import Node from model.jigs import Jig from graphics.drawables.DragHandler import DragHandler_API from utilities.Log import greenmsg class ReferenceGeometry(Jig, DragHandler_API): """ Superclass for various reference geometries. Example or reference geometries: Plane, Point, Line. """ sym = "Geometry" # affects name-making code in __init__ # if not redefined, this means it's just a comment in an mmp file mmp_record_name = "#" featurename = "" color = orange normcolor = color atoms = [] points = None handles = None copyable_attrs = Node.copyable_attrs + ('normcolor', 'color') def __init__(self, win): self.win = win #Node.__init__(self, win.assy, gensym("%s" % self.sym, win.assy)) Jig.__init__(self, win.assy, self.atoms) # note: that sets self.glname self.glpane = self.assy.o #@@Geometry object with a visible direction arrow #(at present used in Plane only) This saves the last geometry object #for which the Direction arrow was drawn #(that decides the direction of a plane offset to the object) #The program needs to skip the arrow drawing (which is done inside the # objects _draw_geometry method) when prop manager is closed or when the #Offset option is no more requested. -- ninad 20070612 self.offsetParentGeometry = None def needs_atoms_to_survive(self): """ Overrided method inherited from Jig. This is used to tell if the jig can be copied even it doesn't have atoms. """ return False def _mmp_record_last_part(self, mapping): """ Return a fake string 'type-geometry' as the last entry for the mmp record. This part of mmp record is NOT used so far for ReferenceGeometry Objects. """ #This is needed as ReferenceGeometry is a subclass of Jig #(instead of Node) , Returning string 'geometry' overcomes #the problem faced due to a kludge in method mmp_record #(see file jigs.py)That kludge makes it not write the #proper mmp record. if last part is an empty string (?)--ninad 20070604 return "type-geometry" def _draw(self, glpane, dispdef): self._draw_geometry(glpane, self.color) def _draw_geometry(self, glpane, color, highlighted = False): """ The main code that draws the geometry. Subclasses should override this method. """ pass def draw(self, glpane, dispdef): if self.hidden: return try: glPushName(self.glname) self._draw(glpane, dispdef) except: glPopName() print_compact_traceback( "ignoring exception when drawing Plane %r: " % self) else: glPopName() def draw_in_abs_coords(self, glpane, color): """ Draws the reference geometry with highlighting. """ self._draw_geometry(glpane, env.prefs[hoverHighlightingColor_prefs_key], highlighted = True) return def pick(self): """ Select the reference geometry. """ if not self.picked: Node.pick(self) self.normcolor = self.color self.color = env.prefs[selectionColor_prefs_key] # russ 080603: pref. return def unpick(self): """ Unselect the reference geometry. """ if self.picked: Node.unpick(self) # see also a copy method which has to use the same statement to #compensate for this kluge self.color = self.normcolor def rot(self, quat): pass ##===============copy methods ==================### #Reimplementing Jig.copy_full_in_mapping. Keeping an old comment by Bruce #-- commented niand 20070613 def copy_full_in_mapping(self, mapping): #bruce 070430 revised to honor mapping.assy clas = self.__class__ new = clas(mapping.assy.w, []) new._orig = self new._mapping = mapping return new ###============== selobj interface ===============### #Methods for selobj interface . Note that draw_in_abs_coords method is #already defined above. All of the following is NIY -- Ninad 20070522 def leftClick(self, point, event, mode): """ Method that handle Mouse Left click event """ mode.geometryLeftDown(self, event) mode.update_selobj(event) return self def mouseover_statusbar_message(self): """ Status bar message to display when an object is highlighted. @return: name of the highlighted object @rtype: str """ return str(self.name) def highlight_color_for_modkeys(self, modkeys): """ Highlight color for the highlighted object """ return env.prefs[hoverHighlightingColor_prefs_key] # copying Bruce's code from class Highlightable with some mods. Need to see # if sleobj_still_ok method is needed. OK for now --Ninad 20070601 def selobj_still_ok(self, glpane): res = self.__class__ is ReferenceGeometry if res: our_selobj = self glname = self.glname owner = glpane.assy.object_for_glselect_name(glname) if owner is not our_selobj: res = False # Do debug prints [perhaps never seen as of 061121] print "%r no longer owns glname %r, instead %r does" \ % (self, glname, owner) if not res and env.debug(): print "debug: selobj_still_ok is false for %r" % self return res ###=========== Drag Handler interface =============### def handles_updates(self): #k guessing this one might be needed return True def DraggedOn(self, event, mode): mode.geometryLeftDrag(self, event) mode.update_selobj(event) return def ReleasedOn(self, selobj, event, mode): pass
NanoCAD-master
cad/src/model/ReferenceGeometry.py
# Copyright 2004-2009 Nanorex, Inc. See LICENSE file for details. """ chem.py -- class Atom, and related code. An instance of Atom represents one atom, pseudoatom, or bondpoint in 3d space, with a list of bonds and jigs, and an optional display mode. @author: Josh @version: $Id$ @copyright: 2004-2009 Nanorex, Inc. See LICENSE file for details. History: - originally by Josh - lots of changes, by various developers - class Chunk (then called class molecule) was moved into new file chunk.py circa 041118 - elements.py was split out of this module on 041221 - class Bond and associated code moved into new file bonds.py by bruce 050502 - bruce optimized some things, including using 'is' and 'is not' rather than '==' and '!=' for atoms, molecules, elements, parts, assys, atomtypes in many places (not all commented individually); 050513 - bruce 050610 renamed class atom to class Atom; for now, the old name still works. The name should gradually be changed in all code (as of now it is not changed anywhere, not even in this file except for creating the class), and then the old name should be removed. ###@@@ - bruce 050610 changing how atoms are highlighted during Build mode mouseover. ###@@@ might not be done - bruce 050920 removing laxity in valence checking for carbomeric bonds, now that mmp file supports them. - bruce 060308 rewriting Atom and Chunk so that atom positions are always stored in the atom (eliminating Atom.xyz and Chunk.curpos, adding Atom._posn, eliminating incremental update of atpos/basepos). One motivation is to make it simpler to rewrite high-frequency methods in Pyrex. - bruce 080327 splitting out PAM_Atom_methods TODO: Subclasses of Atom (e.g. for PAM3 pseudoatoms or even strand atoms) are being considered. One issue to check is whether Undo hardcodes the classname 'Atom' and will need fixing to work properly for subclasses with different names. [bruce 071101 comment] """ import math from OpenGL.GL import glPushName from OpenGL.GL import glPopName from graphics.drawing.ColorSorter import ColorSorter from graphics.drawing.CS_draw_primitives import drawcylinder from graphics.drawing.CS_draw_primitives import drawsphere from graphics.drawing.CS_draw_primitives import drawpolycone from graphics.drawing.CS_draw_primitives import drawwiresphere from model.elements import Singlet from model.elements import Hydrogen from model.elements import PeriodicTable from model.elements import Pl5 from model.atomtypes import AtomType #bruce 080327 from model.bond_constants import V_SINGLE from model.bond_constants import min_max_valences_from_v6 from model.bond_constants import valence_to_v6 from model.bond_constants import ideal_bond_length from model.bonds import bonds_mmprecord, bond_copied_atoms, bond_atoms import model.global_model_changedicts as global_model_changedicts from geometry.VQT import V, Q, A, norm, cross, twistor, vlen, orthodist from geometry.VQT import atom_angle_radians from Numeric import dot from graphics.rendering.mdl.mdldata import marks, links, filler from graphics.rendering.povray.povheader import povpoint from utilities.debug import reload_once_per_event from utilities.debug import print_compact_stack, print_compact_traceback from utilities.debug_prefs import debug_pref, Choice_boolean_False, Choice from utilities.Printing import Vector3ToString from utilities.Log import orangemsg, redmsg, greenmsg from utilities.constants import atKey # generator for atom.key attribute, also used for fake atoms. # [moved from here to constants.py to remove import cycle, bruce 080510] # As of bruce 050228, we now make use of the fact that this produces keys # which sort in the same order as atoms are created (e.g. the order they're # read from an mmp file), so we now require this in the future even if the # key type is changed. [Note: this comment appears in two files.] from utilities.constants import intRound from utilities.constants import diDEFAULT from utilities.constants import diBALL from utilities.constants import diTrueCPK from utilities.constants import diTUBES from utilities.constants import diINVISIBLE from utilities.constants import remap_atom_dispdefs #revised, bruce 080324 from utilities.constants import dispLabel from utilities.constants import default_display_mode from utilities.constants import TubeRadius from utilities.constants import BONDPOINT_LEFT_OUT from utilities.constants import BONDPOINT_UNCHANGED # from utilities.constants import BONDPOINT_ANCHORED from utilities.constants import BONDPOINT_REPLACED_WITH_HYDROGEN from utilities.constants import ATOM_CONTENT_FOR_DISPLAY_STYLE from utilities.constants import pink, yellow from utilities.constants import ErrorPickedColor from utilities.prefs_constants import selectionColor_prefs_key from utilities.GlobalPreferences import bondpoint_policy from utilities.GlobalPreferences import disable_do_not_draw_open_bonds from utilities.GlobalPreferences import usePyrexAtomsAndBonds from utilities.GlobalPreferences import dna_updater_is_enabled from utilities.prefs_constants import arrowsOnFivePrimeEnds_prefs_key from utilities.prefs_constants import arrowsOnThreePrimeEnds_prefs_key from utilities.prefs_constants import showValenceErrors_prefs_key from utilities.prefs_constants import dnaDisplayMinorGrooveErrorIndicators_prefs_key from utilities.prefs_constants import dnaMinorGrooveErrorIndicatorColor_prefs_key from utilities.prefs_constants import cpkScaleFactor_prefs_key from utilities.prefs_constants import diBALL_AtomRadius_prefs_key from utilities.prefs_constants import dnaMinMinorGrooveAngle_prefs_key from utilities.prefs_constants import dnaMaxMinorGrooveAngle_prefs_key from utilities.prefs_constants import dnaStrandThreePrimeArrowheadsCustomColor_prefs_key from utilities.prefs_constants import useCustomColorForThreePrimeArrowheads_prefs_key from utilities.prefs_constants import dnaStrandFivePrimeArrowheadsCustomColor_prefs_key from utilities.prefs_constants import useCustomColorForFivePrimeArrowheads_prefs_key from graphics.drawables.Selobj import Selobj_API from utilities import debug_flags from platform_dependent.PlatformDependent import fix_plurals import foundation.env as env from foundation.state_utils import StateMixin from foundation.state_utils import copy_val from foundation.state_constants import S_CHILDREN, S_PARENT, S_DATA, S_CACHE from foundation.state_constants import UNDO_SPECIALCASE_ATOM, ATOM_CHUNK_ATTRIBUTE_NAME from foundation.changedicts import register_changedict, register_class_changedicts import foundation.undo_archive as undo_archive from foundation.undo_archive import register_undo_updater from foundation.inval import InvalMixin import foundation.Utility as Utility from model.jigs import Jig from dna.operations.crossovers import crossover_menu_spec from model.PAM_Atom_methods import PAM_Atom_methods from graphics.model_drawing.special_drawing import USE_CURRENT from graphics.model_drawing.special_drawing import SPECIAL_DRAWING_STRAND_END # == DEBUG_1779 = False # do not commit with True, but leave the related code in for now [bruce 060414] BALL_vs_CPK = 0.25 # ratio of default diBALL radius to default diTrueCPK radius # [renamed from CPKvdW by bruce 060607] # == # define AtomDict and AtomBase differently depending on whether we are # using Pyrex Atoms and Bonds (atombase.pyx): _using_pyrex_atoms = False if usePyrexAtomsAndBonds(): #bruce 080220 revised this # usePyrexAtomsAndBonds tests that we want to, and can, import all # necessary symbols from atombase from atombase import AtomDictBase, AtomBase class AtomDict(AtomDictBase): def __init__(self): AtomDictBase.__init__(self) self.key = atKey.next() return pass print "Using atombase.pyx in chem.py" _using_pyrex_atoms = True else: def AtomDict(): return { } class AtomBase: def __init__(self): pass def __getattr__(self, attr): # in class AtomBase raise AttributeError, attr pass pass # == class Atom (and support code) def _undo_update_Atom_jigs(archive, assy): """ [register this to run after all Jigs, atoms, and bonds are updated, as cache-invalidator for a.jigs and b.pi_bond_obj] @warning: as of 060414 this also does essential undo updates unrelated to jigs. """ del archive if 1: # bruce 060414 fix bug 1779 (more efficient than doing something in # Atom._undo_update, for every atom) # KLUGE: assume this always runs (true as of 060414), not only if # there are jigs or under some other "when needed" conds. # Note: it would be best to increment this counter at the start and # end of every user op, but there's not yet any central place for code # to run at times like that (except some undo-related code which runs # at other times too). # # A more principled and safer fix would be either for kill functions # participating in "prekill" to take an argument, unique per # prekill/kill event, or to ensure the global counter (acting as if it # was that argument) was unique by again incrementing it after the # kill call returns within the same code that had initiated the # prekill. Utility._will_kill_count += 1 mols = assy.allNodes(assy.Chunk) # note: this covers all Parts, whereas assy.molecules only covers the current Part. jigs = assy.allNodes(Jig) # Note: if we wanted to avoid those imports of Chunk and Jig, # then what we really want instances of is: # - for Chunk, whatever can be stored in atom.molecule # (and will thus include that atom in its .atoms dict); # - for Jig, whatever can be referenced by atom.jigs. # In both cases there could be API superclasses for these # aspects of Nodehood. for m in mols: for a in m.atoms.itervalues(): if a.jigs: _changed_structure_Atoms[a.key] = a #bruce 060322; try to only do this to atoms that need it #k tracking this change is probably not needed by Undo but #might be needed by future non-Undo subscribers to that dict; #Undo itself needs to remember to clear its subscribed cache #of it after this ###@@@DOIT a.jigs = [] #e or del it if we make that optim in Jig (and review #whether this needs to occur outside 'if a.jigs') for b in a.bonds: #k maybe the S_CACHE decl will make this unnecessary? # Not sure... maybe not, and it's safe. b.pi_bond_obj = None # I hope refdecr is enough to avoid a memory leak; if not, # give that obj a special destroy for us to call here. That # obj won't remove itself from a.jigs on refdecr (no __del__); # but it would in current implem of .destroy. del b.pi_bond_obj # save RAM for j in jigs: for a in j.atoms: a.jigs.append(j) _changed_structure_Atoms[a.key] = a #bruce 060322; see comment about same statement above for j in jigs: for a in j.atoms[:]: j.moved_atom(a) # strictly speaking, this is beyond our scope, but # Atom._undo_update can't do it since a.jigs isn't set. Also, # whatever this does should really just be done by # Jig._undo_update. So make that true, then remove this. # ###@@@ if j.killed(): #bruce 080120 added this (precaution) break j.changed_structure(a) #bruce 080120, might be needed by DnaMarker if j.killed(): break continue # next atom continue # next jig return # WARNING: register_undo_updater does not yet pay attention to its arguments # except for the update function itself, so it's not yet suitable for use # with more than one registered function if their relative order matters. # [bruce 071003 comment] register_undo_updater( _undo_update_Atom_jigs, updates = ('Atom.jigs', 'Bond.pi_bond_obj'), after_update_of = ('Assembly', 'Node', 'Atom.bonds') # Node also covers its subclasses Chunk and Jig. # We don't care if Atom is updated except for .bonds, # nor whether Bond is updated at all, # which is good because *we* are presumably a # required part of updating both of those classes! # FYI, we use 'Assembly' (string) rather than Assembly (class) # to avoid a recursive import problem, # and also to avoid an inappropriate import dependency # (low-level -> high-level). ) # == # changedicts for class Atom, used by Undo and by dna updater # [definitions moved from this file to global_model_changedicts.py, bruce 080510] # These global dicts all map atom.key -> atom, for atoms which change in # various ways (different for each dict). The dicts themselves (as opposed to # their contents) never change (so other modules can permanently import them), # but they are periodically processed and cleared. For efficiency, they're # global and not weak-valued, so it's important to delete items from them when # destroying atoms (which is itself nim, or calls to it are; destroying assy # needs to do that ### TODO). # obsolete comment: ###@@@ Note: These are not yet looked at, but the code to # add atoms into them is supposedly completed circa bruce 060322. update # 071106: some of them are looked at (and have been since Undo worked), but # maybe not all of them. from model.global_model_changedicts import _changed_parent_Atoms # record atoms w/ changed assy or molecule or liveness/killedness (an # atom's assy is atom.molecule.assy; no need to track changes here to the # mol's .part or .dad) related attributes: __killed, molecule ###@@@ # declare these?? not yet sure if that should be per-attr or not, re # subclasses... WARNING: name is private, but it's directly accessed in # many places in chunk.py [bruce 071106 comment] register_changedict( _changed_parent_Atoms, '_changed_parent_Atoms', ('__killed', ATOM_CHUNK_ATTRIBUTE_NAME) ) #k or must we say _Atom__killed?? (It depends on whether that routine #knows how to mangle it itself.) (As of long before 071018 that arg of #register_changedict (related_attrs) is not yet used.) from model.global_model_changedicts import _changed_structure_Atoms # tracks changes to element, atomtype, bond set, bond direction (not bond order #k) # WARNING: there is also a related but different global dict earlier than # this one in the same file (global_model_changedicts.py), whose spelling # differs only in 'A' vs 'a' in Atoms, and in having no initial # underscore, namely, changed_structure_atoms. # # This confusion should be cleaned up sometime, by letting that one just # be a subscriber to this one, and if efficiency demands it, first # splitting this one into the part equivalent to that one, and the rest. # # Ways this one has more atoms added to it than that one does: jigs, info, # kill, bond direction. (See also the comment where the other one is # defined.) # See also: _changed_parent_Atoms, which also covers kill (probably in a # better way). # # related attributes: bonds, element, atomtype, info, jigs # (not only # '.jigs =', but '.jigs.remove' or '.jigs.append') # (we include info since it's used for repeat-unit correspondences in # extrude; this is questionable) # (we include jigs since they're most like a form of structure, and in # future might have physical effects, and since the jigs for pi bonds are # structural) register_changedict( _changed_structure_Atoms, '_changed_structure_Atoms', ('bonds', 'element', 'atomtype', 'info', 'jigs') ) from model.global_model_changedicts import _changed_posn_Atoms # tracks changes to atom._posn (not clear what it'll do when we can treat # baseposn as defining state). # related attributes: _posn register_changedict( _changed_posn_Atoms, '_changed_posn_Atoms', ('_posn',) ) from model.global_model_changedicts import _changed_picked_Atoms # tracks changes to atom.picked (for live or dead atoms) # (not to _pick_time etc, we don't cover that in Undo) # related attributes: picked # WARNING: name is private, but it's directly accessed in ops_select.py register_changedict( _changed_picked_Atoms, '_changed_picked_Atoms', ('picked',) ) from model.global_model_changedicts import _changed_otherwise_Atoms # tracks all other model changes to Atoms (display style, dnaBaseName) # related attributes: display, _dnaBaseName register_changedict( _changed_otherwise_Atoms, '_changed_otherwise_Atoms', ('display', '_dnaBaseName') ) # Notes (design scratch): for which Atom attrs is the attr value mutable in # practice? bonds, jigs, maybe _posn (probably not). the rest could be handled # by a setter in a new-style class, or by AtomBase and i wonder if it's # simpler to just have one dict for all attrs... certainly it's simpler, so is # it ok? The reason we have multiple dicts is so undo diff scanning is faster # when (e.g.) lots of atoms change in _posn and nothing else (as after # Minimize or movie playing or (for now) chunk moving). _Atom_global_dicts = [_changed_parent_Atoms, _changed_structure_Atoms, _changed_posn_Atoms, _changed_picked_Atoms, _changed_otherwise_Atoms] # See also some code below class Atom, which registers these changedicts # as being used with that class. That code has to occur after the class is # defined, but we permit the above per-changedict registrations to come # first so that they can help document the dicts near the top of the file. # The dicts themselves needn't come first, since they're only looked up as # module globals (or from external modules), but it's easier to read the # code if they do. # == def Atom_prekill_prep(): #bruce 060328 """ Prepare to kill some set of atoms (known to the caller) more efficiently than otherwise. Return a value which the caller should pass to the _f_prekill method on all (and ONLY) those atoms, before killing them. [#e Note: If we can ever kill atoms and chunks in the same operation, we'll need to revise some APIs so they can all use the same value of _will_kill_count, if we want to make that most efficient.] """ ###e this should be merged with similar code in class Node Utility._will_kill_count += 1 return Utility._will_kill_count class Atom( PAM_Atom_methods, AtomBase, InvalMixin, StateMixin, Selobj_API): #bruce 050610 renamed this from class atom, but most code still uses # "atom" for now (so we have to assign atom = Atom, after this class # definition, until all code has been revised) # update, bruce 071113: I am removing that assignment below. See comment there. #bruce 080327 moved a lot of PAM-specific methods to mixin PAM_Atom_methods. """ An Atom instance represents one real atom, or one "singlet" (a place near a real atom where another atom could bond to it). At any time, each atom has an element, a position in space, a list of bond objects it's part of, a list of jigs it's part of, and a reference to exactly one molecule object ("chunk") which owns it; all these attributes can change over time. It also has a never-changing key used as its key in self.molecule.atoms, a selection state, a display mode (which overrides that of its molecule), and (usually) some attributes added externally by its molecule, notably self.index. The attributes .index and .xyz are essentially for the private use of the owning molecule; see the methods posn and baseposn for details. Other code might add other attributes to an atom; some of those might be copied in the private method Atom.copy_for_mol_copy() [now removed]. """ _selobj_colorsorter_safe = True #bruce 090311 # bruce 041109-16 wrote docstring # default values of instance variables: __killed = 0 # note: this is undoable state, declared below picked = False # self.picked defines whether the atom is selected; see also assembly.selatoms # (note that Nodes also have .picked, with the same meaning, but atoms # are not Nodes) display = diDEFAULT # rarely changed for atoms _dnaBaseName = "" #bruce 080319 revised this; WARNING: accessed directly in DnaLadderRailChunk ghost = False #bruce 080529 _modified_valence = False #bruce 050502 info = None #bruce 050524 optim (can remove try/except if all atoms have this) ## atomtype -- set when first demanded, or can be explicitly set using ## set_atomtype or set_atomtype_but_dont_revise_singlets index = -1 #bruce 060311 add this as a precaution re bug 1661, and since it seems #necessary in principle, given that we store it as undoable state, but #(I guess, re that bug) don't always set it very soon after making an #atom; -1 is also the correct value for an atom in a chunk but not yet #indexed therein; in theory the value doesn't matter at all for a #chunkless atom, but a removed atom (see Chunk.delatom) will have -1 #here, so imitating that seems most correct. # _s_attr decls for state attributes -- children, parents, refs, bulky # data, optional data [bruce 060223] _s_undo_specialcase = UNDO_SPECIALCASE_ATOM # This tells Undo what specialcase code to use for this class # (and any subclasses we might add). It also tells it which # changedicts to look at. # TODO: # - That whole system of Undo changedicts # could be refactored and improved, so that we'd instead point # to a changedict-containing object which knew which attribute # each one was for, as well as knowing this specialcase-type. # That object would be a "description of this class for # purposes of Undo" (except for the _s_attr decls, which might # as well remain as they are). # - Ultimately, Undo shouldn't need specialcases at all; # right now it needs them since we don't have enough control, # when registering updaters that involve several specific # classes, of their calling order. # (And maybe other minor reasons I forget now, but I think # that's the only major one.) # - Meanwhile, it would be good to automatically ensure that # the related_attrs lists passed to register_changedicts # cover all the undoable state attrs in all the classes # that use those changedicts. Otherwise it means changes to # some attr are not noticed by Undo (or, that they are, # but we forgot to declare which changedict notices them # in the related_attrs list for that changedict). # [bruce 071114] _s_attr_bonds = S_CHILDREN _s_attr_molecule = S_PARENT # note: most direct sets of self.molecule are in chunk.py # note: self.molecule is initially None. Later it's self's chunk. If # self is then killed, it's _nullMol. Some buglike behavior might # effectively kill or never-make-fully-alive self's chunk, without # removing self from it (especially in nonstandardly-handled assys # like the ones for the partlib). Finally, undoing to before self was # created will cause its .molecule to become None again. In that state # there is no direct way to figure out self's assy, but it might have # one, since it might be in its undo_archive and be able to come back # to life that way, by Redo. Or the redo stack might get cleared, but # self might still be listed in some dicts in that undo_archive (not # sure), and maybe in various global dicts (changedicts, glname dict, # dna updater error dict, etc). This makes it hard to destroy self and # all its storage, when self's assy is destroyed. To fix this, we # might keep a dict in assy of all atoms ever in it, and/or keep a # permanent _f_assy field in self. Not yet decided. Making _nullMol # per-assy would not help unless we can always use it rather than # None, but that's hard because atoms initially don't know assy, and # Undo probably assumes the initial state of .molecule is None. So a # lot of code would need analysis to fix that, whereas a new # one-purpose system to know self's assy would be simpler. But it # takes RAM and might not really be needed. The main potential need is # to handle atoms found in changedicts with .molecule of None or # _nullMol, to ask their assy if it's destroyed (updater should ignore # atom) or not (updater should handle atom if it handles killed # atoms). But do updaters ever need to handle killed atoms? [bruce # 080219 comment] assert ATOM_CHUNK_ATTRIBUTE_NAME == 'molecule' # must match this _s_attr_molecule decl attr name, # and all the atom.molecule refs in all files [bruce 071114] _s_attr_jigs = S_CACHE # first i said S_REFS, but this is more efficient, and helps handle # pi_bond_sp_chain.py's Jigs. # [not sure if following comment written 060223 is obs as of 060224:] # This means that restored state will unset the .jigs attr, for *all* # atoms (???), and we'll have to recompute them somehow. The alg is # easy (scan all jigs), but exactly how to organize it needs to be # thought about. Is it worth thinking of Atom.jigs in general (not # just re Undo) as a recomputable attribute? We could revise the # incremental updaters to not worry if it's missing, and put in a # __getattr__ which redid the entire model's atoms when it ran on any # atom. (Just scan all jigs, and assume all atoms' .jigs are either # missing or correct, and ignore correct ones.) But that approach # would be wrong for pi_bond_sp_chain.py's Jigs since they would not # be scanned (efficiently). So for them, they have to insist that if # they exist, the atoms know about them. (Using a sister attr to # .jigs?) (Or do we teach atoms how to look for them on nearby bonds? # That's conceivable.) ... or if these fields are derived specifically # from the atomsets of Jigs, then do we know which atoms to touch # based on the manner in which Undo altered certain Jigs (i.e. does # our update routine start by knowing the set of old and new values of # all changed atomsets in Jigs)?? Certainly we could teach the # diff-applyer to make that info available (using suitable attr decls # so it knew it needed to)... but I don't yet see how this can work # for pi_bond Jigs and for incremental Undo. #e we might want to add type decls for the bulky data (including the #objrefs above), so it can be stored in compact arrays: #bruce 060322 zapping _s_attr_key = S_DATA decl -- should be unnecessary #since .key never changes. ####@@@@ TEST # NOTE: for using this for binary mmp files, it might be necessary -- # review that when we have them. ###@@@ ## _s_attr_key = S_DATA # this is not yet related to Undo's concept of objkey (I think #k) [bruce 060223] # storing .index as Undo state is no longer needed [bruce 060313] # note: a long comment removed on 070518 explained that when we had it, # it was only valid since chunk's atom order is deterministic _s_attr__posn = S_DATA #bruce 060308 rewrite _s_attr_element = S_DATA # we'll want an "optional" decl on the following, so they're reset to # class attr (or unset) when they equal it: _s_attr_picked = S_DATA _s_categorize_picked = 'selection' ##k this is noticed and stored, but I don't think it yet has any ##effect (??) [bruce 060313] _s_attr_display = S_DATA _s_attr__dnaBaseName = S_DATA #bruce 080319 # decided to leave out _s_attr_ghost, for now [bruce 080530]: ## _s_attr_ghost = S_DATA #bruce 080529; might not be needed ## # (since no ops change this except on newly made atoms, so far) _s_attr_info = S_DATA _s_attr__Atom__killed = S_DATA # Declaring (name-mangled) __killed seems needed just like for any # other attribute... (and without it, reviving a dead atom triggered # an assertfail, unsurprisingly) #e declare these later when i revise code to unset/redflt them most of the time: ###@@@ ## _picked_time = _picked_time_2 = -1 # note: atoms don't yet have individual colors, labels, names... ###e need atomtype - hard part is when it's unset, might have to revise #how we handle that, e.g. derive it from _hyb; actually, for pure scan, #why is 'unset' hard to handle? i bet it's not. It just has no default #value. It's down here under the 'optional' data since we should derive it #from _hyb which is usually 'default for element'. _s_attr_atomtype = S_DATA # The attributes _PAM3plus5_Pl_Gv_data and _f_Pl_posn_is_definitive # are only used by methods in our mixin superclass PAM_Atom_methods, # except for some of our foundational methods like Atom.copy() # (and soon, writemmp and a method for reading an info record), # but since anything here uses them, we define them here. [bruce 080523] _PAM3plus5_Pl_Gv_data = None # "+5 data", stored only on Ss3, Ss5 (PAM strand sugar atoms). # # This is now copyable as of 080523. # It needs to be savable in mmp file [coded, but mmpformat is not, and mmpread is not ###] # # It should be undoable in theory, but this would be slow and the bugs # it might cause to leave it out seem very unlikely, so it's not # undoable for now -- this will need to change if we implement # "minimize PAM3+5 as PAM5", since then a single undoable operation # (the minimize) can change the +5 data without ever converting it # to PAM5 in an in-between undo snapshot. _f_Pl_posn_is_definitive = True # friend attribute for temporary use by PAM3plus5 code on Pl atoms; # no need to be undoable or copyable or savable, since should always # be True during an Undo snapshot or copy or save operation. # these are needed for repeated destroy: [bruce 060322] _glname = 0 # made this private, bruce 080220 if not _using_pyrex_atoms: key = 0 # BAD FOR PYREX ATOMS - class variable vs. instance variable _f_will_kill = 0 #bruce 060327 _f_dna_updater_should_reposition_baggage = False #bruce 080404 # The iconPath specifies path(string) of an icon that represents the # objects of this class (in this case its gives the path of an 'atom' icon') # see PM.PM_SelectionListWidget.insertItems for an example use of this # attribute. iconPath = "ui/modeltree/Single_Atom.png" # Text to be drawn floating over the atom. Note, you must also # set chunk.chunkHasOverlayText for this to be used. Do this by # just calling setOverlayText() to set both. overlayText = None # piotr 080822: The pdb_info dictionary stores information # read from PDB file (or equivalent information generated by # Peptide Builder). # piotr 080828: Changed the default value of pdb_info to None and # moved it to here from __init__ pdb_info = None # def __init__ is just below a couple undo-update methods def _undo_update(self): if self._f_dna_updater_should_reposition_baggage: del self._f_dna_updater_should_reposition_baggage # expose class default of False # ###REVIEW: will this come late enough to fix any explicit # sets by other undo effects? I think so, since it's only # set by user ops or creating bonds or transmuting atoms. # But Bond._changed_atoms runs at some point during Undo, # and if that comes later than this, it'll be a ###BUG. # And it might well be, so this needs analysis or testing. # If it's a bug, do this in a later pass over atoms, I guess. # [bruce 080404] if self.molecule is None: # new behavior as of 060409, needed to interact well with # differential mash_attrs... i'm not yet fully comfortable with # this (maybe we really need _nullMol in here??) ###@@@ print "bug (ignored): _undo_update on dead atom", self return #bruce 060224 conservative guess -- invalidate everything we can find #any other code in this file invalidating for b in self.bonds: b.setup_invalidate() b.invalidate_bonded_mols() self.molecule.invalidate_attr('singlets') self.molecule.invalidate_attr('externs') #bruce 070602: fix Undo bug after Make Crossover (crossovers.py) # -- the bug was that bonds being (supposedly) deleted during this # undo state-mashing would remain in mol.externs and continue to # get drawn. I don't know why it didn't happen if bonds were also # created on the same atoms (or perhaps on any atoms in the same # chunk), but presumably that happened to invalidate externs in # some other way. # As for why the bug went uncaught until now, maybe no other # operation creates external bonds without also deleting bonds on # the same atoms (which evidently prevents the bug, as mentioned). # For details of what was tried and how it affected what happened, # see crossovers.py cvs history circa now. self.molecule._f_lost_externs = True self.molecule._f_gained_externs = True self._changed_structure() self.changed() posn = self.posn() self.setposn( posn - V(1,1,1) ) # i hope it doesn't optimize for posn being unchanged! just in # case, set wrong then right self.setposn( posn ) # .picked might change... always recompute selatoms in external code ####@@@@ self.molecule.changeapp(1) # anything needed for InvalMixin stuff?? #e ####@@@@ # # can't do this yet: ## for jig in self.jigs[:]: ## jig.moved_atom(self) ####@@@@ need to do this later? StateMixin._undo_update(self) def __init__(self, sym, where, mol = None): #bruce 060612 let mol be left out """ Create an Atom of element sym (e.g. 'C' -- sym can be an element, atomtype, or element-symbol, or another atom to copy these from) at location 'where' (e.g. V(36, 24, 36)) belonging to molecule mol (can be None or missing). Atom initially has no real or open bonds, and default hybridization type. """ # note: it's not necessary to track changes to self's attrs (in e.g. # _changed_parent_Atoms) during __init__. [bruce 060322] AtomBase.__init__(self) self.key = atKey.next() # unique key for hashing and/or use as a dict key; # also used in str(self) _changed_parent_Atoms[self.key] = self # since this dict tracks all new atoms (i.e. liveness of atoms) # (among other things) # done later, since our assy is not yet known: [bruce 080220] ## self._glname = assy.alloc_my_glselect_name( self) # self.element is an Elem object which specifies this atom's element # (this will be redundant with self.atomtype when that's set, # but at least for now we keep it as a separate attr, # both because self.atomtype is not always set, # and since a lot of old code wants to use self.element directly) # figure out atomtype to assume; atype = None means default atomtype for element will be set. # [bruce 050707 revised this; previously the default behavior was to # set no atomtype now (picking one when first asked for), not to set # the default atomtype now. This worked ok when the atomtype guessed # later was also the default one, but not once that was changed to # guess it based on the number of bonds (when first asked for), since # some old code would ask for it before creating all the bonds on a # new atom. Now, the "guessing atomtype from bonds" behavior is still # needed in some cases, and is best asked for by leaving it unset, but # that is done by a special method or init arg ###doc, since it should # no longer be what this init method normally does. BTW the docstring # erroneously claimed we were already setting default atomtype.] #bruce 080327 revised this to not use try/except routinely # (possible optimization, and for clarity) atype = None # might be changed during following if/else chain if type(sym) == type(""): # this is normal, since sym is usually an element symbol like 'C' self.element = PeriodicTable.getElement(sym) elif isinstance(sym, Atom): self.element = sym.element atype = sym.atomtype elif isinstance(sym, AtomType): self.element = sym.element atype = sym else: # note: passing an Element object would probably make sense # to allow, but is nim. [bruce 080514 comment] assert 0, "can't initialize Atom.element from %r" % (sym,) #e could assert self.element is now an Elem, but don't bother -- # if not, we'll find out soon enough if atype is not None: assert atype.element is self.element # trivial in one of these cases, should improve #e # this atomtype atype (or the default one, if atype is None) # will be stored at the end of this init method. # 'where' is atom's absolute location in model space, # until replaced with 'no' by various private methods in Atom or Chunk, indicating # the location should be found using the formula in self.posn(); # or it can be passed as 'no' by caller of __init__ if 1: #bruce 060308 rewrote this part: assert where != 'no' assert type(where) is type(V(0,0,0)) self._posn = + where _changed_posn_Atoms[self.key] = self #bruce 060322 # list of bond objects self.bonds = [] # list of jigs (###e should be treated analogously to self.bonds) self.jigs = [] # pointer to molecule containing this atom # (note that the assembly is not explicitly stored # and that the index is only set later by methods in the molecule) self.molecule = None # checked/replaced by mol.addatom # Note: for info about what self.molecule is set to # when it's not self's chunk, see the long comment below the # undo declaration for the .molecule attribute # (i.e. the assignment of class attr _s_attr_molecule, above). # [bruce 080219 comment] if mol is not None: mol.addatom(self) else: # this now happens in mol.copy as of 041113 # print "fyi: creating atom with mol == None" pass # (optional debugging code to show which code creates bad atoms:) ## if debug_flags.atom_debug: ## self._f_source = compact_stack() self.set_atomtype_but_dont_revise_singlets( atype) return # from Atom.__init__ _f_assy = None # friend attribute for classes Atom, Chunk, perhaps Bond, # and perhaps Undo and updaters [bruce 080220] def _f_set_assy(self, assy): #bruce 080220 """ [friend method for anything that can change our assy or be the first to realize what it is.] Set a new or different value of self._f_assy. Do necessary internal updates. @warning: NOT YET CALLED ENOUGH to be sure all atoms have _f_assy set which have a well-defined assy. If that is needed by anything that might run on non-live atoms, we'll have to find more places to set it so we can be sure it's known for them. @note: self._f_assy might be None, or a different assy. (But I don't know if the "different assy" case ever occurs in practice, or if it works fully.) @note: as an important optimization, callers should only call this if assy is not self._f_assy. @note: the caller may or may not have already changed self.molecule to be consistent with assy, so we can't assume it's consistent. This could probably be changed if necessary. """ assert assy is not None # (in fact it has to be an assembly object, but no assert is needed # since the methods calls below will fail if it's not; # but at least during devel we'll assert it's not the fake one from _nullMol:) assert type(assy) is not type("") # make sure we're not given a fake assy from _nullMol. # If we ever are, we'll need a special case in the caller. # leave old assy, if any if self._f_assy is not None: print "%r._f_set_assy: leaving old assy %r, for new one %r. " \ "Implem of this case is untested." % \ (self, self._f_assy, assy) self._f_assy.dealloc_my_glselect_name( self, self._glname) # join new assy self._glname = assy.alloc_my_glselect_name( self) # needed before drawing self or its bonds, # so those must ask for it via self.get_glname(glpane), # which calls this method if necessary to set it # [bruce 050610, revised 080220] self._f_assy = assy return def _assy_may_have_changed(self): #bruce 080220; UNTESTED & not yet used, see comment """ [private method, for _undo_update or similar code] See if our assy changed, and if so, call _f_set_assy. """ # Note: # This method is probably not needed, since if Undo changes # self.molecule, it must change it to a value it had before, # when last alive. (If atoms were moved between assys which # both supported Undo, they could end up in both at once; # therefore they can't be. If they are moved between assys # but only the new one supports Undo, I think this reasoning # remains valid.) # So I did not yet figure out where to add a call to it for # Undo (I'm not sure if .molecule has changed when _undo_update # is called, since IIRC it's changed in a special case step in # undo). So, it is not yet being called, and it's UNTESTED. # [bruce 080220/080223] chunk = self.molecule if chunk is not None and not chunk.isNullChunk(): assy = chunk.assy if self._f_assy is not assy: self._f_set_assy(assy) return def _undo_aliveQ(self, archive): #bruce 060406 """ Would this (Atom) object be picked up as a child object in a (hypothetical) complete scan of children (including change-tracked objects) by the given undo_archive (or, optional to consider, by some other one)? The caller promises it will only call this when it's just done ... ###doc """ # This implem is only correct because atoms can only appear in the # archive's current state if they are owned by chunks which appear # there. (That's only true because we fix or don't save invalid # _hotspots, since those can be killed bondpoints.) mol = self.molecule return archive.childobj_liveQ(mol) and mol.atoms.has_key(self.key) def _f_jigs_append(self, jig, changed_structure = True): """ [friend method for class Jig] Append a jig to self.jigs, and perform necessary invalidations. @param changed_structure: if true (the default, though whether that's needed has not been reviewed), record this as a change to this atom's structure for purposes of Undo and updaters. """ #bruce 071025 made this from code in class Jig; #bruce 071128 added changed_structure option self.jigs.append(jig) #k not sure if following is needed -- bruce 060322 if changed_structure: _changed_structure_Atoms[self.key] = self return def _f_jigs_remove(self, jig, changed_structure = True): """ [friend method for class Jig] Remove a jig from self.jigs, and perform necessary invalidations. @param changed_structure: if true (the default, though whether that's needed has not been reviewed), record this as a change to this atom's structure for purposes of Undo and updaters. @note: if jig is not in self.jigs, complain (when debug_flags.atom_debug), but tolerate this. (It's probably an error, but of unknown commonness or seriousness.) """ #bruce 071025 made this from code in class Jig; #bruce 071128 added changed_structure option try: self.jigs.remove(jig) except: # Q: does this ever still happen? TODO: if so, document when & why. # Note that, in theory, it could happen for several reasons, # not just the expected one (jig not in a list). # new feature 071025 -- if it's not that, raise a new exception. # (We could also only catch ValueError here -- might be more sensible. # First verify it's the right one for .remove not finding something!) assert type(self.jigs) is type([]) if debug_flags.atom_debug: print_compact_traceback("atom_debug: ignoring exception in _f_jigs_remove (Jig.remove_atom): ") else: #k not sure if following is needed -- bruce 060322 if changed_structure: _changed_structure_Atoms[self.key] = self return # For each entry in this dictionary, add a context menu command on atoms # of the key element type allowing transmutation to each of the element # types in the value list. # (bruce 070412 addition: if the selected atoms are all one element, and # one of those is the context menu target, make this command apply to all # those selected atoms. # [Q: should it apply to the subset of the same element, if that's not all? # Guess: yes. That further enhancement is NIM for now.]) # Revision for dna data model, bruce 080320: remove entries that # transmute *to* deprecated PAM elements when dna updater is active. # As of now, all entries go either to or from deprecated elements # (or both), but some will be retained since they are # "from deprecate to non-deprecated". But they won't normally show up # to users since they only show up on applicable elements. _transmuteContextMenuEntries = { 'Ae3': ['Ax3'], 'Ax3': ['Ae3'], 'Se3': ['Ss3', 'Sh3'], 'Pl3': ['Pe5', 'Sh3'], # Unused in PAM3 'Sh3': ['Ss3', 'Se3'], 'Sj3': ['Ss3'], 'Ss3': ['Sj3', 'Hp3'], 'Hp3': ['Ss3'], 'Ae5': ['Ax5'], 'Ax5': ['Ae5'], 'Pe5': ['Pl5', 'Sh5'], 'Pl5': ['Pe5', 'Sh5'], 'Sh5': ['Pe5', 'Pl5'], 'Sj5': ['Ss5'], 'Ss5': ['Sj5', 'Hp5'], 'Hp5': ['Ss5'], #bruce 070412 added Ss <-> Hp; not sure if that's enough entries for Hp } _transmuteContextMenuEntries_for_dna_updater = None # replaced at runtime, within class def _init_transmuteContextMenuEntries_for_dna_updater(self): #bruce 080320 """ [private helper] Remove entries going *to* deprecated PAM elements from class constant _transmuteContextMenuEntries to initialize class constant _transmuteContextMenuEntries_for_dna_updater. """ assert self._transmuteContextMenuEntries_for_dna_updater is None input = self._transmuteContextMenuEntries output = {} # modified below testing = False if testing: input['C'] = ['Si'] # works for fromSymbol in input.keys(): fromElement = PeriodicTable.getElement(fromSymbol) # don't disallow "from" a deprecated element -- # it might help users fix their input errors! ## if fromElement.deprecated_to: ## continue for toSymbol in input[fromSymbol]: toElement = PeriodicTable.getElement(toSymbol) if toElement.deprecated_to: continue if testing: print "\nfyi: retaining transmute entry: %r -> %r" % (fromSymbol, toSymbol) output.setdefault(fromSymbol, []) output[fromSymbol].append(toSymbol) continue continue self.__class__._transmuteContextMenuEntries_for_dna_updater = output if testing: print "\nfyi: _transmuteContextMenuEntries_for_dna_updater =", output return def make_selobj_cmenu_items(self, menu_spec): """ Add self-specific context menu items to <menu_spec> list when self is the selobj, in modes that support it (e.g. depositMode and selectMode and subclasses). """ if self.element.pam: #bruce 080401 pam_atom_entries = self._pam_atom_cmenu_entries() if pam_atom_entries: menu_spec.extend(pam_atom_entries) pass transmute_entries = self._transmuteContextMenuEntries # non-updater version if dna_updater_is_enabled(): # bruce 080320: use only entries not involving deprecated PAM elements transmute_entries = self._transmuteContextMenuEntries_for_dna_updater if transmute_entries is None: self._init_transmuteContextMenuEntries_for_dna_updater() transmute_entries = self._transmuteContextMenuEntries_for_dna_updater assert transmute_entries is not None pass fromSymbol = self.element.symbol if (transmute_entries.has_key(fromSymbol)): #bruce 070412 (enhancing EricM's recent new feature): # If unpicked, do it for just this atom; # If picked, do it for all picked atoms, # but only if they are all the same element. # (But if they're not, still offer to do it for # just this atom, clearly saying so if possible.) if self.picked: selatoms = self.molecule.assy.selatoms # there ought to be more direct access to this doall = True for atom in selatoms.itervalues(): if atom.element.symbol != fromSymbol: doall = False break continue # Note: both doall and self.picked and len(selatoms) are used below, # to determine the proper menu item name and command. # Note: as a kluge which is important for speed, # we don't actually make a selatoms list here as part of the command, # since this menu item won't usually be the one chosen, # and it can find the selatoms again. # # higher-level entry for Pl, first [bruce 070522, 070601]: if fromSymbol == 'Pl5' and doall and len(selatoms) == 2: ## import crossovers ## try: ## reload(crossovers)### REMOVE WHEN DEVEL IS DONE; for debug only; will fail in a built release ## except: ## print "can't reload crossovers" ms1 = crossover_menu_spec(self, selatoms) if ms1: menu_spec.append(None) # separator menu_spec.extend(ms1) menu_spec.append(None) # separator for toSymbol in transmute_entries[fromSymbol]: newElement = PeriodicTable.getElement(toSymbol) if self.picked and len(selatoms) > 1: if doall: cmdname = "Transmute selected atoms to %s" % toSymbol #e could also say the number of atoms command = ( lambda arg1 = None, arg2 = None, atom = self, newElement = newElement: atom.Transmute_selection(newElement) ) # Kluge: locate that command method on atom, used # for access to selatoms, even though it's not # defined to operate on atom (tho it does in this # case). One motivation is to ease the upcoming # emergency merge by not modifying more files/code # than necessary. else: cmdname = "Transmute this atom to %s" % toSymbol #e could also say fromSymbol, tho it appears elsewhere in the menu command = ( lambda arg1 = None, arg2 = None, atom = self, newElement = newElement: atom.Transmute(newElement) ) else: cmdname = "Transmute to %s" % toSymbol command = ( lambda arg1 = None, arg2 = None, atom = self, newElement = newElement: atom.Transmute(newElement) ) menu_spec.append((cmdname, command)) continue if debug_flags.atom_debug: from foundation.undo_archive import _undo_debug_obj # don't do this at toplevel if self is _undo_debug_obj: checked = 'checked' else: checked = None item = ('_undo_debug_obj = %r' % self, self.set_as_undo_debug_obj, checked) menu_spec.append(item) return def nodes_containing_selobj(self): #bruce 080507 """ @see: interface class Selobj_API for documentation """ # include a lot of safety conditions in case of calls # on out of date selobj... if self.killed(): # note: includes check of chunk is None or chunk.isNullChunk() return [] chunk = self.molecule return chunk.containing_nodes() def set_as_undo_debug_obj(self): undo_archive._undo_debug_obj = self undo_archive._undo_debug_message( '_undo_debug_obj = %r' % self ) return def setOverlayText(self, text): # by EricM self.overlayText = text self.molecule.chunkHasOverlayText = True def __getattr__(self, attr): # in class Atom assert attr != 'xyz' # temporary: catch bugs in bruce 060308 rewrite try: return AtomBase.__getattr__(self, attr) except AttributeError: return InvalMixin.__getattr__(self, attr) def destroy(self): #bruce 060322 (not yet called) ###@@@ """ [see comments in Node.destroy or perhaps StateMixin.destroy] @note: it should be (but may not now be) legal to call this multiple times, in any order w/ other objs' destroy methods. @warning: SEMANTICS ARE UNCLEAR -- whether it should destroy bonds in self.bonds (esp in light of rebond method). @see: comments in assy_clear by bruce 060322 (the "misguided" ones, written as if that was assy.destroy, which it's not). """ # If this proves inefficient, we can dispense with most of it, since # glselect dict can be made weak-valued (and will probably need to be # anyway, for mmkit library part atoms), and change-tracking dicts # (_Atom_global_dicts) are frequently cleared, and subscribers will # ignore objects from destroyed assys. So it's only important here if # we destroy atoms before their assy is destroyed (e.g. when freeing # from redo or old undo diffs), and it's probably not enough for that # anyway (not thought through). # Ideally we'd remove cycles, not worry about transient refs in # change-trackers, make change-trackers robust to being told about # destroyed atoms, and that would be enough. Not yet sure whether # that's practical. [bruce 060327 comment] if self._glname: #bruce 080917 revised this entire statement (never tested, before or after) assy = self._f_assy ###k if assy: assy.dealloc_my_glselect_name( self, self._glname ) # otherwise no need, I think (since changing assy deallocates it too) del self._glname key = self.key for dict1 in _Atom_global_dicts: #e even this might be done by StateMixin if we declare these dicts #to it for the class (but we'd have to tell it what key we use in #them, e.g. provide a method or attr for that (like .key? no, #needs _s_ prefix to avoid accidental definition)) dict1.pop(key, None) # remove self, if it's there ###e we need to also tell the subscribers to those dicts that ###we're being destroyed, I think # is the following in a superclass (StateMixin) method?? ###k self.__dict__.clear() ###k is this safe??? ## self.bonds = self.jigs = self.molecule = \ ## self.atomtype = self.element = self.info = None # etc... return def unset_atomtype(self): #bruce 050707 """ Unset self.atomtype, so that it will be guessed when next used from the number of bonds at that time. """ try: del self.atomtype except: # assume already deleted pass return def atomtype_iff_set(self): return self.__dict__.get('atomtype', None) _inputs_for_atomtype = [] def _recompute_atomtype(self): # used automatically by __getattr__ """ Something needs this atom's atomtype but it doesn't yet have one. Give it our best guess of type, for whatever current bonds it has. """ return self.reguess_atomtype() def reguess_atomtype(self, elt = None): """ Compute and return the best guess for this atom's atomtype given its current element (or the passed one), and given its current real bonds and open bond user-assigned types (but don't save this, and don't compare it to the current self.atomtype). @warning: This is only correct for a new atom if it has already been given all its bonds (real or open). """ #bruce 050702 revised this; 050707 using it much less often # (only on special request ###doc what) ###@@@ Bug: This does not yet [050707] guess correctly for all bond #patterns; e.g. it probably never picks N/sp2(graphitic). That means #there is presently no way to save and reload that atomtype in an mmp #file, and only a "direct way" (specifying it as an atomtype, not #relying on inferring from bonds) would work unless this bug is fixed #here. ###@@@ (need to report this bug) if self.__killed: # bruce 071018 new bug check and new mitigation (return default atomtype) print_compact_stack( "bug: reguess_atomtype of killed atom %s (returning default): " % self) return self.element.atomtypes[0] if len(self.bonds) == 0:## and debug_flags.atom_debug: # [bruce 071018 check this always, to see if skipping killed atoms # in update_bonds_after_each_event has fixed this bug for good] # (I think the following cond (using self.element rather than elt) # is correct even when elt is passed -- bruce 050707) if self.element.atomtypes[0].numbonds != 0: # not a bug for noble gases! print_compact_stack( "warning: reguess_atomtype(%s) sees non-killed %s with no bonds -- probably a bug: " % \ (elt, self) ) return self.best_atomtype_for_numbonds(elt = elt) def set_atomtype_but_dont_revise_singlets(self, atomtype): ####@@@@ should merge with set_atomtype; perhaps use more widely """ #doc; atomtype is None means use default atomtype """ atomtype = self.element.find_atomtype( atomtype) # handles all forms of the request; exception if none matches assert atomtype.element is self.element # [redundant with find_atomtype] self.atomtype = atomtype self._changed_structure() #bruce 050627; note: as of 050707 this is always called during Atom.__init__ ###e need any more invals or updates for this method?? ###@@@ return def set_atomtype(self, atomtype, always_remake_bondpoints = False): """ [public method; not super-fast] Set this atom's atomtype as requested, and do all necessary invalidations or updates, including remaking our singlets as appropriate, and [###@@@ NIM] invalidating or updating bond valences. It's ok to pass None (warning: this sets default atomtype even if current one is different!), atomtype's name (specific to self.element) or fullname, or atomtype object. ###@@@ also match to fullname_for_msg()??? ###e The atomtype's element must match the current value of self.element -- we never change self.element (for that, see mvElement). Special case: if new atomtype would be same as existing one (and that is already set), do nothing (rather than killing and remaking singlets, or even correcting their positions), unless always_remake_bondpoints is true. [not sure if this will be used in atomtype-setting menu-cmds ###@@@] """ # Note: mvElement sets self.atomtype directly; if it called this # method, we'd have infrecur! atomtype = self.element.find_atomtype( atomtype) # handles all forms of the request; exception if none matches assert atomtype.element is self.element # [redundant with find_atomtype] #e or transmute if not?? if always_remake_bondpoints or (self.atomtype_iff_set() is not atomtype): self.direct_Transmute( atomtype.element, atomtype ) ###@@@ not all its needed invals/updates are implemented yet # note: self.atomtype = atomtype is done in direct_Transmute when it calls mvElement return def setAtomType(self, atomtype, always_remake_bondpoints = False): """ Same as self.set_atomtype(), provided for convenience. """ self.set_atomtype(atomtype, always_remake_bondpoints) def getAtomType(self): """ Returns the atomtype. @return: The atomtype. @rtype: L{AtomType} """ return self.atomtype def getAtomTypeName(self): """ Returns the name of this atom's atomtype. @return: The atomtype name. @rtype: str """ return self.atomtype.name def posn(self): """ Return the absolute position of this atom in space. [Public method; should be ok to call for any atom at any time.] """ #bruce 041104,041112 revised docstring #bruce 041130 made this return copies of its data, using unary '+', # to ensure caller's version does not change if the atom's version does, # or vice versa. Before this change, some new code to compare successive # posns of the same atom was getting a reference to the curpos[index] # array element, even though this was part of a longer array, so it # always got two refs to the same mutable data (which compared equal)! #bruce 060308 rewrote the following res = + self._posn try: #bruce 060208: try to protect callers against almost-overflowing values stored by buggy code # (see e.g. bugs 1445, 1459) res * 1000 except: # note: print_compact_traceback is not informative -- the call stack might be, tho it's long. print_compact_stack("bug: atom position overflow for %r; setting position to 0,0,0: " % self) ##e history message too? only if we can prevent lots of them from coming out at once. res = V(0,0,0) ##e is there any better choice of position for this purpose? # e.g. a small random one, so it's unique? self.setposn(res) # I hope this is safe here... we need the invals it does. return res def sim_posn(self): #bruce 060111 """ Return our posn, as the simulator should see it -- same as posn except for Singlets, which should pretend to be H and correct their distance from base atom accordingly. Should work even for killed atoms (e.g. singlets with no bonds). Note that if this is used on a corrected singlet position derived from a simulated H position (as in the 060111 approximate fix of bug 1297), it's only approximate, since the actual H position might not have been exactly its equilibrium position. """ if self.element is Singlet and len(self.bonds) == 1: oa = self.bonds[0].other(self) # like self.singlet_neighbor() but fewer asserts return self.ideal_posn_re_neighbor( oa, pretend_I_am = Hydrogen ) # see also self.writemmp() return self.posn() def baseposn(self): #bruce 041107; rewritten 041201 to help fix bug 204; optimized 050513 """ Like posn, but return the mol-relative position. Semi-private method -- should always be legal, but assumes you have some business knowing about the mol-relative coordinate system, which is somewhat private since it's semi-arbitrary and is changed by some recomputation methods. Before 041201 that could include this one, if it recomputed basepos! But as of that date we'll never compute basepos or atpos if they're invalid. """ #comment from 041201: #e Does this mean we no longer use basepos for drawing? Does that # matter (for speed)? We still use it for things like mol.rot(). # We could inline the old baseposn into mol.draw, for speed. # BTW would checking for basepos here be worth the cost of the check? (guess: yes.) ###e # For speed, I'll inline this here: return self.molecule.abs_to_base( self.posn()) #new code from 050513: mol = self.molecule basepos = mol.__dict__.get('basepos') #bruce 050513 if basepos is not None: ##[bruce 060308 zapped:]## and self.xyz == 'no': #bruce 050516 bugfix: fix sense of comparison to 'no' return basepos[self.index] # note: since mol.basepos exists, mol.atlist does, so # self.index is a valid index into both of them [bruce 060313 # comment] # fallback to slower code from 041201: return mol.quat.unrot(self.posn() - mol.basecenter) # this inlines mol.abs_to_base( self.posn() ) [bruce 060411 comment] def setposn(self, pos): """ set this atom's absolute position, adjusting or invalidating whatever is necessary as a result. (public method; ok for atoms in frozen molecules too) """ # fyi: called from depositMode, but not (yet?) from movie-playing. [041110] # [bruce 050406: now this is called from movie playing, at least for now. # It's also been called (for awhile) from reading xyz files from Minimize.] # bruce 041130 added unary '+' (see Atom.posn comment for the reason). #bruce 060308 rewrite #bruce 090112 removed setposn_batch alias, since no distinction for ages self._f_setposn_no_chunk_or_bond_invals(pos) mol = self.molecule if mol is not None: mol.changed_atom_posn() # also invalidate the bonds or jigs which depend on our position. # (review: should this be a separate method -- does anything else need # it?) note: the comment mentions jigs, but this code doesn't alert # them to the move. Bug?? [bruce 070518 question] for b in self.bonds: b.setup_invalidate() return # from setposn def _f_setposn_no_chunk_or_bond_invals(self, pos): #bruce 060308 (private for Chunk and Atom) self._posn = + pos _changed_posn_Atoms[self.key] = self #bruce 060322 if self.jigs: #bruce 050718 added this, for bonds code for jig in self.jigs[:]: jig.moved_atom(self) #e note: this does nothing for most kinds of jigs, so in #theory we might optim by splitting self.jigs into two lists; #however, there are other change methods for atoms in jigs #(maybe changed_structure?), so it's not clear how many #different lists are needed, so it's unlikely the complexity #is justified. return # from setposn_no_chunk_or_bond_invals def adjBaggage(self, atom, nupos): """ We're going to move atom, a neighbor of yours, to nupos, so adjust the positions of your singlets (and other baggage) to match. """ ###k could this be called for atom being itself a singlet, # when dragging a singlet? [bruce 050502 question] apo = self.posn() # find the delta quat for the average non-baggage bond and apply # it to the baggage #bruce 050406 comment: this first averages the bond vectors, # old and new, then rotates old to match new. This is not # correct, especially if old or new (average) is near V(0,0,0). # The real problem is harder -- find a quat which best moves # atom as desired without moving the other neighbors. # Fixing this might fix some reported bugs with dragging atoms # within their chunks in Build mode. Better yet might be to # use old singlet posns purely as hints, recomputing new ones # from scratch (hints are useful to disambiguate this). ###@@@ baggage, nonbaggage = self.baggage_and_other_neighbors() if atom in baggage: #bruce 060629 for safety (don't know if ever needed) # make sure atom counts as nonbaggage baggage.remove(atom) nonbaggage.append(atom) ## nonbaggage = self.realNeighbors() old = V(0,0,0) new = V(0,0,0) for atom_nb in nonbaggage: old += atom_nb.posn() - apo if atom_nb is atom: new += nupos-apo else: new += atom_nb.posn() - apo if nonbaggage: # slight safety tweaks to old code, though we're about to add new # code to second-guess it [bruce 060629] old = norm(old) #k not sure if these norms make any difference new = norm(new) if old and new: q = Q(old, new) for atom_b in baggage: ## was self.singNeighbors() atom_b.setposn(q.rot(atom_b.posn() - apo) + apo) # similar to code in drag_selected_atom, but not identical #bruce 060629 for bondpoint problem self.reposition_baggage(baggage, (atom, nupos)) return def __repr__(self): return self.element.symbol_for_printing + str(self.key) def __str__(self): return self.element.symbol_for_printing + str(self.key) _f_valid_neighbor_geom = False # privately, also used as valid_data tuple # this is reset to False by some Atom methods, and when any bond of self # is invalidated, which covers (I think) motion or element change of a # neighbor atom. _f_checks_neighbor_geom = False # kluge: set in _changed_structure based on element bond_geometry_error_string = "" def _f_invalidate_neighbor_geom(self): # bruce 080214 """ Cause self.bond_geometry_error_string to be recomputed when self.check_bond_geometry() is next called. [friend method for classes Atom & Bond] """ self._f_valid_neighbor_geom = False # too slow to also do this: ## self.molecule.changeapp(0) # # Note: in theory we should now do self.molecule.changeapp(0). # In practice this is too slow -- it would remake chunk display lists # whenever they were dragged (on every mouse motion), even if a lot of # chunks are being dragged together. # # Possible solutions: # # - short term mitigation: do a changeapp later, when something else calls # check_bond_geometry. This seems to happen at the end of the drag # or shortly after (not sure why). Note, this may be an illegal or lost # call of changeapp, since it can happen when drawing that same chunk. # ### REVIEW THIS... could we replace it with an incr of a counter in # the chunk, added to havelist data... or just put that inside changeapp # itself, so calls of changeapp at any time are permitted...??) # # - long term: when dragging selections rigidly, optimize by knowing # what needs recomputing due to "crossing the boundary" (between # selected and non-selected). # # - short term kluge: when drawing an external bond, have it overdraw the # error atoms with error indicators for this purpose. Since those bonds # are always drawn, let them be the only indicator of this error for # atoms that have any external bonds (otherwise we'd fail to turn off # error indicators soon enough when errors in a chunk were fixed by # dragging that chunk). For an interior atom, if a neighbor moves (other # than during rigid motion of their shared chunk), that will invalidate # its chunk's display list, ensuring it gets redrawn right away, # so no other inval is needed. AFAIK this is complete and correct. # # I'll do only the "short term kluge" solution, for now. [bruce 080214] return def check_bond_geometry(self, external = -1): # bruce 080214 # todo: probably should move this method within class """ Check the geometry of our bonds, and update self.bond_geometry_error_string with current data. Also return it for convenience, as modified by the <external> option. (For no error which should be displayed for that value of <external>, it's "".) Be fast if nothing relevant has changed. @param external: If -1 (default), return the new or changed value of self.bond_geometry_error_string. If False, only return that value if self._f_draw_bond_geometry_error_indicator_externally is False, otherwise return "". This returns the error indication to use when drawing this atom itself into a chunk display list. If True, only return that value if self._f_draw_bond_geometry_error_indicator_externally is True, otherwise return "". This returns the error indication to use when drawing external bonds connected to this atom (which are not drawn into a chunk display list). @return: new or unchanged value of self.bond_geometry_error_string, unless external is passed (see that param's doc for more info). """ ## # TODO: update this while dragging a chunk, for that chunk's ## # external bonds; right now it only updates when the drag is done. ## # (Not sure if that's due to a lack of inval or a lack of calling this. ## # Or more likely it's a LOGIC BUG -- this does changeapp, but that is needed ## # when this is invalled, if it would happen when we recompute! ## # In fact, it might be illegal to do it here (since we might be drawing ## # that very same chunk). current_data = (self.molecule._f_bond_inval_count,) # must never equal False if self._f_valid_neighbor_geom != current_data: # need to recompute/update self._f_valid_neighbor_geom = current_data try: error_string = self._recompute_bond_geometry_error_string() except: error_string = \ "exception in _recompute_bond_geometry_error_string" # only seen in case of bugs msg = "\n*** BUG: %s: " % error_string print_compact_stack(msg) if error_string != self.bond_geometry_error_string: # error string changed if (not error_string) != (not self.bond_geometry_error_string): # even its set- or cleared-ness changed ## self.molecule.changeapp(0) # in case of error color, etc # this might not be safe, and is not sufficient, # so don't do it at all. (For more info see comment in # _f_invalidate_neighbor_geom.) if debug_pref("report bond_geometry_error_string set or clear?", Choice_boolean_False, prefs_key = True ): print "fyi: check_bond_geometry(%r) set or cleared error string %r" % \ (self, error_string) self.bond_geometry_error_string = error_string pass if self.bond_geometry_error_string: # make sure drawing code knows whether to draw the error indicator # into the chunk display list or not (for explanation, see comment # in _f_invalidate_neighbor_geom) draw_externally = not not self.has_external_bonds() self._f_draw_bond_geometry_error_indicator_externally = draw_externally # this attr might never be used if external == -1 or external == draw_externally: return self.bond_geometry_error_string return "" _f_draw_bond_geometry_error_indicator_externally = True def has_external_bonds(self): # bruce 080214 # should refile within this class """ Does self have any external bonds? (i.e. bonds to atoms in different chunks) """ for bond in self.bonds: if bond.atom1.molecule is not bond.atom2.molecule: ## todo: def bond.is_external()? return True return False def _recompute_bond_geometry_error_string(self): # bruce 080214 # todo: should refactor, put some in AxisAtom section, or atomtype """ Recompute and return an error string about our bond geometry, which is "" if there is no error. """ if not self._f_checks_neighbor_geom: # optimize elements that don't do checks at all return "" if self.element.symbol in ('Ax3', 'Ax5', 'Ae3', 'Ae5'): # not correct for Gv5! # Prototype implem for just these elements. # (Ideally, the specific code for this would be in the atomtype.) if len(self.bonds) != self.atomtype.valence: # differs for Ax and Ae return "valence error" strand_neighbors = self.strand_neighbors() if not len(strand_neighbors) in (1, 2): # this is an error even if pref_permit_bare_axis_atoms() is true if not strand_neighbors: return "bare axis" else: return "more than 2 strand neighbors" if len(strand_neighbors) == 2: # check minor groove angle # REVIEW: when this error happens, can we or dna updater # propogate it throughout base pair? ss1, ss2 = strand_neighbors angle = atom_angle_radians( ss1, self, ss2 ) * 180/math.pi angle = intRound(angle) ## low, high = 130, 155 low = env.prefs[dnaMinMinorGrooveAngle_prefs_key] high = env.prefs[dnaMaxMinorGrooveAngle_prefs_key] ### TODO: make sure changing those invalidates enough # to recompute this, and redraw if needed. BUG until done. # Probably easiest to refactor: separate recomputing the angle # (inval code same as now) from testing it against limits # (done each time we draw it). The latter would be part of # drawing code, and would test all related prefs, and capture # their usage as for other drawing prefs. [bruce 080326] if not (low <= angle <= high): error = "minor groove angle %d degrees (should be %d-%d)" % \ (angle, low, high) return error return "" _BOND_GEOM_ERROR_RADIUS_MULTIPLIER = 1.5 # not sure this big is good # (or that a solid sphere is the best error indicator) def overdraw_bond_geometry_error_indicator(self, glpane, dispdef): #bruce 080214, revised 080406 """ ###doc """ assert self._f_draw_bond_geometry_error_indicator_externally # for now assert self.bond_geometry_error_string # make private?? disp = dispdef ### REVIEW -- is it ok if diDEFAULT is passed?? does that happen? pos = self.posn() # assume in abs coords pickedrad = 2 ### STUB, WRONG -- unless we want it to stay extra big; maybe we do... # (but, inconsistent with the value used for interior atoms # by another call of this method; but this kind of error is rare # on interior atoms, maybe nonexistent when dna updater is active) self.draw_error_wireframe_if_needed( glpane, disp, pos, pickedrad, external = True, prefs_key = dnaDisplayMinorGrooveErrorIndicators_prefs_key, color_prefs_key = dnaMinorGrooveErrorIndicatorColor_prefs_key ) return def get_glname(self, glpane): #bruce 080220 """ Return our OpenGL GLSELECT name, allocating it now (in self._f_set_assy, using glpane for its assy) if necessary. """ glname = self._glname # made this private, 080220 if not glname: # Note: testing for this here seems correct, and might even be more # principled than in Chunk.addatom (where I iniiially tried testing # for self._f_assy, an equivalent test for now, 080220), and is # surely more efficient, and is easier since addatom is inlined a # lot. BUT this place alone is not enough to guarantee self._f_assy # gets set for all atoms that have one. See comment about that in # self._f_set_assy(). [bruce 080220] assert self._f_assy is None if glpane.assy is not self.molecule.assy: print "\nbug?: glpane %r .assy %r is not %r.molecule %r .assy %r" % \ (glpane, glpane.assy, self, self.molecule, self.molecule.assy ) assy = glpane.assy # todo: in principle we'd prefer self.molecule.assy if it's always set; # but unless we add code to look for it carefully and fall back to # glpane.assy, that's less safe, so use this for now. This is the only # reason we need glpane as an argument, btw. The glname doesn't depend # on it and will never need to AFAIK. self._f_set_assy( assy) # this sets self._glname (and nothing else does) # note: it's not clearly better to set _f_assy than to just set _glname # directly here. This will change if more things use _f_assy, but then # other places to set it will also be needed. glname = self._glname assert glname ## print "fyi: set glname during draw of %r, assy = %r, glpane = %r" % \ ## (self, assy, glpane) pass return glname def draw(self, glpane, dispdef, col, level, special_drawing_handler = None, special_drawing_prefs = USE_CURRENT): """ Draw this atom (self), using an appearance which depends on whether it is picked (selected) and its display mode (possibly inherited from dispdef). An atom's display mode overrides the inherited one from the molecule or glpane, but a molecule's color (passed as col) overrides the atom's element-dependent color. Also draws picked-atom wireframe. @note: this method doesn't draw any bonds -- caller must draw bonds separately. (Unlike self.draw_in_abs_coords, which *does* draw self's bond when self is a bondpoint.) @return: the display mode we used (whether self's or inherited), or will use (if our drawing is handled by special_drawing_handler). @param col: the molecule color to use, or None to use per-atom colors. (Should not be a boolean-false color -- black is ok if passed as (0,0,0), but not if passed as V(0,0,0).) @note: This method no longer treats glpane.selatom specially (caller can draw selatom separately, on top of the regular atom). """ assert not self.__killed # figure out display style to use disp, drawrad = self.howdraw(dispdef) # review: future: should we always compute _draw_atom_style here, # just once, so we can avoid calling it multiple times inside # various methods we call? if special_drawing_handler and ( self._draw_atom_style(special_drawing_handler = special_drawing_handler) == 'special_drawing_handler' ): # defer all drawing of self to special_drawing_handler [bruce 080605] # REVIEW: it seems wrong that if self is a bondpoint, we're not # deferring its open bond here, even though that uses our glname # and gets drawn by self.draw_in_abs_coords. But disabling this 'if' # statement doesn't fix bug 2945 or cause any obvious bugs. # (Unless it causes the 5' arrowhead to sometimes not be drawn # even though its bond is drawn, as an update bug when entering # Join Strands -- I saw this once, but not sure if it's repeatable # or what the real cause is, and related update bugs seem common.) # [bruce 081211 comment] def func(special_drawing_prefs, args = (glpane, dispdef, col, level)): self.draw(*args, **dict(special_drawing_prefs = special_drawing_prefs)) special_drawing_handler.draw_by_calling_with_prefsvalues( SPECIAL_DRAWING_STRAND_END, func ) return disp # if we didn't defer, we shouldn't use special_drawing_handler at all del special_drawing_handler glname = self.get_glname(glpane) # note use of basepos (in atom.baseposn) since it's being drawn under # rotation/translation of molecule pos = self.baseposn() if disp == diTUBES: pickedrad = drawrad * 1.8 # this code snippet is now shared between draw and draw_in_abs_coords [bruce 060315] else: pickedrad = drawrad * 1.1 color = col or self.drawing_color() glPushName( glname) #bruce 050610 (for comments, see same code in Bond.draw) # (Note: these names won't be nested, since this method doesn't draw bonds; # if it did, they would be, and using the last name would be correct, # which is what's done (in GLPane.py) as of 050610.) ColorSorter.pushName(glname) try: if disp in (diTrueCPK, diBALL, diTUBES): self.draw_atom_sphere(color, pos, drawrad, level, dispdef, special_drawing_prefs = special_drawing_prefs ) self.draw_wirespheres(glpane, disp, pos, pickedrad, special_drawing_prefs = special_drawing_prefs ) except: ColorSorter.popName() glPopName() print_compact_traceback("ignoring exception when drawing atom %r: " % self) else: ColorSorter.popName() glPopName() return disp # from Atom.draw. [bruce 050513 added retval to help with an optim] def drawing_color(self, molcolor = None): #bruce 070417; revised, 080406 # BUG: most calls have the bug of letting molcolor override this. ###FIX """ Return the color in which to draw self, and certain things that touch self. This is molcolor or self.element.color by default (where molcolor is self.molecule.drawing_color() if not supplied). """ if molcolor is None: molcolor = self.molecule.drawing_color() color = molcolor if color is None: color = self.element.color ## # see if warning color is needed ## if self.check_bond_geometry(): #bruce 080214 (minor groove angle) ## ### REVIEW: should this be done for interior atoms? maybe only for some calls of this method?? ## color = orange ## elif self._dna_updater__error: #bruce 080130 ## color = orange return color # bruce 070409 split this out of draw_atom_sphere; # 070424 revised return value (None -> "") def _draw_atom_style(self, special_drawing_handler = None, special_drawing_prefs = None): """ [private helper method for L{draw_atom_sphere}, and perhaps related methods like L{draw_wirespheres}] Return a short hardcoded string (known to L{draw_atom_sphere}) saying in what style to draw the atom's sphere. @param special_drawing_handler: if not None, an object to which all drawing which is dependent on special_drawing_prefs needs to be deferred. In this method, this argument is used only for tests which let us tell the caller whether we need to defer to it. @param special_drawing_prefs: an object that knows how to find out how to draw strand ends. Never passed along with special_drawing_handler -- only passed if we're doing drawing which was *already* deferred do that. @return: Returns one of the following values: - "" (Not None) means to draw an actual sphere. - "special_drawing_handler" means to defer drawing to the special_drawing_handler. - "arrowhead-in" means to draw a 5' arrowhead. - "arrowhead-out" means to draw a 3' arrowhead. - "do not draw" means don't draw anything. - "bondpoint-stub" means to draw a stub. - 'five_prime_end_atom' means draw 5' end base atom in a special color if arrows are not drawn at 5' end - 'three_prime_end_atom' means draw 3' end base atom in a special color if arrows are not drawn at 3' end @note: We check not only the desirability of the special cases, but all their correctness conditions, making sure that those don't depend on the other parameters of L{draw_atom_sphere} (like abs_coords), and making it easier for L{draw_atom_sphere} to fallback to its default style when those conditions fail. """ # WARNING: various routines make use of this return value in different # ways, but these ways are not independent (e.g. one might draw a cone # and one might estimate its size), so changes in any of the uses need # to be reviewed for possibly needing changes in the others. [bruce # 070409] if self.element is Singlet and len(self.bonds) == 1: # self is a bondpoint if debug_pref("draw bondpoints as stubs", Choice_boolean_False, prefs_key = True): # current implem has cosmetic bugs (details commented there), # so don't say non_debug = True return 'bondpoint-stub' #k this might need to correspond with related code in Bond.draw if self.element.bonds_can_be_directional: #bruce 070415, correct end-arrowheads # note: as of mark 071014, this can happen for self being a Singlet # figure out whether to defer drawing to special_drawing_handler [bruce 080605] if self.isFivePrimeEndAtom() or \ self.isThreePrimeEndAtom() or \ self.strand_end_bond() is not None: if special_drawing_handler and \ special_drawing_handler.should_defer( SPECIAL_DRAWING_STRAND_END): # tell caller to defer drawing self to special_drawing_handler return 'special_drawing_handler' else: # draw using the values in special_drawing_prefs res = self._draw_atom_style_using_special_drawing_prefs( special_drawing_prefs ) if res: return res pass pass return "" # from _draw_atom_style def _draw_atom_style_using_special_drawing_prefs(self, special_drawing_prefs): """ [private helper for _draw_atom_style] """ #bruce 080605 split this out, revised it assert special_drawing_prefs, "need special_drawing_prefs" # note: for optimal redraw (by avoiding needless remakes of some # display lists), only access each of the values this can provide # when that value is actually needed to do the drawing. if self.isFivePrimeEndAtom() and not special_drawing_prefs[arrowsOnFivePrimeEnds_prefs_key]: # (this happens even if self.isThreePrimeEndAtom() is also true # (which may happen for a length-1 PAM3 strand); # I guess that's either ok or good [bruce 080605 comment]) return 'five_prime_end_atom' elif self.isThreePrimeEndAtom() and not special_drawing_prefs[arrowsOnThreePrimeEnds_prefs_key]: return 'three_prime_end_atom' bond = self.strand_end_bond() # never non-None if self has two bonds with directions set # (assuming no errors) -- i.e. for -Ss3-X, only non-None # for the X, never for the Ss3 # [bruce 080604 quick analysis, should re-review] if bond is not None: # Determine how singlets of strand open bonds should be drawn. # draw_bond_main() takes care of drawing bonds accordingly. # - mark 2007-10-20. if bond.isFivePrimeOpenBond() and special_drawing_prefs[arrowsOnFivePrimeEnds_prefs_key]: return 'arrowhead-in' elif bond.isThreePrimeOpenBond() and special_drawing_prefs[arrowsOnThreePrimeEnds_prefs_key]: return 'arrowhead-out' else: return 'do not draw' #e REVIEW: does Bond.draw need to be updated due to this, if "draw #bondpoints as stubs" is True? #e REVIEW: Do we want to draw even an isolated Pe (with bondpoint) #as a cone, in case it's in MMKit, since it usually looks like a #cone when it's correctly used? Current code won't do that. #e Maybe add option to draw the dir == 0 case too, to point out #you ought to propogate the direction pass return "" def draw_atom_sphere(self, color, pos, drawrad, level, dispdef, abs_coords = False, special_drawing_prefs = USE_CURRENT ): """ #doc @param dispdef: can be None if not known to caller @param special_drawing_handler: see _draw_atom_style for related doc @param special_drawing_prefs: see _draw_atom_style for doc @return: None """ #bruce 060630 split this out for sharing with draw_in_abs_coords style = self._draw_atom_style( special_drawing_prefs = special_drawing_prefs) if style == 'do not draw': if disable_do_not_draw_open_bonds(): ## or self._dna_updater__error: # (first cond is a debug_pref for debugging -- bruce 080122) ## # (the other cond [bruce 080130] should be a more general ## # structure error flag...) style = '' ## color = orange else: return ## if self.check_bond_geometry(external = False): #bruce 080214 (needed?) ## color = orange ## elif self._dna_updater__error: #bruce 080130; needed both here and in self.drawing_color() ## color = orange if style == 'bondpoint-stub': #bruce 060629/30 experiment -- works, incl for highlighting, # and even fixes the bondpoint-buried-in-big-atom bugs, # but sometimes the bond cyls project out beyond the bp cyls # after repositioning bondpoints, or for N(sp2(graphitic)), # and it looks bad for double bonds, # and sometimes the highlighting cylfaces mix with the # non-highlighted ones, as if same depth value. ###@@@ other = self.singlet_neighbor() if abs_coords: otherpos = other.posn() else: otherpos = other.baseposn() # note: this is only correct since self and other are # guaranteed to belong to the same chunk -- if they # didn't, their baseposns (pos and otherpos) would be in # different coordinate systems. rad = other.highlighting_radius(dispdef) # ok to pass None out = norm(pos - otherpos) buried = max(0, rad - vlen(pos - otherpos)) inpos = pos - 0.015 * out outpos = pos + (buried + 0.015) * out # be sure we're visible outside a big other atom drawcylinder(color, inpos, outpos, drawrad, 1) #e see related code in Bond.draw; drawrad is slightly more than the bond rad elif style.startswith('arrowhead-'): #arrowColor will be changed later arrowColor = color # two options, bruce 070415: # - arrowhead-in means pointing in along the strand_end_bond # - arrowhead-out means pointing outwards from the strand_end_bond if style == 'arrowhead-in': bond = self.strand_end_bond() other = bond.other(self) otherdir = 1 # Following implements custom arrowhead colors for the 3' and 5' end # (can be changed using Preferences > Dna page). Feature implemented # for Rattlesnake v1.0.1. bool_custom_arrowhead_color = special_drawing_prefs[ useCustomColorForFivePrimeArrowheads_prefs_key] if bool_custom_arrowhead_color and not abs_coords: arrowColor = special_drawing_prefs[ dnaStrandFivePrimeArrowheadsCustomColor_prefs_key] elif style == 'arrowhead-out': bond = self.strand_end_bond() other = bond.other(self) otherdir = -1 # Following implements custom arrowhead colors for the 3' and 5' end # (can be changed using Preferences > Dna page). Feature implemented # for Rattlesnake v1.0.1. bool_custom_arrowhead_color = special_drawing_prefs[ useCustomColorForThreePrimeArrowheads_prefs_key] if bool_custom_arrowhead_color and not abs_coords: arrowColor = special_drawing_prefs[ dnaStrandThreePrimeArrowheadsCustomColor_prefs_key] else: assert 0 if abs_coords: otherpos = other.posn() elif self.molecule is other.molecule: otherpos = other.baseposn() # this would be wrong if it's in a different chunk! else: otherpos = self.molecule.abs_to_base(other.posn()) ###BUG: this becomes wrong if the chunks move relative to ###each other! But we don't get updated then. ###FIX ## color = gray # to indicate the direction is suspicious and ## # might become invalid (for now) out = norm(otherpos - pos) * otherdir # Set the axis and arrow radius. if self.element is Singlet: assert Singlet.bonds_can_be_directional #bruce 071105 # mark 071014 (prior code was equivalent to else case) if dispdef == diTUBES: axis = out * drawrad * 1.5 arrowRadius = drawrad * 3 elif dispdef == diBALL: axis = out * drawrad * 1.9 arrowRadius = drawrad * 4.5 else: axis = out * drawrad * 2 arrowRadius = drawrad * 5.8 else: axis = out * drawrad arrowRadius = drawrad * 2 # the following cone dimensions enclose the original sphere (and # therefore the bond-cylinder end too) (when axis and arrowRadius # have their default values above -- not sure if this remains true # after [mark 071014]): cone base at pos - axis, radius = 2 * # drawrad, cone midplane (radius = drawrad) at pos + axis, thus # cone tip at pos + 3 * axis. # WARNING: this cone would obscure the wirespheres, except for # special cases in self.draw_wirespheres(). If you make the cone # bigger you might need to change that code too. ### TODO: a newer, better way to draw a cone is by passing a tuple # of two radii (one 0) to drawcylinder. This uses shaders when # available, and makes a polycone otherwise. [bruce 090225 comment] drawpolycone(arrowColor, [[pos[0] - 2 * axis[0], pos[1] - 2 * axis[1], pos[2] - 2 * axis[2]], [pos[0] - axis[0], pos[1] - axis[1], pos[2] - axis[2]], [pos[0] + 3 * axis[0], pos[1] + 3 * axis[1], pos[2] + 3 * axis[2]], [pos[0] + 5 * axis[0], pos[1] + 5 * axis[1], pos[2] + 5 * axis[2]]], # Point array (the two end # points not drawn) [arrowRadius, arrowRadius, 0, 0] # Radius array ) elif style == 'five_prime_end_atom': sphereColor = color bool_custom_color = special_drawing_prefs[ useCustomColorForFivePrimeArrowheads_prefs_key] if bool_custom_color and not abs_coords: sphereColor = special_drawing_prefs[ dnaStrandFivePrimeArrowheadsCustomColor_prefs_key] drawsphere(sphereColor, pos, drawrad, level) elif style == 'three_prime_end_atom': sphereColor = color bool_custom_color = special_drawing_prefs[ useCustomColorForThreePrimeArrowheads_prefs_key] if bool_custom_color and not abs_coords: sphereColor = special_drawing_prefs[ dnaStrandThreePrimeArrowheadsCustomColor_prefs_key] drawsphere(sphereColor, pos, drawrad, level) else: if style: print "bug (ignored): unknown _draw_atom_style return value for %r: %r" % (self, style,) if 0: #### experiment, unfinished [bruce 080917] verts = [b.center for b in self.bonds] if len(verts) == 4: drawtetrahedron(color, verts) # implem elif len(verts) == 3: drawtriangle(color, verts) # implem pass ### else: drawsphere(color, pos, drawrad, level) return # from draw_atom_sphere def draw_wirespheres(self, glpane, disp, pos, pickedrad, special_drawing_prefs = USE_CURRENT): #bruce 060315 split this out of self.draw so I can add it to draw_in_abs_coords if self._draw_atom_style(special_drawing_prefs = special_drawing_prefs).startswith('arrowhead-'): # compensate for the cone (drawn by draw_atom_sphere # in this case) being bigger than the sphere [bruce 070409] pickedrad *= debug_pref("Pe pickedrad ratio", Choice([1.8, 1.9, 1.7, 1.0])) #### if self.picked: # (do this even if disp == diINVISIBLE or diLINES [bruce comment 050825]) #bruce 041217 experiment: show valence errors for picked atoms by # using a different color for the wireframe. # (Since Transmute operates on picked atoms, and leaves them picked, # this will serve to show whatever valence errors it causes. And # showing it only for picked atoms makes it not mess up any images, # even though there's not yet any way to turn this feature off.) if self.bad(): color = ErrorPickedColor else: # russ 080530: Changed to pref from PickedColor constant (blue). color = env.prefs[selectionColor_prefs_key] drawwiresphere(color, pos, pickedrad) ##e worry about glname hit test if atom is invisible? [bruce 050825 comment] #bruce 050806: check valence more generally, and not only for picked atoms. self.draw_error_wireframe_if_needed(glpane, disp, pos, pickedrad, external = False, prefs_key = showValenceErrors_prefs_key ) return def draw_error_wireframe_if_needed(self, glpane, disp, pos, pickedrad, external = -1, prefs_key = None, color_prefs_key = None ): #bruce 080406 split this out, added options """ ###doc @param external: see docstring of self.check_bond_geometry """ if disp == diINVISIBLE: #bruce 050825 added this condition to fix bug 870 return # The calling code in draw_wirespheres only checks for number of bonds. # Now that we have higher-order bonds, we also need to check valence more generally. # The check for glpane class is a kluge to prevent this from showing in thumbviews: # should remove ASAP. ####@@@@ need to do this in atom.getinfo(). #e We might need to be able to turn this [what?] off by a preference setting; # or, only do it in Build mode. # Don't check prefs until we know we need them, to avoid needless # gl_update when user changes prefs value. if not glpane.should_draw_valence_errors(): return if not self.bad_valence(external = external): return if prefs_key is not None and not env.prefs[prefs_key]: return if color_prefs_key is not None: color = env.prefs[color_prefs_key] else: color = pink drawwiresphere(color, pos, pickedrad * 1.08) # experimental, but works well enough for A6. #e we might want to not draw this when self.bad() but draw that differently, # and optim this when atomtype is initial one (or its numbonds == valence). return def draw_overlap_indicator(self, prior_atoms_too_close = ()): # bruce 080411 """ Draw an indicator around self which indicates that it is too close to the atoms in the list prior_atoms_too_close (perhaps empty). In the initially implemented calling code, this will be called multiple times per atom -- on the average, about once for each other atom it's too close to, but possibly as much as twice per other close atom. More specifically: for each pair of too-close atoms, and for each ordering of that pair as a1, a2, this will be called exactly once on a1 with a2 an element of prior_atoms_too_close. If a1 was scanned first, it will receive a2 alone in that list; otherwise it might receive other atoms in that list in the same call. This means that if the distance tolerance should depend on the elements or bonding status (or any other property) of a pair of too-close atoms, this can be implemented in this method by only drawing the indicator around self if one of the atoms in the argument is in fact too close to self, considering that property of the pair of atoms. (This could be optimized, but only by using new code in the caller.) """ color = yellow # ?? pos = self.posn() pickedrad = self.drawing_radius(picked_radius = True) draw_at_these_radii = [] for other in prior_atoms_too_close: otherrad = other.drawing_radius(picked_radius = True) maxrad = max(otherrad, pickedrad) if maxrad not in draw_at_these_radii: draw_at_these_radii.append(maxrad) for maxrad in draw_at_these_radii: # this is to make it easier to see a small atom (e.g. a bondpoint) # buried inside another one. radius = maxrad * 1.12 drawwiresphere(color, pos, radius) return def max_pixel_radius(self): #bruce 070409 """ Return an estimate (upper bound) of the maximum distance from self's center to any pixel drawn for self. """ res = self.highlighting_radius() + 0.2 if self._draw_atom_style(special_drawing_prefs = USE_CURRENT).startswith('arrowhead-'): res *= 3 return res def bad(self): #bruce 041217 experiment; note: some of this is inlined into self.getinfo() """ is this atom breaking any rules? @note: this is used to change the color of the atom.picked wireframe @note: not all kinds of rules are covered. @see: _dna_updater__error (not covered by this; maybe it should be) """ if self.element is Singlet: # should be correct, but this case won't be used as of 041217 # [probably no longer needed even if used -- 050511] numbonds = 1 else: numbonds = self.atomtype.numbonds return numbonds != len(self.bonds) ##REVIEW: this doesn't check bond valence at all... should it?? def bad_valence(self, external = -1): #bruce 050806; should review uses (or inlinings) of self.bad() # to see if they need this too ##REVIEW #bruce 080406 added external option """ is this atom's valence clearly wrong, considering valences presently assigned to its bonds? @param external: see docstring of self.check_bond_geometry(). """ #WARNING: keep the code of self.bad_valence() and #self.bad_valence_explanation() in sync! e we might optimize this by #memoizing it (in a public attribute), and letting changes to any bond #invalidate it. # REVIEW: see comments in bad_valence_explanation # NOTE: to include check_bond_geometry, we might need an "external" arg to pass it bonds = self.bonds if self.element is Singlet: ok = (len(bonds) == 1) return not ok # any bond order is legal on an open bond, for now if self.atomtype.numbonds != len(bonds): ok = False return not ok minv, maxv = self.min_max_actual_valence() # min and max reasonable interpretations of actual valence, based on bond types want_valence = self.atomtype.valence ok = (minv <= want_valence <= maxv) if not ok: return True #bruce 080406 new feature: include dna updater errors in this indicator # (superseding the orange color-override, which has UI issues) if self._dna_updater__error: # note: doesn't cover duplex errors or bond geometry errors return True if self.check_bond_geometry(external = external): return True return False def bad_valence_explanation(self): #bruce 050806; revised 060703 ####@@@@ use more widely """ Return the reason self's valence is bad (as a short text string suitable for use as part of a statusbar string), or "" if it's not bad. [TODO: Some callers might want an even shorter string; if so, we'll add an option to ask for that, and perhaps implement it by stripping off " -- " and whatever follows that.] """ # WARNING: keep the code of self.bad_valence() and self.bad_valence_explanation() in sync! # note: this is used in statusbar, not tooltip (as of 080406) ### TODO: REVIEW and unify: all uses of this, .bad, .bad_valence, # dna updater error methods, # geometry errors (check_bond_geometry -- nontrivial re external bonds), # duplex errors, Atom methods getinfo, getInformationString bonds = self.bonds if self.element is Singlet: ok = (len(bonds) == 1) return (not ok) and "internal error: open bond with wrong number of bonds" or "" if self.atomtype.numbonds != len(bonds): ok = False return (not ok) and "wrong number of bonds" or "" minv, maxv = self.min_max_actual_valence() # min and max reasonable interpretations of actual valence, based on bond types want_valence = self.atomtype.valence ok = (minv <= want_valence <= maxv) if not ok: if len(self.element.atomtypes) > 1: ordiff = " or different atomtype" else: ordiff = "" if maxv < want_valence: return "valence too small -- need higher bond orders" + ordiff elif minv > want_valence: return "valence too large -- need lower bond orders" + ordiff else: return "internal error in valence-checking code" if self._dna_updater__error: #bruce 080406 # don't return self.dna_updater_error_string(), # it might be too long for statusbar # (also it's not reviewed for whether it contains # only legal characters for statusbar) return "PAM DNA error; see tooltip" bges = self.check_bond_geometry() # note: external option is not needed here, # in spite of being needed in self.bad_valence() if bges: return bges ### REVIEW: whether it has enough context, or is too long return "" def min_max_actual_valence(self): #bruce 051215 split this out of .bad and .bad_valence """ Return the pair (minv, maxv) of the min and max reasonable values for the sum of all bond orders for all of the bonds to self, based on bond types. Single, double, and triple bonds give exact floating point values, while aromatic and graphitic allow ranges. This allows complex resonance structures to be deemed ok even without an exact match. Note: these are actual float bond orders, NOT v6 values. """ minv = maxv = 0 for bond in self.bonds: minv1, maxv1 = min_max_valences_from_v6(bond.v6) minv += minv1 maxv += maxv1 return minv, maxv def deficient_valence(self): #bruce 051215 """ If this atom clearly wants more valence (based on existing bond types), return the minimum amount it needs (as an int or float valence number, NOT as a v6). Otherwise return 0. """ minv_junk, maxv = self.min_max_actual_valence() want_valence = self.atomtype.valence if maxv < want_valence: return want_valence - maxv return 0 def deficient_v6(self): #bruce 051215 return valence_to_v6(self.deficient_valence()) def mouseover_statusbar_message(self): msg = self.getInformationString() more = self.bad_valence_explanation() if more: msg += " (%s)" % more return msg def is_ghost(self): #bruce 080529 """ """ if self.ghost: return True # only set on Ss3 or Ss5 pseudoatoms elif self.element is Singlet and len(self.bonds) == 1: return self.bonds[0].other(self).is_ghost() elif self.element is Pl5: # we're a ghost if all Ss neighbors are ghosts for n in self.strand_neighbors(): if not n.ghost: return False continue return True return False def overdraw_with_special_color(self, color, level = None, factor = 1.0): """ Draw this atom slightly larger than usual with the given special color and optional drawlevel, in abs coords. @param factor: if provided, multiply our usual slightly larger radius by factor. """ #bruce 050324; meant for use in Fuse Chunks mode; # also could perhaps speed up Extrude's singlet-coloring #e if level is None: level = self.molecule.assy.drawLevel pos = self.posn() # note, unlike for draw_as_selatom, this is in main model coordinates drawrad = self.highlighting_radius() # slightly larger than normal drawing radius drawrad *= factor #bruce 080214 new feature ## drawsphere(color, pos, drawrad, level) # always draw, regardless of display mode self.draw_atom_sphere(color, pos, drawrad, level, None, abs_coords = True, special_drawing_prefs = USE_CURRENT ) #bruce 070409 bugfix (draw_atom_sphere); important if it's really a cone return def draw_in_abs_coords(self, glpane, color): """ Draw this atom in absolute (world) coordinates, using the specified color (ignoring the color it would naturally be drawn with). See code comments about radius and display mode (current behavior might not be correct or optimal). This is only called for special purposes related to mouseover-highlighting, and should be renamed to reflect that, since its behavior can and should be specialized for that use. (E.g. it doesn't happen inside display lists; and it need not use glName at all.) In this case (Atom), this method (unlike the main draw method) will also draw self's bond, provided self is a singlet with a bond which gets drawn, so that for an "open bond" it draws the entire thing (bond plus bondpoint). In order for this to work, the bond must (and does, in current code) borrow the glname of self whenever it draws itself (with any method). (This is only possible because bonds have at most one bondpoint.) """ #bruce 050610 # todo: needs to be told whether or not to "draw as selatom"; # for now it always does [i.e. it's misnamed] if self.__killed: return # I hope this is always ok... level = self.molecule.assy.drawLevel # this doesn't work if atom has been killed! pos = self.posn() ###@@@ remaining code might or might not be correct # (issues: larger radius, display-mode independence) drawrad = self.highlighting_radius() # slightly larger than normal drawing radius if self.bond_geometry_error_string: drawrad *= self._BOND_GEOM_ERROR_RADIUS_MULTIPLIER * 1.02 ## drawsphere(color, pos, drawrad, level) self.draw_atom_sphere(color, pos, drawrad, level, None, abs_coords = True) # always draw, regardless of display mode #bruce 050825 comment: it's probably incorrect to do this even for #invisible atoms. This probably caused the "highlighting part" of #bug 870, but bug 870 has been fixed by other changes today, but #this still might cause other bugs of highlighting #otherwise-invisible atoms. Needs review. ###@@@ # (Indirectly related: drawwiresphere acts like drawsphere for # hit-test purposes.) if len(self.bonds) == 1 and self.element is Singlet: #bruce 050708 new feature - bond is part of self for highlighting dispdef = self.molecule.get_dispdef() #bruce 050719 question: is it correct to ignore .display of self # and its base atom? ###@@@ #bruce 060630 guess answer: yes, since howdraw covers it. disp, drawradjunk = self.howdraw(dispdef) # (this arg is required) if disp in (diBALL, diTUBES): self.bonds[0].draw_in_abs_coords(glpane, color) #bruce 060315 try to fix disappearing hover highlight when mouse goes #over one of our wirespheres. We have to do it in the same coordinate #system as the original wirespheres were drawn. (This will only work #well if there is also a depth offset, or (maybe) an increased line #thickness. I think there's a depth offset in the calling code, and it #does seem to work. Note that it needs testing for rotated chunks, #since until you next modify them, the wirespheres are also drawn #rotated.) self.molecule.pushMatrix(glpane) try: # note: the following inlines self.drawing_radius(picked_Radius = True), # but makes further use of intermediate values which that method # computes but does not return, so merging them would require a # variant method that returned more values. [bruce 080411 comment] dispdef = self.molecule.get_dispdef() #e could optimize, since sometimes computed above -- but doesn't matter. disp, drawrad = self.howdraw(dispdef) if disp == diTUBES: pickedrad = drawrad * 1.8 # this code snippet is now shared between several places # [bruce 060315/080411] else: pickedrad = drawrad * 1.1 pos = self.baseposn() self.draw_wirespheres(glpane, disp, pos, pickedrad) except: print_compact_traceback("exception in draw_wirespheres " \ "part of draw_in_abs_coords ignored: ") pass self.molecule.popMatrix(glpane) return def drawing_radius(self, picked_radius = False): """ Return the current drawing radius of the atom. It determines it using the following order -- Returns drawing radius based on atom's current display. If the atom's display is 'default display'it then looks for the chunk's display. If even the chunk's display is default display, it returns the GLPane's current display. Note that these things are done in self.molecule.get_dispdef() and self.howdraw(). @param picked_radius: instead of the drawing radius, return the larger radius used by the selected-atom wireframe. (Note: not all effects on that radius are implemented yet.) @type: bool @see: DnaSegment_EditCommand._determine_resize_handle_radius() that uses this method to draw the resize handles. @see: self.howdraw() @see: Chunk.get_dispdef() """ # note: this is inlined into draw_in_abs_coords, and possibly elsewhere dispdef = self.molecule.get_dispdef() disp, drawrad = self.howdraw(dispdef) if picked_radius: #bruce 080411 added this option if disp == diTUBES: pickedrad = drawrad * 1.8 else: pickedrad = drawrad * 1.1 return pickedrad return drawrad def highlighting_radius(self, dispdef = None): """ @return: the radius to use for highlighting this atom (self), in the given display style (by default, in the style it would currently be drawn in). This is larger than self's drawing_radius. @note: this is not used for atoms that are part of highlighted chunks. """ # maybe todo: integrate this with draw_as_selatom if dispdef is None: dispdef = self.molecule.get_dispdef() disp, drawrad = self.howdraw(dispdef) if self.element is Singlet: drawrad *= 1.02 # increased radius might not be needed, if we would modify the # OpenGL depth threshhold criterion used by GL_DEPTH_TEST # to overwrite when depths are equal [bruce 041206] else: if disp == diTUBES: drawrad *= 1.7 else: drawrad *= 1.02 return drawrad def setDisplayStyle(self, disp): #bruce 080910 renamed from setDisplay """ set self's display style """ disp = remap_atom_dispdefs.get(disp, disp) #bruce 060607 # note: error message from rejecting disp, if any, # should be done somewhere else, not here # (since doing it per atom would be too verbose). if self.display == disp: # bruce 080305 optimization (also done in class Chunk). # This would be unsafe if any callers first set self.disp directly, # then called this method to bless that. I reviewed all calls and # think this change is safe. It might be important if it causes # some chunks to not changeapp, out of those touched by a large # selection of atoms. return self.revise_atom_content( ATOM_CONTENT_FOR_DISPLAY_STYLE[self.display], ATOM_CONTENT_FOR_DISPLAY_STYLE[disp] ) #bruce 080307; see also Chunk._ac_recompute_atom_content self.display = disp _changed_otherwise_Atoms[self.key] = self #bruce 060322 self.molecule.changeapp(1) self.changed() # bruce 041206 bugfix (unreported bug); revised, bruce 050509 # bruce 041109 comment: # Atom.setDisplayStyle changes appearance of this atom's bonds, # so: do we need to invalidate the bonds? No, they don't store display # info, and the geometry related to bond.setup_invalidate has not changed. # What about the chunks on both ends of the bonds? The changeapp() handles # that for internal bonds. Before 090213: external bonds are redrawn # every time so no invals are needed if their appearance changes. # After 090213 (roughly), we need to invalidate external bond appearance. self._changed_external_bond_appearance() #bruce 090213 return def revise_atom_content(self, old, new): #bruce 080306/080307 """ We're changing self's atom content from old to new. Invalidate or update self.molecule's knowledge of its atom content as needed. """ if not self.molecule: return # needed? if old & ~new: self.molecule.remove_some_atom_content(old & ~new) if new & ~old: self.molecule.add_some_atom_content(new & ~old) return def howdraw(self, dispdef): # warning: if you add env.prefs[] lookups to this routine, modify selradius_prefs_values! """ Tell how to draw the atom depending on its display mode (possibly inherited from dispdef, usually the molecule's effective dispdef). An atom's display mode overrides the inherited one from the molecule or glpane, but a molecule's color overrides the atom's element-dependent one (color is handled in Atom.draw, not here, so this is just FYI). Return display mode and radius to use, in a tuple (disp, rad). For display modes in which the atom is not drawn, such as diLINES or diINVISIBLE, we return the same radius as in diBALL; it's up to the caller to check the disp we return and decide whether/how to use this radius (e.g. it might be used for atom selection in diLINES mode, even though the atoms are not shown). """ if dispdef == diDEFAULT: #bruce 041129 permanent debug code, re bug 21 #bruce 050419 disable this since always happens for Element Color Prefs dialog: ## if debug_flags.atom_debug: ## print "bug warning: dispdef == diDEFAULT in Atom.howdraw for %r" % self dispdef = default_display_mode # silently work around that bug [bruce 041206] if self.element is Singlet: try: disp, rad_unused = self.bonds[0].other(self).howdraw(dispdef) except: # exceptions here (e.g. from bugs causing unbonded singlets) # cause too much trouble in other places to be permitted # (e.g. in selradius_squared and recomputing the array of them) # [bruce 041215] disp = default_display_mode else: if self.display == diDEFAULT: disp = dispdef else: disp = self.display # Compute "rad" if disp == diTUBES: rad = TubeRadius * 1.1 else: #bruce 060307 moved all this into else clause; this might prevent #some needless (and rare) gl_updates when all is shown in Tubes #but prefs for other dispmodes are changed. rad = self.element.rvdw # correct value for diTrueCPK (formerly, default); # modified to produce values for other dispmodes if disp == diTrueCPK: rad = rad * env.prefs[cpkScaleFactor_prefs_key] if disp != diTrueCPK: rad = rad * BALL_vs_CPK # all other dispmode radii are based on diBALL radius if disp == diBALL: rad = rad * env.prefs[diBALL_AtomRadius_prefs_key] return (disp, rad) def selradius_prefs_values(): # staticmethod in Atom #bruce 060317 for bug 1639 (and perhaps an analogue for other prefs) """ Return a tuple of all prefs values that are ever used in computing any atom's selection radius (by selradius_squared). """ return ( env.prefs[cpkScaleFactor_prefs_key] , env.prefs[diBALL_AtomRadius_prefs_key] ) # both used in howdraw selradius_prefs_values = staticmethod( selradius_prefs_values) def selradius_squared(self): # warning: if you add env.prefs[] lookups to this routine, modify selradius_prefs_values! """ Return square of desired "selection radius", or -1.0 if atom should not be selectable (e.g. invisible). This might depend on whether atom is selected (and that might even override the effect of invisibility); in fact this is the case for this initial implem. It also depends on the current display mode of self, its mol, and its glpane. Ignore self.molecule.hidden and whether self == selatom. Note: self.visible() should agree with self.selradius_squared() >= 0.0. """ #bruce 041207. Invals for this are subset of those for changeapp/havelist. disp, rad = self.howdraw( self.molecule.get_dispdef() ) if disp == diINVISIBLE and not self.picked: return -1.0 else: return rad ** 2 def visible(self, dispdef = None): #bruce 041214 """ Say whether this atom is currently visible, for purposes of selection. Note that this depends on self.picked, and display modes of self, its chunk, and its glpane, unless you pass disp (for speed) which is treated as the chunk's (defined or inherited) display mode. Ignore self.molecule.hidden and whether self == selatom. Return a correct value for singlets even though no callers [as of 041214] would care what we returned for them. Note: self.visible() should agree with self.selradius_squared() >= 0.0. """ if self.picked: return True # even for invisible atoms if self.element is Singlet and self.bonds: disp = self.bonds[0].other(self).display else: disp = self.display if disp == diDEFAULT: # usual case; use dispdef # (note that singlets are assumed to reside in same chunks as their # real neighbor atoms, so the same dispdef is valid for them) if dispdef is None: disp = self.molecule.get_dispdef() else: disp = dispdef return not (disp == diINVISIBLE) def is_hidden(self, glpane = None): #bruce 080521 """ Return whether self should be considered hidden by other things (like Jigs) whose drawing should depend on that. Take into account everything checked by self.visible(), but also (unlike it) self.molecule.hidden and (if glpane is passed) whether self == glpane.selobj. """ if self.picked: return False if glpane is not None and self is glpane.selobj: return False if self.molecule.hidden: return True return not self.visible() # == file input/output methods (ideally to be refactored out of this class) def writemmp(self, mapping, dont_write_bonds_for_these_atoms = ()): """ Write the mmp atom record for self, the bond records for whatever bonds have then had both atoms written (internal and external bonds are treated identically), and any bond_direction records needed for the bonds we wrote. Let mapping options influence what is written for any of those records. @param mapping: an instance of class writemmp_mapping. Can't be None. @param dont_write_bonds_for_these_atoms: a dictionary (only keys matter) or sequence of atom.keys; we will not write any bonds whose atoms' keys are both in that dictionary or sequence, nor any dnaBaseName for those atoms, nor (KLUGE) any rung bonds for those atoms. @note: compatible with Node.writemmp, though we're not a subclass of Node, except for additional optional args. @see: Fake_Pl.writemmp """ # WARNING: has common code with Fake_Pl.writemmp # figure out what to do if self is a bondpoint [revised, bruce 080603] policy = BONDPOINT_UNCHANGED # simplifies code for non-Singlet cases if self.element is Singlet: policy = bondpoint_policy(self, mapping.sim) if policy == BONDPOINT_LEFT_OUT: # note: this is probably correct for this code considered alone # (since it probably needs to not call encode_next_atom, and doesn't), # but some necessary consequences of leaving this atom out # are probably NIM. For more info see other comments in, # and/or around other calls of, bondpoint_policy. # # review: want summary message about number of bondpoints left out? # guess: no, at least not once it happens by default. return elif policy == BONDPOINT_UNCHANGED: pass # handled correctly by the code for general elements, below elif policy == BONDPOINT_REPLACED_WITH_HYDROGEN: pass # this is tested again below and handled separately else: # e.g. BONDPOINT_ANCHORED (can't yet happen) assert 0, "not yet implemented: bondpoint_policy of %r" % (policy,) pass num_str = mapping.encode_next_atom(self) # (note: pre-050322 code used an int here) disp = mapping.dispname(self.display) # note: affected by mapping.sim flag posn = self.posn() # might be revised below eltnum = self.element.eltnum # might be revised below if policy == BONDPOINT_REPLACED_WITH_HYDROGEN: # condition revised, bruce 080603 # special case for singlets in mmp files meant only for simulator: # pretend we're a Hydrogen, and revise posn and eltnum accordingly # (for writing only, not stored in our attrs) # [bruce 050404 to help fix bug 254] eltnum = Hydrogen.eltnum posn = self.ideal_posn_re_neighbor( self.singlet_neighbor(), pretend_I_am = Hydrogen ) # see also self.sim_posn() disp = "openbond" # kluge, meant as a comment in the file #bruce 051115 changed this from "singlet" to "openbond" #bruce 051209 for history message in runSim (re bug 254): stats = mapping.options.get('dict_for_stats') if stats is not None: # might be {} nsinglets_H = stats.setdefault('nsinglets_H', 0) nsinglets_H += 1 stats['nsinglets_H'] = nsinglets_H pass pass #bruce 080521 refactored the code for printing atom coordinates # (and fixed a rounding bug, described in encode_atom_coordinates) xs, ys, zs = mapping.encode_atom_coordinates( posn ) print_fields = (num_str, eltnum, xs, ys, zs, disp) mapping.write("atom %s (%d) (%s, %s, %s) %s\n" % print_fields) if self.key not in dont_write_bonds_for_these_atoms: # write dnaBaseName info record [mark 2007-08-16] # but not for atoms whose bonds will be written compactly, # since the dnaBaseName is too, for them [bruce 080328] dnaBaseName = self.getDnaBaseName() if dnaBaseName and dnaBaseName != 'X': #bruce 080319 optimization -- never write this when it's 'X', # since it's assumed to be 'X' when not present (for valid atoms). mapping.write( "info atom dnaBaseName = %s\n" % dnaBaseName ) if self.ghost: mapping.write( "info atom ghost = True\n" ) #bruce 080529 # Write dnaStrandName info record (only for Pe atoms). Mark 2007-09-04 # Note: maybe we should disable this *except* for Pe atoms # (hoping Mark's comment was right), so it stops happening for files # written with the dna updater active, as a step towards deprecating it. # Review soon. [bruce 080311 comment] #See self.getDnaStrandId_for_generators() for comments about this #attr. Basically, its used only while creating a new duplex from scratch #(while reading in the reference base mmp files in the plugins dir) dnaStrandId_for_generators = self.getDnaStrandId_for_generators() if dnaStrandId_for_generators: mapping.write( "info atom dnaStrandId_for_generators = %s\n" % dnaStrandId_for_generators ) #bruce 050511: also write atomtype if it's not the default atype = self.atomtype_iff_set() if atype is not None and atype is not self.element.atomtypes[0]: mapping.write( "info atom atomtype = %s\n" % atype.name ) # also write PAM3+5 data when present [bruce 080523] if self._PAM3plus5_Pl_Gv_data is not None: self._writemmp_PAM3plus5_Pl_Gv_data( mapping) # this writes "info atom +5data = ..." # write only the bonds which have now had both atoms written # (including internal and external bonds, not treated differently) #bruce 050502: write higher-valence bonds using their new mmp records, # one line per type of bond (only written if we need to write any bonds # of that type) bldict = {} # maps valence to list of 0 or more atom-encodings for # bonds of that valence we need to write ## bl = [] # (note: in pre-050322 code bl held ints, not strings) bonds_with_direction = [] for b in self.bonds: oa = b.other(self) if self.key in dont_write_bonds_for_these_atoms and ( oa.key in dont_write_bonds_for_these_atoms or b.is_rung_bond()): # Note: checking oa.key is fine, but b.is_rung_bond is a KLUGE: # we know all current subclasses that pass nonempty # dont_write_bonds_for_these_atoms also take care of writing # rung bonds themselves. This is not presently a bug, but needs # to be cleaned up, for clarity and before any other chunk # subclasses besides DnaLadderRailChunk make use of this feature. # [bruce 080328] continue #bruce 050322 revised this: oa_code = mapping.encode_atom(oa) # None, or true and prints as "atom number string" if oa_code: # we'll write this bond, since both atoms have been written valence = b.v6 bl = bldict.setdefault(valence, []) bl.append(oa_code) if b._direction: bonds_with_direction.append(b) bondrecords = bldict.items() bondrecords.sort() # by valence for valence, atomcodes in bondrecords: assert len(atomcodes) > 0 mapping.write( bonds_mmprecord( valence, atomcodes ) + "\n") for bond in bonds_with_direction: #bruce 070415 mapping.write( bond.mmprecord_bond_direction(self, mapping) + "\n") return # from writemmp def readmmp_info_atom_setitem( self, key, val, interp ): """ Reads an atom info record from the MMP file. @see: The docstring of an analogous method, such as L{Node.readmmp_info_leaf_setitem()}. """ if key == ['atomtype']: #bruce 050511 # val should be the name of one of self.element's atomtypes # (not an error if unrecognized) try: atype = self.element.find_atomtype(val) except: # didn't find it. # (todo: find_atomtype ought to have a different API, so a # real error could be distinguished from not finding val.) if debug_flags.atom_debug: print "atom_debug: fyi: " \ "info atom atomtype (in class Atom) with " \ "unrecognized atomtype %r (not an error)" % (val,) pass else: self.set_atomtype_but_dont_revise_singlets( atype) # don't add bondpoints (aka singlets), since this # mmp record comes before the bonds, including bonds # to bondpoints elif key == ['dnaBaseName']: # Mark 2007-08-16 try: self.setDnaBaseName(val) except Exception, e: #bruce 080304 revised printed error, added history summary print "Error in mmp record, info atom dnaBaseName: %s" \ " (continuing)" % (e,) msg = "Error: illegal DNA base name on [N] atom(s) " \ "(see console prints for details)" summary_format = redmsg( msg ) env.history.deferred_summary_message(summary_format) pass elif key == ['ghost']: #bruce 080529 if val == "True": self.ghost = True elif key == ['dnaStrandId_for_generators']: # Mark 2007-09-04 try: #@see: self.getDnaStrandId_for_generators() for comments #about this attr self.setDnaStrandId_for_generators(val) except Exception, e: #bruce 080304 revised printed error, added history summary print "Error in mmp record, info atom dnaStrandId_for_generators: %s" \ " (continuing)" % (e,) msg = "Error: illegal DNA strand id (used by dna generator) on [N] atom(s) " \ "(see console prints for details)" summary_format = redmsg( msg ) env.history.deferred_summary_message(summary_format) pass elif key == ['+5data']: #bruce 080523 try: self._readmmp_3plus5_data(key, val, interp) except: msg = "error in reading info atom +5data = %s\n" % (val,) + \ "for %r (ignored)" % self if debug_flags.atom_debug: print_compact_traceback( msg + ": ") else: print msg pass else: if debug_flags.atom_debug: print "atom_debug: fyi: info atom (in class Atom) with "\ "unrecognized key %r (not an error)" % (key,) return def writepov(self, file, dispdef, col): """ write to a povray file: draw a single atom """ color = col or self.drawing_color() disp, rad = self.howdraw(dispdef) if disp in [diTrueCPK, diBALL]: file.write("atom(" + povpoint(self.posn()) + "," + str(rad) + "," + Vector3ToString(color) + ")\n") if disp == diTUBES: ###e this should be merged with other case, and should probably # just use rad from howdraw [bruce 041206 comment] file.write("atom(" + povpoint(self.posn()) + "," + str(rad) + "," + Vector3ToString(color) + ")\n") return def writepdb(self, file, atomSerialNumber, chainId): # REFACTORING DESIRED: most of this ought to be split out # into a helper function or wrapper class in files_pdb.py. # (And similarly with writepov, writemdl, writemmp, etc.) # [bruce 080122 comment] """ Write a PDB ATOM record for this atom into I{file}. @param file: The PDB file to write the ATOM record to. @type file: file @param atomSerialNumber: A unique number for this atom. @type atomSerialNumber: int @param chainId: The chain id. It is a single character. See the PDB documentation for the ATOM record more information. @type chainId: str @note: If you edit the ATOM record, be sure to to test QuteMolX. @see: U{B{ATOM Record Format}<http://www.wwpdb.org/documentation/format23/sect9.html#ATOM>} """ space = " " # Begin ATOM record ---------------------------------- # Column 1-6: "ATOM " (str) atomRecord = "ATOM " # Column 7-11: Atom serial number (int) atomRecord += "%5d" % atomSerialNumber # Column 12: Whitespace (str) atomRecord += "%1s" % space # Column 13-16 Atom name (str) # piotr 080711 : Changed atom name alignment to start from column 14. # This should make our files more compatible with software that # is very strict about PDB format compliance. atomRecord += " %-3s" % self.element.symbol # Column 17: Alternate location indicator (str) *unused* atomRecord += "%1s" % space # Column 18-20: Residue name - unused (str) atomRecord += "%3s" % space # Column 21: Whitespace (str) atomRecord += "%1s" % space # Column 22: Chain identifier - single letter (str) # This has been tested with 35 chunks and still works in QuteMolX. atomRecord += "%1s" % chainId.upper() # Column 23-26: Residue sequence number (int) *unused*. # piotr 080711: Use "1" as a residue number, as certain programs # may have difficulties readin the file if this field is empty. atomRecord += "%4d" % int(1) # Column 27: Code for insertion of residues (AChar) *unused* atomRecord += "%1s" % space # Column 28-30: Whitespace (str) atomRecord += "%3s" % space # Get atom XYZ coordinate _xyz = self.posn() # Column 31-38: X coord in Angstroms (float 8.3) atomRecord += "%8.3f" % float(_xyz[0]) # Column 39-46: Y coord in Angstroms (float 8.3) atomRecord += "%8.3f" % float(_xyz[1]) # Column 47-54: Z coord in Angstroms (float 8.3) atomRecord += "%8.3f" % float(_xyz[2]) # Column 55-60: Occupancy (float 6.2) *unused* atomRecord += "%6s" % space # Column 61-66: Temperature factor. (float 6.2) *unused* atomRecord += "%6s" % space # Column 67-76: Whitespace (str) atomRecord += "%10s" % space # Column 77-78: Element symbol, right-justified (str) *unused* # piotr 080711: Output the element symbol here, as well (but # truncate it to two characters). atomRecord += "%2s" % self.element.symbol[:2].upper() # Column 79-80: Charge on the atom (str) *unused* atomRecord += "%2s\n" % space # End ATOM record ---------------------------------- file.write(atomRecord) return def writemdl(self, alist, f, dispdef, col): """ write to a MDL file """ # By Chris Phoenix and Mark for John Burch [04-12-03] color = col or self.drawing_color() disp, radius = self.howdraw(dispdef) xyz = map(float, A(self.posn())) rgb = map(int,A(color)*255) atnum = len(alist) # current atom number alist.append([xyz, radius, rgb]) # Write spline info for this atom atomOffset = 80*atnum (x,y,z) = xyz for spline in range(5): f.write("CPs=8\n") for point in range(8): index = point+spline*8 (px,py,pz)=marks[index] px = px*radius + x; py = py*radius + y; pz = pz*radius + z if point == 7: flag = "3825467397" else: flag = "3825467393" f.write("%s 0 %d\n%f %f %f\n%s%s"% (flag, index+19+atomOffset, px, py, pz, filler, filler)) for spline in range(8): f.write("CPs=5\n") for point in range(5): index = point+spline*5 f.write("3825467393 1 %d\n%d\n%s%s"% (index+59+atomOffset, links[index]+atomOffset, filler, filler)) return # == def getinfo(self): # [mark 2004-10-14] """ Return information about the selected atom for the msgbar """ # bruce 041217 revised XYZ format to %.2f, added bad-valence info # (for the same atoms as self.bad(), but in case conditions are added to # that, using independent code). # bruce 050218 changing XYZ format to %.3f (after earlier discussion with Josh). if self is self.molecule.assy.ppa2: return xyz = self.posn() atype_string = "" if len(self.element.atomtypes) > 1: #bruce 050511 atype_string = "(%s) " % self.atomtype.name ainfo = ("Atom %s %s[%s] [X = %.3f] [Y = %.3f] [Z = %.3f]" % \ ( self, atype_string, self.element.name, xyz[0], xyz[1], xyz[2] )) # ppa2 is the previously picked atom. ppa3 is the atom picked before ppa2. # They are both reset to None when entering SELATOMS mode. # Include the distance between self and ppa2 in the info string. if self.molecule.assy.ppa2: try: ainfo += (". Distance between %s-%s is %.3f Angstroms." % \ (self, self.molecule.assy.ppa2, vlen(self.posn() - self.molecule.assy.ppa2.posn()))) # fix bug 366-2 ninad060721 except: print_compact_traceback("bug, fyi: ignoring exception " \ "in atom distance computation: ") #bruce 050218 pass # Include the angle between self, ppa2 and ppa3 in the info string. if self.molecule.assy.ppa3: try: # bruce 050218 protecting angle computation from exceptions # (to reduce severity of undiagnosed bug 361). #bruce 050906 splitting angle computation into separate function. ###e its inaccuracy for angles near 0 and 180 degrees should be fixed! ang = atom_angle_radians( self, self.molecule.assy.ppa2, self.molecule.assy.ppa3 ) * 180/math.pi ainfo += (" Angle for %s-%s-%s is %.2f degrees." %\ (self, self.molecule.assy.ppa2, self.molecule.assy.ppa3, ang)) except: print_compact_traceback("bug, fyi: ignoring exception in atom angle computation: ") #bruce 050218 pass # ppa3 is ppa2 for next atom picked. self.molecule.assy.ppa3 = self.molecule.assy.ppa2 # ppa2 is self for next atom picked. self.molecule.assy.ppa2 = self if len(self.bonds) != self.atomtype.numbonds: # I hope this can't be called for singlets! [bruce 041217] ainfo += fix_plurals(" (has %d bond(s), should have %d)" % \ (len(self.bonds), self.atomtype.numbonds)) elif self.bad_valence(): #bruce 050806 msg = self.bad_valence_explanation() ainfo += " (%s)" % msg return ainfo def getInformationString(self, mention_ghost = True): """ If a standard atom, return a string like C26(sp2) with atom name and atom hybridization type, but only include the type if more than one is possible for the atom's element and the atom's type is not the default type for that element. If a PAM Ss (strand sugar) atom, returns a string like Ss28(A) with atom name and dna base letter. """ res = str(self) if self.atomtype is not self.element.atomtypes[0]: res += "(%s)" % self.atomtype.name if self.getDnaBaseName(): res += "(%s)" % self.getDnaBaseName() if mention_ghost and self.is_ghost(): res += " (placeholder base)" return res def getToolTipInfo(self, isAtomPosition, isAtomChunkInfo, isAtomMass, atomDistPrecision): """ Returns this atom's basic info string for the dynamic tooltip """ atom = self atomStr = atom.getInformationString( mention_ghost = False) elementNameStr = " [" + atom.element.name + "]" atomInfoStr = atomStr + elementNameStr #Display tooltip info if its a PAM atom. (implemented for Ss atoms only) strand = atom.getDnaStrand() segment = atom.getDnaSegment() if strand: atomInfoStr += "<br>" + strand.getDefaultToolTipInfo() elif segment: atomInfoStr += "<br>" + segment.getDefaultToolTipInfo() if atom.display: # show display style of atoms that have one [bruce 080206] atomInfoStr += "<br>" + "display style: %s" % atom.atom_dispLabel() if atom.is_ghost(): atomInfoStr += "<br>" + "(placeholder base)" # report dna updater errors in atom or its DnaLadder msg = atom.dna_updater_error_string(newline = '<br>') if msg: atomInfoStr += "<br>" + orangemsg(msg) if debug_pref("DNA: show wholechain baseindices in atom tooltips?", Choice_boolean_False, prefs_key = True ): #bruce 080421 (not in rc2) try: wholechain = atom.molecule.wholechain # only works for some atoms; might be None except AttributeError: wholechain = None if wholechain: # also check whether it's valid?? try: baseatom = atom if baseatom.element is Singlet: baseatom = baseatom.singlet_neighbor() #bruce 080603 bugfix if baseatom.element is Pl5: baseatom = baseatom.Pl_preferred_Ss_neighbor() #bruce 080603 bugfix rail = atom.molecule.get_ladder_rail() whichrailjunk, baseindex = atom.molecule.ladder.whichrail_and_index_of_baseatom(baseatom) bi_min, bi_max = wholechain.wholechain_baseindex_range() bi_rail0, bi_rail1 = wholechain.wholechain_baseindex_range_for_rail(rail) bi_baseatom = wholechain.wholechain_baseindex(rail, baseindex) msg = "wholechain baseindices: (%d, %d), (%d, %d), %d" % \ (bi_min, bi_max, bi_rail0, bi_rail1, bi_baseatom) atomInfoStr += "<br>" + greenmsg(msg) except: print_compact_traceback("exception in show wholechain baseindices: ") pass pass pass if isAtomPosition: xyz = atom.posn() xPosn = str(round(xyz[0], atomDistPrecision)) yPosn = str(round(xyz[1], atomDistPrecision)) zPosn = str(round(xyz[2], atomDistPrecision)) atomposn = ("<font color=\"#0000FF\">X:</font> %s<br><font color=\"#0000FF\">Y:</font> %s<br>"\ "<font color=\"#0000FF\">Z:</font> %s" %(xPosn, yPosn, zPosn)) atomInfoStr += "<br>" + atomposn if isAtomChunkInfo: if atom is not None: atomChunkInfo = "<font color=\"#0000FF\">Parent Chunk:</font> [" + atom.molecule.name + "]" atomInfoStr += "<br>" + atomChunkInfo if isAtomMass: atomMass = "<font color=\"#0000FF\">Mass: </font>" + str(atom.element.mass) + " x 10-27 Kg" atomInfoStr += "<br>" + atomMass #if isRVdw: # rVdw = "<font color=\"#0000FF\">Vdw:Radius: </font>" + str(atom.element.rvdw) + "A" return atomInfoStr def atom_dispLabel(self): #bruce 080206 """ Return the full name of self's individual (single-atom) display style, corresponding to self.display (a small int which encodes it). (If self.display is not recognized, just return str(self.display).) Normally self.display is 0 (diDEFAULT) and this method returns "Default" (which means a display style from self's context will be used when self is drawn). """ self.display # make sure this is set try: return dispLabel[self.display] # usually "Default" for self.display == diDEFAULT == 0 except IndexError: return str(self.display) pass # == def checkpick(self, p1, v1, disp, r = None, iPic = None): """ Selection function for atoms: [Deprecated! bruce 041214] Check if the line through point p1 in direction v1 goes through the atom (treated as a sphere with the same radius it would be drawn with, which might depend on disp, or with the passed-in radius r if that's supplied). If not, or if the atom is a singlet, or if not iPic and the atom is already picked, return None. If so, return the distance along the ray (from p1 towards v1) of the point closest to the atom center (which might be 0.0, which is false!), or None if that distance is < 0. """ #bruce 041206 revised docstring to match code #bruce 041207 comment: the only call of checkpick is from assy.findpick if self.element is Singlet: return None if not r: disp, r = self.howdraw(disp) # bruce 041214: # following is surely bad in only remaining use (depositMode.getCoords): ## if self.picked and not iPic: return None dist, wid = orthodist(p1, v1, self.posn()) if wid > r: return None if dist<0: return None return dist # == def pick(self): """ make this atom selected """ if self.element is Singlet: return if self.filtered(): return # mark 060303. # [note: bruce 060321 has always thought it was nonmodular to # check this here] #bruce 060331 comment: we can't move this inside the conditional #to optimize it, since we want it to affect whether we set #picked_time, but we want to set that even for already-picked #atoms. (Which are reasons of dubious value if this missed optim #is important (don't know if it is), but are real ones.) self._picked_time = self.molecule.assy._select_cmd_counter #bruce 051031, for ordering selected atoms; two related attrs if not self.picked: self.picked = True _changed_picked_Atoms[self.key] = self #bruce 060321 for Undo (or future general uses) self._picked_time_2 = self.molecule.assy._select_cmd_counter #bruce 051031 self.molecule.assy.selatoms[self.key] = self #bruce comment 050308: should be ok even if selatoms recomputed for assy.part self.molecule.changeapp(1) #bruce 060321 comment: this needs its arg of 1, since self.selradius_squared() # can be affected (if self is invisible). Further review might determine this is # not required (if it's impossible to ever pick invisible atoms), or we might # optim to see if this actually *does* change selradius_squared. Not sure if # that potential optim is ever significant. # bruce 041227 moved message from here to one caller, pick_at_event #bruce 050308 comment: we also need to ensure that it's ok to pick atoms # (wrt selwhat), and change current selection group to include self.molecule # if it doesn't already. But in practice, all callers might be ensuring these # conditions already (this is likely to be true if pre-assy/part code was correct). # In particular, atoms are only picked by user in glpane or perhaps by operations # on current part, and in both cases the picked atom would be in the current part. # If atoms can someday be picked from the mtree (directly or by selecting a jig that # connects to them), this will need review. self.molecule.changed_selection() #bruce 060227 return _picked_time = _picked_time_2 = -1 def pick_order(self): #bruce 051031 """ Return something which can be sorted to determine the order in which atoms were selected; include tiebreakers. Legal to call even if self has never been selected or is not currently selected, though results will not be very useful then. """ return (self._picked_time, self._picked_time_2, self.key) def unpick(self, filtered = True): """ Make this atom (self) unselected, if the selection filter permits this or if filtered = False. """ #bruce 060331 adding filtered = False option, as part of fixing bug 1796 # note: this is inlined (perhaps with filtered = False, not sure) # into assembly.unpickatoms (in ops_select.py) # bruce 041214: singlets should never be picked, so Singlet test is not needed, # and besides if a singlet ever *does* get picked (due to a bug) you should let # the user unpick it! ## if self.element is Singlet: return if self.picked: if filtered and self.filtered(): return # mark 060303. # [note: bruce 060321 has always thought it was nonmodular to check this here] # [and as of sometime before 060331 it turns out to cause bug 1796] #bruce 060331 moved this inside 'if picked', as a speed optimization try: #bruce 050309 catch exceptions, and do this before picked = 0 # so that if selatoms is recomputed now, the del will still work # (required by upcoming "assy/part split") del self.molecule.assy.selatoms[self.key] except: if debug_flags.atom_debug: print_compact_traceback("atom_debug: Atom.unpick finds atom not in selatoms: ") self.picked = False _changed_picked_Atoms[self.key] = self #bruce 060321 for Undo (or future general uses) # note: no need to change self._picked_time -- that would have no effect unless # we later forget to set it when atom is picked, and if that can happen, # it's probably better to use a prior valid value than -1. [bruce 051031] self.molecule.changeapp(1) #bruce 060321 comment: this needs its arg of 1; see comment in self.pick(). self.molecule.changed_selection() #bruce 060227 return def copy(self): #bruce 041116, revised bruce 080319 to not copy default-valued attrs """ Public method: copy the atom self, with no special assumptions, and return the copy (a new atom); new atom is not initially in any chunk, but could be added to one using Chunk.addatom. """ nuat = Atom(self, self.posn(), None) #bruce 050524: pass self so its atomtype is copied # optimization: assume the class defaults for the following copied # attrs are all boolean false [verified by test], and the legal # nondefault values are all boolean true (believed) -- this optimizes # the following tests for whether they need to be set in nuat # [bruce 080319] if self.display: nuat.display = self.display if self.info: nuat.info = self.info #bruce 041109; revised 050524; # needed by extrude and other future things if self._dnaBaseName: nuat._dnaBaseName = self._dnaBaseName #bruce 080319 if self.ghost: # (note: can be set on PAM strand baseatoms, # but not on Pl atoms or bondpoints) nuat.ghost = self.ghost #bruce 080529 # Note: the following attributes are used only by methods in our # mixin superclass, PAM_Atom_methods, except for a few foundational # methods in this class. If we introduce per-element subclasses of # this class, these would only need to be copied in the subclass # corresponding to PAM_Atom_methods. [bruce 080523] if not self._f_Pl_posn_is_definitive: print "bug? copying %r in which ._f_Pl_posn_is_definitive is not set" % self if self._PAM3plus5_Pl_Gv_data is not None: nuat._PAM3plus5_Pl_Gv_data = copy_val(self._PAM3plus5_Pl_Gv_data) if (self.overlayText): nuat.overlayText = self.overlayText # no need in new atoms for anything like # _changed_otherwise_Atoms[nuat.key] = nuat # [bruce 060322 guess ###@@@ #k] return nuat def set_info(self, newinfo): #bruce 060322 self.info = newinfo _changed_structure_Atoms[self.key] = self return def break_unmade_bond(self, origbond, origatom): #bruce 050524 """ Add singlets (or do equivalent invals) as if origbond was copied from origatom onto self (a copy of origatom), then broken; uses origatom so it can find the other atom and know bond direction in space (it assumes self might be translated but not rotated, wrt origatom). For now this works like mol.copy used to, but later it might "inval singlets" instead. """ # compare to code in Bond.unbond() (maybe merge it? ####@@@@ need to # inval things to redo singlets sometimes?) a = origatom b = origbond numol = self.molecule x = Atom('X', b.ubp(a), numol) ###k verify Atom.__init__ makes copy of posn, not stores original ###(tho orig ok if never mods it) na = self ## na = ndix[a.key] bond_copied_atoms(na, x, origbond, origatom) # same properties as origbond... sensible in all cases?? ##k return def unbond(self, b, make_bondpoint = True): """ Private method (for use mainly by bonds); remove bond b from self and usually replace it with a singlet (which is returned). Details: Remove bond b from self (error if b not in self.bonds). Note that bonds are compared with __eq__, not 'is', by 'in' and 'remove'. Only call this when b will be destroyed, or "recycled" (by bond.rebond); thus no need to invalidate the bond b itself -- caller must do whatever inval of bond b is needed (which is nothing, if it will be destroyed). Then replace bond b in self.bonds with a new bond to a new singlet, unless self or the old neighbor atom is a singlet, or unless make_bondpoint is false. Return the new singlet, or None if one was not created. Do all necessary invalidations, including self._changed_structure(), EXCEPT: - of Chunk._f_lost_externs flags (since some callers don't need this even when self is an external bond); - of b. If self is a singlet, kill it (singlets must always have one bond). @note: As of 041109 (still true 080701), this is called only from Atom.kill of the other atom, and from bond.bust, and from bond.rebond. @note: As of 050727, newly created open bonds have same bond type as the removed bond. """ self._changed_structure() b.invalidate_bonded_mols() #e would be more efficient if callers did this try: self.bonds.remove(b) # note: _changed_structure is done just above except ValueError: # list.remove(x): x not in list # this is always a bug in the caller, but we catch it here to # prevent turning it into a worse bug [bruce 041028] msg = "fyi: Atom.unbond: bond %r should be in bonds %r\n of atom %r, " \ "but is not:\n " % (b, self.bonds, self) print_compact_traceback(msg) # normally replace an atom (bonded to self) with a singlet, # but don't replace a singlet (at2) with a singlet, # and don't add a singlet to another singlet (self). if self.element is Singlet: if not self.bonds: self.kill() # bruce 041115 added this and revised all callers else: # don't kill it, in this case [bruce 041115; I don't know if this ever happens] from dna.updater.dna_updater_globals import get_dnaladder_inval_policy from dna.updater.dna_updater_globals import DNALADDER_INVAL_IS_NOOP_BUT_OK # can't be a toplevel import for now [review: still true? might be...] if get_dnaladder_inval_policy() == DNALADDER_INVAL_IS_NOOP_BUT_OK: pass # this now happens routinely during PAM conversion [bruce 080413] else: # I don't recall ever seeing this otherwise, but it's good # to keep checking for it [bruce 080413] print "fyi: bug: unbond on a singlet %r finds unexpected " \ " bonds left over in it, %r" % (self, self.bonds) return None if not make_bondpoint: #bruce 070601 new feature # WARNING [mild; updated 070602]: I'm not 100% sure this does sufficient invals. # I added it for Make Crossover and wondered if it caused the Undo bug # triggered by that, but that bug turned out to have a different cause, # and this option is still used in that command without triggering that bug. # So it can be presumed safe for now. return None at2 = b.other(self) if at2.element is Singlet: return None if at2.element.role == 'handle': #bruce 080516 kluge # (Ultimately we'd want bond.bust to decide this based on both # atomtypes or on asking each atom about the other's type. # For now, only this case matters (for element Ah5). if self.molecule is not None: # update valence error indicator appearance on self self.molecule.changeapp(0) return None if 1: #bruce 060327 optim of Chunk.kill: # if we're being killed right now, don't make a new bondpoint if self._f_will_kill == Utility._will_kill_count: if DEBUG_1779: print "DEBUG_1779: self._f_will_kill %r == Utility._will_kill_count %r" % \ ( self._f_will_kill , Utility._will_kill_count ) return None if self.__killed: #bruce 080208 new debug print (should never happen) msg = "bug: killed atom %r still had bond %r, being unbonded now" % \ ( self, b ) print msg return None if DEBUG_1779: print "DEBUG_1779: Atom.unbond on %r is making X" % self x = Atom('X', b.ubp(self), self.molecule) # invals mol as needed bond_copied_atoms( self, x, b, self) # copies bond type from old bond return x def get_neighbor_bond(self, neighbor): """ Return the bond to a neighboring atom, or None if none exists. """ for b in self.bonds: ## if b.other(self) == neighbor: could be faster [bruce 050513]: if b.atom1 is neighbor or b.atom2 is neighbor: return b return None def hopmol(self, numol): #bruce 041105-041109 extensively revised this """ If this atom is not already in molecule numol, move it to molecule numol. (This only changes the owning molecule -- it doesn't change this atom's position in space!) Also move its singlet-neighbors. Do all necessary invalidations of old and new molecules, including for this atom's bonds (both internal and external), since some of those bonds might change from internal to external or vice versa, which changes how they need to be drawn. """ # bruce 041222 removed side effect on self.picked if self.molecule is numol: return if self.molecule.assy is not numol.assy: #bruce 080219 debug code, might be slow, might print routinely ## msg = "\nBUG?: hopmol(%r, %r) but self.molecule %r .assy %r != numol.assy %r" % \ (self, numol, self.molecule, self.molecule.assy, numol.assy) print_compact_stack(msg + ": ") #bruce 080411 # We only have to set this in numol, not clear it in self, as it # is cleared by the display routine when needed. if (self.overlayText): numol.chunkHasOverlayText = True self.molecule.delatom(self) # this also invalidates our bonds numol.addatom(self) for atom in self.singNeighbors(): assert self.element is not Singlet # (only if we have singNeighbors!) # (since hopmol would infrecur if two singlets were bonded) atom.hopmol(numol) return def neighbors(self): """ return a list of all atoms (including singlets) bonded to this one """ return map((lambda b: b.other(self)), self.bonds) def realNeighbors(self): """ return a list of the real atoms (not singlets) bonded to this atom """ return filter(lambda atom: atom.element is not Singlet, self.neighbors()) def singNeighbors(self): # todo: rename to singletNeighbors or bondpointNeighbors """ return a list of the singlets bonded to this atom """ return filter(lambda atom: atom.element is Singlet, self.neighbors()) def baggage_and_other_neighbors(self): #bruce 051209 """ Return a list of the baggage bonded to this atom (monovalent neighbors which should be dragged along with it), and a list of the others (independent neighbors). Special case: in H2 (for example) there is no baggage (so that there is some way to stretch the H-H bond); but singlets are always baggage, even in HX. """ nn = self.neighbors() if len(nn) == 1: # special case: no baggage unless neighbor is a Singlet if nn[0].element is Singlet: return nn, [] else: return [], nn baggage = [] other = [] for atom in nn: if len(atom.bonds) == 1: baggage.append(atom) else: other.append(atom) return baggage, other def baggageNeighbors(self): #bruce 051209 baggage, other_unused = self.baggage_and_other_neighbors() return baggage def bondpoint_most_perpendicular_to_line(self, vector): #bruce 080529 """ Return one of our bondpoints whose spatial direction from self is farthest from the line through self defined by vector, or None if self has no bondpoints. """ candidates = [] for bond in self.bonds: other = bond.other(self) if not other.element is Singlet: continue other_vector = norm( other.posn() - self.posn() ) closeness_to_line = abs( dot( other_vector, vector) ) # scale depends on vlen(vector), but that doesn't matter here candidates.append( (closeness_to_line, other) ) if candidates: candidates.sort() # closest one is last, farthest is first return candidates[0][1] return None def deleteBaggage(self): #mark 060129. """ Deletes any monovalent atoms connected to self. """ for a in self.baggageNeighbors(): a.kill() def mvElement(self, elt, atomtype = None): #bruce 050511 added atomtype arg """ [Public low-level method:] Change the element type of this atom to element elt (an element object for a real element, not Singlet), and its atomtype to atomtype (which if provided must be an atomtype for elt), and do the necessary invalidations (including if the *prior* element type was Singlet). Note: this does not change any atom or singlet positions, so callers wanting to correct the bond lengths need to do that themselves. It does not even delete or add extra singlets to match the new element type; for that, use Atom.Transmute. """ if atomtype is None: atomtype = elt.atomtypes[0] # Note: we do this even if self.element is elt and self.atomtype # is not elt.atomtypes[0] ! That is, passing no atomtype is # *always* equivalent to passing elt's default atomtype, even if # this results in changing this atom's atomtype but not its # element. assert atomtype.element is elt if debug_flags.atom_debug: if elt is Singlet: #bruce 041118 # this is unsupported; if we support it it would require # moving this atom to its neighbor atom's chunk, too [btw we # *do* permit self.element is Singlet before we change it] print "atom_debug: fyi, bug?: mvElement changing %r to a singlet" % self if self.atomtype_iff_set() is atomtype: assert self.element is elt # i.e. assert that self.element and self.atomtype were consistent if debug_flags.atom_debug: #bruce 050509 msg = "atom_debug: fyi, bug?: mvElement changing %r to its existing element and atomtype" % self print_compact_stack( msg + ": " ) return #bruce 050509, not 100% sure it's correct, but if not, # caller probably has a bug (eg relies on our invals) # now we're committed to doing the change if (self.element is Singlet) != (elt is Singlet): # set of singlets is changing #bruce 050224: fix bug 372 by invalidating singlets self.molecule.invalidate_attr('singlets') self.changed() #bruce 050509 self.element = elt self.atomtype = atomtype # note: we have to set self.atomtype directly -- if we used set_atomtype, # we'd have infrecur since it calls *us*! [#e maybe this should be revised??] # (would it be ok to call set_atomtype_but_dont_revise_singlets?? #k) for b in self.bonds: b.setup_invalidate() self.molecule.changeapp(1) # no need to invalidate shakedown-related things, I think [bruce 041112] self._changed_structure() #bruce 050627 return def changed(self): #bruce 050509; perhaps should use more widely chunk = self.molecule if chunk is None: return #k needed?? chunk.changed() return def killed(self): #bruce 041029; totally revised 050702; revised 080227 """ (Public method) Report whether an atom has been killed. """ # Note: some "friend code" inlines an old incomplete version of # this method for speed (and omits the debug code). To find it, # search for _Atom__killed (the mangled version of __killed). # [bruce 071018/080227 comment] # # Note: (theory about an Undo bug in dna updater, bruce 080227): # Undo can be too lazy to set __killed, but then it clears .molecule. # And, break_interpart_bonds can then dislike .molecule being None # and set it back to _nullMol. So test for these values too. chunk = self.molecule res = self.__killed or chunk is None or chunk.isNullChunk() if debug_flags.atom_debug: # this cond is for speed better_alive_answer = chunk is not None and self.key in chunk.atoms and not chunk.isNullChunk() ##e and chunk is not killed?? if (not not better_alive_answer) != (not self.__killed): #bruce 060414 re bug 1779, but it never printed for it (worth keeping in for other bugs) #bruce 071018 fixed typo of () after debug_flags.atom_debug -- could that be why it never printed it?!? print "debug: better_alive_answer is %r but (not self.__killed) is %r" % \ (better_alive_answer , not self.__killed) return res def killed_with_debug_checks(self): # renamed by bruce 050702; was called killed(); by bruce 041029 """ (Public method) Report whether an atom has been killed, but do lots of debug checks and bug-workarounds (whether or not ATOM_DEBUG is set). Details: For an ordinary atom, return False. For an atom which has been properly killed, return True. For an atom which has something clearly wrong with it, print an error message, try to fix the problem, effectively kill it, and return True. Don't call this on an atom still being initialized. """ try: killed = not (self.key in self.molecule.atoms) if killed: assert self.__killed == 1 assert not self.picked chunk = self.molecule assert chunk is None or chunk.isNullChunk() # thus don't do this: assert not self.key in chunk.assy.selatoms assert not self.bonds assert not self.jigs else: assert self.__killed == 0 return killed except: print_compact_traceback("fyi: Atom.killed detects some problem" \ " in atom %r, trying to work around it:\n " % self ) try: self.__killed = 0 # make sure kill tries to do something _changed_parent_Atoms[self.key] = self self.kill() except: print_compact_traceback("fyi: Atom.killed: ignoring" \ " exception when killing atom %r:\n " % self ) return True pass # end of Atom.killed_with_debug_checks() def _f_prekill(self, val): #bruce 060328; usually inlined (but was tested when first written) self._f_will_kill = val return def kill(self): """ [public method] kill self: unpick it, remove it from its jigs, remove its bonds, then remove it from its chunk. Do all necessary invalidations. (Note that molecules left with no atoms, by this or any other op, will immediately kill themselves.) """ if DEBUG_1779: print "DEBUG_1779: Atom.kill on %r" % self if self.__killed: if not self.element is Singlet: print_compact_stack("fyi: atom %r killed twice; ignoring:\n" % self) else: # Note: killing a selected chunk, using Delete key, kills a lot of # singlets twice; I guess it's because we kill every atom # and singlet in chunk, but also kill singlets of killed atoms. # So I'll declare this legal, for singlets only. [bruce 041115] pass return self.atomtype #bruce 080208 bugfix of bugs which complain about # "reguess_atomtype of killed atom" in a console print: # make sure atomtype is set, since it's needed when neighbor atom # makes a bondpoint (since bond recomputes geometry all at once). # (I don't know whether it needs to be set *correctly*, so we might # optim by setting it to its default, if analysis shows this is ok. # But it seems likely that this choice does affect the final # position of the created bondpoint on the neighbor.) # The reason this bug is rare is that most killed atoms were alive # long enough for something to need their atomtype (e.g. to draw # their bonds). But when generators immediately kill some atoms # they temporarily make or read, we can have this bug. # The above is partly guessed; we'll see if this really fixes # those bugs. self.__killed = 1 # do this now, to reduce repeated exceptions (works??) _changed_parent_Atoms[self.key] = self # unpick self try: self.unpick(filtered = False) #bruce 060331 adding filtered = False (and implementing it in unpick) to fix bug 1796 except: print_compact_traceback("fyi: Atom.kill: ignoring error in unpick: ") pass # bruce 041115 reordered everything that follows, so it's safe to use # delatom (now at the end, after things which depend on self.molecule), # since delatom resets self.molecule to None. # remove from jigs for j in self.jigs[:]: try: j.remove_atom(self) # note: this might kill the jig (if it has no atoms left), # and/or it might remove j from self.jigs, but it will never # recursively kill this atom, so it should be ok # [bruce 050215 comment] except: # does this ever still happen? TODO: if so, document when & why. print_compact_traceback("fyi: Atom.kill: ignoring error in remove_atom %r from jig %r: " % (self, j) ) self.jigs = [] # mitigate repeated kills _changed_structure_Atoms[self.key] = self #k not sure if needed; if it is, also covers .bonds below #bruce 060322 # remove bonds selfmol = self.molecule for b in self.bonds[:]: other = b.other(self) if DEBUG_1779: print "DEBUG_1779: Atom.kill on %r is calling unbond on %r" % (self, b) if other.molecule is not selfmol: #bruce 080701 other.molecule._f_lost_externs = True selfmol._f_lost_externs = True other.unbond(b) # note: this can create a new singlet on other, if other is a real atom, # which requires computing b.ubp, which uses self.posn() # or self.baseposn(); or it can kill other if it's a singlet. # In some cases this is optimized to avoid creating singlets # when killing lots of atoms at once; search for "prekill". # It also invalidates chunk externs lists if necessary # (but not their _f_lost_externs flags). self.bonds = [] # mitigate repeated kills # only after disconnected from everything else, remove self from its chunk try: selfmol.delatom(self) # delatom also kills our chunk (self.molecule) if it becomes empty except KeyError: print "fyi: Atom.kill: atom %r not in its molecule (killed twice?)" % self pass return # from Atom.kill def filtered(self): # mark 060303 """ Returns True if self is not the element type/name currently listed in the Select Atoms filter combobox. """ if self.is_singlet(): return False # Fixes bug 1608 [mark 060303] if self.molecule.assy.w.selection_filter_enabled: for e in self.molecule.assy.w.filtered_elements: if e is self.element: return False return True return False def Hydrogenate(self): """ [Public method; does all needed invalidations:] If this atom is a singlet, change it to a hydrogen, and move it so its distance from its neighbor is correct (regardless of prior distance, but preserving prior direction). [#e sometimes it might be better to fix the direction too, like in depositMode...] @return: If hydrogenate succeeds, the int 1, otherwise, 0. @rtype: int """ # Huaicai 1/19/05 added return value. if not self.element is Singlet: return 0 other = self.bonds[0].other(self) self.mvElement(Hydrogen) #bruce 050406 rewrote the following, so it no longer depends # on old pos being correct for self being a Singlet. newpos = self.ideal_posn_re_neighbor( other) self.setposn(newpos) return 1 def ideal_posn_re_neighbor(self, neighbor, pretend_I_am = None): # see also snuggle #bruce 050404 to help with bug 254 and maybe Hydrogenate """ Given one of our neighbor atoms (real or singlet) [neighborness not verified! only posn is used, not the bond -- this might change when we have bond-types #e] and assuming it should remain fixed and our bond to it should remain in the same direction, and pretending (with no side effects) that our element is pretend_I_am if this is given, what position should we ideally have so that our bond to neighbor has the correct length? @see: methods Bond.ubp, Atom.snuggle, move_closest_baggage_to @warning: does not use getEquilibriumDistanceForBond/bond_params """ # review: should this use bond_params (which calls # getEquilibriumDistanceForBond when available)? # [bruce 080404 comment] me = self.posn() it = neighbor.posn() length = vlen( me - it ) if not length: #e atom_debug warning? # choose a better direction? only caller knows what to do, i guess... # but [050406] I think an arbitrary one is safer than none! ## return me # not great... it_to_me_direction = V(1,0,0) else: it_to_me_direction = norm( me - it ) it_to_me_direction = norm( it_to_me_direction ) # for original len close to 0, this might help make new len 1 [bruce 050404] if pretend_I_am: #bruce 050511 revised for atomtype ## my_elem = pretend_I_am # not needed my_atype = pretend_I_am.atomtypes[0] # even if self.element is pretend_I_am else: ## my_elem = self.element my_atype = self.atomtype ## its_elem = neighbor.element # not needed its_atype = neighbor.atomtype # presently we ignore the bond-valence between us and that neighbor atom, # even if this can vary for different bonds to it (for the atomtype it has) newlen = my_atype.rcovalent + its_atype.rcovalent #k Singlet.atomtypes[0].rcovalent better be 0, check this return it + newlen * it_to_me_direction def Dehydrogenate(self): """ [Public method; does all needed invalidations:] If this is a hydrogen atom (and if it was not already killed), kill it and return 1 (int, not boolean), otherwise return 0. (Killing it should produce a singlet unless it was bonded to one.) """ # [fyi: some new features were added by bruce, 041018 and 041029; # need for callers to shakedown or kill mols removed, bruce 041116] if self.element is Hydrogen and not self.killed(): #bruce 041029 added self.killed() check above to fix bug 152 self.kill() # note that the new singlet produced by killing self might be in a # different chunk (since it needs to be in our neighbor atom's chunk) #bruce 050406 comment: if we reused the same atom (as in Hydrogenate) # we'd be better for movies... just reusing its .key is not enough # if we've internally stored alists. But, we'd like to fix the direction # just like this does for its new singlet... so I'm not changing this for now. # Best solution would be a new method for H or X to fix their direction # as well as their distance. ###@@@ return 1 else: return 0 pass def snuggle(self): """ self is a bondpoint and the simulator has moved it out to the radius of an H (or moved it to a nonsensical position, and/or not moved it at all, if it's next to a PAM atom). Move it to a reasonable position. self.molecule may or may not be still in frozen mode. If self's neighbor is a PAM atom, the dna updater may or may not have ever run on it, and/or have run since it was last modified. Do all needed invals. @warning: if you are moving several atoms at once, first move them all, then snuggle them all, since snuggling self is only correct after self's real neighbor has already been moved to its final position. [Ignorance of this issue was the cause of bug 1239.] @see: methods Bond.ubp, Atom.ideal_posn_re_neighbor, move_closest_baggage_to """ #bruce 051221 revised docstring re bug 1239 #bruce 080501 revised behavior for PAM atoms if not self.bonds: #bruce 050428: a bug, but probably just means we're a killed singlet. # The caller should be fixed, and maybe is_singlet should check this # too, but for now let's also make it harmless here: if debug_flags.atom_debug: print_compact_stack( "atom_debug: bug (ignored): snuggling a killed singlet of atomkey %r: " % self.key ) #bruce 051221 revised this; untested return #bruce 050406 revised docstring to say chunk needn't be frozen. # note that this could be rewritten to call ideal_posn_re_neighbor, # but we'll still use it since it's better tested and faster. other = self.bonds[0].other(self) op = other.posn() sp = self.posn() np = op + norm(sp - op) * other.atomtype.rcovalent self.setposn(np) # bruce 041112 rewrote last line if other.element.pam: #bruce 080501 bugfix/nfr for v1.0.1 # print "fyi: fixing posn of %r on %r" % (self, other) # seems to work other.reposition_baggage_using_DnaLadder( dont_use_ladder = True, only_bondpoints = True ) pass return def move_closest_baggage_to(self, newpos, baggage = None, remove = False, min_bond_length = 0.1 ): """ Find the atom in baggage (self.baggageNeighbors() by default) which is closest *in direction from self* to newpos, and then move it to newpos, correcting its distance from self based on its and self's atomtypes (using newpos only for direction) unless an option (nim) is set to false. Return the atom moved, or None if no atom could be found to move. If remove is true, baggage must have been passed, and we also remove the moved atom (if any) from baggage (modifying it destructively). @param newpos: desired position to move an atom to; used only for its direction from self (by default) @param baggage: a sequence (mutable if remove is false), or None @param remove: whether to remove the moved atom from baggage (which must be a mutable sequence if we do) @param min_bond_length: minimum allowed distance from self to moved atom @return: the atom we moved, or None if we found no atom to move. """ #bruce 080404 if baggage is None: assert not remove baggage = self.baggageNeighbors() # or singNeighbors?? if not baggage: return None # can't move anything # todo: assert baggage is a list (which we can remove from if remove is true) # figure out which atom in baggage to move selfpos = self.posn() newpos_direction = norm(newpos - selfpos) sortme = [] # rename? for atom in baggage: atom_direction = norm(atom.posn() - selfpos) dist = vlen(atom_direction - newpos_direction) sortme.append( (dist, atom) ) sortme.sort() moveme = sortme[0][1] # maybe: don't move if already at newpos? only matters if that case # often happens (on atoms which didn't already inval their chunks # due to whatever caused this to be called), which I doubt (at least # for its initial use in reposition_baggage_using_DnaLadder). # note: that optim could probably be done by testing sortme[0][0] # for being close to zero. But worry about corrections for distance # on both newpos vs newpos_direction, and below. # fix distance want_length = ideal_bond_length(self, moveme) # note: depends on moveme.atomtype (and therefore, possibly, # on which element of baggage is chosen to be moveme) if want_length < min_bond_length: if debug_flags.atom_debug: print "fyi, in move_closest_baggage_to: " \ "ideal_bond_length(%r, %r) == %r < min_bond_length == %r" % \ (self, moveme, want_length, min_bond_length) want_length = min_bond_length pass fixed_newpos = selfpos + newpos_direction * want_length moveme.setposn(fixed_newpos) if remove: baggage.remove(moveme) return moveme def Passivate(self): """ [Public method, does all needed invalidations:] Change the element type of this atom to match the number of bonds with other real atoms, and delete singlets. """ # bruce 041215 modified docstring, added comments, capitalized name. # REVIEW: not yet modified for atomtypes since it's not obvious what it # should do! [bruce 050511] el = self.element PTsenil = PeriodicTable.getPTsenil() line = len(PTsenil) for i in range(line): if el in PTsenil[i]: line = i break if line == len(PTsenil): return #not in table # (note: we depend on singlets not being in the table) nrn = len(self.realNeighbors()) for atom in self.singNeighbors(): atom.kill() try: newelt = PTsenil[line][nrn] except IndexError: pass # bad place for status msg, since called on many atoms at once else: self.mvElement(newelt) # note that if an atom has too many bonds we'll delete the # singlets anyway -- which is fine def is_singlet(self): return self.element is Singlet # [bruce 050502 comment: it's possible self is killed and # len(self.bonds) is 0] def singlet_neighbor(self): """ Assume self is a bondpoint (aka singlet). Such an atom should be bonded to exactly one neighbor, a real atom (i.e. non-bondpoint). Return that neighbor atom, after checking some assertions. """ assert self.element is Singlet, "%r should be a singlet but is %s" % (self, self.element.name) #bruce 050221 added data to the assert, hoping to track down bug 372 when it's next seen obond = self.bonds[0] atom = obond.other(self) assert atom.element is not Singlet, "bug: a singlet %r is bonded to another singlet %r!!" % (self, atom) return atom # higher-valence bonds methods [bruce 050502] # [bruce 050627 comment: a lot of this might be obsolete. ###@@@] def singlet_v6(self): assert self.element is Singlet, "%r should be a singlet but is %s" % (self, self.element.name) assert len(self.bonds) == 1, "%r should have exactly 1 bond but has %d" % (self, len(self.bonds)) return self.bonds[0].v6 def singlet_reduce_valence_noupdate(self, vdelta): # this might or might not kill it; # it might even reduce valence to 0 but not kill it, # letting base atom worry about that # (and letting it take advantage of the singlet's # position, when it updates things) assert self.element is Singlet, \ "%r should be a singlet but is %s" % \ (self, self.element.name) assert len(self.bonds) == 1, \ "%r should have exactly 1 bond but has %d" % \ (self, len(self.bonds)) self.bonds[0].reduce_valence_noupdate(vdelta, permit_illegal_valence = True) # permits in-between, 0, or negative(?) valence return def update_valence(self, dont_revise_valid_bondpoints = False): """ warning: following docstring used to be a comment, hasn't been verified recently: repositions/alters existing bondpoints, updates bonding pattern, valence errors, etc; might reorder bonds, kill bondpoints; but doesn't move the atom and doesn't alter existing real bonds or other atoms; it might let atom record how it wants to move, when it has a chance and wants to clean up structure, if this can ever be ambiguous later, when the current state (including positions of old bondpoints) is gone. Update 071019: if dont_revise_valid_bondpoints is passed, then only bondpoints with invalid valence (e.g. zero valence) are altered. """ #bruce 050728 revised this and also disabled the debug prints #bruce 071019 added dont_revise_valid_bondpoints option # (though it's untested, since I ended up fixing a current bug # in a different way; but it looks correct and seems useful # enough to leave). from model.bond_constants import V_ZERO_VALENCE, BOND_VALENCES _debug = False ## debug_flags.atom_debug is sometimes useful here if self._modified_valence: self._modified_valence = False # do this first, so exceptions in the following only happen once if _debug: print "atom_debug: update_valence starting to updating it for", self # the only easy part is to kill bondpoints with illegal valences, # and warn if those were not 0. zerokilled = badkilled = 0 for sing in self.singNeighbors(): ###@@@ check out the other calls of this for code that might help us here... sv = sing.singlet_v6() if sv == V_ZERO_VALENCE: sing.kill() zerokilled += 1 elif sv not in BOND_VALENCES: # hmm... best to kill it and start over, I think, at least for now sing.kill() badkilled += 1 if _debug: print "atom_debug: update_valence %r killed %d " \ "zero-valence and %d bad-valence bondpoints" % \ (self, zerokilled, badkilled) ###e now fix things up... not sure exactly under what conds, or ###using what code (but see existing code mentioned above) #bruce 050702 working on bug 121, here is a guess: change atomtype #to best match new total number of bonds (which we might have #changed by killing some bondpoints). But only do this if we did #actually kill bondpoints. if zerokilled or badkilled: self.adjust_atomtype_to_numbonds( dont_revise_bondpoints = dont_revise_valid_bondpoints ) ### WARNING: if dont_revise_bondpoints is not set, # adjust_atomtype_to_numbonds can remake bondpoints just # to move them, even if their number was correct. Both the # remaking and the moving can be bad for some callers; # thus the new option. It may need to be used more widely. # [bruce 071019] #bruce 050728 temporary fix for bug 823 (in which C(sp2) is left #with 2 order1 bondpoints that should be one bondpoint); but in #the long run we need a more principled way to decide whether to #remake bondpoints or change atomtype when they don't agree: if len(self.bonds) != self.atomtype.numbonds and not dont_revise_valid_bondpoints: if _debug: print "atom_debug: update_valence %r calling remake_bondpoints" self.remake_bondpoints() elif _debug: print "atom_debug: update_valence thinks it doesn't need to update it for", self return def adjust_atomtype_to_numbonds(self, dont_revise_bondpoints = False): """ [Public method, does all needed invals, might emit history messages #k] If this atom's number of bonds (including open bonds) is better matched by some other atomtype of its element than by its current atomtype, or if its atomtype is not yet set, then change to the best atomtype and (if atomtype was already set) emit a history message about this change. The comparison is of current atomtype to self.best_atomtype_for_numbonds(). The change is done by set_atomtype if number of bonds is correct and dont_revise_bondpoints is not passed (since set_atomtype also remakes bondpoints in better positions), or by set_atomtype_but_dont_revise_singlets otherwise (no attempt is made to correct the number of open bonds in that case). [See also self.can_reduce_numbonds().] """ #bruce 050702, part of fixing bug 121 for Alpha6 #bruce 071019 added dont_revise_bondpoints option atype_now = self.atomtype_iff_set() best_atype = self.best_atomtype_for_numbonds(atype_now = atype_now) if best_atype is atype_now: return # never happens if atype_now is None if atype_now is not None: env.history.message("changing %s atomtype from %s to %s" % \ (self, atype_now.name, best_atype.name)) # this will often happen twice, plus a third message from Build # that it increased bond order, so i'm likely to decide not to # print it if (not dont_revise_bondpoints) and best_atype.numbonds == len(self.bonds): # right number of open bonds for new atype -- # let's move them to better positions when we set it self.set_atomtype( best_atype) else: # wrong number of open bonds -- leave them alone (in number and position); # or, dont_revise_bondpoints option was passed self.set_atomtype_but_dont_revise_singlets( best_atype) return def best_atomtype_for_numbonds(self, atype_now = None, elt = None): """ [Public method] Compute and return the best choice of atomtype for this atom's element (or for the passed element <elt>, if any) and number of bonds (including open bonds), breaking ties by favoring <atype_now> (if provided), otherwise favoring atomtypes which come earlier in the list of this element's (or elt's) possible atomtypes. For comparing atomtypes which err in different directions (which I doubt can ever matter in practice, since the range of numbonds of an element's atomtypes will be contiguous), we'll say it's better for an atom to have too few bonds than too many. In fact, we'll say any number of bonds too few (on the atom, compared to the atomtype) is better than even one bond too many. This means: the "best" atomtype is the one with the right number of bonds, or the fewest extra bonds, or (if all of them have fewer bonds than this atom) with the least-too-few bonds. (This method is used in Build mode, and might later be used when reading mmp files or pdb files, or in other ways. As of 050707 it's also used in Transmute.) [###k Should we also take into account positions of bonds, or their estimated orders, or neighbor elements??] """ #bruce 050702; elt arg added 050707 # see also best_atype in bond_utils.py, which does something different # but related [bruce 060523] if elt is None: elt = self.element atomtypes = elt.atomtypes if len(atomtypes) == 1: return atomtypes[0] # optimization nbonds = len(self.bonds) # the best atomtype has numbonds == nbonds. Next best, nbonds+1, # +2, etc. Next best, -1,-2, etc. items = [] for i, atype in zip(range(len(atomtypes)), atomtypes): if atype is atype_now: # (if atype_now is None or is not for elt, this is a legal # comparison and is always False) i = -1 # best to stay the same (as atype_now), or to be earlier # in the list of atomtypes, other things being equal numbonds = atype.numbonds if numbonds < nbonds: order = (1, nbonds - numbonds, i) # higher is worse else: order = (0, numbonds - nbonds, i) items.append((order, atype)) items.sort() best_atype = items[0][1] return best_atype # might or might not be the same as atype_now def can_reduce_numbonds(self): #bruce 050702, part of fixing bug 121 """ Say whether this atom's element has any atomtype which would better match this atom if it had one fewer bond. Note that this can be true even if that element has only one atomtype (when the number of bonds is currently incorrect). """ nbonds = len(self.bonds) # if nbonds < 1 (which will never happen based on how we're presently called), # the following code will (correctly) return False, so no special case is needed. for atype in self.element.atomtypes: if atype.numbonds < nbonds: return True return False # == def _changed_structure(self): # WARNING: this has some external calls. See docstring. [bruce 080404 comment] #bruce 050627; docstring revised and some required calls added, 050725; revised 051011 """ [friend method, mostly used privately. Should be renamed with _f_ prefix. OR, maybe it's really a public method and should be renamed with no _ like the method on Jig.] This must be called by all low-level methods which change this atom's or bondpoint's element, atomtype, or set of bonds. It doesn't need to be called for changes to neighbor atoms, or for position changes, or for changes to chunk membership of this atom, or when this atom is killed (but it will be called indirectly when this atom is killed, when the bonds are broken, unless this atom has no bonds). Calling it when not needed is ok, but might slow down later update functions by making them inspect this atom for important changes. (For example, calling it on a PAM atom invalidates that atom's entire DnaLadder.) All user events which can call this (indirectly) should also call env.do_post_event_updates() when they're done. """ ####@@@@ I suspect it is better to also call this for all # killed atoms or bondpoints, but didn't do this yet. [bruce 050725] ## before 051011 this used id(self) for key #e could probably optim by importing this dict at toplevel, # or perhaps even assigning a lambda in place of this method global_model_changedicts.changed_structure_atoms[ self.key ] = self _changed_structure_Atoms[ self.key ] = self #bruce 060322 # (see comment at _changed_structure_Atoms about how these two dicts are related) self._f_valid_neighbor_geom = False self._f_checks_neighbor_geom = (self.element.role == 'axis') self._changed_external_bond_appearance() # precaution, need not analyzed [bruce 090213] return def _changed_external_bond_appearance(self): #bruce 090213 """ If self has external bonds, invalidate their appearance. """ # (Could be optimized by knowing which atoms have external bonds, # and in other ways. Some calls may be redundant, or may make other # invalidations of ExternalBondSet display redundant.) mychunk = self.molecule for bond in self.bonds: otherchunk = bond.other_chunk(mychunk) if otherchunk is not mychunk: mychunk.invalidate_ExternalBondSet_display_for( otherchunk) return def _f_changed_some_bond_direction(self): #bruce 080210 """ [friend method] One of our bonds changed its bond direction. Do necessarily invals on self (other than Undo or changeapp, handled by our caller in the bond). """ _changed_structure_Atoms[ self.key ] = self return # debugging methods (not yet fully tested; use at your own risk) def invalidate_everything(self): # in class Atom """ debugging method -- remove self from its chunk, then add it back """ if len(self.molecule.atoms) <= 1: print "warning: invalidate_everything on the lone " \ "atom %r in chunk %r does nothing" % (self, self.molecule) print " since otherwise it might kill that chunk as a side effect!" else: # note: delatom invals self.bonds, # and kills the chunk if it becomes empty! # (which won't happen here due to the condition above) self.molecule.delatom(self) self.molecule.addatom(self) return def update_everything(self): """ debugging method """ # too verbose, don't do this [bruce 080318]: ## print "Atom.update_everything() does nothing" return #bruce 050511 added atomtype arg ###@@@ callers should pass atomtype def Transmute(self, elt, force = False, atomtype = None): """ (TODO: clean up this docstring.) Transmute self into a different element, unless it is a singlet. If this is a real atom, change its element type to I{elt} (which should not be Singlet unless precautions listed below are taken) and its atomtype to the I{atomtype} object passed, or if None is passed as atomtype, to elt's default atomtype or self's existing one (not sure which!###@@@) -- no, to the best one given the number of real bonds, or real and open bonds [maybe? 050707] -- and replace its bondpoints (if any) with new ones (if any are needed) to match the desired number of bonds for the new element/atomtype. If self is a singlet, don't transmute it. (But this is not an error.) [As of 050511 before atomtype arg added, new atom type is old one if elt is same and old one already correct, else is default atom type. This needs improvement. ###@@@] Never remove real bonds, even if there are too many. Don't change bond lengths (except in new open bonds created when replacing bondpoints) or atom positions. If there are too many real bonds for the new element type, refuse to transmute unless force is True. @param elt: The new element to transmute this atom (self) into, if self is not a bondpoint. elt must not be Singlet unless the caller has checked certain conditions documented below. @type elt: L{Elem} @param force: If there are too many real bonds for the new element type, refuse to transmute unless force is True. @type force: bool @param atomtype: The atomic hybrid of the element to transmute to. If None (the default), the default atomtype is assumed for I{elt}. @type atomtype: L{AtomType} @note: Does all needed invalidations. @note: If elt is Singlet (bondpoint), the caller must be sure that self has exactly one bond, that self is in the same chunk as its neighbor atom, and that the neighbor atom is not a bondpoint (aka singlet), or serious but hard-to-notice bugs will ensue. In practice, this is usually only safe when self was a bondpoint earlier in the same user operation, and was temporarily transmuted to something else, and nothing happened in the meantime that could have changed those conditions. The caller must also not mind creating an open bond with a nonstandard length, since Transmute does not normalize open bond length as is done when they are created normally. @attention: This method begins with a capital letter. So that it conforms to our coding standards, I will rename it in the near future (and fix callers). - Mark 2007-10-21 (But the new name can't be "transmute", since that would be too hard to search for. -- bruce 071101) """ if self.element is Singlet: # Note: some callers depend on this being a noop, # including the user Transmute operation, which calls this on # every atom in a chunk, including bondpoints. return if atomtype is None: if self.element is elt and \ len(self.bonds) == self.atomtype.numbonds: # this code might be used if we don't always return due to bond valence: ###@@@ ## atomtype = self.atomtype ## # use current atomtype if we're correct for it now, ## # even if it's not default atomtype # return since elt and desired atomtype are same as now and # we're correct return else: ## atomtype = elt.atomtypes[0] # use default atomtype of elt ##print "transmute picking this dflt atomtype", atomtype #bruce 050707: use the best atomtype for elt, given the number # of real and open bonds atomtype = self.reguess_atomtype(elt) assert atomtype.element is elt # in case a specific atomtype was passed or the default one was chosen, # do another check to return early if requested change is a noop and # our bond count is correct if self.element is elt and \ self.atomtype is atomtype and \ len(self.bonds) == atomtype.numbonds: # leave existing bondpoint positions alone in this case # -- not sure this is best! ###@@@ #e review ##print "transmute returning since noop to change to these: %r %r" % (elt, atomtype) return # now we're committed to changing things nbonds = len(self.realNeighbors()) ###@@@ should also consider the bond-valence to them... if nbonds > atomtype.numbonds: # transmuting would break valence rules # [###@@@ should instead use a different atomtype, if possible!] ###@@@ but a more normal case for using different one is if existing bond *valence* is too high... # note: this msg (or msg-class, exact text can vary) can get # emitted too many times in a row. name = atomtype.fullname_for_msg() if force: msg = "warning: Transmute broke valence rules, " \ "made (e.g.) %s with %d bonds" % (name, nbonds) env.history.message( orangemsg(msg) ) # fall through else: msg = "warning: Transmute refused to make (e.g.)" \ " a %s with %d bonds" % (name, nbonds) env.history.message( orangemsg(msg) ) return # in all other cases, do the change (even if it's a noop) and also # replace all bondpoints with 0 or more new ones self.direct_Transmute( elt, atomtype) return def Transmute_selection(self, elt): """ [this may be a private method for use when making our cmenu; if not, it needs more options and a better docstring.] Transmute as many as possible of the selected atoms to elt. """ #bruce 070412; could use review for appropriate level, error handling, etc selatoms = self.molecule.assy.selatoms atoms = selatoms.values() # not itervalues, too dangerous for atom in atoms: atom.Transmute(elt) return def permitted_btypes_for_bond(self, bond): #bruce 060523 """ If we are a real atom: Given one of our bonds (either real or open), and considering as fixed only its and our real bonds' existence (not their current bond types or our current atomtype), and ignoring everything else about the given bond (like the other atom on it), return the set of bond types it could have (as a dict from permitted bond v6's to lists of atomtypes that permit them), without forcing valence errors on this atom (but assuming the other bonds can adjust in btype however needed). Only consider disallowing bond types whose order is too high, not too low, even though the latter might also be needed in theory [I'm not sure -- bruce 060523]). If we are a bondpoint: return something in the same format which permits all bondtypes. """ bonds = [] # which bonds (besides bond) need to keep existing (with order 1 or higher)? nbonds = 0 # how many bonds (including bond, whether or not it's open) need to keep existing? for b in self.bonds: if b is not bond and not b.is_open_bond(): bonds.append(b) elif b is bond: nbonds += 1 min_other_valence = len(bonds) # probably the only way this bonds list is used permitted = {} # maps each permitted v6 to the list of atomtypes which permit it # (in same order as self.element.atomtypes) is_singlet = self.is_singlet() #k not sure if the cond that uses this is needed for atype in self.element.atomtypes: if nbonds > atype.numbonds: continue # atype doesn't permit enough bonds # if we changed self to that atomtype, how high could bond's valence be? # (expressed as its permitted valences) # Do we take into account min_other_valence, or not? Yes, I think. ##k review once this is tried. Maybe debug print whether this matters. #e # There are two limits: atype.permitted_v6_list, and atype.valence # minus min_other_valence. But the min_other_valence is the max of # two things: other real bonds, or required numbonds (for this # atype) minus 1 (really, that times the minimum bond order for # this atomtype, if that's not 1, but minimum bond order not being # 1 is nim in all current code). (BTW, re fixed bug 1944, I don't # know why double is in N(sp2)g's permitted_v6_list, and that's # wrong and remains unfixed, though our_min_other_valence makes it # not matter in this code.) for v6 in atype.permitted_v6_list: our_min_other_valence = max(min_other_valence, atype.numbonds - 1) #bruce 060524 fix bug 1944 if is_singlet or v6 <= (atype.valence - our_min_other_valence) * V_SINGLE: permitted.setdefault(v6, []).append(atype) return permitted def direct_Transmute(self, elt, atomtype): #bruce 050511 split this out of Transmute """ [Public method, does all needed invalidations:] With no checks except that the operation is legal, kill all bondpoints, change elt and atomtype (both must be provided and must match), and make new bondpoints. """ for atom in self.singNeighbors(): atom.kill() # (since atom is a bondpoint, this kill doesn't replace it with a bondpoint) self.mvElement(elt, atomtype) self.make_enough_bondpoints() return # from direct_Transmute def reposition_baggage(self, baggage = None, planned_atom_nupos = None): """ Your baggage atoms (or the given subset of them) might no longer be sensibly located, since you and/or some neighbor atoms have moved (or are about to move, re planned_atom_nupos as explained below), so fix up their positions based on your other neighbors' positions, using old baggage positions only as hints. BUT one of your other neighbors (but not self) might be about to move (rather than already having moved) -- if so, planned_atom_nupos = (that neighbor, its planned posn), and use that posn instead of its actual posn to decide what to do. @warning: we assume baggage is a subset of self.baggageNeighbors(), but we don't check this except when ATOM_DEBUG is set. """ #bruce 060629 for bondpoint problem try: import operations.reposition_baggage as reposition_baggage # don't make this a toplevel import reload_once_per_event(reposition_baggage) # this can be removed when devel is done, but doesn't need to be reposition_baggage.reposition_baggage_0(self, baggage, planned_atom_nupos) except: # this is always needed, since some of the code for special alignment cases # is so rarely exercised that we can't effectively test it print_compact_traceback("bug in reposition_baggage; skipping it: ") pass return def remake_bondpoints(self): """ [Public method, does all needed invalidations] Destroy this real atom's existing bondpoints (if any); then call make_enough_bondpoints to add the right number of new ones in the best positions. """ for atom in self.singNeighbors(): atom.kill() # (since atom is a bondpoint, this kill doesn't replace it with a bondpoint) self.make_enough_bondpoints() return def remake_baggage_UNFINISHED(self): #bruce 051209 -- pseudocode; has sample calls, desirable but commented out, since it's unfinished ###@@@ bn = self.baggageNeighbors() for atom in bn: if not atom.is_singlet(): pass ###e record element and position atom.mvElement(Singlet) ####k ??? ####@@@@ kluge to kill it w/o # replacing w/ singlet; better to just tell kill that atom.kill() # (since atom is a singlet, this kill doesn't replace it with a singlet) self.make_enough_bondpoints() ###e might pass old posns to ask this to imitate them if it can pass ###e now transmute the elts back to what they were, if you can, based on nearness return def make_enough_bondpoints(self): """ [Public method, does all needed invalidations:] Add 0 or more bondpoints to this real atom, until it has as many bonds as its element and atom type prefers (but at most 4, since we use special-case code whose knowledge only goes that high). Add them in good positions relative to existing bonds (if any) (which are not changed, whether they are real or open bonds). """ #bruce 050510 extending this to use atomtypes; # all subrs still need to set singlet valence ####@@@@ if len(self.bonds) >= self.atomtype.numbonds: return # don't want any more bonds # number of existing bonds tells how to position new open bonds # (for some n we can't make arbitrarily high numbers of wanted open # bonds; for other n we can; we can always handle numbonds <= 4) n = len(self.bonds) if n == 0: self.make_bondpoints_when_no_bonds() elif n == 1: self.make_bondpoints_when_1_bond() elif n == 2: self.make_bondpoints_when_2_bonds() elif n == 3: self.make_bondpoints_when_3_bonds() # (makes at most one open bond) else: pass # no code for adding open bonds to 4 or more existing bonds return # the make_singlets methods were split out of the private depositMode methods # (formerly called bond1 - bond4), to help implement Atom.Transmute [bruce 041215] def make_bondpoints_when_no_bonds(self): #bruce 050511 partly revised this for atomtypes """ [public method, but trusts caller about len(self.bonds)] see docstring for make_bondpoints_when_2_bonds """ assert len(self.bonds) == 0 # bruce 071019 added this atype = self.atomtype if atype.bondvectors: r = atype.rcovalent pos = self.posn() chunk = self.molecule for dp in atype.bondvectors: x = Atom('X', pos + r * dp, chunk) bond_atoms(self, x) ###@@@ set valence? or update it later? return def make_bondpoints_when_1_bond(self): # by josh, with some comments and mods by bruce """ [public method, but trusts caller about len(self.bonds)] see docstring for make_bondpoints_when_2_bonds """ assert len(self.bonds) == 1 assert not self.is_singlet() atype = self.atomtype if len(atype.quats): #bruce 041119 revised to support "onebond" elements # There is at least one other bond we should make (as open bond); # compute rq, which rotates this atom's bonding pattern (base and quats) # to match the existing bond. (If q is a quat that rotates base to another # bond vector (in std position), then rq + q - rq rotates r to another # bond vector in actual position.) [comments revised/extended by bruce 050614] pos = self.posn() s1pos = self.bonds[0].ubp(self) r = s1pos - pos # this points towards our real neighbor del s1pos # same varname used differently below rq = Q(r,atype.base) # if the other atom has any other bonds, align 60 deg off them # [new feature, bruce 050531: or 0 degrees, for both atomtypes sp2; # should also look through sequences of sp atoms, but we don't yet do so] # [bruce 041215 comment: might need revision if numbonds > 4] a1 = self.bonds[0].other(self) # our real neighbor if len(a1.bonds)>1: if not (a1.atomtype.is_linear() and atype.potential_pi_bond()): # figure out how to line up one arbitrary bond from each of self and a1. # a2 = a neighbor of a1 other than self if self is a1.bonds[0].other(a1): a2 = a1.bonds[1].other(a1) else: a2 = a1.bonds[0].other(a1) a2pos = a2.posn() else: #bruce 050728 new feature: for new pi bonds to sp atoms, # use pi_info to decide where to pretend a2 lies. # If we give up, it's safe to just say a2pos = a1.posn() -- # twistor() apparently tolerates that ambiguity. try: # catch exceptions in case for some reason it's too # early to compute this... note that, if we're running # in Build mode (which just deposited self and bonded # it to a1), then that new bond and that change to a1 # hasn't yet been seen by the bond updating code, so # an old pi_info object might be on the other bonds to # a1, and none would be on the new bond a1-self. But # we don't know if this bond is new, so if it has a # pi_bond_obj we don't know if that's ok or not. So to # fix a bug this exposed, I'm making bond.rebond warn # the pi_bond_obj on its bond, immediately (not # waiting for bond updating code to do it). # [050729: this is no longer needed, now that we # destroy old pi_bond_obj (see below), but is still # done.] b = self.bonds[0] # if there was not just one bond on self, we'd say find_bond(self,a1) #bruce 050729: it turns out there can be incorrect # (out of date) pi_info here, from when some prior # singlets on self were still there -- need to get rid # of this and recompute it. This fixes a bug I found, # and am reporting, in my mail (not yet sent) saying # bug 841 is Not A Bug. if b.pi_bond_obj is not None: b.pi_bond_obj.destroy() pi_info = b.get_pi_info(abs_coords = True) # without the option, vectors would be in bond's coordsys ((a1py, a1pz), (a2py, a2pz), ord_pi_y, ord_pi_z) = pi_info del ord_pi_y, ord_pi_z # note that we don't know whether we're atom1 or atom2 # in that info, but it shouldn't matter since self is # not affecting it so it should not be twisted along # b. So we'll pretend a1py, a1pz are about a1, though # they might not be. We'll use a1pz as the relative # place to imagine a1's neighbor, if a1 had been sp2 # rather than sp. a2pos = a1.posn() + a1pz except: print_compact_traceback("exception ignored: ") a2pos = a1.posn() pass s1pos = pos+(rq + atype.quats[0] - rq).rot(r) # un-spun posn of one of our new singlets spin = twistor(r,s1pos-pos, a2pos-a1.posn()) # [bruce 050614 comments] # spin is a quat that says how to twist self along r to line up # the representative bonds perfectly (as projected into a plane perpendicular to r). # I believe we'd get the same answer for either r or -r (since it's a quat, not an angle!). # This won't work if a1 is sp (and a2 therefore projects right on top of a1 as seen along r); # I don't know if it will have an exception or just give an arbitrary result. ##k ##e This should be fixed to look through a chain of sp atoms to the next sp2 atom (if it finds one) # and to know about pi system alignments even if that chain bends # (though for long chains this won't matter much in practice). # Note that we presently don't plan to store pi system alignment in the mmp file, # which means it will be arbitrarily re-guessed for chains of sp atoms as needed. # (I'm hoping other people will be as annoyed by that as I will be, and come to favor fixing it.) if (atype.potential_pi_bond() and a1.atomtype.potential_pi_bond()): # for now, same behavior for sp2 or sp atoms [revised 050630] pass # no extra spin else: spin = spin + Q(r, math.pi/3.0) # 60 degrees of extra spin else: spin = Q(1,0,0,0) chunk = self.molecule if 1: # see comment below [bruce 050614] spinsign = debug_pref("spinsign", Choice([1,-1])) for q in atype.quats: # the following old code has the wrong sign on spin, # thus causing bug 661: [fixed by bruce 050614] ## q = rq + q - rq - spin # this would be the correct code: ## q = rq + q - rq + spin # but as an example of how to use debug_pref, I'll put in # code that can do it either way, with the default pref value # giving the correct behavior (moved just above, outside of this loop). q = rq + q - rq + spin * spinsign xpos = pos + q.rot(r) x = Atom('X', xpos, chunk) bond_atoms(self, x) return def make_bondpoints_when_2_bonds(self): """ [public method, but trusts caller about len(self.bonds)] Given an atom with exactly 2 real bonds (and no singlets), see if it wants more bonds (due to its atom type), and make extra singlets if so, [###@@@ with what valence?] in good positions relative to the existing real bonds. Precise result might depend on order of existing bonds in self.bonds. """ assert len(self.bonds) == 2 # usually both real bonds; doesn't matter atype = self.atomtype if atype.numbonds <= 2: return # optimization # rotate the atom to match the 2 bonds it already has # (i.e. figure out a suitable quat -- no effect on atom itself) pos = self.posn() s1pos = self.bonds[0].ubp(self) s2pos = self.bonds[1].ubp(self) r = s1pos - pos rq = Q(r,atype.base) # this moves the second bond to a possible position; # note that it doesn't matter which bond goes where q1 = rq + atype.quats[0] - rq b2p = q1.rot(r) # rotate it into place tw = twistor(r, b2p, s2pos - pos) # now for all the rest # (I think this should work for any number of new bonds [bruce 041215]) chunk = self.molecule for q in atype.quats[1:]: q = rq + q - rq + tw x = Atom('X', pos + q.rot(r), chunk) bond_atoms(self, x) return def make_bondpoints_when_3_bonds(self): """ [public method, but trusts caller about len(self.bonds)] see docstring for make_bondpoints_when_2_bonds """ assert len(self.bonds) == 3 atype = self.atomtype if atype.numbonds > 3: # bruce 041215 to fix a bug (just reported in email, no bug number): # Only do this if we want more bonds. # (But nothing is done to handle more than 4 desired bonds. # Our element table has a comment claiming that its elements with # numbonds > 4 are not yet used, but nothing makes me confident # that comment is up-to-date.) pos = self.posn() s1pos = self.bonds[0].ubp(self) s2pos = self.bonds[1].ubp(self) s3pos = self.bonds[2].ubp(self) opos = (s1pos + s2pos + s3pos)/3.0 try: assert vlen(pos - opos) > 0.001 dir = norm(pos - opos) except: # [bruce 041215:] # fix unreported unverified bug (self at center of its neighbors): # [bruce 050716 comment: one time this can happen is when we # change atomtype of some C in graphite to sp3] if debug_flags.atom_debug: print "atom_debug: fyi: self at center of its neighbors " \ "(more or less) while making singlet", self, self.bonds dir = norm(cross(s1pos - pos, s2pos - pos)) # that assumes s1 and s2 are not opposite each other; #e it would be safer to pick best of all 3 pairs opos = pos + atype.rcovalent * dir chunk = self.molecule x = Atom('X', opos, chunk) bond_atoms(self, x) return pass # end of class Atom # == register_class_changedicts( Atom, _Atom_global_dicts ) # error if one class has two same-named changedicts # (so be careful re module reload) # == # this test code can be removed when the test code that uses it # in bond_updater.py is removed [bruce 071119] ##class Atom2(Atom): #bruce 071116 ## """ ## For development tests only -- a clone of class Atom, ## for testing the effect of replace_atom_class on live atoms. ## """ ## # tell undo to treat the class as Atom when grabbing and storing diffs: ## _s_undo_class_alias = Atom ## pass # end
NanoCAD-master
cad/src/model/chem.py
# Copyright 2004-2009 Nanorex, Inc. See LICENSE file for details. """ bonds.py -- class Bond, for any supported type of chemical bond between two atoms (one of which might be a "singlet" to represent an "open bond" in the UI), and related code @author: Josh @version: $Id$ @copyright: 2004-2009 Nanorex, Inc. See LICENSE file for details. History: - originally by Josh - lots of changes, by various developers - split out of chem.py by bruce 050502 - support for higher-valence bonds added by bruce 050502 - ??? [ongoing] - bruce optimized some things, including using 'is' and 'is not' rather than '==', '!=' for atoms, molecules, elements, parts, assys in many places (not all commented individually); 050513 - bruce split bond_constants.py into a separate module; 050707 - 050727 bruce moved bond drawing code into a separate module, bond_drawer.py (also removed some imports not needed here, even though chem.py still does "from bonds import *" and some other modules import * from chem, so there is no guarantee these were not needed indirectly) """ debug_1951 = False # DO NOT COMMIT with True from geometry.VQT import Q, vlen, norm from utilities import debug_flags from utilities.constants import MAX_ATOM_SPHERE_RADIUS from utilities.debug import print_compact_stack from utilities.debug import compact_stack from utilities.debug import print_compact_traceback from utilities.debug import reload_once_per_event from utilities.debug_prefs import debug_pref, Choice_boolean_False from utilities.GlobalPreferences import usePyrexAtomsAndBonds from utilities.Log import quote_html import foundation.env as env from foundation.changedicts import register_changedict, register_class_changedicts from foundation.state_utils import StateMixin from foundation.state_constants import S_CACHE, S_DATA, S_PARENT from foundation.state_constants import UNDO_SPECIALCASE_BOND from model.bond_constants import V_SINGLE from model.bond_constants import BOND_VALENCES from model.bond_constants import BOND_MMPRECORDS from model.bond_constants import BOND_VALENCES_HIGHEST_FIRST from model.bond_constants import bond_params from model.bond_constants import bonded_atoms_summary from model.bond_constants import bond_type_names from model.bond_constants import atoms_are_bonded from model.bond_constants import find_bond from model.elements import Singlet import model.global_model_changedicts as global_model_changedicts from operations.bond_chains import grow_directional_bond_chain from graphics.model_drawing.bond_drawer import writepov_bond from graphics.model_drawing.special_drawing import USE_CURRENT from graphics.drawables.Selobj import Selobj_API # bond length constants # (note: these ought to be moved to bond_constants.py # or to a new file for chemistry-related data [bruce 080122 comment]) # Linus Pauling # http://www.pubmedcentral.gov/articlerender.fcgi?artid=220148 CC_GRAPHITIC_BONDLENGTH = 1.421 # page 1647 BN_GRAPHITIC_BONDLENGTH = 1.446 # page 1650 # == # define BondDict and BondBase differently depending on whether we are # using Pyrex Atoms and Bonds (atombase.pyx): if usePyrexAtomsAndBonds(): #bruce 080220 revised this # usePyrexAtomsAndBonds tests that we want to, and can, import all # necessary symbols from atombase from atombase import BondDictBase, BondBase # WARNING: same_vals probably uses __eq__ for Bond when it inherits from # BondBase (a new-style class), and this could conceivably cause Undo bugs; # a warning is printed lower down if Bond is new-style for any reason # (search for is_new_style_class(Bond) to find it). # For more info see 090205 comments in state_utils.py docstring # and in Comparison.py. [bruce 090205] class BondDict(BondDictBase): # not yet used, except maybe in atombasetests.py # renamed from BondSet, bruce 080229 # probably not correctly defined; see assert 0 message below def __init__(self): BondDictBase.__init__(self) assert 0, "BondDictBase is probably incorrect after 080229 " \ "renaming of bond.key to bond.bond_key, with new " \ "formula which is much less globally unique than " \ "before. (Before this, it probably had at least a" \ "rare bug due to that nonuniqueness.)" #bruce 080229 bdkey = 'stub' # NIM self.key = bdkey.next() # FIX: Undefined variable 'bdkey'. # This bdkey should be distinct from the atKey used by # class Atom, i think (and thus needs a different name, # and no import atKey). # But first I need to see how it's used... # maybe the (experimental) C code assumes all atom & bond keys # are distinct in a single namespace. # If so, we should make a single global key allocator in env. # [but note that this is not a bond key, it's a BondDict key] # [bruce 071107/080223 comment; renamed atKey -> bdkey, 080327] return pass print "Using atombase.pyx in bonds.py" else: def BondDict(): return { } class BondBase: def __init__(self): pass def __getattr__(self, attr): # in class BondBase raise AttributeError, attr pass pass # == # [Note: the functions atoms_are_bonded (aka bonded), and find_bond, were moved # from here to bond_constants.py (to remove an import cycle) by bruce 071216] # == _bond_atoms_oldversion_noops_seen = {} #bruce 051216 def bond_atoms_oldversion(a1, a2): """ Make a new bond between atoms a1 and a2 (and add it to their lists of bonds), if they are not already bonded; if they are already bonded do nothing. Return None. (The new bond object, if one is made, can't be found except by scanning the bonds of one of the atoms.) If a1 == a2, this is an error; print a warning and do nothing. This increases the number of bonds on each atom (when it makes a new bond) -- it never removes any singlets. Therefore it is mostly for low-level use. """ #bruce 050502 renamed this from bond_atoms; # it's called from the newer version of bond_atoms #bruce 041109 split this out of [later removed] molecule.bond method. # Since it's the only caller of # Bond.__init__, what it does to the atoms could (and probably should) be put # inside the constructor. However, it should not simply be replaced with calls # to the constructor, in case we someday want it to return the bond which it # either makes (as the constructor does) or doesn't make (when the atoms are # already bonded). The test for a prior bond makes more sense outside of the # Bond constructor. if a1 is a2: #bruce 041119, partial response to bug #203 print "BUG: bond_atoms was asked to bond %r to itself." % a1 print "Doing nothing (but further bugs may be caused by this)." print_compact_stack("stack when same-atom bond attempted: ") return #bruce 051216 rewriting this to be faster and avoid console warning when #bond already exists (re bug 1226), but still verify bond is on both atoms #or neither b1 = find_bond(a1, a2) # a Bond or None b2 = find_bond(a2, a1) if b1 is not b2: print "bug warning: bond between %r and %r inconsistent in " \ " their .bonds lists; %r (id %#x) vs %r (id %#x)" \ % (a1, a2, b1, id(b1), b2, id(b2)) msg = "will remove one or both existing bonds, then make requested new one" print_compact_stack(msg + ": ") if b1: a1.bonds.remove(b1) # probably no need for a1._changed_structure() since we'll do it # in Bond(a1, a2) below; probably same for a2; but as a precaution # in case of bugs (or misanalysis or future change of this code), # I'll do it anyway. [bruce 060322] a1._changed_structure() b1 = None if b2: a2.bonds.remove(b2) a2._changed_structure() b2 = None if b1: # these atoms are already bonded ###e should we verify bond order is 1, otherwise complain more loudly?? if debug_flags.atom_debug: # print debug warning #e refile this code -- only print warning once for each place # in the code it can happen from blame = compact_stack() # slow, but should be ok since this case should be rare # known cases as of 051216 include only one: # reading pdb files with redundant CONECT records if not _bond_atoms_oldversion_noops_seen.has_key(blame): msg = "atom_debug: note: bond_atoms_oldversion doing nothing " \ "since %r and %r already bonded" % (a1, a2) print_compact_stack( msg + ": ") if not _bond_atoms_oldversion_noops_seen: print "(above message (bond_atoms_oldversion noop) is " \ "only printed once for each compact_stack that calls it)" _bond_atoms_oldversion_noops_seen[blame] = None pass return b = Bond(a1, a2) # (this does all necessary invals, including a1 and a2._changed_structure()) a1.bonds.append(b) a2.bonds.append(b) return ## # pre-051216 code (starting from where new code starts above) ## at1, at2 = a1, a2 ## b = Bond(at1, at2) # (this does all necessary invals) ## ## #bruce 041029 precautionary change -- I find in debugging that the bond ## # can be already in one but not the other of at1.bonds and at2.bonds, ## # as a result of prior bugs. To avoid worsening those bugs, we should ## # change this... but for now I'll just print a message about it. ## #bruce 041109: when this happens I'll now also remove the obsolete bond. ## if (b in at1.bonds) != (b in at2.bonds): ## print "fyi: debug: for new bond %r, (b in at1.bonds) != " \ ## "(b in at2.bonds); removing old bond" % b ## try: ## at1.bonds.remove(b) ## except: ## pass ## try: ## at2.bonds.remove(b) ## except: ## pass ## if not b in at2.bonds: ## at1.bonds.append(b) ## at2.bonds.append(b) ## else: ## # [bruce comment 041115: I don't know if this ever happens, ## # or if it's a good idea for it to be allowed, but it is allowed. ## # #e should it inval the old bond? I think so, but didn't add that. ## # later: it happens a lot when entering Extrude; guess: mol.copy copies ## # each internal bond twice (sounds right, but I did not verify this).] ## # ## # [addendum, bruce 051018: I added a message for when a new bond is equal to ## # an existing one, but entering Extrude does not print that, so either it's ## # been changed or mol.copy has or I misunderstand the above code (which ## # I predict would hit that message). Just to check, I'll print a debug ## # message here (below); that message is not happening either, so maybe ## # this deprecated feature is no longer used at all. #k ###@@@ ## # (Should also try reading a pdb file with the same bond ## # listed twice... ###k) [like bug 1226!] ## if debug_flags.atom_debug: ## print "atom_debug: fyi (possible bug): bond_atoms_oldversion " \ ## "is a noop since an equal bond exists:", b ## pass ## return def bond_atoms_faster(at1, at2, v6): #bruce 050513; docstring corrected 050706 """ Bond two atoms, which must not be already bonded (this might not be checked). Doesn't remove singlets. [###k should verify that by a test] Return the new bond object (which is given the bond order code (aka valence) v6, which must be specified). """ b = Bond(at1, at2, v6) # (this does all necessary invals, including _changed_structure on # atoms, and asserts at1 is not at2) at1.bonds.append(b) at2.bonds.append(b) return b def bond_copied_atoms(at1, at2, oldbond, origat1): #bruce 050524; revised 070424 """ Bond the given atoms, at1 and at2 (and return the new bond object), copying whatever bond state is relevant from oldbond, which is presumably a bond between the originals of the same atoms, or it might be a half-copied bond if at1 or at2 is a singlet (whether to use this function like that is not yet decided). As of 050727 this is also used in Atom.unbond to copy bond types onto open bonds which replace broken real bonds. In case oldbond might be "directional" (and thus might have state which is directional, i.e. which looks different depending on which of its atoms you're looking at), the caller must also pass origat1, an atom of oldbond corresponding to at1 in the new bond. """ newbond = bond_atoms_faster(at1, at2, oldbond.v6) if origat1 is not None: #bruce 070424 also copy bond_direction, if newbond is directional # (which can be false in practice when at2 is a bondpoint) if oldbond._direction and newbond.is_directional(): direction = oldbond.bond_direction_from(origat1) newbond.set_bond_direction_from(at1, direction) else: # this case is deprecated, and thought never to happen, as of bruce 070424 ## if oldbond._direction and debug_flags.atom_debug: msg = "debug: bond_copied_atoms%r needs origat1" % \ ((at1, at2, oldbond, origat1),) print_compact_stack( msg + ": ") return newbond # == helper functions related to bonding (I might move these lower in the file #e) def bonds_mmprecord( valence, atomcodes ): """ Return the mmp record line (not including its terminating '\n') which represents one or more bonds of the same (given) valence (which must be a supported valence) from the prior atom in the mmp file to each of the listed atoms (given as atomcodes, a list of the strings used to encode them in the mmp file being written). """ ind = BOND_VALENCES.index(valence) # exception if not a supported bond order code (aka valence) recname = BOND_MMPRECORDS[ind] return recname + " " + " ".join(atomcodes) def bond_atoms(a1, a2, vnew = None, s1 = None, s2 = None, no_corrections = False): """ WARNING: If vnew is not provided, this function behaves differently and is much less safe for general use (details below). Behavior when vnew is provided: Bond atoms a1 and a2 by making a new bond of order vnew (which must be one of the constants in chem.BOND_VALENCES, not a numerically expressed bond order; for the effect of not providing vnew, see below). The new bond is returned. If for some reason it can't be made, None is returned (but if that can happen, we should revise the API so an error message can be returned). Error if these two atoms are already bonded. [Question: is this detected? ###k] If provided, s1 and s2 are the existing singlets on a1 and a2 (respectively) whose valence (i.e. bond order code on their open bonds) should be reduced (or eliminated, in which case they are deleted) to provide valence (bond order) for the new bond. (If they don't have enough, other adjustments will be made; this function is free to alter, remove, or replace any existing singlets on either atom.) For now, this function will never alter the bond order of any existing bonds to real atoms. If necessary, it will introduce valence errors on a1 and/or a2. (Or if they already had valence errors, it might remove or alter those.) If no_corrections = True, this function will not alter singlets on a1 or a2, but will either completely ignore issues of total valence of these atoms, or will limit itself to tracking valence errors or setting related flags (this is undecided). (This might be useful for code which builds new atoms rather than modifying existing ones, such as when reading mmp files or copying existing atoms.) If no_corrections is false, and if the open bonds on s1 or s2 have directions set, not inconsistently, then if the new bond is directional, it's given a direction consistent with those open bonds (new feature 071017). Behavior when vnew is not provided (less safe in general): For backwards compatibility, when vnew is not provided, this function calls the old code [pre-higher-valence-bonds, pre-050502] which acts roughly as if vnew = V_SINGLE, s1 = s2 = None, no_corrections = True, except that it returns None rather than the newly made bond, and unlike this function doesn't mind if there's an existing bond, but does nothing in that case; this behavior might be relied on by the current code for copying bonds when copying a chunk, which might copy some of them twice. Using the old bond_atoms code by not providing vnew is deprecated, and might eventually be made impossible after all old calling code is converted for higher-order bonds. [However, as of 051216 it's still called in lots of places.] """ # DOCSTRING BUG (unconfirmed, docstring is unclear): if s1 and s2 are not # provided but vnew is provided, the docstring is unclear about whether # this will find bondpoints to remove in order to keep the valence # correct. In at least one piece of new code it seems that it's not doing # that, resulting in valence errors. Maybe it was never intended to do # that. To fix that new code I'll find the right bondpoints to pass. # [bruce 080529, issue needs REVIEW] if vnew is None: assert s1 is s2 is None assert no_corrections == False bond_atoms_oldversion( a1, a2) # warning [obs??#k]: mol.copy might rely on this being noop when # bond already exists! return make_corrections = not no_corrections del no_corrections # quick hack for new version, using optimized/stricter old version ## assert vnew in BOND_VALENCES assert not atoms_are_bonded(a1, a2) assert s1 is None or not s1._Atom__killed assert s2 is None or not s2._Atom__killed assert not a1._Atom__killed assert not a2._Atom__killed if make_corrections: # make sure atomtypes are set, so bondpoints other than the ones passed # won't be needlessly replaced or moved by Atom.update_valence below # [bruce 071019 revision to make this easier to use in DNA Generator] # ### UNTESTED for that purpose a1.atomtype # has side effect in __getattr__ a2.atomtype assert s1 is None or not s1._Atom__killed assert s2 is None or not s2._Atom__killed # depending on whether the new bond will be directional, # adjust bond directions on all open bonds on a1 and a2 to fit # (including open bonds not on s1 or s2). [bruce 080213] ### NIM is_directional want_dir = 0 # maybe modified below new_bond_is_directional = ( a1.element.bonds_can_be_directional and a2.element.bonds_can_be_directional ) if new_bond_is_directional: # figure out desired direction for new bond (measured from a1 to a2) # first grab existing directions on s1 and s2 (from their baseatoms # to them), for the rare cases where we need them dir1 = (s1 is not None and s1.bonds[0].bond_direction_from(a1)) dir2 = (s2 is not None and s2.bonds[0].bond_direction_from(a2)) # note: these might be False, but Python guarantees that will # act as 0 in the arithmetic below # find out, for each atom, the desired new direction away from it, # using existing open bond directions only to disambiguate # (they're needed only if a bare X-Ss-X is permitted, or if some # directional real bonds have directions unset) want_dir_a1 = a1.desired_new_real_bond_direction() or dir1 want_dir_a2 = a2.desired_new_real_bond_direction() or dir2 # decide on the desired direction for the new bond, # measured from a1 to a2 (so negate the "from a2" variables) sumdir = want_dir_a1 + (- want_dir_a2) # this is 0 if the dirs wanted by each side are inconsistent; # otherwise its sign gives the new dir (if any) want_dir = max(-1, min(1, sumdir)) del sumdir # if possible, fix open bond directions in advance (matters??) if want_dir != dir1: a1.fix_open_bond_directions(s1, want_dir) if want_dir != - dir2: a2.fix_open_bond_directions(s2, - want_dir) if 0 and debug_flags.atom_debug and \ (dir1 or dir2 or want_dir_a1 or want_dir_a2 or want_dir): print "bond at open bonds with directions, %r and %r, => %r" % \ (s1 and s1.bonds[0], s2 and s2.bonds[0], want_dir) pass bond = bond_atoms_faster(a1, a2, vnew) #bruce 050513 assert bond is not None if make_corrections: if s1 is not None: s1.singlet_reduce_valence_noupdate(vnew) if s2 is not None: s2.singlet_reduce_valence_noupdate(vnew) ###k # REVIEW: should we also zero their open-bond direction if it was # used above or will be used below? Not needed for now; might be # needed later if it affects update_valence somehow (seems unlikely) # or if directional bonds can ever be higher-order than single. # [bruce 071019] # Note [bruce 071019]: update_valence kills bondpoints with zero or # other illegal bond order, and replaces/moves all bondpoints if it also # decides to change the atomtype and can do so to one which matches # the number of existing bonds. This can be prevented by passing it # the new option dont_revise_valid_bondpoints (untested), but for # some uses of this function that would remove desirable behavior # so we can't do it. The code above to make sure atomtypes are set # should have the same effect when the atomtype doesn't need to # change in update_valence. ### UNTESTED for that purpose # # [bruce comment 050728: to fix bug 823, update_valence needs to # merge singlets to match atomtype; now it does] a1.update_valence() a2.update_valence() assert new_bond_is_directional == bond.is_directional() if bond.is_directional(): # Note: we do this now (after update_valence removed zero-valence # bondpoints, presumably including s1 and s2) to make sure # is_directional and the other code below won't be confused # by the bondpoints still being there. # If any open bond directions are unideal, the dna updater # (if active) will complain and might fix them (it knows to # preserve real bond directions like the one we're setting now). # [bruce 071019, 080213] bond.set_bond_direction_from( a1, want_dir) pass return bond def bond_v6(bond): """ Return bond.v6. Useful in map, filter, etc. """ return bond.v6 def bond_direction(atom1, atom2): #bruce 070601 """ The atoms must be bonded (assertion failure if not); return the bond_direction (-1, 0, or 1) of their bond (in the given order of atoms). """ bond = find_bond(atom1, atom2) assert bond, "the atoms %s and %s must be bonded" % (atom1, atom2) return bond.bond_direction_from(atom1) # == _changed_Bonds = {} # tracks all changes to Bonds: existence/liveness (maybe not needed), # which atoms, bond order # (for now, maps id(bond) -> bond, since a bond's atoms and .key can change) # # Note: we don't yet have any explicit way to kill or destroy a Bond, and # perhaps no Bond attrs change when a Bond is removed from its atoms (I'm # not sure, and it might depend on which code does it); for now, this is # ok, and it means those events needn't be tracked as changes to a Bond. # If a Bond is later given a destroy method, that should remove it from # this dict; If it has a kill or delete method (or one that's called when # it's not on its atoms), that should count as a change in this dict (and # perhaps it should also change its atom attrs). # #bruce 060322 for Undo change-tracking; the related global dict # global_model_changedicts.changed_bond_types should perhaps become a # subscriber (though as of 071107 there are several things that get into # _changed_Bonds but not into global_model_changedicts.changed_bond_types # -- should REVIEW the correctness of that) # # todo: see comments about similar dicts in chem.py for how this will end up ##being used register_changedict( _changed_Bonds, '_changed_Bonds', ()) ###k related attrs arg?? #bruce 060329 _Bond_global_dicts = [_changed_Bonds] # == class Bond(BondBase, StateMixin, Selobj_API): #bruce 041109 partial rewrite """ @warning: this docstring is partly obsolete. A Bond is essentially a record pointing to two atoms (either one of which might be a real atom or a "singlet"), representing a bond between them if it also occurs in atom.bonds for each atom. It should occur in both or neither of atom.bonds of its two atoms, except transiently. The two atoms in a bond should always be different objects. We don't support more than one bond between the same two atoms; trying to add the second one will do nothing, because of Bond.__eq__. We don't yet support double or triple bonds... but [bruce 050429 addendum] soon after Alpha 5 we'll start supporting those, and I'll start prototyping them right now -- DO NOT COMMIT until post-Alpha5. Bonds have a private member 'key' so they can be compared equal whenever they involve the same pair of atoms (in either order). Bonds sometimes store geometric info used to draw them; see the method setup_invalidate, which must be called when the atoms are changed in certain ways. Bonds don't store any selection state or display-mode state, and they record no info about the bonded molecules (but each bonded atom knows its molecule). Bonds are called "external" if they connect atoms in two different molecules, or "internal" if they connect two atoms in the same molecule. This affects what kind of info is invalidated by the private method invalidate_bonded_mols, which should be called by internal code whenever the bond is actually added to or removed from its atoms (or is probably about to be added or removed). Bonds can be removed from their atoms by Bond.bust, and then forgotten about (no need to kill or otherwise explicitly destroy them after they're not on their atoms). """ _selobj_colorsorter_safe = True #bruce 090311 pi_bond_obj = None #bruce 050718; used to memoize a perceived PiBondSpChain object (if # any) which covers this bond. sometimes I search for pi_bond_info when # I want this; see also get_pi_info and pi_info _s_undo_specialcase = UNDO_SPECIALCASE_BOND # This tells Undo what specialcase code to use for this class # (and any subclasses we might add). It also tells it which # changedicts to look at. # TODO: See comment near use of UNDO_SPECIALCASE_ATOM in class Atom. # [bruce 071114] _s_attr_pi_bond_obj = S_CACHE # see comments in pi_bond_sp_chain.py. _s_attr_v6 = S_DATA _s_attr__direction = S_DATA #bruce 070414 _s_attr_atom1 = S_PARENT # too bad these can change, or we might not need them (not sure, might # need them for saving a file... #k) _s_attr_atom2 = S_PARENT atom1 = atom2 = _valid_data = None # make sure these attrs always have values! _saved_geom = None _direction = 0 # default value of private (except known to Atom.writemmp) # instance variable for bond_direction [bruce 070414] # _direction is 0 for most bonds; for directional bonds # [###e term to be defined elsewhere] it will be 1 if atom1 comes first, # or -1 if atom2 comes first, or 0 if the direction is not known. # # I think no code destructively swaps the atoms in a bond; # if it ever does, it needs to invert self._direction too. # That goes for the process of mmp save/load as well, and # for copying of a bond (which *might* reverse the atoms) -- # write and read this info with care, since it's the first # time in NE1 that the order of a bond's atoms will matter. # # This is a private attr, since its meaning depends on atom # order; public access methods must be passed one of self's atoms, # so they can accept or return directions relative to that atom. # # For comments about how chains/rings of directional bonds might # best be perceived, for purposes of inferring directions or # warning about inconsistencies, see pi_bond_sp_chain.py's module # docstring. [bruce 070414] _s_attr_key = S_DATA #bruce 060405, not sure why this wasn't needed before (or if it will # help now) # (update 060407: I don't if it did help, but it still seems # needed in principle. It's change-tracked by self._changed_atoms.) # this default value is needed for repeated destroy [bruce 060322] glname = 0 def _undo_update(self): #bruce 060223 guess self._changed_atoms() # note: we don't set chunk flags _f_lost_externs or _f_gained_externs; # see comment where they are defined about why Bond._undo_update # needs to do that instead. [bruce 080702 comment] self._changed_v6() self._changed_bond_direction() #bruce 070415 # probably not needed, leave out at first: ## self.invalidate_bonded_mols() # don't call setup_invalidate, that needs calling by our Atom's # _undo_update methods ##k StateMixin._undo_update(self) return def __init__(self, at1, at2, v6 = V_SINGLE): """ create a bond from atom at1 to atom at2. the key created will be the same whichever order the atoms are given, and is used to compare bonds. [further comments by bruce 041029:] Private method (that is, creating of bond objects is private, for affected molecules and/or atoms). Note: the bond is not actually added to the atoms' molecules! Caller must do that. But [new feature 041109] we will do all necessary invalidations, in case the new bond is indeed added to those atoms (as I think it always will be in the current code). """ BondBase.__init__(self) self.atom1 = at1 self.atom2 = at2 # review: are atom1, atom2 public attributes? # For now I'll assume yes. [bruce 050502] self.v6 = v6 # bond-valence times 6, as exact int; a public attribute assert v6 in BOND_VALENCES self._changed_atoms() self.invalidate_bonded_mols() #bruce 041109 new feature if at1.molecule is not at2.molecule: at1.molecule._f_gained_externs = True at2.molecule._f_gained_externs = True self.glname = at1.molecule.assy.alloc_my_glselect_name( self) #bruce revised 080917 def _undo_aliveQ(self, archive): #bruce 060405, rewritten 060406 """ @see: docstring of L{Atom._undo_aliveQ}. @see: new_Bond_oursQ in undo_archive.py """ # There are two ways to reach a bond (one per atom), so return True if # either one would reach it, but also report an error if one would and # one would not. # note: I don't recall if a1 and a2 can ever be None, so be safe. a1 = self.atom1 a2 = self.atom2 res1 = a1 is not None and archive.trackedobj_liveQ(a1) and self in a1.bonds res2 = a2 is not None and archive.trackedobj_liveQ(a2) and self in a2.bonds if res1 != res2: print "bug: Bond._undo_aliveQ gets different answer on " \ "each atom; relevant data:", res1, res2, self return True # not sure if this or False would be safer; using True so # we're covered if any live atom refers to us return res1 def bond_direction_from(self, atom): #bruce 070414 """ Assume self is a directional bond (not checked); return its direction, starting from the given atom (which must be one of its atoms). This is 1 if the bond direction points away from that atom, -1 if it points towards it, and 0 if no direction has been set. """ if atom is self.atom1: return self._direction elif atom is self.atom2: return - self._direction else: assert 0, "%r.bond_direction_from(%r), but that bond " \ "doesn't have that atom" % (self, atom) return def bond_direction_vector(self): """ Return self's bond direction vector (in abs coords). """ return self._direction * (self.atom2.posn() - self.atom1.posn()) def spatial_direction_from(self, atom): #bruce 080405 """ Return the vector in absolute model coords from atom to self.other(atom). """ return self.other(atom).posn() - atom.posn() def set_bond_direction_from(self, atom, direction, propogate = False): """ Assume self is a directional bond (not checked); set its direction (from atom to the other atom) to the given direction. The given direction must be -1, 0, or 1 (not checked); atom must be one of self's atoms. (The direction from the other atom will be the negative of the direction from the given atom.) If propogate is True, call this recursively in both directions in a chain of directional bonds, stopping only when the chain ends or loops back to self. This will set an entire strand or ring of directional bonds to the same direction. """ old = self._direction if atom is self.atom1: self._direction = direction elif atom is self.atom2: self._direction = - direction else: assert 0, "%r.set_bond_direction_from(%r, %r), but that bond " \ "doesn't have that atom" % \ (self, atom, direction) if debug_flags.atom_debug: assert self.bond_direction_from(atom) == direction assert self.bond_direction_from(self.other(atom)) == - direction if old != self._direction: if 0 and debug_flags.atom_debug: print "fyi: changed direction of %r from %r to %r" % \ (self, old, self._direction) self._changed_bond_direction() if propogate: # propogate self's direction both ways, as far as possible, # overwriting any prior directions encountered (and do this even # if this bond's direction was already the same as the one we're # setting). (note: the direction being set here can be 0) (note: # if self can ever be a bond which *silently ignores* sets of # direction, then for the following to be correct, we'd need to # pass the initial direction to use, which would be an opposite # one to each call. Not doing that now makes direction-switching # bugs less likely or tests the default direction used by # propogate_bond_direction_towards.) ringQ = self.propogate_bond_direction_towards(self.atom1) if not ringQ: self.propogate_bond_direction_towards(self.atom2) return def clear_bond_direction(self): #bruce 070415; made public 080213 """ If self has a bond direction set, clear it. (Legal to call even if self is not a directional bond.) [public; does all needed invalidations] """ if self._direction: del self._direction # let default value (0) show through assert not self._direction self._changed_bond_direction() return def _changed_bond_direction(self): #bruce 070415, bugfixed 080210 """ [private method] Do whatever invalidations or change-notices are needed due to an internal change to self._direction. @see: _undo_update, which calls this, and the other self.changed*() methods. """ # For Undo, we only worry about changes to "definitive" (not derived) # state. That's only in self. Since Bonds use an optimized system for # changetracking, we have to store self in a dictionary. (This is more # efficient than calling atom._changed_structure on each of our atoms, # since that would make Undo scan more attributes.) _changed_Bonds[id(self)] = self # tells Undo that something in this bond has changed # Someday, doing that should also cover all modification notices to # model object containers that contain us, such as the file we're # saved in. It might already do that, but I'm not sure, so do that # explicitly: self.changed() # tell the dna updater we changed the structure of both our atoms. # (this is needed equally for internal and external bonds, # since it's not directly related to appearance.) # [doing this is a bugfix when dna updater is active [bruce 080210]] for atom in (self.atom1, self.atom2): atom._f_changed_some_bond_direction() # For appearance changes, we only need to worry about direction arrows # on self -- if the dna updater changes error codes (as far away as on # other atoms in the same base pair as one of ours, or for an entire # duplex we're in), it'll call changeapp() on its own. # [note: pre-080211 code was calling changeapp() on several atoms' # chunks here, but this is no longer needed (even if the dna updater # is not turned on) since only the dna updater can set direction error # indications in current code.] self._changed_bond_appearance() return def propogate_bond_direction_towards(self, atom): #bruce 070414 """ Copy the bond_direction on self (which must be a directional bond) onto all bonds in the same chain or ring of directional bonds in the direction (from self) of atom (which must be one of self's atoms). Stop when reaching self (in a ring) or the last bond in a chain. (Note that this means we *don't* change bonds *before* self in a chain, unless it's a ring; to change all bonds in a chain we have to be called twice.) Don't modify self's own direction. Do all necessary change-notification. Return ringQ, a boolean which is True if self is part of a ring (as opposed to a linear chain) of directional bonds. """ backdir = self.bond_direction_from(atom) # measured backwards, relative to direction in which we're propogating ringQ, listb, lista = grow_directional_bond_chain(self, atom) for b, a in zip(listb, lista): b.set_bond_direction_from(a, backdir) return ringQ def is_directional(self): #bruce 070415 """ Does self have the atomtypes that make it want to have a direction? (We assume this property is independent of bond order, so that changing self's bond order needn't update it.) Note: before 071015, open bonds never counted as directional, since that can lead to them getting directions which become illegal when something is deposited on them (like Ax), and can lead to an atom with three directional bonds but no errors (which confuses or needlessly complicates related algorithms). Update, bruce 071015: there is experimental code [by mark 071014] enabled by debug_pref, which means open bonds are sometimes directional. That code is likely to become the usual case soon. To make that code safe, either this method or its callers have to require that at most two bonds per atom are directional, for most purposes. For now, I'll assume the caller does this, so that one bond's is_directional value can't change except when its own elements change. Effectively this means there are lower and higher level concepts of a bond being directional, which can differ. For now, each caller implements the high-level case, but most or all of those are channelled through one caller, Atom.directional_bond_chain_status(). """ # maybe: this might be replaced with an auto-updated attribute, # self.directional if self.atom1.element.bonds_can_be_directional and \ self.atom2.element.bonds_can_be_directional: return True return False def mmprecord_bond_direction(self, atom, mapping): #bruce 070415 """ Return an mmp record line or lines (not including terminating \n) which identifies self (which has already been written into the mmp file, along with both its atoms, just after the given atom was written), and encodes the direction of self, using mapping (a writemmp_mapping object) to find atom codes. Note that this API makes no provision for writing one record to encode the direction of more than one bond at a time (e.g. an entire strand). However, the record format we're writing could support that, and the mmp reading code we're adding at the same time does support that. """ # We'll support a bond_direction record which only writes atoms in # bond_direction order. That way we needn't write out the direction # itself, and the record format permits encoding a bond-chain in one # record listing a chain of atomcodes (though we don't yet take # advantage of that when writing). other = self.other(atom) direction = self.bond_direction_from(atom) assert direction # otherwise we should not be writing this record #e (could extend API to let us return "" in this case) if direction < 0: atom, other = other, atom atomcodes = map( mapping.encode_atom, (atom, other) ) return "bond_direction " + " ".join(atomcodes) #- DNA helper functions. ------------------------------------------ def getDnaSegment(self): """ """ segment = None if self.is_open_bond(): return None atom1 = self.atom1 atom2 = self.atom2 for atom in (atom1, atom2): if atom.is_singlet(): continue segment = atom.getDnaSegment() if segment: return segment return segment def getDnaStrand(self): """ Return the parent DnaStrand of the bond if its a strand bond. Returns None otherwise. """ if not self.isStrandBond(): return None chunk = self.atom1.molecule #Assume that there is no DNA updater error, so, the chunk of self.atom2 #has the same strand as the one for chunk of atom1. if chunk and not chunk.isNullChunk(): return chunk.getDnaStrand() return None def getStrandName(self): # probably by Mark """ Return the strand name, which is this bond's chunk name. @return: The strand name, or a null string if the two atoms of this bond belong to two different chunks. @rtype: str @see: L{setStrandName} @see: Atom.getDnaStrandId_for_generators @see:SelectAtoms_GraphicsMode.bondDelete """ # Note: used only in SelectAtoms_GraphicsMode.bondDelete, # for a history message, as of before 080225. # See also: Atom.getDnaStrandId_for_generators. # [bruce 080225 comment] strand = self.getDnaStrand() if strand: return strand.name return "" def isStrandBond(self): # by Mark # Note: still used as of 080225. Not quite correct # for bonds on free-floating single strands -- probably # it ought to check whether a direction is set. ###FIX # [bruce 080225 comment] """ Checks if this bond is a DNA (backbone) bond. @return: True if this bond is a DNA (backbone) bond. Otherwise, returns False. @note: This function is identical to L{is_directional} and is provided for convenience. """ return self.is_directional() def isThreePrimeOpenBond(self): # by Mark """ Checks if this is a 3' open bond. @return: True if this is a 3' open bond. Otherwise, returns False. """ if self.isStrandBond(): for atom in (self.atom1, self.atom2): if atom.is_singlet(): direction = self.bond_direction_from(atom) if direction == -1: return True return False def isFivePrimeOpenBond(self): # by Mark """ Returns True if this is a 5' open bond. """ if self.isStrandBond(): for atom in (self.atom1, self.atom2): if atom.is_singlet(): direction = self.bond_direction_from(atom) if direction == 1: return True return False def _dna_updater_error_tooltip_info(self): #bruce 080206 """ [private helper for getToolTipInfo] Return a string to be used in self.getToolTipInfo which describes dna updater errors on self's atoms if those exist (perhaps containing internal newlines). In the usual case, there are no such errors and we return "". """ ### BUG: doesn't show anything for whole-duplex errors, # though atom.dna_updater_error_string() does. @@@@@ # not optimized for the common case -- doesn't matter, ok to be slow res = "" add_labelled_error_strings = False atom1_error = self.atom1._dna_updater__error atom2_error = self.atom2._dna_updater__error # REVIEW: compare and show atom.dna_updater_error_string() # instead? (several places) More likely, that's not right when # this is a rung bond (both atoms in same basepair) and one has a # propogated error and one has a direct error, so we'll need # fancier code which notices propogated errors. if (atom1_error and atom2_error): if (atom1_error == atom2_error): res = "[%s]" % (atom2_error,) else: res = "[dna updater error on both atoms]" add_labelled_error_strings = True elif (atom1_error or atom2_error): res = "[dna updater error on one atom]" add_labelled_error_strings = True if add_labelled_error_strings: for atom in (self.atom1, self.atom2): if atom._dna_updater__error: res += "\n" + "[ %s: %s]" % \ (str(atom), atom._dna_updater__error) return res #- end of DNA bond helper functions ---------------------------- def getToolTipInfo(self, isBondChunkInfo, isBondLength, atomDistPrecision): """ Returns a string that has bond related info, for use in Dynamic Tool Tip """ bondInfoStr = "" bondInfoStr += quote_html(str(self)) # might be extended below dna_error = self._dna_updater_error_tooltip_info() #bruce 080206 if dna_error: bondInfoStr += "<br>" + dna_error else: strand = self.getDnaStrand() segment = self.getDnaSegment() if strand: bondInfoStr += "<br>" + strand.getToolTipInfoForBond(self) elif segment: bondInfoStr += "<br>" + segment.getDefaultToolTipInfo() # check for user pref 'bond_chunk_info' if isBondChunkInfo: bondChunkInfo = self.getBondChunkInfo() bondInfoStr += "<br>" + bondChunkInfo #check for user pref 'bond length' if isBondLength: bondLength = self.getBondLength(atomDistPrecision) bondInfoStr += "<br>" + bondLength #ninad060823 don't use "<br>" ..it is weird. doesn't break # into a new line. perhaps because I am not using html stuff in # getBondLength etc functions?? return bondInfoStr def getBondChunkInfo(self): #Ninad 060830 """ Returns chunk information of the atoms forming a bond. Returns none if Bond chunk user pref is unchecked. It uses some code of bonded_atoms_summary method. """ a1 = self.atom1 a2 = self.atom2 chunk1 = a1.molecule.name chunk2 = a2.molecule.name #ninad060822 I am not checking if chunk 1 and 2 are the same. #I think it's not needed as the tooltip string won't be compact #even if it is implemented. so leaving it as is bondChunkInfo = str(a1) + " in [" + \ str(chunk1) + "]<br>" + \ str(a2) + " in [" + str(chunk2) + "]" return bondChunkInfo def getBondLength(self, atomDistPrecision):#Ninad 060830 ### TODO: RENAME """ Returns a string describing the distance between the centers of atoms, bonded by the highlighted bond. @param atomDistPrecision: Number of digits after the decimals. (atom distance precision) to be included in the string that returns the distance @type atomDistPrecision: int @return the string that gives bond length information. @note: this does *not* return the covalent bondlength. """ a1 = self.atom1 a2 = self.atom2 nuclearDist = str(round(vlen(a1.posn() - a2.posn()), atomDistPrecision)) bondLength = "Distance " + str(a1) + "-" + str(a2) + ": " + \ nuclearDist + " A" return bondLength # == def destroy(self): #bruce 060322 (not yet called) ###@@@ """ @see: comments in L{Atom.destroy} docstring. """ if self.glname: #bruce 080917 revised this entire 'if' statement # (never tested, before or after, since routine not yet used) if self.at1 and self.at1.molecule and self.at1.molecule.assy: self.at1.molecule.assy.dealloc_my_glselect_name( self, self.glname ) else: msg = "bug: can't find assy for dealloc_my_glselect_name in " \ "%r.destroy()" % self print msg del self.glname try: self.bust() #bruce 080702 precaution except: # FIX: ignoring this exception is necessary for repeated destroy, # given current implem -- should fix (TODO) pass if self._direction: self._changed_bond_direction() #bruce 070415 key = id(self) for dict1 in _Bond_global_dicts: dict1.pop(key, None) if self.pi_bond_obj is not None: self.pi_bond_obj.destroy() ###k is this safe, if that obj and ones its knows are destroyed? ##e is this also needed in self._changed_atoms or _changed_v6??? # see if bond orientation bugs are helped by that... ###@@@ [bruce 060322 comments] self.__dict__.clear() ###k is this safe??? [see comments in # Atom.destroy implem for ways we might change this ##e] return def is_open_bond(self): #bruce 050727 return self.atom1.element is Singlet or self.atom2.element is Singlet def set_v6(self, v6): #bruce 050717 revision: only call _changed_v6 when needed """ #doc; can't be used for illegal valences, as some of our actual setters need to do... """ assert v6 in BOND_VALENCES if self.v6 != v6: self.v6 = v6 self._changed_v6() return def reduce_valence_noupdate(self, vdelta, permit_illegal_valence = False): # option permits in-between, 0, or negative(?) valence """ Decrease this bond's valence by at most vdelta (which must be nonnegative), but always to a supported value in BOND_VALENCES (unless permit_illegal_valence is true). @return: the actual amount of decrease (maybe 0; in the same scale as BOND_VALENCES). When permit_illegal_valence is true, any valence can be reached, even one which is lower than any permitted valence, zero, or negative (###k not sure that's good, or ever tried). [The starting valence (self.v6) need not be a legal one(??); but by default the final valence must be legal; not sure what should happen if no delta in [0, vdelta] makes it legal! For now, raise an AssertionError(?) exception then. ###@@@] """ # we want the lowest permitted valence which is at least v_have - # vdelta, i.e. in the range v_want to v_have. This code is very # similar to that of increase_valence_noupdate, but differs in a few # important places! assert vdelta >= 0 v_have = self.v6 v_want = v_have - vdelta if not permit_illegal_valence: # make v_want legal (or raise exception if that's not possible) did_break = else_reached = 0 for v_to_try in BOND_VALENCES: # this list is in lowest-to-highest order if v_want <= v_to_try <= v_have: # warning: order of comparison will differ in the sister # method for "increase" v_want = v_to_try # good thing we'll break now, since this # assignment alters the meaning of the loop-test did_break = 1 break else: else_reached = 1 if debug_flags.atom_debug: print "debug: else clause reached" # i don't know python's rules about this; # it might relate to #iters == 0 if debug_flags.atom_debug: if not (did_break != else_reached): # this is what I hope it means (whether we fell out the # end or not) but fear it doesn't print "debug: hoped for did_break != else_reached, but not true" if not did_break: # no valence is legal! Not yet sure what to do in this case. # (Or whether it ever happens.) assert 0, "no valence reduction of %r from 0 to " \ " vdelta %r is legal!" % (v_have, vdelta) assert v_want in BOND_VALENCES # sanity check # now set valence to v_want if v_want != v_have: self.v6 = v_want self._changed_v6() return v_have - v_want # return actual decrease # (WARNING: order of subtraction will differ in sister method) def increase_valence_noupdate(self, vdelta, permit_illegal_valence = False #k is that option needed? ): """ Increase this bond's valence by at most vdelta (which must be nonnegative), but always to a supported value in BOND_VALENCES (unless permit_illegal_valence is true); return the actual amount of increase (maybe 0; in the same scale as BOND_VALENCES). When permit_illegal_valence is true, any valence can be reached, even one which is higher than any permitted valence (###k not sure that's good, or ever tried). [The starting valence (self.v6) need not be a legal one(??); but by default the final valence must be legal; not sure what should happen if no delta in [0, vdelta] makes it legal! For now, raise an AssertionError(?) exception then. ###@@@] """ # we want the highest permitted valence which is at most v_have + # vdelta, i.e. in the range v_have to v_want. This code is very # similar to that of reduce_valence_noupdate but several things are # reversed. assert vdelta >= 0 v_have = self.v6 v_want = v_have + vdelta if not permit_illegal_valence: # make v_want legal (or raise exception if that's not possible) did_break = else_reached = 0 for v_to_try in BOND_VALENCES_HIGHEST_FIRST: # note: this list is in highest-to-lowest order, unlike BOND_VALENCES if v_have <= v_to_try <= v_want: # WARNING: order of comparison differs in sister method v_want = v_to_try # good thing we'll break now, since this # assignment alters the meaning of the loop-test did_break = 1 break else: else_reached = 1 if debug_flags.atom_debug: print "atom_debug: else reached in increase_valence_noupdate" if debug_flags.atom_debug: if not (did_break != else_reached): print "atom_debug: i hoped for did_break != else_reached " \ "but it's not true, in increase_valence_noupdate" if not did_break: # no valence is legal! Not yet sure what to do in this case. # (Or whether it ever happens.) assert 0, "no valence increase of %r from 0 to vdelta %r " \ "is legal!" % (v_have, vdelta) assert v_want in BOND_VALENCES # sanity check # now set valence to v_want if v_want != v_have: self.v6 = v_want if debug_1951: print "debug_1951: increase_valence_noupdate changes " \ "%r.v6 from %r to %r, returns %r" % \ (self, v_have, v_want, v_want - v_have) self._changed_v6() return v_want - v_have # return actual increase # (WARNING: order of subtraction differs in sister method) def _changed_v6(self): #bruce 080702 renamed changed_valence -> _changed_v6 """ [private method] This should be called whenever this bond's v6 (bond order code) is changed (whether to a legal or (presumably temporary) illegal value). It does whatever invalidations that requires, but does no "updates". """ ###e update geometric things, using setup_invalidate?? ###@@@ self.setup_invalidate() # not sure this is needed, but let's do it to # make sure it's safe if/when it's needed [bruce 050502] # as of 060324, it's needed, since sim.getEquilibriumDistanceForBond # depends on it # tell the atoms we're doing this self.atom1._modified_valence = self.atom2._modified_valence = True # (this uses a private attr of class atom; might be revised) self._changed_bond_and_atom_appearances() # Fix for bug 886 [bruce 050811, revised 080210]: # Both atoms might look different if whether they have valence # errors changes (re bug 886), so if valence errors are presently # being displayed, invalidate both of their display lists. # # If valence errors are not being displayed, I think we don't have # to inval either display list for an external bond (though we do # for an internal bond), but I'm not sure, so to be safe for A6, # just do it regardless. # # Potential optim: check whether presence of valence error actually # changes, for each atom; if not, or if they are not being shown # (due to pref not set or chunk or atom display style or hidden # chunk), just call _changed_bond_appearance instead. # (But it often does change, and is or ought to be shown, # so nevermind for now.) global_model_changedicts.changed_bond_types[id(self)] = self _changed_Bonds[id(self)] = self #bruce 060322 (covers changes to self.v6) return def _changed_bond_appearance(self): #bruce 080210 """ [private] Self's appearance might have changed, but not necessarily that of its atoms. Do necessary invals of chunk and/or ExternalBondSet display lists. """ mol1 = self.atom1.molecule mol2 = self.atom2.molecule if mol1 is mol2: # internal bond: we're in our chunk's display list, # so it needs to know we'll look different when redrawn mol1.changeapp(0) else: # external bond mol1.invalidate_ExternalBondSet_display_for( mol2) # note: both of those do gl_update if needed # older note: _changed_bond_and_atom_appearances is an alias # for this method -- that will need revision for ExternalBondSet. ### REVIEW: is that really true? I don't see why. Ah. maybe for # external bonds, we also need to call both changeapps... my guess is # we already do (since we only added calls to this method for them now, # we didn't remove any changeapps when adding it and they would # already have been needed), but analyze this sometime. [bruce 090213] return def _changed_atom_appearances(self): #bruce 080210 split this out """ [private] A change to self means that self's atoms' appearances may have changed. Do necessary invals of chunk display lists. """ # assume changeapp is fast, so don't bother checking # whether this calls it twice on the same chunk self.atom1.molecule.changeapp(0) self.atom2.molecule.changeapp(0) return _changed_bond_and_atom_appearances = _changed_atom_appearances #bruce 080210 def changed(self): #bruce 050719 """ Mark this bond's atoms (and thus their chunks, part, and mmp file) as changed. (As of 050719, only the file (actually the assy object) records this fact.) """ self.atom1.changed() self.atom2.changed() # for now, only the file (assy) records this, so # 2nd call is redundant, but someday that will change. return def numeric_valence(self): # note: this method has a long name so you won't be tempted to use it # when you should use .v6 ###@@@ not yet used? return self.v6 / 6.0 def _changed_atoms(self): """ Private method to call when the atoms assigned to this bond are changed. @warning: does not call setup_invalidate(), though that would often also be needed, as would invalidate_bonded_mols() both before and after the change. """ _changed_Bonds[id(self)] = self # covers changes to atoms, and __init__ at1 = self.atom1 at2 = self.atom2 at1._changed_structure() #bruce 050725 at2._changed_structure() assert at1 is not at2 # This version of bond_key helps atombase.c not to fail when atom keys # exceed 32768, but is only unique for bonds attached to the # same atom. Within __eq__, it can only be considered a hash. # WARNING: as of 080402, __eq__ assumes this is the formula. self.bond_key = at1.key + at2.key #bruce 050317: debug warning for interpart bonds, or bonding killed # atoms/chunks, or bonding to chunks not yet added to any Part (but not # warning about internal bonds, since mol.copy makes those before a # copied chunk is added to any Part). # # This covers new bonds (no matter how made) and the .rebond method. # # Maybe this should be an actual error, or maybe it should set a flag # so that involved chunks are checked for interpart bonds when the # user event is done (in case caller plans to move the chunks into the # same part, but hasn't yet). It might turn out this happens a lot # (and is not a bug), if callers make a new chunk, bond to it, and # only then add it into the tree of Nodes. if debug_flags.atom_debug and at1.molecule is not at2.molecule: msg = "" if (at1.molecule.assy is None) or (at2.molecule.assy is None): msg = "bug?: bonding to a killed chunk(?); " \ "atoms are: %r, %r" % (at1, at2) elif (at1.molecule.part is None) or (at2.molecule.part is None): if 0: # this happens a lot when reading an mmp file, # so disable it for now [bruce 050321] msg = "bug or fyi: one or both Parts None when " \ "bonding atoms: %r, %r" % (at1, at2) elif at1.molecule.part is not at2.molecule.part: msg = "likely bug: bonding atoms whose parts differ: " \ "%r, %r" % (at1, at2) if msg: print_compact_stack("atom_debug: " + msg + ": ") if self._direction and not self.is_directional(): #bruce 070415 self.clear_bond_direction() #bruce 080404 new feature: # newly made bondpoints should be repositioned by dna updater. # # Notes / caveats / bugs: # # - ideally this would be generalized (to let atomtype decide whether # and how to handle this). # # - the tests are thought to be in optimal order, but could be optimized # more if the atomtype or element had better flags. # # - in theory we should do this for all monovalent elements, not just # Singlet. In practice it doesn't matter, and there is not yet a flag # for that, and len(atom.bonds) might not yet be up to date if atom # is still being constructed. I guess atomtype.valence could be used. # # - in theory we should *not* do this for atoms being read from an mmp # file (or any other trusted source of already-made structure, like # when copying a partlib part or anything else), at least if this new # bond is also read from that file or copied from that same source. # In practice this would require a new argument flag (or the callers # unsetting _f_dna_updater_should_reposition_baggage themselves -- # easy if we find them all, but a kluge), and worse, there are a lot # of mmp files with incorrect bondpoint positions that we ought to # fix! Nonetheless, except for that, it's a bug to do it then. If this # is an issue, we'll fix the callers to unset this flag on the atoms # that were just read or copied, unless they made their own bondpoints # on them, or before they do so. # # - if for some reason the updater does not see this flag (probably # only possible if the new bondpoint is later removed from the atom # we set it on before it runs), no harm should be caused, even if # it sees it much later on the same atom, since that only happens # if the atom shows up at a ladder-end, and since it will verify # it still has bondpoints before "fixing them", and if it got new # ones then, that would have readded the same flag anyway. It does # mean that turning on the updater after making an atom and manually # moving its bondpoints would make it "correct" the manual moves, # but that's ok since having the dna updater off is not supported. # # - what we do here is only sufficient because we know # _changed_structure() is always called above on both atoms. # if at2.element.pam and \ at1.element is Singlet and \ at2.element.role in ('strand', 'axis'): at2._f_dna_updater_should_reposition_baggage = True if at1.element.pam and \ at2.element is Singlet and \ at1.element.role in ('strand', 'axis'): at1._f_dna_updater_should_reposition_baggage = True return def invalidate_bonded_mols(self): #bruce 041109, revised 090211 """ Mostly-private method (also called from methods in our atoms), to be called when a bond is made or destroyed; knows which kinds of bonds are put into chunk display lists and/or into chunk.externs, though this knowledge should ideally be private to class Chunk. @note: we don't set the chunk flags _f_lost_externs and _f_gained_externs (on our atoms' chunks) if we're an external bond; caller must do this if desired. """ # assume mols are not None (they might be _nullMol, that's ok); # if they are, we'll detect the error with exceptions in either case below mol1 = self.atom1.molecule mol2 = self.atom2.molecule if mol1 is not mol2: # external bond mol1.invalidate_attr('externs') mol2.invalidate_attr('externs') # note: we don't also set these flags: ## mol1._f_lost_externs = mol1._f_gained_externs = True ## mol2._f_lost_externs = mol2._f_gained_externs = True # since some callers want to optimize that away (rebond) # and others do it themselves, perhaps in an optimized # manner (e.g. __init__). [bruce 080702 comment] # note: assume no need to invalidate appearance of ExternalBondSet # between mol1 and mol2, since they should detect that themselves # due to caller setting _f_gained_externs or _f_lost_externs # if needed. [bruce 090211 comment] #### REVIEW/TEST, is that correct? else: # internal bond mol1.invalidate_internal_bonds_display() return # == def setup_invalidate(self): # revised 050516 """ Semi-private method for bonds -- used by code in Bond, atom and chunk classes. Invalidates cached geometric values related to drawing the bond. This must be called whenever the position or element of either bonded atom is changed, or when either atom's molecule changes if this affects whether it's an external bond (since the coordinate system used for drawing is different in each case), UNLESS either bonded chunk's _invalidate_all_bonds() methods is called (which increment a counter checked by our __getattr__). (FYI: It need not be called for other changes that might affect bond appearance, like disp or color of bonded molecules, though for internal bonds, something should call invalidate_internal_bonds_display (a chunk method) when those things change.) (It's not yet clear whether this needs to be called when bond-valence is changed. If it does, that will be done from one place, the _changed_v6() method. [bruce 050502]) Note that before the "inval/update" revisions [bruce 041104], self.setup() (the old name for this method, from point of view of callers) did the recomputation now done on demand by __setup_update; now this method only does the invalidation which makes sure that recomputation will happen when it's needed. """ self._valid_data = None # For internal bonds, or bonds that used to be internal, callers # need to call invalidate_internal_bonds_display on affected mols, # but the changes in atoms that required them to call setup_invalidate # mean they should have done that anyway (except for bond making and # breaking, in this file, which does this in invalidate_bonded_mols). # Bruce 041207 scanned all callers and concluded they do this as needed, # so I'm removing the explicit resets of havelist here, which were often # more than needed since they hit both mols of external bonds. # This change might speed up some redraws, esp. in move or deposit modes. # update, bruce 090211: ### REVIEW -- still true? # new feature, bruce 080214: atom1 = self.atom1 if atom1._f_checks_neighbor_geom and atom1._f_valid_neighbor_geom: atom1._f_invalidate_neighbor_geom() atom2 = self.atom2 if atom2._f_checks_neighbor_geom and atom2._f_valid_neighbor_geom: atom2._f_invalidate_neighbor_geom() # new feature, bruce 090211: mol1 = atom1.molecule mol2 = atom2.molecule if mol1 is not mol2: # external bond -- invalidate the appropriate ExternalBondSet # (review/profile: should we optim by storing a pointer on self?) mol1.invalidate_ExternalBondSet_display_for( mol2) return def bond_to_abs_coords_quat(self): #bruce 050722 """ Return a quat which can be used (via .rot) to rotate vectors from this bond's drawing coords into absolute coords. (There is no method abs_to_bond_coords_quat which goes the other way -- just use .unrot for that.) @note: as of 050722, this is identity for external bonds, and chunk.quat for internal bonds. """ atom1 = self.atom1 atom2 = self.atom2 if atom1.molecule is not atom2.molecule: return Q(1,0,0,0) return atom1.molecule.quat def _recompute_geom(self, abs_coords = False): """ [private method meant for our __getattr__ method, and for writepov, but also called as "friend method" from draw_bond_main in another file] Recompute and return (but don't store) the 6-tuple (a1pos, c1, center, c2, a2pos, toolong), which describes this bond's geometry, useful for drawing (OpenGL or writepov) and for self.ubp(). If abs_coords is true, always use absolute coords; otherwise, use them only for external bonds, and for internal bonds (i.e. between atoms in the same mol) use mol-relative coords. """ #bruce 050516 made this from __setup_update atom1 = self.atom1 atom2 = self.atom2 if abs_coords or (atom1.molecule is not atom2.molecule): # external bond; use absolute positions for all attributes. a1pos = atom1.posn() a2pos = atom2.posn() else: # internal bond; use mol-relative positions for all attributes. # Note [bruce 041115]: this means any change to mol's coordinate system # (basecenter and quat) requires calling setup_invalidate # in this bond! That's a pain (and inefficient), so I might # replace it by a __getattr__ mol-coordsys-version-number check... # [and sometime after that, before 050719, I did.] a1pos = atom1.baseposn() a2pos = atom2.baseposn() # note: could optim, since their calcs of whether basepos is # present are the same return self.geom_from_posns(a1pos, a2pos) def geom_from_posns(self, a1pos, a2pos): #bruce 050727 split this out """ Return a geometry tuple from the given atom positions (ignoring our actual atom positions but using our actual atomtypes/bondtype). Correct for either absolute or mol-relative positions (return value will be in same coordinate system as arg positions). """ vec = a2pos - a1pos leng = 0.98 * vlen(vec) # 0.98 makes it a bit less common that # we set toolong below [bruce 050516 comment] vec = norm(vec) #e possible optim, don't know if it matters: # norm could be inlined, since we already have vlen; # but what would really be faster (I suspect) is to compute these # bond params for all internal bonds in an entire chunk at once, # using Numeric. ###@@@ [bruce 050516] # (note: as of 041217 rcovalent is always a number; it's 0.0 for # Helium, etc, so for nonsense bonds like He-He the entire bond is # drawn as if "too long".) ## rcov1 = self.atom1.atomtype.rcovalent ## rcov2 = self.atom2.atomtype.rcovalent rcov1, rcov2 = bond_params(self.atom1.atomtype, self.atom2.atomtype, self.v6) #bruce 060324 experiment re bug 900 c1 = a1pos + vec * rcov1 c2 = a2pos - vec * rcov2 toolong = (leng > rcov1 + rcov2) center = (c1 + c2) / 2.0 # before 041112 this was None when toolong return a1pos, c1, center, c2, a2pos, toolong def __getattr__(self, attr): # Bond.__getattr__ """ Return attributes related to bond geometry, recomputing them if they are not stored or if the stored ones are no longer valid. For all other attr names, raise an AttributeError (quickly, for __xxx__ names). """ #bruce 041104; totally revised 050516 try: return BondBase.__getattr__(self, attr) except AttributeError: pass if attr[0] == '_': raise AttributeError, attr # be fast since probably common for __xxx__ # after this, attr is either an updated_attr or a bug, so it's ok to # assume we need to recompute if invalid... if any of the attrs used # by recomputing geom are missing, we'll get infinite recursion; these # are just atom1, atom2, and the ones used herein. current_data = (self.atom1.molecule._f_bond_inval_count, self.atom2.molecule._f_bond_inval_count) if self._valid_data != current_data: # need to recompute # (note: to inval this bond alone, set self._valid_data = None; # this is required if you change anything used by _recompute_geom, # unless you change _f_bond_inval_count for one of the bonded # chunks.) self._valid_data = current_data # do this first, even if exception in _recompute_geom() self._saved_geom = geom = self._recompute_geom() else: geom = self._saved_geom # when valid, should always have been computed, thus be of # proper length if attr == 'geom': # note: callers desiring speed should use this case, to get # several attrs but only check validity once return geom elif attr == 'a1pos': return geom[0] elif attr == 'c1': return geom[1] elif attr == 'center': return geom[2] elif attr == 'c2': return geom[3] elif attr == 'a2pos': return geom[4] elif attr == 'toolong': return geom[5] elif attr == 'axis': # [bruce 050719 new feature] # a2pos - a1pos (not normalized); in relative coords return geom[4] - geom[0] else: raise AttributeError, attr pass # == def get_pi_info(self, **kws): #bruce 050718 """ Return the pi orbital orientation/occupancy info for this bond, if any [#doc the format], or None if this is a single bond (which is not always a bug, e.g. in -C#C- chains, if we someday extend the subrs this calls to do any bond inference -- presently they just trust the existing bond order, self.v6). This info might be computed, and perhaps stored, or stored info might be used. It has to be computed all at once for all pi bonds in a chain connected by sp atoms with 2 bonds. If computed, and if it's partly arbitrary, **kws (out/up) might be used. """ if debug_flags.atom_debug: import model.pi_bond_sp_chain as pi_bond_sp_chain reload_once_per_event(pi_bond_sp_chain) from model.pi_bond_sp_chain import bond_get_pi_info return bond_get_pi_info(self, **kws) # no need to pass an index -- that method can find one on self if # it stored one def potential_pi_bond(self): #bruce 050718 """ Given our atomtypes, are we a potential pi bond? """ return (self.atom1.atomtype.potential_pi_bond() and self.atom2.atomtype.potential_pi_bond()) # == def other(self, atom): """ Given one atom the bond is connected to, return the other one """ if self.atom1 is atom: return self.atom2 assert self.atom2 is atom #bruce 041029 return self.atom1 def other_chunk(self, mol): #bruce 041123; revised and first used, 080702 """ Given the chunk of one atom of this bond, return the chunk of the other atom. Error if chunk is not one of our atoms' cnunks. @note: if self is an internal bond in chunk1, our specification implies that mol must be chunk1 and we always return chunk1. """ c1 = self.atom1.molecule c2 = self.atom2.molecule if mol is c1: return c2 elif mol is c2: return c1 else: assert mol in (c1, c2) # this always fails (so it's ok if it's slow) -- # it's just our "understandable error message" pass def ubp(self, atom): """ unbond point (atom must be one of the bond's atoms) [Note: this is used to make replacement singlets in atom.unbond and atom.kill methods, even if they'll be discarded right away as all atoms in some big chunk are killed 1 by 1.] """ #bruce 041115 bugfixed this for when mol.quat is not 1, # tho i never looked for or saw an effect from the bug in that case if atom is self.atom1: point = self.c1 # this might call self.__setup_update() else: assert atom is self.atom2 point = self.c2 # now figure out what coord system that's in if self.atom1.molecule is not self.atom2.molecule: return point else: # convert to absolute position for caller # (note: this never recomputes basepos/atpos or modifies the mol- # relative coordinate system) return self.atom1.molecule.base_to_abs(point) pass def bust(self, make_bondpoints = True): #bruce 080701 cleaned up comments """ Destroy this bond, modifying the bonded atoms as needed, and invalidating the bonded molecules as needed. If either bonded atom is a singlet, kill that atom. @param make_bondpoints: if true (the default), add singlets on this bond's atoms in its place (unless prevented by various conditions). Note that the added singlets might overlap in space. @return: the added singlets, as a 2-tuple (with None in place of a singlet if no singlet was added for that atom). The order is: added singlet for self.atom1 (if any), then added singlet for self.atom2 (if any). @rtype: 2-tuple, of atom or None. @note: This method is named 'bust' since 'break' is a python keyword. @note: as of 041115 bust is never called with either atom a singlet. If it ever is, retval remains a 2-tuple but has None in 1 or both places ... precise effect needs review in that case. """ atom1 = self.atom1 atom2 = self.atom2 if atom1.molecule is not atom2.molecule: # external bond -- warn our chunks they're losing us [bruce 080701] atom1.molecule._f_lost_externs = True atom2.molecule._f_lost_externs = True # note: the following unbond calls might: # - copy self's bond direction onto newly created open bonds [review: really?] # - kill singlets left with no bonds x1 = atom1.unbond(self, make_bondpoint = make_bondpoints) x2 = atom2.unbond(self, make_bondpoint = make_bondpoints) # note: Atom.unbond does all needed invals # REVIEW: change our atoms and key to None, for safety? # check all callers and decide -- in case some callers # reuse the bond or for some reason still need its atoms. return x1, x2 def rebond(self, old, new): """ Self is a bond between old (typically a Singlet, or a Pl5 being discarded during PAM3+5 conversion) and some atom A; replace old with new in this same bond (self), so that old no longer bonds to A but new does. The bond-valence of self is not used or changed, even if it would be incorrect for the new atomtypes used in the bond. The bond_direction of self (if any) is cleared if new.element does not permit it, and is retained otherwise. Unlike some other bonding methods, the number of bonds on new increases by 1, since no singlet on new is removed -- new is intended to be a just-created atom, not one with the right number of existing bonds. If old is a singlet, then kill it since it now has no bonds. Otherwise, *don't* add a new bondpoint to it [new behavior 080312]. Do the necessary invalidations in self and all involved molecules. Warning: this can make a duplicate of an existing bond (so that atoms A and B are connected by two equal copies of a bond). That situation is an error, not supported by the code as of 041203, and is drawn exactly as if it was a single bond. Avoiding this is entirely up to the caller. """ # [bruce 041109 added docstring and rewrote Josh's code:] # Josh said: intended for use on singlets, other uses may have bugs. # bruce 041109: I think that means "old" is intended to be a singlet. # I will try to make it safe for any atoms, and do all needed invals. def _inval_externs( old, new, other): #bruce 080701, maybe untested """ [local helper function] We're moving a bond from old to new, always bonded to other. If it was or becomes external, do appropriate invals. """ if old.molecule is not new.molecule: # guess: this condition is rarely satisfied; optim for it failing. # REVIEW: is .molecule ever None or not yet correct at # this point? BUG IF SO. if old.molecule is not other.molecule: old.molecule._f_lost_externs = True other.molecule._f_lost_externs = True if new.molecule is not other.molecule: new.molecule._f_gained_externs = True other.molecule._f_gained_externs = True return # from local helper function if self.atom1 is old: _inval_externs( old, new, self.atom2) old.unbond(self, make_bondpoint = False) # (make_bondpoint = False added by bruce 080312) # also kills old if it's a singlet self.atom1 = new elif self.atom2 is old: _inval_externs( old, new, self.atom1) old.unbond(self, make_bondpoint = False) self.atom2 = new else: print "fyi: bug: rebond: %r doesn't contain atom %r to replace " \ "with atom %r" % (self, old, new) # no changes in the structure return # bruce 041109 worries slightly about order of the following: # invalidate this bond itself self._changed_atoms() self.setup_invalidate() # add this bond to new (it's already on A, i.e. in the list A.bonds) new.bonds.append(self) #e put this in some private method on new, new.add_new_bond(self)?? # Note that it's intended to increase number of bonds on new, # not to zap a singlet already bonded to new. # Invalidate molecules (of both our atoms) as needed, due to our existence self.invalidate_bonded_mols() #bruce 050728: this is needed so depositmode (in # atom.make_enough_bondpoints) can depend on bond.get_pi_info() being # up to date: if self.pi_bond_obj is not None: self.pi_bond_obj.destroy() ###e someday this might be more incremental if that obj # provides a method for it; or we could call _changed_structure # on the two atoms of self, like bond updating code will do upon # next redraw. if 1: # This debug code helped catch bug 232, but seems useful in general: # warn if this bond is a duplicate of an existing bond on A or new. # (Usually it will have the same count on each atom, but other bugs # could make that false, so we check both.) [bruce 041203] A = self.other(new) if A.bonds.count(self) > 1: print "rebond bug (%r): A.bonds.count(self) == %r" % \ (self, A.bonds.count(self)) if new.bonds.count(self) > 1: print "rebond bug (%r): new.bonds.count(self) == %r" % \ (self, new.bonds.count(self)) return # == #bruce 080402 revised __eq__ and removed clearly obsolete portions of the # following comments [not sure whether remaining ones are also obs]: # #bruce 050513 comment: we should seriously consider removing these # __eq__/__ne__ methods and revising bond_atoms accordingly (as an optim). # One use of them is probably in a .count method in another file. # #bruce 060209 comment: these now override different defs in UndoStateMixin. # This is wrong in theory (since the undo system assumes those defs will be # used), but I can't yet think of bugs it will cause, and it's probably also # still necessary due to how the atom-bonding code works. Wait, I bet the # debug print in here would print if it could ever make a difference, which # means, I could probably take them out... ok, I'll try that soon, but not # exactly now. def __eq__(self, obj): """ Are self and obj Bonds between the same pair of atoms? (If so, return True, without comparing anything else, like .v6.) """ #bruce 080402 revised this to remove false positives # for bonds not on the same atom. # # Note: known calls of this method include: # - items.sort() in glpane where items includes selobj candidates # (before a bugfix earlier on 080402 to work around the bug # being fixed now) # - I suspect this happens when asking "bond in atom.bonds" # when making a new bond [bruce 070601 comment]. # That use used to depend on our same-atoms-means-equal behavior. # I don't know if it still does. if self is obj: return True if not isinstance(obj, Bond): return False if obj.bond_key != self.bond_key: return False # bond_key hashes the atoms by summing their .keys; # self and obj are now known to be equal iff they have either atom # in common. In fact, it's a bit stronger, since equal bond_keys # means they have both atoms or neither atom in common, # so the following is correct: res = self.atom1 is obj.atom1 or self.atom1 is obj.atom2 if res and debug_flags.atom_debug: # This is a use of the deprecated feature of two Bonds with the # same atoms comparing equal. This is not known to happen # as of 080402, but it's not necessarily a bug. If we could be sure # it never happened (or was never needed), we could redefine # __eq__ to always return (self is obj). Older related info # (not sure if obs): bruce 070601: this does sometimes happen, # for unknown reasons, but probably repeatably. At least one bug # report (eg bug 2401) mentions it. It has no known harmful effects # (and by now I forget whether it's predicted to have any -- some # older comments suggest it's not, it just means a certain optim- # ization in __eq__ would be an illegal change). When it does happen # it may not be an error (but this is not yet known) -- it may # involve some comparison by undo of old and new bonds between the # same atoms (a speculation; but the tracebacks seem to always # mention undo, and the atoms in the bonds seem to be the same). # Or maybe there is code to make a new bond, see if it's already # on the atoms, and discard it if so (Bond.__init__ might do that). msg = "debug: fyi: different bond objects (on same atoms) equal: " \ "%r == %r: " % (self, obj) print_compact_stack( msg ) return res def __ne__(self, obj): # bruce 041028 -- python doc advises defining __ne__ whenever you # define __eq__; on 060228 i confirmed this is needed by test # (otherwise != doesn't call __eq__) return not self.__eq__(obj) # == def bounding_lozenge(self): """ Return the bounding lozenge of self, in absolute coordinates (whether or not self is an external bond). """ #bruce 080702 split out of Chunk._draw_external_bonds # Note: # MAX_ATOM_SPHERE_RADIUS = maximum atom radius # in any display style. Look at Chunk.draw # for derivation. [piotr 080402] # [comment from original context in Chunk._draw_external_bonds:] # The radius is currently not used. It should be # replaced by a proper maximum bond radius # when the is_lozenge_visible method is fully # implemented. [piotr 080401] # update [bruce 080702]: actually, radius is used # (when calling gplane.is_lozenge_visible, as is done # in the context in which that comment was written). # I'm not sure whether this comment implies # that the radius above is too small, # nor whether it is in fact too small. # I'm not sure how the 0.5 additional radius was derived. res = ( self.atom1.posn(), self.atom2.posn(), MAX_ATOM_SPHERE_RADIUS + 0.5 ) return res def should_draw_as_picked(self): """ Should the visual appearance conventions for a selected object be used on (all of) self when drawing it? @see: same method in ExternalBondSet """ #bruce 080702 split this out of Chunk._draw_external_bonds; # ExternalBondSet method of same name has equivalent code as of 090227 return self.atom1.molecule.picked and self.atom2.molecule.picked def draw(self, glpane, dispdef, col, detailLevel, highlighted = False, special_drawing_handler = None, special_drawing_prefs = USE_CURRENT ): """ Draw the bond self. Note that for external bonds, this is [or used to be?] called twice, once for each bonded molecule (in arbitrary order) (and is never cached in either mol's display list); each of these calls gets dispdef, col, and detailLevel from a different mol. [bruce, 041104, thinks that leads to some bugs in bond looks.] Bonds are drawn only in certain display modes. The display mode is inherited from the atoms or molecule (as passed in via dispdef from the calling molecule -- this would cause bugs if some callers change display mode but don't invalidate their display lists containing bonds, but maybe they do). Lines or tubes change color from atom to atom, and are red in the middle for long bonds. oldCPK(?) bonds are drawn in the calling chunk's color or in the user pref color whose default value used to be called bondColor (which is light gray). Note that all drawing coords are based on either .posn or .baseposn of the atoms, according to whether this is an external or internal bond, and the caller has to draw those kinds of bonds in the proper coordinate system (absolute or chunk-relative for external or internal bonds respectively). """ #bruce 041104 revised docstring, added comments about possible bugs. # Note that this code depends on finding the attrs toolong, center, # a1pos, a2pos, c1, c2, as created by self.__setup_update(). # As of 041109 this is now handled by bond.__getattr__. # The attr toolong is new as of 041112. if debug_flags.atom_debug: import graphics.model_drawing.bond_drawer as bond_drawer reload_once_per_event( bond_drawer) from graphics.model_drawing.bond_drawer import draw_bond draw_bond( self, glpane, dispdef, col, detailLevel, highlighted, special_drawing_handler = special_drawing_handler, special_drawing_prefs = special_drawing_prefs ) # if we're an external bond, also draw our atoms' # geometry_error_indicators, so those stay out of their chunk # display lists (since they depend on external info, namely, # this bond). (not needed when a chunk is highlighted, but the caller # is not passing that flag then; don't know if needed when self alone # is highlighted.) [bruce 080214] if self.atom1.molecule is not self.atom2.molecule: if self.atom1.check_bond_geometry(external = True): self.atom1.overdraw_bond_geometry_error_indicator(glpane, dispdef) if self.atom2.check_bond_geometry(external = True): self.atom2.overdraw_bond_geometry_error_indicator(glpane, dispdef) return def legal_for_atomtypes(self): #bruce 050716 v6 = self.v6 return self.atom1.atomtype.permits_v6(v6) and \ self.atom2.atomtype.permits_v6(v6) def permits_v6(self, v6): #bruce 050806 # todo: should merge this somehow with self.legal_for_atomtypes() return self.atom1.atomtype.permits_v6(v6) and \ self.atom2.atomtype.permits_v6(v6) def draw_in_abs_coords(self, glpane, color): #bruce 050609 """ Draw this bond in absolute (world) coordinates (even if it's an internal bond), using the specified color (ignoring the color it would naturally be drawn with). This is only called for special purposes related to mouseover-highlighting, and should be renamed to reflect that, since its behavior can and should be specialized for that use. (E.g. it doesn't happen inside display lists; and it need not use glName at all.) """ highlighted = True # ninad 070214 - passing 'highlighted' to # bond.draw instead of highlighted = bool if self.killed(): #bruce 050702, part of fix 2 of 2 redundant fixes for bug 716 #(both fixes are desirable) return mol = self.atom1.molecule mol2 = self.atom2.molecule if mol is mol2: # internal bond; geometric info is stored in chunk-relative # coords; we need mol's help to use those mol.pushMatrix(glpane) self.draw(glpane, mol.get_dispdef(glpane), color, mol.assy.drawLevel, highlighted ) # sorry for all the kluges (e.g. 1 or 2 of those args) that beg for # refactoring! The info passing in draw methods is not # designed for drawing leaf nodes by themselves in a clean # way! (#e should clean up somehow) #bruce 050702 using shorten_tubes [as of 050727, this is done #via highlighted = True] to help make room to #mouseover-highlight the atoms, when in tubes mode (thus #fixing bug 715-1); a remaining bug was that it's sometimes #hard to highlight the tube bonds, apparently due to selatom #seeming bigger even when not visible (not sure). In another #commit, same day, GLPane.py (sort selobj candidates) and this #file (don't shorten_tubes next to singlets [later moved to #bond_drawer.py]), this has been fixed. mol.popMatrix(glpane) else: # external bond -- draw it at max dispdef of those from its mols disp = max( mol.get_dispdef(glpane), mol2.get_dispdef(glpane) ) self.draw(glpane, disp, color, mol.assy.drawLevel, highlighted) #bruce 080406 bugfix: pass highlighted (lost recently??) return def nodes_containing_selobj(self): #bruce 080507 """ @see: interface class Selobj_API for documentation """ atom1 = self.atom1 atom2 = self.atom2 # safety check in case of calls on out of date selobj if atom1.killed() or atom2.killed(): return [] if atom1.molecule is atom2.molecule: # optimization res = atom1.nodes_containing_selobj() else: res = atom1.nodes_containing_selobj() + \ atom2.nodes_containing_selobj() # note: this includes some nodes twice, which we might want to # remove as an optimization in principle, # but I think it's faster to ignore that than to detect which ones # to remove, especially since current code elsewhere only uses # this list for whether it includes any nodes currently # showing in the model tree. return res def killed(self): #bruce 050702 try: return self.atom1.killed() or self.atom2.killed() # This last condition doesn't yet work right, not sure why: ## ... or not self in atom1.bonds # Problem: without it, this might be wrong if the bond was "busted" # without either atom being killed. For now, just leave it out; # fix this sometime. ###@@@ # Warning: that last condition is slow, too. # [later: see also ExternalBondSet._correct_bond, which # checks this itself, and its comments. [bruce 080702 comment]] except: # (if this can happen, it's probably from one of the atoms being # None, though self.bust() doesn't presently set them to None) return True pass def writepov(self, file, dispdef, col): """ Write this bond to a povray file (always using absolute coords, even for internal bonds). """ writepov_bond(self, file, dispdef, col) return def __str__(self): #bruce 050705 revised this; note that it contains chars not compatible #with HTML unless quoted ## return str(self.atom1) + " <--> " + str(self.atom2) # No quat is easily available here; better results if you call that # subr directly and pass one; the right one is (in current code, # AFAIK, 070415) glpane.quat for the glpane that will display the bond # (whether or not it's an internal bond); let's try to guess that: quat = Q(1,0,0,0) try: glpane = self.atom1.molecule.assy.o quat = glpane.quat except: if env.debug(): # don't print self here! msg = "bug: exception in self.atom1.molecule.assy.o.quat" print_compact_traceback(msg + ": ") pass return bonded_atoms_summary(self, quat = quat) #bruce 070415 added quat arg and above code to guess it ###UNTESTED def __repr__(self): return str(self.atom1) + "::" + str(self.atom2) # == def bond_menu_section(self, quat = Q(1,0,0,0)): """ Return a menu_spec subsection for displaying info about a highlighted bond, changing its bond_type, offering commands about it, etc. If given, use the quat describing the rotation used for displaying it to order the atoms in the bond left-to-right (e.g. in text strings). """ if debug_flags.atom_debug: import operations.bond_utils as bond_utils reload(bond_utils) # at least during development from operations.bond_utils import bond_menu_section return bond_menu_section(self, quat = quat) # == def is_rung_bond(self): #bruce 080212 """ Is self a dna "ladder rung" bond (between axis and strand)? """ roles = (self.atom1.element.role, self.atom2.element.role) return (roles == ('axis', 'strand') or roles == ('strand', 'axis')) pass # end of class Bond # == def is_new_style_class(c): #bruce 090206, refile # I'm not sure if this is the best test, but it's the best I have now. # isinstance(c, object) is true for both old and new style classes; # the type of c varies (classobj or type) but I'm not sure if the specific # types are guaranteed, and I don't want to exclude metaclasses (subclasses # of type), and for all I know classobj might be (or become someday) # a subclass of type. return hasattr(c, '__mro__') if is_new_style_class(Bond): #bruce 090205 # see comments in state_utils.py docstring, Comparison.py, and above. # The comments also say how to fix this (not hard, but does require # changes to the C version of same_vals). Note that on 090206 I'm # making this true as an experiment. ### TODO: cleanup before release. msg = "WARNING: Bond (%r) is new-style -- possible Undo bugs related " \ "to same_vals; see comments dated 090205" % Bond print msg ## assert 0, msg + ". Assert 0 to make sure this is noticed." # ok to remove this assertion for testing atombase register_class_changedicts( Bond, _Bond_global_dicts ) # error if one class has two same-named changedicts # (so be careful re module reload) # == # some more bond-related functions def bond_at_singlets(s1, s2, **opts): """ [Public function; does all needed invalidations.] s1 and s2 are bondpoints (formerly called singlets); make a bond between their real atoms in their stead. If the real atoms are in different chunks, and if move = 1 (the default), move s1's chunk to match the bond, and [bruce 041109 observes that this last part is not yet implemented] set its center to the bond point and its axis to the line of the bond. [I suspect this feature is no longer operative -- should review, update doc. -- bruce 080213] It's an error if s1 == s2, or if they're on the same atom. It's a warning (no error, but no bond made) if the real atoms of the singlets are already bonded, unless we're able to make the existing bond have higher bond order, which we'll only attempt if increase_bond_order = True, and [bruce 050702] which is only possible if the bonded elements have suitable atomtypes. If the singlets are bonded to their base atoms with different bond orders, it's an error if we're unable to adjust those to match... ###@@@ #k. (We might add more error or warning conditions later.) If the bond directions on the open bonds of s1 and s2 are not what is required for maintaining correct directions in a chain of directional bonds, then we will try to fix them by altering bond directions on them or any other open bonds on their base atoms, if we can be sure how this ought to be done. This is not an error and causes no messages when the final state can be fully correct (unless debug flags are set). Note that this operates independently of and before the dna updater (which would also try to fix such errors, but can't do it as well since it doesn't know which bonds are new). This can be disabled by the option XXX. [### NIM; intended new feature soon; implem is all in bond_atoms(); bruce 080213] The return value says whether there was an error, and what was done: @return: (flag, status), where flag is 0 for ok (a bond was made or an existing bond was given a higher bond order, and s1 and s2 were killed), or 1 or 2 for no bond made (1 = not an error, 2 = an error), and status is a string explaining what was done, or why nothing was done, suitable for displaying in a status bar. If no bond is made due to an error, and if option print_error_details = 1 (the default), then we also print a nasty warning with the details of the error, saying it's a bug. """ ### REVIEW what we are allowed to do and will do, and what docstring # should say: # - Can we remove those singlets we're passed? [either here, or in # subsequent bond_updater.py actions] # - Can we alter (e.g. replace) any other singlets on their atoms? # I think we used to not do this in most cases, and extrude & # fusechunks depended on that. ### # Now, with debug pref to not use OLD code below, it looks like # we or an immediate subsequent update removes and remakes # (in different posns) bondpoints other than the ones passed. # Still working on it. # [bruce 071018 comment] obj = _bonder_at_singlets(s1, s2, **opts) return obj.retval class _bonder_at_singlets: """ handles one call of bond_at_singlets """ #bruce 041109 rewrote this, added move arg, renamed it from makeBonded #bruce 041119 added args and retvals to help fix bugs #203 and #121 #bruce 050429 plans to permit increasing the valence of an existing bond, ###@@@doit # and also checking for matched valences of s1 and s2. ###@@@doit # also changed it from function to class def __init__(self, s1, s2, move = True, print_error_details = True, increase_bond_order = False ): self.s1 = s1 self.s2 = s2 self.move = move self.print_error_details = print_error_details self.increase_bond_order = increase_bond_order self.retval = self.main() return def do_error(self, status, error_details): if self.print_error_details and error_details: print "BUG: bond_at_singlets:", error_details print "Doing nothing (but further bugs may be caused by this)." print_compact_stack() if error_details: # i.e. if it's an error flag = 2 else: flag = 1 status = status or "can't bond here" return (flag, status) def main(self): s1 = self.s1 s2 = self.s2 do_error = self.do_error if not s1.is_singlet(): return do_error("not both singlets", "not a singlet: %r" % s1) if not s2.is_singlet(): return do_error("not both singlets", "not a singlet: %r" % s2) a1 = self.a1 = s1.singlet_neighbor() a2 = self.a2 = s2.singlet_neighbor() if s1 is s2: #bruce 041119 return do_error( "can't bond a singlet to itself", "asked to bond atom %r to itself,\n" " from the same singlet %r (passed twice)" % (a1, s1) ) # untested formatting if a1 is a2: #bruce 041119, part of fix for bug #203 ###@@@ should we permit this as a way of changing the bonding ###pattern by summing the valences of these bonds? YES! [doit] # [later comment, 050702:] this is low-priority, since it's # difficult to do for a free atom (the atom tries to rotate to # make it impossible) (tho I have to admit, for a bound C(sp3) # with 2 open bonds left, it's not too hard, due to the # arguable-bug in which only one of them moves) and since the # context menu lets you do it more directly. ... even so, let's # try it: if self.increase_bond_order and a1.can_reduce_numbonds(): return self._merge_open_bonds() #bruce 050702 new feature else: return do_error("can't bond an atom (%r) to itself" % a1, "asked to bond atom %r to itself,\n" " from different singlets, %r and %r." % (a1, s1, s2)) if atoms_are_bonded(a1, a2): #bruce 041119, part of fix for bug #121 # not an error (so arg2 is None) if self.increase_bond_order and \ a1.can_reduce_numbonds() and \ a2.can_reduce_numbonds(): # we'll try that -- it might or might not work, but it has its # own error messages if it fails #bruce 050702 added can_reduce_numbonds conditions, which #check whether the atoms can change their atomtypes #appropriately return self.upgrade_existing_bond() else: if a1.can_reduce_numbonds() and a2.can_reduce_numbonds(): why = "won't" else: why = "can't" return do_error("%s increase bond order between already-" \ "bonded atoms %r and %r" % (why, a1, a2), None ) ###@@@ worry about s1 and s2 valences being different # [much later, 050702: that might be obs, but worrying about their # *permitted* valences might not be...] (not sure exactly what # we'll do then! do bonds want to keep track of a range of # permissible valences?? it's a real concept (I think) and it's # probably expensive to recompute. BTW, if there is more than one # way to resolve the error, they might want to permit the linkage # but not pick the way to resolve it, but wait for you to drag the # v-error indicator (or whatever).) ###@@@ worry about s1 and s2 valences being not V_SINGLE # ok, now we'll really do it. return self.bond_unbonded_atoms() def bond_unbonded_atoms(self): s1, a1 = self.s1, self.a1 s2, a2 = self.s2, self.a2 status = "bonded atoms %r and %r" % (a1, a2) #e maybe subr should make this?? #e subr might prefix it with bond-type made ###@@@ # we only consider "move m1" in the case of no preexisting bond, # so we only need it in this submethod (in fact, if it was in # the other one, it would never run, due to the condition about # sep mols and no externs) m1 = a1.molecule m2 = a2.molecule if m1 is not m2 and self.move: # Comments by bruce 041123, related to fix for bug #150: # # Move m1 to an ideal position for bonding to m2, but [as bruce's fix # to comment #1 of bug 150, per Josh suggestion; note that this bug will # be split and what we're fixing might get a new bug number] only if it # has no external bonds except the one we're about to make. (Even a bond # to the other of m1 or m2 will disqualify it, since that bond might get # messed up by a motion. This might be a stricter limit than Josh meant # to suggest, but it seems right. If bonds back to the same mol should # not prevent the motion, we can use 'externs_except_to' instead.) # # I am not sure if moving m2 rather than m1, in case m1 is not qualified # to be moved, would be a good UI feature, nor whether it would be safe # for the calling code (a drag event processor in Build mode), so for now # I won't permit that, though it would be easy to do. # # Note that this motion feature will be much more useful once we fix # another bug about not often enough merging atoms into single larger # molecules, in Build mode. [end of bruce 041123 comments] def ok_to_move(mol1, mol2): "ok to move mol1 if we're about to bond it to mol2?" return mol1.externs == [] #e you might prefer externs_except_to(mol1, [mol2]), but probably not if ok_to_move(m1, m2): status += ", and moved %r to match" % m1.name m1.rot(Q(a1.posn()-s1.posn(), s2.posn()-a2.posn())) m1.move(s2.posn()-s1.posn()) else: status += " (but didn't move %r -- it already has a bond)" % m1.name self.status = status return self.actually_bond() def actually_bond(self): """ #doc... (if it succeeds, uses self.status to report what it did) """ #e [bruce 041109 asks: does it matter that the following code # forgets which singlets were involved, before bonding?] ###@@@ this needs to worry about valence of s1 and s2 bonds, # and thus of new bond s1 = self.s1 s2 = self.s2 a1 = self.a1 a2 = self.a2 #bruce 071018, stop using old code here, finally; # might fix open bond direction; clean up if so ###TODO #bruce 071019 change default to False since new code works now USE_OLD_CODE = debug_pref("Bonds: use OLD code for actually_bond?", Choice_boolean_False ) v1 = s1.singlet_v6() v2 = s2.singlet_v6() if USE_OLD_CODE: new_code_needed = (v1 != V_SINGLE or v2 != V_SINGLE) if not new_code_needed: # old code can be used for now if debug_flags.atom_debug \ and env.once_per_event("using OLD code for actually_bond"): print "atom_debug: fyi (once per event): " \ "using OLD code for actually_bond" s1.kill() s2.kill() bond_atoms(a1, a2) return (0, self.status) # effectively from bond_at_singlets # new code, handles any valences for s1, s2 ## if debug_flags.atom_debug: ## print "atom_debug: NEW code used for actually_bond" vnew = min(v1, v2) bond = bond_atoms(a1, a2, vnew, s1, s2) # tell it the singlets to replace or reduce; let this do # everything now, incl updates. can that fail? I don't think so; # if it could, it'd need to have new API and return us an error # message explaining why. ###@@@ TODO bruce 071018: need to make this not #harm any *other* singlets on these atoms, since some callers #already recorded them and want to call this immediately again to #make other bonds. it's good if it kills *these* singlets when #that's correct, though. REVIEW: what's the status of that? vused = bond.v6 # this will be the created bond prefix = bond_type_names[vused] + '-' status = prefix + self.status # use prefix even for single bond, for now #k # now, add something to status message if not all valence from s1 or # s2 was used # (can this happen for both singlets at once? # maybe 'a' vs 'g' can do that -- not sure.) if v1 > vused or v2 > vused: status += "; some bond-valence unused on " if v1 > vused: status += "%r" % a1 if v1 > vused and v2 > vused: status += " and " #e could rewrite: " and ".join(atomreprs) if v2 > vused: status += "%r" % a2 return (0, status) def upgrade_existing_bond(self): s1, a1 = self.s1, self.a1 s2, a2 = self.s2, self.a2 v1, v2 = s1.singlet_v6(), s2.singlet_v6() if len(a1.bonds) == 2: # (btw, this method is only called when a1 and a2 have at least 2 # bonds) # Since a1 will have only one bond after this (if it's able to use # up all of s1's valence), we might as well try to add even more # valence to the bond, to correct any deficient valence on a1. But # we'll never do this if there are uninvolved bonds to a1, since # user might be planning to manually increase their valence after # doing this operation. # [bruce 051215 new feature, which ought to also fix bug 1221; # other possible fixes seem too hard to do in isolation. # In that bug, -N-N- temporarily became N=N and was then "corrected" # to N-N rather than to N#N as would be better.] v1 += a1.deficient_v6() # usually adds 0 if len(a2.bonds) == 2: v2 += a2.deficient_v6() vdelta = min(v1, v2) # but depending on existing bond, we might use less than this, or none bond = find_bond(a1, a2) ## old_bond_v6 = bond.v6 #bruce 051215 debug code vdelta_used = bond.increase_valence_noupdate(vdelta) # increases as much as possible up to vdelta, to some legal value # (ignores elements and other bond orders -- "legal" just means # for any conceivable bond); returns actual amount of increase # (maybe 0) ## new_bond_v6 = bond.v6 #bruce 051215 debug code ###@@@ why didn't we use vdelta_used in place of vdelta, below? (a #likely bug, which would erroneously reduce valence; but so far I #can't find a way to make it happen -- except dNdNd where it fixes #preexisting valence errors! I will fix it anyway, since it obviously #should have been written that way to start with. [bruce 051215]) ## if debug_flags.atom_debug: #bruce 051215 ## print "atom_debug: bond_v6 changed from %r to %r; " \ ## "vdelta_used (difference) is %r; vdelta is %r" % \ ## (old_bond_v6, new_bond_v6, vdelta_used, vdelta) if not vdelta_used: return self.do_error("can't increase order of bond between " \ "atoms %r and %r" % (a1, a2), None) #e say existing order? say why not? vdelta = vdelta_used # fix unreported hypothetical bug (see comment above) s1.singlet_reduce_valence_noupdate(vdelta) # this might or might not kill it; # it might even reduce valence to 0 but not kill it, # letting base atom worry about that # (and letting it take advantage of the singlet's position, # when it updates things) s2.singlet_reduce_valence_noupdate(vdelta) a1.update_valence() # note: update_valence repositions/alters existing singlets, # updates bonding pattern, valence errors, etc; might reorder # bonds, kill singlets; but doesn't move the atom and doesn't # alter existing real bonds or other atoms; it might let atom # record how it wants to move, when it has a chance and wants to # clean up structure, if this can ever be ambiguous later when the # current state (including positions of old singlets) is gone. a2.update_valence() return (0, "increased bond order between atoms %r and %r" % (a1, a2)) #e say existing and new order? # Note, bruce 060629: the new bond order would be hard to say, # since later code in bond_updater.py is likely to decrease the # value, but in a way it might be hard to predict at this point # (it depends on what happens to the atomtypes which that code # will also fix, and that depends on the other bonds we modify # here; in theory we have enough info here, but the code is not # well structured for this -- unless we save up this message here # and somehow emit it later after that stuff has been resolved). # Not an ideal situation.... def _merge_open_bonds(self): """ Merge the bond-valence of s1 into that of s2 """ #bruce 050702 new feature; # implem is a guess and might be partly obs when written s1, a1 = self.s1, self.a1 s2, a2 = self.s2, self.a2 assert a2 is a1 #bruce 090119 implied by old code v1 = s1.singlet_v6() ## v2 = s2.singlet_v6() vdelta = v1 ## bond1 = s1.bonds[0] bond2 = s2.bonds[0] #e should following permit illegal values? be a singlet method? vdelta_used = bond2.increase_valence_noupdate(vdelta) # increases to legal value, returns actual amount of increase (maybe 0) if not vdelta_used: return self.do_error( "can't merge these two bondpoints on atom %r" % (a1,), None ) #e say existing orders? say why not? s1.singlet_reduce_valence_noupdate(vdelta) a1.update_valence() # this can change the atomtype of a1 to match the fact that it # deletes a singlet [bruce comment 050728] return (0, "merged two bondpoints on atom %r" % (a1,)) pass # end of class _bonder_at_singlets, the helper for function bond_at_singlets # === # some unused old code that would be premature to completely remove # [moved here by bruce 050502] ##def externs_except_to(mol, others): #bruce 041123; not yet used or tested ## # [written to help bond_at_singlets fix bug 150, but not used for that] ## """Say whether mol has external bonds (bonds to other mols) ## except to the mols in 'others' (a list). ## In fact, return the list of such bonds ## (which happens to be true when nonempty, so we can be used ## as a boolean function as well). ## """ ## res = [] ## for bond in mol.externs: ## mol2 = bond.other_chunk(mol) ## assert mol2 != mol, \ ## "an internal bond %r was in self.externs of %r" % (bond, mol) ## if mol not in others: ## if mol not in res: ## res.append(mol) ## return res # == ##class bondtype: ## """not implemented ## """ ## pass ## # int at1, at2; /* types of the elements */ ## # num r0, ks; /* bond length and stiffness */ ## # num ediss; /* dissociation (breaking) energy */ ## # int order; /* 1 single, 2 double, 3 triple */ ## # num length; // bond length from nucleus to nucleus ## # num angrad1, aks1; // angular radius and stiffness for at1 ## # num angrad2, aks2; // angular radius and stiffness for at2 # == # this code knows where to place missing bonds in carbon # sure to be used later # [code and comment by Josh, in chem.py, long before 050502] # [bruce adds, 050510: probably this was superseded by his depositMode code; # as of today it would fail since Carbon.bonds[0][1] is now # Carbon.atomtypes[0].rcovalent * 100.0, I think] ## # length of Carbon-Hydrogen bond ## lCHb = (Carbon.bonds[0][1] + Hydrogen.bonds[0][1]) / 100.0 ## for a in self.atoms.values(): ## if a.element == Carbon: ## valence = len(a.bonds) ## # lone atom, pick 4 directions arbitrarily ## if valence == 0: ## b=atom("H", a.xyz + lCHb * norm(V(-1, -1, -1)), self) ## c=atom("H", a.xyz + lCHb * norm(V(1, -1, 1)), self) ## d=atom("H", a.xyz + lCHb * norm(V(1, 1, -1)), self) ## e=atom("H", a.xyz + lCHb * norm(V(-1, 1, 1)), self) ## bond_atoms(a, b) ## bond_atoms(a, c) ## bond_atoms(a, d) ## bond_atoms(a, e) ## # pick an arbitrary tripod, and rotate it to ## # center away from the one bond ## elif valence == 1: ## bpos = lCHb * norm(V(-1, -1, -1)) ## cpos = lCHb * norm(V(1, -1, 1)) ## dpos = lCHb * norm(V(1, 1, -1)) ## epos = V(-1, 1, 1) ## q1 = Q(epos, a.bonds[0].other(a).xyz - a.xyz) ## b=atom("H", a.xyz + q1.rot(bpos), self) ## c=atom("H", a.xyz + q1.rot(cpos), self) ## d=atom("H", a.xyz + q1.rot(dpos), self) ## bond_atoms(a, b) ## bond_atoms(a, c) ## bond_atoms(a, d) ## # for two bonds, the new ones can be constructed ## # as linear combinations of their sum and cross product ## elif valence == 2: ## b=a.bonds[0].other(a).xyz - a.xyz ## c=a.bonds[1].other(a).xyz - a.xyz ## v1 = - norm(b + c) ## v2 = norm(cross(b, c)) ## bpos = lCHb*(v1 + sqrt(2)*v2)/sqrt(3) ## cpos = lCHb*(v1 - sqrt(2)*v2)/sqrt(3) ## b=atom("H", a.xyz + bpos, self) ## c=atom("H", a.xyz + cpos, self) ## bond_atoms(a, b) ## bond_atoms(a, c) ## # given 3, the last one is opposite their average ## elif valence == 3: ## b=a.bonds[0].other(a).xyz - a.xyz ## c=a.bonds[1].other(a).xyz - a.xyz ## d=a.bonds[2].other(a).xyz - a.xyz ## v = - norm(b + c + d) ## b=atom("H", a.xyz + lCHb * v, self) ## bond_atoms(a, b) # end of bonds.py
NanoCAD-master
cad/src/model/bonds.py
# Copyright 2004-2008 Nanorex, Inc. See LICENSE file for details. """ assembly.py -- provides class Assembly, for everything stored in one mmp file, including one main part and zero or more clipboard items; see also part.py. @version: $Id$ @copyright: 2004-2008 Nanorex, Inc. See LICENSE file for details. == About the Assembly and Part classes, and their relationship: [###@@@ warning, 050309: docstring not reviewed recently] Each Assembly has a set of Parts, of which one is always "current"; the current part is what is displayed in the glpane and operated on by most operations, and (for now, as of 050222) the assy attributes selmols, selatoms, and molecules always refer to the same-named attrs of the current Part. (In fact, many other assy methods and attrs are either delegated to the current Part or have directly become Part methods or been split into assy and Part methods.) All selected objects (even atoms) must be in the current part; the current part is changed by using the model tree to select something in some other part. The main model is one part, and each clipboard item is another part. It is not yet possible to form Groups of separate parts in the Clipboard, but this might be added somehow in the future. For now, any Group in the clipboard is necessarily a single Part (or inside one); each toplevel member of the clipboard is exactly one separate Part. Once several known bugs (like 371) are fixed, then bonds between parts will not be allowed (since they would be bonds between atoms or jigs in different physical spaces), and bonds that become "interspace bonds" (due to move or copy operations) will be automatically broken, or will cause things to be placed into the same space in order not to break them. Note that all info in the assy relates either to its named file or to something about the current command (in the general sense of that term, not just the current assy.win.commandSequencer.currentCommand object); but the assy's info relating to its named file is not all stored directly in that file -- some of it is stored in other files (such as movie files), and in the future, some of it might be stored in files referred to from some object within one of its Parts. == Both Part and Assembly might well be renamed. We don't yet know the best terms with which to refer to these concepts, or even the exact ideal boundary between them in the code. == History: The Part/Assembly distinction was introduced by bruce 050222 (though some of its functionality was anticipated by the "current selection group" introduced earlier, just before Alpha-1). [I also rewrote this entire docstring then.] The Part/Assembly distinction is unfinished, particularly in how it relates to some modes and to movie files. Prior history unclear; almost certainly originated by Josh. Bruce 050513-16 replaced some == with 'is' and != with 'is not', to avoid __getattr__ on __xxx__ attrs in python objects. Bruce 080403 renamed class assembly -> class Assembly. """ ###@@@ Note: lots of old code below has been commented out for the initial # assy/part commit, to help clarify what changed in viewcvs, # but will be removed shortly thereafter. # Also, several functions will be moved between files after that first commit # but have been kept in the same place before then for the benefit of viewcvs diff. import os import time import utilities.Initialize as Initialize from foundation.Utility import node_name from foundation.Group import Group from operations.pastables import is_pastable from utilities.debug import print_compact_traceback from utilities.prefs_constants import workingDirectory_prefs_key from utilities.Log import orangemsg ##, greenmsg, redmsg from utilities import debug_flags from platform_dependent.PlatformDependent import find_or_make_any_directory import foundation.env as env from foundation.state_utils import StateMixin from utilities.debug import print_compact_stack import foundation.undo_archive as undo_archive from utilities.constants import gensym, SELWHAT_CHUNKS, SELWHAT_ATOMS from foundation.state_constants import S_CHILD, S_DATA, S_REF from model.part import Part as Part_class # use a name we can search for [bruce 071029] ### TODO: rename the class Part itself somehow; both Part and part are too generic from model.part import MainPart from model.part import ClipboardItemPart from utilities.icon_utilities import imagename_to_pixmap from commands.PartProperties.PartProp import PartProp from PyQt4 import QtGui from foundation.Assembly_API import Assembly_API import foundation.undo_manager as undo_manager from files.mmp.files_mmp_writing import writemmpfile_assy # == debug_assy_changes = 0 #bruce 050429 if 1: #bruce 060124 debug code; safe but dispensable debug_assy_changes = debug_assy_changes or undo_archive.debug_undo2 _global_assy_number = 0 # count Assembly objects [bruce 050429] _assy_owning_win = None #bruce 060122; assumes there's only one main window; probably needs cleanup # == class Assembly( StateMixin, Assembly_API): """ (This is the closest thing we have to an object representing the contents of an open mmp file, but it also has associated state like selection and undo_archive, controllers like undo_manager, and lots of miscellaneous methods for manipulating that data.) """ # The following class constant attrs can be used in isinstance tests # (e.g. isinstance( node, assy.DnaGroup)) and also as arguments # to Node.parent_node_of_class. Using them can avoid import cycles # (compared to other code importing these classes directly) # # Note that these imports must not be moved to toplevel, # and are not redundant with toplevel imports of the same symbols, # if they exist. [bruce 080310] from foundation.Group import Group from model.chunk import Chunk from model.chem import Atom from model.jigs import Jig from model.Plane import Plane from foundation.Utility import Node from dna.model.DnaGroup import DnaGroup from dna.model.DnaSegment import DnaSegment from dna.model.DnaStrand import DnaStrand from dna.model.DnaMarker import DnaMarker from dna.model.DnaLadderRailChunk import DnaLadderRailChunk from dna.model.DnaLadderRailChunk import DnaStrandChunk from dna.model.DnaStrandOrSegment import DnaStrandOrSegment from cnt.model.NanotubeSegment import NanotubeSegment # --mark 2008-03-09 #bruce 060224 adding alternate name Assembly for this (below), which should become the preferred name #bruce 071026 inheriting Assembly_API so isinstance tests need only import that file #bruce 071026 added docstring # change counters (actually more like modtimes than counters, since changes occurring between checkpoints # might count as only one change -- see code for details): # model changes (all changes that affect mmp file and should mark it in UI as needing to be saved) # (includes all structural changes and many display changes) # (note that a few changes are saved but don't mark it as needing save, like "last view" (always equals current view)) _model_change_indicator = 0 #bruce 060121-23; sometimes altered by self.changed() (even if self._modified already set) #bruce 060227 renamed this from _change_indicator to # _model_change_indicator, but don't plan to rename self.changed(). # # maybe: add a separate change counter for drag changes vs other kinds # of changes (less frequent), to help optimize some PM updates; # not necessary unless we notice drag being too slow due to PM updates # (or diffs which prevent them but take time), which this would fix # [bruce 080808 comment] _selection_change_indicator = 0 _view_change_indicator = 0 # also includes changing current part, glpane display mode # [mostly nim as of 060228, 080805] def all_change_indicators(self): #bruce 060227; 071116 & 080805, revised docstring ### TODO: fix docstring after tests """ Return a tuple of all our change indicators which relate to undoable state, suitable for later passing to self.reset_changed_for_undo(). (Presently, this means all of our change indicators except the one returned by command_stack_change_indicator.) The order is guaranteed to be: (model_change_indicator, selection_change_indicator, view_change_indicator) and if we add new elements, we guarantee we'll add them at the end (so indices of old elements won't change). @note: view_change_indicator is mostly NIM (as of 080805) @note: these are not really "counters" -- they might increase by more than 1 for one change, or only once for several changes, or decrease after Undo. All the numbers mean is that, if they don't differ, no change occurred in the corresponding state. They might be renamed to "change indicators" to reflect this. @note: model_change_indicator only changes when assy.changed() is called, and at most once per potential undoable operation. For example, during a drag, some model component's position changes many times, but model_change_indicator only changes once during that time, when the user operation that does the drag happens to call assy.changed() for the first time during that undoable operation. @note: I don't know whether model_change_indicator works properly when automatic Undo checkpointing is turned off -- needs review. (The issue is whether it changes at most once during any one *potential* or *actual* undoable operation.) This relates to whether env.change_counter_checkpoint() is called when Undo checkpointing is turned off. I am planning to try a fix to this today [080805], and also to the "changing only once during drag" issue noted above, by adding a call to that function sometime during every user event -- probably after all ui updaters are called. @see: self.command_stack_change_indicator (not included in our return value) """ return self._model_change_indicator, self._selection_change_indicator, self._view_change_indicator def model_change_indicator(self): #bruce 080731 """ @see: all_change_indicators """ # todo: ensure it's up to date return self._model_change_indicator def selection_change_indicator(self): #bruce 080731 """ @see: all_change_indicators """ # todo: ensure it's up to date return self._selection_change_indicator def view_change_indicator(self): #bruce 080731 """ NOT YET IMPLEMENTED @see: all_change_indicators """ # todo: ensure it's up to date assert 0, "don't use this yet, the counter attr is mostly NIM" #bruce 080805 return self._view_change_indicator def command_stack_change_indicator(self): #bruce 080903 """ @see: same-named method in class CommandSequencer. @note: this is intentionally not included in the value of self.all_change_indicators(). """ return self.commandSequencer.command_stack_change_indicator() # state declarations: # (the change counters above should not have ordinary state decls -- for now, they should have none) _s_attr_tree = S_CHILD #bruce 060223 _s_attr_shelf = S_CHILD #e then more, including current_movie, temperature, etc (whatever else goes in mmp file is probably all that's needed); # not sure if .part is from here or glpane or neither; not sure about selection (maybe .picked is enough, then rederive?); # view comes from glpane and it should be its own root object, i think; mode is also in glpane ###@@@ #bruce 060227 more decls (some guesses): # not root (since i think tree & shelf are never replaced), filename _s_attr_temperature = S_DATA _s_attr_current_movie = S_CHILD _s_attr__last_current_selgroup = S_REF # this should fix bug 1578 [bruce 060227 guess] # don't need .part, it's derived by __getattr__ from selgroup ### might need _modified? probably not, do separately _s_attr_selwhat = S_DATA #bruce 060302 fix bug 1607 _s_attr__last_set_selwhat = S_DATA # avoids debug warning when undo changes self.selwhat without this decl # initial values of some instance variables undo_manager = None #bruce 060127 assy_valid = False # whether it's ok for updaters to run right now [###misnamed] [bruce 080117] assy_closed = False # whether this assy has been closed by calling self.close_assy [bruce 080314] # todo: use this more. permanently_disable_updaters = False # whether the running of updaters on objects # in this assy has been permanently disabled. Note that once this is set # to True, it might cause errors to ever reset it to False. # Currently it is only set when closing this assy, but we could also # set it on assys in which we want to disable ever running updaters # (e.g. the assys used in MMKit) if desired. # Not yet implemented in all updaters. Implemented in dna updater. # [bruce 080314] def __init__(self, win, name = None, own_window_UI = False, run_updaters = False, commandSequencerClass = None ): """ @type win: MWsemantics or None """ self.own_window_UI = own_window_UI if not run_updaters: #bruce 080403 self.permanently_disable_updaters = True # ignore changes to this Assembly during __init__, and after it, # until the client code first calls our reset_changed method. # [bruce 050429 revised that behavior and this comment, re bug 413] self._modified = 1 # the MWsemantics displaying this Assembly (or None, when called from ThumbView) self.w = win # deprecated but widely used [bruce 071008] self.win = win #bruce 071008 # both of the following are done later in MWsemantics # to avoid a circularity, via self.set_glpane and # self.set_modelTree: # self.mt = win.modelTreeView [or win.mt, probably the same thing, not 100% clear -- bruce 070503 comment] # self.o = win.glpane # the name if any self.name = str(name or gensym("Assembly")) # note: we intentionally don't pass an assy argument to gensym. # [bruce 080407 comment] #bruce 050429 global _global_assy_number _global_assy_number += 1 self._debug_name = self.name + "-%d" % _global_assy_number self._assy_number = _global_assy_number # use in __repr__, bruce 080219 want_undo_manager = False if own_window_UI: #bruce 060127 added own_window_UI flag to help fix bug 1403 # (this is false when called from ThumbView to make its "dummy Assembly" (which passes self.w of None), # or from MMKit for Library assy (which passes self.w of main window, same as main assy). # Another way would be to test (self.w.assy is self), but w.assy could not yet be set up at this time, # so any fix like that is more unclear than just having our __init__-caller pass us this flag. assert self.w global _assy_owning_win if 1: #bruce 070517 fix a change that looks wrong -- make this always happen, like it used to ## from constants import MULTIPANE_GUI ## if not MULTIPANE_GUI: ## # wware 20061115 - we need to permit assys to coexist if _assy_owning_win is not None: _assy_owning_win.deinit() # make sure assys don't fight over control of main menus, etc [bruce 060122] _assy_owning_win = self want_undo_manager = True #bruce 060223: don't actually make one until init of all state attrs is complete # the Clipboard... this is replaced by another one later (of a different class), # once or twice each time a file is opened. ####@@@@ should clean up self.shelf = Group("Clipboard", self, None, []) self.shelf.open = False # the model tree for this Assembly self.tree = Group(self.name, self, None) # a node containing both tree and shelf (also replaced when a file is opened) ####@@@@ is this still needed, after assy/part split? not sure why it would be. ###k self.root = Group("ROOT", self, None, [self.tree, self.shelf]) # bruce 050131 for Alpha: # For each Assembly, maintain one Node or Group which is the # "current selection group" (the PartGroup or one of the # clipboard items), in which all selection is required to reside. # It might sometimes be an out-of-date node, either a # former shelf item or a node from a previously loaded file -- # not sure if these can happen, but "user beware". # [As of 030510, we store it privately and check it in all uses.] # Sometime after Alpha, we'll show this group in the glpane # and let operations (which now look at self.tree or self.molecules) # affect it instead of affecting the main model # (or having bugs whenever clipboard items are selected, as they # often do now). # bruce 050228 update: this is still used after assy/part split, # but some of the above comment has been done differently, # and this needs to be kept in sync with self.part. #doc sometime. self.init_current_selgroup() # must be re-called when self.tree is replaced # filename if this entire Assembly (all parts) was read from a file self.filename = "" # what to select: 0=atoms, 2 = molecules # [bruce 050308 change: new code should use SELWHAT_ATOMS and SELWHAT_CHUNKS # instead of hardcoded constants, and never do boolean tests of selwhat] #bruce 050517: as of now, self.selwhat should only be set (other than by this init) # via self.set_selwhat(). [BTW, when we make a new assy and init this, are we sure it # always corresponds to the mode? Probably it does now only since we change to that mode # when opening files. #k] self.selwhat = SELWHAT_CHUNKS # initial value for new assy self._last_set_selwhat = self.selwhat #bruce 050131 for Alpha: self.kluge_patch_toplevel_groups( ) self.update_parts( do_post_event_updates = False) #bruce 050309 for assy/part split #bruce 050429 as part of fixing bug 413, no longer resetting self._modified here -- # client code should call reset_changed instead, when appropriate. # the current version of the MMP file format # this is set in files_mmp_writing.writemmpfile_assy. Mark 050130 # [bruce 050325 comments: it's not clear to me what this means # (eg if you read an old file does this indicate that old file's format?) # or why it needs to be set here at all.] self.mmpformat = '' self.temperature = 300 # bruce 050325 have to put this back here for now # bruce 050325 revising Movie code for assy/part split and other reasons. # Now it works like this: there can be several active Movie objects, # but if one is playing or is the one to be played by default (e.g. the last one made), # then it's stored here in assy.current_movie; otherwise that's None. However, unlike before, # each movie object knows the alist which is correct for it (or, thinks it knows, # since with old .dpb format it could easily be wrong unless we made it in this session), # and in principle old movies can be replayed (but only in the same session) # as long as their alist atoms still exist, # even if they've been reordered or new ones made, etc # (though we might enforce their being all in one Part, and later, add more conditions). # For movies made in prior sessions (actually it's worse -- made from prior opened files), # we still depend on our guess that the atom order is the same as in the current Part # when the moviefile is loaded, checked only by number of atoms. When we have new .dpb format # we can improve that. self.current_movie = None # before 050325 this was called self.m and was always the same Movie object (per assy) if debug_assy_changes: print "debug_assy_changes: creating", self # make sure these exist [bruce 050418]: assert self.tree assert self.tree.part assert self.tree.part.homeView assert self.tree.part.lastView if want_undo_manager: #bruce 060223: we no longer do this until we're fully inited, since when undoing to initial checkpoint # and doing some new op from there, the new op needs to see a fully initialized assy. #obs older comment (can be mostly removed soon): #bruce 051005: create object for tracking changes in our model, before creating any # model objects (ie nodes for tree and shelf). Since this is not initially used except # to record changes as these objects are created, the fact that self is still incomplete # (e.g. lacks important attributes like tree and root and part) should not matter. [#k I hope] menus = (win.editMenu,) # list of menus containing editUndo/editRedo actions (for aboutToShow signal) [060122] self.undo_manager = undo_manager.AssyUndoManager(self, menus) # be sure to call init1() on this within self.__init__! # fyi: this [no longer, 060223] sets self._u_archive for use by our model objects when they report changes # (but its name and value are private to AssyUndoManager's API for our model objects, # which is why we don't set it here) self.undo_manager.init1() #k still exists and needed, but does it still need to be separate from __init__? [060223] # Note: self.undo_manager won't start recording checkpoints until someone calls self.clear_undo_stack() at least once, # which can't be done until some more initialization is done by our callers, # in ways which currently differ for the first Assembly created, and later ones. # This is not even done by the end of MWsemantics.__init__, as of now. # For details, search out the highest-level calls to clear_undo_stack. [bruce 060223] # [update, 080229: be sure to call it before adding much data to the model, though, # since it scans all current data twice the first time it's called, only once thereafter. # See its docstring for details.] pass # could remove these when they work, but no need: # test node_depth method: [bruce 080116] assert self.root.node_depth() == 0 assert self.tree.node_depth() == 1 assert self.shelf.node_depth() == 1 self._init_glselect_name_dict() assert bool(commandSequencerClass) == bool(own_window_UI) # since own_window_UI determines whether external code # expects us to have self.commandSequencer accessible if commandSequencerClass: #bruce 080813 # make and own a command sequencer of the given class # Note: importing the usual class directly causes import cycle # problems, for legitimate or at least hard-to-avoid reasons -- # it knows a lot of command classes, and some of them know how # to construct Assemblies (albeit ones that don't need command # sequencers, as it happens for now, but that might not be # fundamental). So we make the caller tell us, to avoid that, # and since it makes perfect sense. # Review: is class Assembly not the ideal object to own a # command sequencer?? Other candidates: partwindow; or a # specialized subclass of Assembly. # The same question might apply to our undo manager. # Related Q: is finding commandSequencer via assy legitimate? # [bruce 080813 questions] self.commandSequencer = commandSequencerClass(self) #bruce 080813 self.assy_valid = True return # from Assembly.__init__ # == def set_glpane(self, glpane): #bruce 080216 self.o = glpane # historical name for our glpane, widely used self.glpane = glpane # clearer name, added 080216 return def set_modelTree(self, modelTree): #bruce 080216 self.mt = modelTree return def __repr__(self): #bruce 080117 # report _assy_number & main-ness, bruce 080219 # main-ness code revised (bugfix during __init__), bruce 080516 global _global_assy_number extra = "(bug in repr if seen)" try: win = env.mainwindow() except: extra = "(exception in env.mainwindow())" else: if win is None: extra = "(no mainwindow)" else: try: assy = win.assy except AttributeError: extra = "(mainwindow has no .assy)" else: if self is assy: extra = "(main)" else: extra = "(not main)" pass pass pass # now extra describes the "main assy status" res = "<%s #%d/%d %s %r at %#x>" % \ (self.__class__.__name__.split('.')[-1], self._assy_number, _global_assy_number, # this lets you tell if it's the most # recent one -- but beware of confusion from partlib assys; # so also report whether it's currently the main one: extra, self.name, id(self)) return res def deinit(self): # bruce 060122 """ make sure assys don't fight over control of main menus, etc """ # as of 080314, this is only called by: # - MWsemantics.cleanUpBeforeExiting # - __init__ of the next mainwindow assy, if this is one (I think). if not self.assy_closed: print "\nbug: deinit with no close_assy of %r" % self self.close_assy() pass ###e should this be extended into a full destroy method, and renamed? guess: yes. [bruce 060126] if self.undo_manager: self.undo_manager.deinit() #e more? forget self.w?? maybe someday, in case someone uses it now who should be using env.mainwindow() return def close_assy(self): #bruce 080314 """ self is no longer being actively used, and never will be again. (I.e. it's being discarded.) Record this state in self, and do (or permit later code to do, by recording it) various optimizations and safety changes for closed assys. @note: doesn't yet do most of what it ought to do (e.g. destroy atoms). """ self.assy_closed = True self.permanently_disable_updaters = True return # == _glselect_name_dict = None # in case of access before init def _init_glselect_name_dict(self): #bruce 080220 if 0: # use this code as soon as: # - all users of env.py *glselect_name funcs/attrs # are replaced with calls of our replacement methods below. # - moving a Node to a new assy, if it can happen, reallocates its glname # or can store the same one in the new assy. # (or decide that makes no sense and retain this shared dict?) # - destroyed bonds (etc) can figure out how to call dealloc_my_glselect_name # [bruce 080220/080917] from graphics.drawing.glselect_name_dict import glselect_name_dict self._glselect_name_dict = glselect_name_dict() # todo: clear this when we are destroyed, and make sure accesses to it # either never happen or don't mind not finding an object for a name. else: # use the global one in env.py, until we are able to use the above code # and can remove the one in env.py and its access functions/attrs. self._glselect_name_dict = env._shared_glselect_name_dict return def alloc_my_glselect_name(self, obj): #bruce 080220 """ Allocate a GL_SELECT name for obj to pass to glPushName during its OpenGL drawing, and record obj as its owner for purposes of hit-testing by our GLPane. @see: glselect_name_dict.alloc_my_glselect_name for details. @see: our method dealloc_my_glselect_name """ return self._glselect_name_dict.alloc_my_glselect_name(obj) def dealloc_my_glselect_name(self, obj, name): #bruce 080220 """ Deallocate the GL_SELECT name which was allocated for obj using self.alloc_my_glselect_name. @see: glselect_name_dict.dealloc_my_glselect_name for details. """ return self._glselect_name_dict.dealloc_my_glselect_name(obj, name) def object_for_glselect_name(self, name): #bruce 080220 """ Look up the owning object for a GL_SELECT name which was allocated for obj using self.alloc_my_glselect_name. @return: the object we find, or None if none is found. @note: old code used env.obj_with_glselect_name.get for this; a cleanup which replaces that with access to this method was partly done as of 080220, and is perhaps being completed on 080917. (Note the spelling differences: obj vs object and with vs for.) """ # (I don't know if the following test for self._glselect_name_dict # already existing is needed. Maybe only after we're destroyed (nim)?) return self._glselect_name_dict and \ self._glselect_name_dict.object_for_glselect_name(name) # == def kluge_patch_toplevel_groups(self, assert_this_was_not_needed = False): #bruce 050109 #bruce 071026 moved this here from helper function kluge_patch_assy_toplevel_groups in Utility.py """ [friend function; not clearly documented] This kluge is needed until we do the same thing in whatever makes the toplevel groups in an Assembly (eg files_mmp). Call it as often as you want (at least once before updating model tree if self might be newly loaded); it only changes things when it needs to (once for each newly loaded file or inited assy, basically); in theory it makes assy (self) "look right in the model tree" without changing what will be saved in an mmp file, or indeed what will be seen by any other old code looking at the 3 attrs of self which this function replaces (shelf, tree, root). Note: if any of them is None, or not an instance object, we'll get an exception here. """ #bruce 050131 for Alpha: # this is now also called in Assembly.__init__ and in readmmp, # not only from the mtree. ## oldmod = assy_begin_suspend_noticing_changes(self) oldmod = self.begin_suspend_noticing_changes() # does doing it this soon help? don't know why, was doing before root mod... # now i am wondering if i was wrong and bug of wrongly reported assy mod # got fixed even by just doing this down below, just before remaking root. # anyway that bug *is* fixed now, so ok for now, worry about it later. ###@@@ fixroot = 0 try: if self.shelf.__class__ is Group: self.shelf = self.shelf.kluge_change_class( ClipboardShelfGroup) fixroot = 1 if self.tree.__class__ is Group: self.tree = self.tree.kluge_change_class( PartGroup) ##bruce 050302 removing use of 'viewdata' here, # since its elements are no longer shown in the modelTree, # and I might as well not figure them out re assy/part split until we want # them back and know how we want them to behave regarding parts. ## lis = list(self.viewdata.members) ## # are these in the correct order (CSys XY YZ ZX)? I think so. [bruce 050110] ## self.tree.kluge_set_initial_nonmember_kids( lis ) fixroot = 1 if self.root.__class__ is Group or fixroot: fixroot = 1 # needed for the "assert_this_was_not_needed" check #e make new Root Group in there too -- and btw, use it in model tree widgets for the entire tree... # would it work better to use kluge_change_class for this? # academic Q, since it would not be correct, members are not revised ones we made above. self.root = RootGroup("ROOT", self, None, [self.tree, self.shelf]) #k ok to not del them from the old root?? ###@@@ BUG (suspected caused here): fyi: too early for this status msg: (fyi: part now has unsaved changes) # is it fixed now by the begin/end funcs? at leastI don't recall seeing it recently [bruce 050131] ## removed this, 050310: self.current_selection_group = self.tree #bruce 050131 for Alpha self.root.unpick() #bruce 050131 for Alpha, not yet 100% sure it's safe or good, but probably it prevents bugs ## revised this, 050310: ## self.current_selection_group = self.tree # do it both before and after unpick (though in theory either alone is ok) ## self.current_selgroup_changed() ## self.set_current_selgroup( self.tree) -- no, checks are not needed and history message is bad self.init_current_selgroup() #050315 finally: ## assy_end_suspend_noticing_changes(self,oldmod) self.end_suspend_noticing_changes(oldmod) if fixroot and assert_this_was_not_needed: #050315 if debug_flags.atom_debug: print_compact_stack("atom_debug: fyi: kluge_patch_toplevel_groups sees fixroot and assert_this_was_not_needed: ") return # == #bruce 051031: keep counter of selection commands in assy (the model object), not Part, # to avoid any chance of confusion when atoms (which will record this as their selection time) # move between Parts (though in theory, they should be deselected then, so this might not matter). _select_cmd_counter = 0 def begin_select_cmd(self): # Warning: same named method exists in Assembly, GLPane, and ops_select, with different implems. # The best place to save this state is not clear, but probably it's a place that won't explicitly exist # until we restructure the code, since it's part of the "current selection" state, which in principle # should be maintained as its own object, either per-window or per-widget or per-model. # [bruce 051031] self._select_cmd_counter += 1 return def set_selwhat(self, selwhat): #bruce 050517 ## print_compact_stack( "set_selwhat to %r: " % (selwhat,)) assert selwhat in (SELWHAT_ATOMS, SELWHAT_CHUNKS) if not self._last_set_selwhat == self.selwhat: # compare last officially set one to last actual one if debug_flags.atom_debug: # condition is because BuildCrystal_Command will do this, for now print_compact_stack( "atom_debug: bug: this failed to call set_selwhat, but set it directly, to %r:\n " \ % (self.selwhat,) ) self.selwhat = selwhat self._last_set_selwhat = self.selwhat return def construct_viewdata(self): #bruce 050418; this replaces old assy.data attribute for writing mmp files #bruce 050421: extend this for saving per-part views (bug 555) grpl1 = self.tree.part.viewdata_members(0) # Now grab these from the other parts too, # but store them in some other way which won't mess up old code which reads the file we'll write these into # (namely, as some new mmp record type which the old code would ignore)... # or just as a Csys with a name the old code will not store! # (This name comes from the argument we pass in.) partnodes = self.shelf.members # would not be correct to use self.topnodes_with_own_parts() here grpl1 = list(grpl1) # precaution, not needed for current implem as of 050421 for i,node in zip(range(len(partnodes)),partnodes): ll = node.part.viewdata_members(i+1) grpl1.extend(ll) #bruce 050429 part of fix for bug 413: insulate self from misguided self.changed() # done when this Group is made. oldmod = self.begin_suspend_noticing_changes() res = Group("View Data", self, None, grpl1) self.end_suspend_noticing_changes(oldmod) return res def init_current_selgroup(self): self._last_current_selgroup = self.tree return next_clipboard_item_number = 1 # initial value of instance variable def name_autogrouped_nodes_for_clipboard(self, nodes, howmade = ""): """ Make up a default initial name for an automatically made Group whose purpose is to keep some nodes in one clipboard item. The nodes in question might be passed, but this is optional (but you have to pass None or [] if you don't want to pass them), and they might not yet be in the clipboard, might not be the complete set, and should not be disturbed by this method in any way. A word or phrase describing how the nodes needing this group were made can also optionally be passed. Someday we might use these args (or anything else, e.g. self.filename) to help make up the name. """ # original version: return "<Clipboard item>" # bruce 050418: to improve this and avoid the unfixed bug of '<' in names # (which mess up history widget's html), # I'll use "Clipboard item <n>" where n grows forever, per-file, # except that rather than storing it, I'll just look at the nodes now in the file, # and remember the highest one used while the file was loaded in the session. # (So saving and reloading the file will start over based on the numbers used in the file, # which is basically good.) #e (Should I use a modtime instead (easier to implement, perhaps more useful)? No; # instead, someday make that info available for *all* nodes in a 2nd MT column.) prefix = "Clipboard item" # permit space, or not, between this and a number, to recognize a number for node in self.shelf.members: name = node.name number = None if name.startswith(prefix): rest = name[len(prefix):].strip() if rest and rest.isdigit(): try: number = int(rest) except: # can this happen (someday) for weird unicode digits permitted by isdigit? who knows... print "ignoring clipboard item name containing weird digits: %r" % (name,) number = None if number is not None and self.next_clipboard_item_number <= number: # don't use any number <= one already in use self.next_clipboard_item_number = number + 1 res = "%s %d" % (prefix, self.next_clipboard_item_number) self.next_clipboard_item_number += 1 # also don't reuse this number in this session return res # == Parts def topnode_partmaker_pairs(self): #bruce 050602 """ Return a list of (node, partclass) pairs, for each node (in the tree of our nodes we'd display in a model tree) which should be at the top of its own Part of the specified Part subclass. The partclass might actually be any Part constructor with similar API to a Part subclass, though as of 050602 it's always a Part subclass. Return value is a mutable list owned by the caller (nothing will modify it unless caller does (more precisely, except via caller's reference to it)). Implem note: we don't ask the nodes themselves for the partclass, since it might depend on their position in the MT rather than on the nodetype. """ res = [(self.tree, MainPart)] for node in self.shelf.members: res.append(( node, ClipboardItemPart )) return res def topnodes_with_own_parts(self): #bruce 050602; should match topnode_partmaker_pairs res = [self.tree] + self.shelf.members return res def all_parts(self): #bruce 080319 """ Return all Parts in assy. Assume without checking that update_parts (or the part of it that fixes .part structure) has been run since the last time assy's node tree structure changed. """ return [topnode.part for topnode in self.topnodes_with_own_parts()] def update_parts(self, do_post_event_updates = True, do_special_updates_after_readmmp = False ): """ For every node in this assy, make sure it's in the correct Part, creating new parts as necessary (of the correct classes). Also break any inter-part bonds, and set the current selgroup (fixing it if necessary). Also call env.do_post_event_updates(), unless the option do_post_event_updates is false. Also do special updates meant to be done just after models are read by readmmp (or after part of them are inserted by insertmmp), if the option do_special_updates_after_readmmp is True. Some of these might happen before any updaters run in this call (and might be desirable to do before they *ever* run to make it safe and/or effective to run the updaters), so be sure to pass this on the first update_parts call (which happens when updaters are enabled by kluge_main_assy.assy_valid) after readmmp or insertmmp modifies assy. [See also the checkparts method.] """ #bruce 080319 added option do_special_updates_after_readmmp # #bruce 071119 revised docstring, added do_post_event_updates option # (which was effectively always True before). # #bruce 060127: as of now, I'll be calling update_parts # before every undo checkpoint (begin and end both), so that all resulting changes # (and the effect of calling assy.changed, now often done by do_post_event_updates as of yesterday) # get into the same undo diff.) [similar comment is in do_post_event_updates] # ###@@@ revise the following comment, it's just notes during development: # this is a simple brute-force scan, which might be good enough, and if so might be the simplest method that could work. # so if it works and seems ok to use whenever nodes change parts, then take care of entirely new nodes somehow (mol init), # and then just call this whenever needed... and it should be ok to add nodes to parts in addmember, when they're new # (and when dad has a part); and to do this to kids when groups with no parts are added to nodes with parts. # So only for a node-move must we worry and do it later... or so it seems, 050308 806pm. #bruce 050602 revised the following: for (node, part_constructor) in self.topnode_partmaker_pairs(): self.ensure_one_part( node, part_constructor) # now all nodes have correct parts, so it's safe to break inter-part bonds. # in the future we're likely to do this separately for efficiency (only on nodes that might need it). partnodes = self.topnodes_with_own_parts() # do this again in case the nodes changed (though I doubt that can happen) for node in partnodes: # do this for all parts, even though the experimental PrefNode doesn't need it (as such) # (as a kluge, it might use it for smth else; if so, could #e rename the method and then say this is no longer a kluge) node.part.break_interpart_bonds() # note: this is not needed when shelf has no members, unless there are bugs its assertions catch. # but rather than not do it then, I'll just make it fast, since it should be able to be fast # (except for needing to recompute externs, but probably something else would need to do that anyway). # [bruce 050513] [####@@@@ review this decision later] # now make sure current_selgroup() runs without errors, and also make sure # its side effects (from fixing an out of date selgroup, notifying observers # of any changes (e.g. glpane)) happen now rather than later. sg = self.current_selgroup() # and make sure selgroup_part finds a part from it, too assert self.selgroup_part(sg) if do_special_updates_after_readmmp: # do the "pre-updaters" updates of this kind. # initial kluge: don't use registration, or pass new args to # env.do_post_event_updates, just hardcode the before and after # updaters. This also makes it easier to run only on the correct assy # (self). from dna.updater.fix_after_readmmp import fix_after_readmmp_before_updaters fix_after_readmmp_before_updaters(self) if do_post_event_updates: # 050519 new feature: since bonds might have been broken above # (by break_interpart_bonds), do this too: ## self.update_bonds() #e overkill -- might need to be optimized env.do_post_event_updates() #bruce 050627 this replaces update_bonds if do_special_updates_after_readmmp: # Do the "post-updaters" updates of this kind. # For now, there is only one (hardcoded), for the dna updater. # And [bruce 080319 bugfix] it's only safe if the last potential run # of the dna updater (in env.do_post_event_updates, above) # actually happened, and succeeded. from dna.updater.fix_after_readmmp import fix_after_readmmp_after_updaters import model.global_model_changedicts as global_model_changedicts from model.global_model_changedicts import LAST_RUN_SUCCEEDED if global_model_changedicts.status_of_last_dna_updater_run == LAST_RUN_SUCCEEDED: fix_after_readmmp_after_updaters(self) else: print "fyi: skipped fix_after_readmmp_after_updaters since status_of_last_dna_updater_run = %r, needs to be %r" % \ ( global_model_changedicts.status_of_last_dna_updater_run, LAST_RUN_SUCCEEDED ) pass try: self.fix_nodes_that_occur_twice() #bruce 080516 except: msg = "\n*** BUG: exception in %r.fix_nodes_that_occur_twice(); " \ "will try to continue" % self print_compact_traceback(msg + ": ") msg2 = "Bug: exception in fix_nodes_that_occur_twice; " \ "see console prints. Will try to continue." env.history.redmsg( msg2 ) pass return # from update_parts def ensure_one_part(self, node, part_constructor): #bruce 050420 revised this to help with bug 556; revised again 050527 """ Ensure node is the top node of its own Part, and all its kids are in that Part, either by verifying this situation, or creating a new Part just for node and its kids. Specifically: If node's part is None or not owned by node (ie node is not its own part's topnode), give node its own new Part using the given constructor (permitting the new part to copy some info from node's old part, like view attrs, if it wants to). (Class is not used if node already owns its Part.) If node's kids (recursively) are not in node's (old or new) part, add them. [But don't try to break inter-Part bonds, since when this is run, some nodes might still be in the wrong Part, e.g. when several nodes will be moved from one part to another.] We have no way to be sure node's old part doesn't have other nodes besides our node's recursive kids; caller can assure this by covering all nodes with some call of this method. """ #bruce 050420: don't remove node from its old wrong part. Old code [revised 050516] was: ## if node.part and node is not node.part.topnode: #revised 050513 ## # this happens, e.g., when moving a Group to the clipboard, and it becomes a new clipboard item ## node.part.remove(node) # node's kids will be removed below ## assert node.part is None ## if node.part is None: if node.part is None or node.part.topnode is not node: # if node has no part or does not own its part (as its topnode) part1 = part_constructor(self, node) # make a new part with node on top -- uses node's old part (if any) for initial view assert node.part is part1 # since making the new part should have added node to it, and set node.part to it assert node is node.part.topnode # now make sure all node's kids (recursively) are in node.part addmethod = node.part.add node.apply2all( addmethod ) # noop for nodes already in part; # also auto-removes nodes from their old part, if any; # also destroys emptied parts. return def fix_nodes_that_occur_twice(self): # bruce 080516 """ Detect, report, and fix nodes that occur more than once as group members under self.root. """ # WARNING: the code here that runs when this kind of error is detected # is untested (as of the initial commit on 080516). That's ok, since # the call is exception-protected, and that protection has been tested. # # Motivation: there have been bugs that prevented saving an mmp file # that could have been caused by some chunks occurring more than once # in the internal model tree. (One such bug turned out to have another # cause, and it's unconfirmed that any bug has this cause, but it's # possible in principle, or could happen for some new bug.) # # This kind of bug is bad enough to always check for (since the check # can be fast), and if found, to always report and fix. The initial check # shouldn't be too slow, since we've already scanned every atom (in the # caller update_parts) and this only needs to scan all nodes. If it finds # a problem, it scans again, doing more work to know how to report and fix # the problem. nodes_seen = {} # id(node) -> node, for all nodes in assy.tree nodes_seen_twice = {} # same, but only for nodes seen more than once def func(node): if node is None: # should never happen, but if it does, don't be confused # (todo: actually check for isinstance Node) print "bug: found None in place of a node, inside", self return # filter this later (bug: won't always happen) if nodes_seen.has_key(id(node)): # error; save info to help fix it later nodes_seen_twice[id(node)] = node nodes_seen[id(node)] = node return self.root.apply2all(func) if nodes_seen_twice: # bug. report and try to fix. print "\n*** Bug found by %r.fix_nodes_that_occur_twice()" % self msg2 = "Bug: some node occurs twice in the model; " \ "see console prints for details. Will try to continue." env.history.redmsg(msg2) # error details will now just be printed as we discover them print "for %d nodes:" % len(nodes_seen_twice), nodes # To fix, first decide which parent is legitimate for each duplicate # node (which is node.dad if that parent node was seen), # then filter all members lists to only include one occurrence # of each node and only inside its legitimate parent. # But if existing parent is not legit, change node.dad to # first legal one. parents_seen = {} for m in nodes_seen_twice.itervalues(): parents_seen[id(m)] = [] # even if not found again below def func2(node): if node.is_group(): for m in node.members: if nodes_seen_twice.has_key(id(m)): parents_seen[id(m)].append( node) # might list one parent twice, but only consecutively return self.root.apply2all(func2) # parents_seen now knows all the groups whose members lists need # filtering (as entries in one of its parent-list values) # (but we may not bother using it for that optim), # and helps us figure out which parent of each node is legit. current_parent_slot = [None] # kluge nodes_returned_true = {} def fixer(node): """ Fix node to have correct parent, and return True if it should remain in the place where we just saw it. (Can be passed to filter() over a group's members list.) """ if node is None: return False # todo: actually check for isinstance Node if not nodes_seen_twice.has_key(id(node)): return True if nodes_returned_true.has_key(id(node)): # don't think about it again, once we said where it goes, # and make sure it's not allowed anywhere else # (in same parent or another one) return False if nodes_seen.has_key(id(node.dad)): # correct even if dad is None legit_parent = node.dad else: candidates = parents_seen[id(node)] if not candidates: # should never happen or we would not have seen this node print "should never happen: no parent for", node return False oldp = node.dad # for debug print legit_parent = node.dad = candidates[0] node.changed_dad() ####k safe now? print "changed parent of node %r from %r to %r" % (node, oldp, node.dad) if not nodes_seen.has_key(id(node.dad)): print "should never happen: node.dad still not in nodes_seen for", node # assuming that doesn't happen, node.dad is only fixed once per node pass # now see if legit_parent is the current one if legit_parent is current_parent_slot[0]: nodes_returned_true[id(node)] = node return True return False def func3(node): if node.is_group(): # filter its members through fixer current_parent_slot[0] = node oldmembers = node.members newmembers = filter( fixer, oldmembers) if len(newmembers) < len(oldmembers): print "removing %d members from %r, " \ "changing them from %r to %r" % \ ( len(oldmembers) - len(newmembers), node, oldmembers, newmembers ) node.members = newmembers node.changed_members() ###k safe now? pass pass return self.root.apply2all( func3) print pass # end of case for errors detected and fixed return # from fix_nodes_that_occur_twice # == Part-related debugging functions def checkparts(self, when = ""): """ make sure each selgroup has its own Part, and all is correct about them """ # presumably this is only called when debug_flags.atom_debug, # but that's up to the caller, and as of 080314 there are many calls, # including at least one which calls it even when not atom_debug. for node in self.topnodes_with_own_parts(): try: assert node.is_top_of_selection_group() ##e rename node.is_selection_group()?? assert node.part.topnode is node # this also verifies each node has a different part, which is not None kids = [] node.apply2all( kids.append ) # includes node itself for kid in kids: #bruce 060412 added output string to this assert assert kid.part is node.part, "%r.part == %r, %r.part is %r, should be same" % (kid, kid.part, node, node.part) ## assert node.part.nodecount == len(kids), ... if not (node.part.nodecount == len(kids)): # Note: this now fails if you make duplex under dna updater, # undo to before that, then redo. And nodecount is only used # to destroy Parts, which is dubious since Undo can revive # them, and is probably harmless to skip since only non-assert # side effect is assy.forget_part, but assy probably checks current # part before returning it (#k verify). # So, change it into a minor debug print for now, but, # leave it enough on to be told by other developers about the causes. # There is still a bug this may signify, since duplex/undo/redo # fails to recreate the duplex! # [bruce 080325] if not env.seen_before("nodecount bug for Part %#x" % (id(node.part),)): msg = "\nbug for %r: node.part.nodecount %d != len(kids) %d" % \ (node.part, node.part.nodecount, len(kids)) print msg except: #bruce 080325 revised message, removed re-raise at end; #bruce 080410 revising again -- this seems to happen when pasting CX4 with hotspot # into free space in its own clipboard item, so reducing the print messiness # until we can debug this if debug_flags.atom_debug: msg = "\n***BUG?: ignoring exception in checkparts(%s) of %r about node %r" % \ (when and `when` or "", self, node) print_compact_traceback(msg + ": ") else: print "exception in checkparts about node %r ignored, set debug_flags to see" % \ (node,) # this would be useful, but doesn't seem to work right in this context: ## if not when: ## print_compact_stack(" ... which was called from here: ") #bruce 080314 pass continue return # == def draw(self, glpane): #bruce 050617 renamed win arg to glpane, and made submethod use it for the first time if debug_flags.atom_debug and self.own_window_UI: #bruce 060224 added condition, so we don't keep reporting this old bug in MMKit Library ThumbView: # AssertionError: node.part.nodecount 3 != len(kids) 1 # ... # self <assembly.Assembly instance at 0xd1d62b0>, # glpane <ThumbView.MMKitView object at 0xcc38f00>: [main.py:186] [ThumbView.py:193] [ThumbView.py:594] [assembly.py:513] try: self.checkparts() except: #bruce 051227 catch exception in order to act more like non-atom_debug version print_compact_traceback("atom_debug: exception in checkparts; drawing anyway though this might not work: ") print_compact_stack("atom_debug: more info about that exception: self %r, glpane %r: " % (self, glpane)) if self.part is not None: #k not None condition needed?? self.part.draw(glpane) return # == current selection group (see it and/or change it) def current_selgroup_iff_valid(self): """ If the current selection group, as stored (with no fixing!), is valid in all ways we can think of checking (except any ways related to Parts, which are not examined here), return it, otherwise return None (not an error). Never has side effects. """ sg = self._last_current_selgroup if not self.valid_selgroup( sg): return None return sg def valid_selgroup(self, sg): """ If the GIVEN (not current) selection group (with no fixing!) is valid in all ways we can think of checking (except ways related to its .part, which is not examined -- see selgroup_part for that) as a candidate for being or becoming our current selection group, then return True, otherwise False (not an error). Never has side effects. """ if sg is None: return False if sg.assy is not self: return False if not sg.is_top_of_selection_group(): return False if not self.root.is_ascendant(sg): return False # can this ever happen?? # I think we won't check the Part, even though it could, in theory, # be present but wrong (in the sense that sg.part.topnode is not sg), # since that way, this method can be independent of Parts, # and since is_top_of_selection_group should have been enough # for what this method is used for. Logically, we use this to see # the selgroup structure, but consider it lower-level than where we # know that each selgroup wants its own Part (and maintain that). return True def current_selgroup(self): """ If the current selection group is valid as stored, return it. If not, try to fix it, choosing a new one which includes the stored one if possible (this situation might be normal after a DND move of a whole clipboard item into the inside of some other Part), or the main part (self.tree) if not (this might happen if some code deletes nodes without changing the selection group). Like current_selgroup_iff_valid(), ignore its Part; see selgroup_part for that. Also, new Parts are never made (or old Parts revised) in this method. If the current selgroup is changed, the new one is both returned and stored. """ sg = self.current_selgroup_iff_valid() if sg is not None: return sg # now we're a bit redundant with that method (this seems necessary); # also, at this point we're almost certain to debug print and/or # to change self._last_current_selgroup (via self.set_current_selgroup ###k). sg = self._last_current_selgroup # since that guy was invalid, we'll definitely forget about it now # except for its use below as 'sg' (in this run of this method). self._last_current_selgroup = None # hopefully to be revised below if sg is not None and sg.assy is self and self.root.is_ascendant(sg): assert not sg.is_top_of_selection_group() # the only remaining way it could have been wrong # this is the one case where we use the invalid _last_current_selgroup in deciding on the new one. newsg = sg.find_selection_group() # might be None if newsg is None: newsg = self.tree else: newsg = self.tree # now newsg is the one we'll *try* to change to and return, if *it* is valid. # (if it is not None but not valid, that's probably a bug, and we won't change to it; # ideally we'd change to self.tree then, but since it's probably a bug we won't bother.) if newsg is None: #k probably can't happen unless self.tree is None, which I hope never happens here if debug_flags.atom_debug: print_compact_stack("atom_debug: cur selgroup None, no tree(?), should never happen: ") # we already stored None, and it's not good to call current_selgroup_changed now (I think) ##k return None # Note: set_current_selgroup looks at prior self._last_current_selgroup, # so the fact that we set that to None (above) is important. # Also, what if newsg is sg (should never happen here)? # Then it won't be valid (else we'd have returned at top of this method) # and we'll see debug prints in set_current_selgroup. self.set_current_selgroup( newsg) # this stores it and notifies observers if any (eg updates glpane) return self._last_current_selgroup # (this will be same as newsg, or debug prints already occurred) def selgroup_part(self, sg): """ Given a valid selgroup sg (or None), check that it's its .part's topnode, and if so return its .part, and if not return None after emitting debug prints (which always indicates a bug, I'm 90% sure as I write it -- except maybe during init ###k #doc). """ try: assert sg is not None assert sg.part is not None, "sg %r .part should not be None" % (sg,) #bruce 060412 assert sg.part.topnode is not None, "part %r topnode is None, should be %r" % (sg.part, sg) #bruce 060412 assert sg.part.topnode is sg, "part %r topnode is %r should be %r" % (sg.part, sg.part.topnode, sg) except: print_compact_traceback("bug: in assy %r, selgroup.part problem: " % self ) # printing assy in case it's not the main one print_compact_stack(" location of selgroup.part problem: ") return None return sg.part # == def current_selgroup_index(self): #bruce 060125 so Undo can store "current part" w/o doing update_parts [guess; wisdom unreviewed] """ Return the index of the current selgroup, where 0 means self.tree and 1, 2, etc refer to the clipboard items in their current positional order. [Note that this won't be useful for out-of-order redo.] """ sg = self.current_selgroup() if sg is self.tree: return 0 try: return self.shelf.members.index(sg) + 1 except: print_compact_traceback("bug in current_selgroup_index, returning 0: ") return 0 pass def selgroup_at_index(self, i): #bruce 060125 for Undo """ Return the selection group at index i (0 means self.tree), suitable for passing to set_current_selgroup. """ if i == 0: return self.tree try: return self.shelf.members[i-1] except: print_compact_traceback("bug in selgroup_at_index(%d), returning self.tree: " % (i,) ) return self.tree pass # == changing the current selection group ##e move this lower down? def fyi_part_topnode_changed(self, old_top, new_top): """ [private method for a single caller in Part] Some Part tells us that its topnode changed from old_top to new_top. If our current selgroup happened to be old_top, make it now be new_top, but don't emit a history message about this change. [#e: not sure if we should do any unpicking or updating, in general; current caller doesn't need or want any.] """ if self._last_current_selgroup is old_top: self._last_current_selgroup = new_top # no need (in fact, it would be bad) to call current_selgroup_changed, AFAIK # (does this suggest that "current part" concept ought to be more # primitive than "current selgroup" concept??) # now the Part situation should be ok, no need for assy.update_parts return def set_current_part(self, part): self.set_current_selgroup( part.topnode) def set_current_selgroup(self, node): #bruce 050131 for Alpha; heavily revised 050315; might need options wrt history msg, etc """ Set our current selection group to node, which should be a valid one. [public method; no retval] """ assert node prior = self.current_selgroup_iff_valid() # don't call current_selgroup itself here -- # it might try to "fix an out of date current selgroup" # and end up unpicking the node being passed to us. if node is prior: return # might be redundant with some callers, that's ok [#e simplify them?] if prior is None and self._last_current_selgroup: prior = 0 # tell submethod that we don't know the true prior one if not self.valid_selgroup(node): # probably a bug in the caller. Complain, and don't change current selgroup. if debug_flags.atom_debug: print_compact_stack("atom_debug: bug: invalid selgroup %r not being used" % (node,)) #e if this never happens, change it to raise an exception (ie just be an assert) ###@@@ return #####@@@@@ now inline the rest # ok to set it and report that it changed. self._last_current_selgroup = node self.current_selgroup_changed(prior = prior) # as of 050315 this is the only call of that method return def current_selgroup_changed(self, prior = 0): #bruce 050131 for Alpha """ #doc; caller has already stored new valid one; prior == 0 means unknown -- caller might pass None """ #e in future (post-Alpha) this might revise self.molecules, what to show in glpane, etc # for now, make sure nothing outside it is picked! # This is the only place where that unpicking from changing selgroup is implemented. ###@@@ verify that claim sg = self._last_current_selgroup # unpick everything in a different selgroup (but save the message about this for last) didany = self.root.unpick_all_except( sg ) # notify observers of changes to our current selgroup (after the side effect of the unpick!) self.o.set_part( self.part) ## done by that: self.o.gl_update() # print a history message about a new current Part, if possible #####@@@@@ not when initing to self.tree! try: # during init, perhaps lots of things could go wrong with this, so catch them all msg = "showing %r (%s)" % (sg.part.topnode.name, sg.part.location_name()) # AttributeError: 'NoneType' object has no attribute 'topnode' ######@@@@@@ ## this was too frequent to leave them all in, when clicking around the clipboard: ## env.history.message( greenmsg( msg)) ###e need option for this? env.history.message( msg, transient_id = "current_selgroup_changed") except: if debug_flags.atom_debug: print_compact_traceback("atom_debug: bug?? or just init?: can't print changed-part msg: ") pass # emit a message about what we unpicked, if anything if didany: try: # precaution against new bugs in this alpha-bug-mitigation code # what did we deselect? # [note, prior might be None or 0, so boolean test is needed [bruce guess/comment 050516]] if prior and not isinstance(prior, Group): what = node_name(prior) elif prior: what = "some items in " + node_name(prior) else: what = "some items" ## why = "since selection should not involve more than one clipboard item or part at a time" #e wording?? why = "to limit selection to one clipboard item or the part" #e wording?? #e could make this more specific depending on which selection groups were involved msg = "Warning: deselected %s, %s" % (what, why) except: if debug_flags.atom_debug: raise msg = "Warning: deselected some previously selected items" try: env.history.message( orangemsg( msg)) except: pass # too early? (can this happen?) return # from current_selgroup_changed # == general attribute code def initialize(): if (Initialize.startInitialization(__name__)): return # attrnames to delegate to the current part # (ideally for writing as well as reading, until all using-code is upgraded) ###@@@ use __setattr__ ?? etc?? Assembly.part_attrs = ['molecules','selmols','selatoms','homeView','lastView'] ##part_methods = ['selectAll','selectNone','selectInvert']###etc... the callable attrs of part class?? Assembly.part_methods = filter( lambda attr: not attr.startswith('_') and callable(getattr(Part_class,attr)), # note: this tries to get self.part before it's ready... dir(Part_class) ) #approximation! #####@@@@@ for both of the following: Assembly.part_attrs_temporary = ['bbox','center','drawLevel'] # temp because caller should say assy.part or be inside self.part Assembly.part_attrs_review = ['ppa2','ppa3','ppm'] ###@@@ bruce 050325 removed 'alist', now all legit uses of that are directly on Part or Movie ### similarly removed 'temperature' (now on assy like it was),'waals' (never used) #e in future, we'll split out our own methods for some of these, incl .changed #e and for others we'll edit our own methods' code to not call them on self but on self.assy (incl selwhat) Assembly.part_attrs_all = Assembly.part_attrs + Assembly.part_attrs_temporary + Assembly.part_attrs_review Initialize.endInitialization(__name__) # can we use the decorator @staticmethod instead? initialize = staticmethod(initialize) def __getattr__(self, attr): # in class Assembly if attr.startswith('_'): # common case, be fast raise AttributeError, attr elif attr == 'part': sg = self.current_selgroup() # this fixes it if possible; should always be a node but maybe with no Part during init ## return self.parts[node_id(sg)] #bruce 050528 removing this since it prevents clipboard from opening in MT once it's closed, when displaying a clipboard item! ## if 1: ## # open all containing nodes below assy.root (i.e. the clipboard, if we're a clipboard item) ## containing_node = sg.dad ## while containing_node is not None and containing_node is not self.root: ## containing_node.open = True ## containing_node = containing_node.dad part = self.selgroup_part(sg) if part is None: ## #e [this IS REDUNDANT with debug prints inside selgroup_part] ## # no point in trying to fix it -- if that was possible, current_selgroup() did it. ## # if it has no bugs, the only problem it couldn't fix would be assy.tree.part being None. ## # (which might happen during init, and trying to make a part for it might infrecur or otherwise be bad.) ## # so if following debug print gets printed, we might extend it to check whether that "good excuse" is the case. ## if 1: ## print_compact_stack("atom_debug: fyi: assy %r getattr .part finds selgroup problem: " % self ) return None return part elif attr in self.part_attrs_all: # delegate to self.part try: part = self.part except: print "fyi: following exception getting self.part happened just before we looked for its attr %r" % (attr,) raise try: return getattr(part, attr) ###@@@ detect error of infrecur, since part getattr delegates to here?? except: print "fyi: following exception in assy.part.attr was for attr = %r" % (attr,) raise elif attr in self.part_methods: # attr is a method-name for a method we should delegate to our current part. # it's not enough to return the current self.part's bound method... # we need to create and return a fake bound method of our own # which, when called in the future, will delegate to our .part *at that time* -- # in case it is not called immediately, but stored away (e.g. as a menu item's callable) # and used later when our current part might have changed. def deleg(*args,**kws): meth = getattr(self.part, attr) return meth(*args,**kws) return deleg raise AttributeError, attr # == tracking undoable changes that aren't saved def changed_selection(self): #bruce 060129; this will need revision if we make it part-specific # see also same-named Node method if self._suspend_noticing_changes: return self._selection_change_indicator = env.change_counter_for_changed_objects() return def changed_view(self): #bruce 060129 ###@@@ not yet called enough if self._suspend_noticing_changes: return self._view_change_indicator = env.change_counter_for_changed_objects() return # == change-tracking [needs to be extended to be per-part or per-node, and for Undo] def has_changed(self): """ Report whether this Assembly (or something it contains) has been changed since it was last saved or loaded from a file. See self.changed() docstring and comments for more info. Don't use or set self._modified directly! #e We might also make this method query the current mode to see if it has changes which ought to be put into this Assembly before it's saved. """ return self._modified def changed(self): # by analogy with other methods this would be called changed_model(), but we won't rename it [060227] """ Record the fact that this Assembly (or something it contains) has been changed, in the sense that saving it into a file would produce meaningfully different file contents than if that had been done before the change. Note that some state changes (such as selecting chunks or atoms) affect some observers (like the glpane or model tree), but not what would be saved into a file; such changes should *not* cause calls to this method (though in the future there might be other methods for them to call, e.g. perhaps self.changed_selection() #e). [Note: as of 050107, it's unlikely that this is called everywhere it needs to be. It's called in exactly the same places where the prior code set self.modified = 1. In the future, this will be called from lower-level methods than it is now, making complete coverage easier. #e] See also: changed_selection, changed_view. """ # bruce 050107 added this method; as of now, all method names (in all # classes) of the form 'changed' or 'changed_xxx' (for any xxx) are # hereby reserved for this purpose! [For beta, I plan to put in a # uniform system for efficiently recording and propogating change- # notices of that kind, as part of implementing Undo (among other uses).] if self._suspend_noticing_changes: return #bruce 060121 -- this changes effective implem of begin/end_suspend_noticing_changes; should be ok newc = env.change_counter_for_changed_objects() #bruce 060123 if debug_assy_changes: oldc = self._model_change_indicator print self.modflag_asserts() if oldc == newc: print "debug_assy_changes: self._model_change_indicator remains", oldc else: print_compact_stack("debug_assy_changes: self._model_change_indicator %d -> %d: " % (oldc, newc) ) pass self._model_change_indicator = newc ###e should optimize by feeding new value from changed children (mainly Nodes) only when needed ##e will also change this in some other routine which is run for changes that are undoable but won't set _modified flag if not self._modified: self._modified = 1 # Feel free to add more side effects here, inside this 'if' # statement, even if they are slow! They will only run the first # time you modify this Assembly since it was last saved, opened, or closed # (i.e. since the last call of reset_changed). # A long time ago, this is where we'd emit a history message about unsaved changes. # Now we denote a file change by adding an asterisk (or whatever the user prefers) # to the end of the filename in the window caption. self.w.update_mainwindow_caption_properly() #e should this depend on self.own_window_UI? [bruce 060127 question] ####@@@@ if debug_assy_changes: print time.asctime(), self, self.name print_compact_stack("atom_debug: part now has unsaved changes") pass # If you think you need to add a side-effect *here* (which runs every # time this method is called, not just the first time after each save), # that would probably be too slow -- we'll need to figure out a different # way to get the same effect (like recording a "modtime" or "event counter"). self.modflag_asserts() #e should speed-optimize this eventually return # from Assembly.changed() def modflag_asserts(self): #bruce 060123; revised 060125 """ check invariants related to self._modified """ if 1: ###@@@ maybe should be: if debug_flags.atom_debug: hopetrue = ( (not self._modified) == (self._model_change_indicator == self._change_indicator_when_reset_changed) ) if not hopetrue: print_compact_stack( "bug? (%r.modflag_asserts() failed; %r %r %r): " % \ (self, self._modified, self._model_change_indicator, self._change_indicator_when_reset_changed) ) return # Methods to toggle change-noticing during specific sections of code. # (These depend on assy._modified working as it did on 050109 - 050429; # they'll need review when we add per-Part _modified flag, Undo, etc.) # [written by bruce 050110 as helper functions in Utility.py; # renamed and moved here by bruce 050429, re bug 413] _suspend_noticing_changes = False #bruce 060121 for Undo; depends on proper matching and lack of nesting of following methods, # which looks true at the moment; see also use of this in self.changed(), which changes # effective implem of following methods. def begin_suspend_noticing_changes(self): #bruce 060121 revised implem, see comment above and in self.changed() """ See docstring of end_suspend_noticing_changes. """ assert not self._suspend_noticing_changes self._suspend_noticing_changes = True # this prevents self.changed() from doing much oldmod = self._modified self._modified = 1 # probably no longer needed as of 060121 return oldmod # this must be passed to the 'end' function # also, if this is True, caller can safely not worry about # calling "end" of this, i suppose; best not to depend on that def end_suspend_noticing_changes(self, oldmod): """ Call this sometime after every call of begin_suspend_noticing_changes. These begin/end pairs can be nested, but see the caveat below about the oldmod argument in that case. The argument should be the begin method's return value, unless you know you want the new situation to look "not modified", in which case the argument should be False. Note that even calls of self.reset_changed() (between the begin and end methods) are not noticed, so if one occurred and should have been noticed, this can only be fixed by passing False to this method. Caveat: with nested begin/end pairs, if an inner end's oldmod was False (instead of the "correct" value returned by its matching begin method), then changes after that inner end method *will* (incorrectly) be noticed. This is a bug in the present implementation which needs to be worked around. It might be inherent in the present API, I don't know; the present API has no protection for mismatch-bugs and needs revision anyway. It's probably safe even if the Assembly object these methods are being called on is not the same for the begin and end methods! """ # docstring by bruce 050429 ; might be wrong due to changes of 060121 assert self._suspend_noticing_changes self._suspend_noticing_changes = False self._modified = oldmod return _change_indicator_when_reset_changed = -1 #bruce 060123 for Undo; as of 060125 it should no longer matter whether the value is even def reset_changed(self): # bruce 050107 """ [private method] #doc this... see self.changed() docstring... """ #bruce 060123 assuming all calls are like File->Save call... # actual calls are from MWsem.__init__, File->Open, # File->Save (actually saved_main_file; does its own update_mainwindow_caption), File->Close if self._suspend_noticing_changes: print "warning, possible bug: self._suspend_noticing_changes is True during reset_changed" #bruce guess 060121 if debug_assy_changes: print_compact_stack( "debug_assy_changes: %r: reset_changed: " % self ) self._modified = 0 #e should this call self.w.update_mainwindow_caption(changed = False), # or fulfill a subs to do that?? [bruce question 060123] self._change_indicator_when_reset_changed = self._model_change_indicator #bruce 060125 (eve) revised this; related to bugs 1387, 1388?? ## = env.change_counter_checkpoint() #bruce 060123 for Undo ##k not sure it's right to call change_counter_checkpoint and not subsequently call change_counter_for_changed_objects, # but i bet it's ok... more problematic is calling change_counter_checkpoint at all! #######@@@@@@@ # the issue is, this is not actually a change to our data, so why are we changing self._model_change_indicator?? # OTOH, if just before saving we always changed our data just for fun, the effect would be the same, right? # Well, not sure -- what about when we Undo before... if we use this as a vers, maybe no diffs will link at it... # but why would they not? this is not running inside undo, but from an op that does changes like anything else does # (namely file save) (open or close is yet another issue since assy is replaced during the cmd ###@@@). # so i'm guessing it's ok. let's leave it in and find out. hmm, it might make it *look* like file->save did a change # and should be undoable -- but undoing it will have no effect. Really in order to make sure we know that diff # is empty, it would be better not to do this, or somehow to know there was no real change. # plan: zap the final '= env...' and revise modflag_asserts accordingly. worry about real changes for sure # changing counter even if they wouldn't... call checkpoint here even if not using value?!?!?!? #####@@@@@ 060124 230pm #bruce 060201 update for bug 1425: if you call self.changed() right after this, you'll asfail unless we # call env.change_counter_checkpoint() now (discarding result is ok), for a good reason -- once we "used up" # the current value of _model_change_indicator in _change_indicator_when_reset_changed, we better use a different value # for the next real change (so it looks like a change)! This would be needed (to make sure checkpoints notice the change) # even if the asserts were not being done. So the following now seems correct and required: env.change_counter_checkpoint() #bruce 060201 fix bug 1425 return def reset_changed_for_undo(self, change_counters ): #bruce 060123 guess; needs cleanup """ External code (doing an Undo or Redo) has made our state like it was when self.all_change_indicators() was as given. Set all self._xxx_change_indicator attrs to match that tuple, and update self._modified to match (using self._change_indicator_when_reset_changed without changing it). Note that modified flag is false if no model changes happened, even if selection or structural changes happened. Thus if we redo or undo past sel or view changes alone, modified flag won't change. """ # in other words, treat self.all_change_indicators() as a varid_vers for our current state... ###@@@ model_cc, sel_cc, view_cc = change_counters # order must match self.all_change_indicators() retval modflag = (self._change_indicator_when_reset_changed != model_cc) if debug_assy_changes: print_compact_stack( "debug_assy_changes for %r: reset_changed_for_undo(%r), modflag %r: " % \ (self, change_counters, modflag) ) self._modified = modflag self._model_change_indicator = model_cc self._selection_change_indicator = sel_cc self._view_change_indicator = view_cc self.modflag_asserts() #####@@@@@ need any other side effects of assy.changed()?? if self.w: self.w.update_mainwindow_caption_properly() return # == ## bruce 050308 disabling checkpicked for assy/part split; they should be per-part ## and they fix errors in the wrong direction (.picked is more fundamental) def checkpicked(self, always_print = 0): if always_print: print "fyi: checkpicked() is disabled until assy/part split is completed" return # == def apply2movies(self, func): #bruce 050428 """ apply func to all possibly-ever-playable Movie objects we know about. (Not to mere sim-param-holders for minimize, etc.) """ if self.current_movie: # for now, this is the only one! (even if it's a "mere param-holder".) # at some point there'll also be movie nodes in the MT... ##e when there can be more than one, perhaps catch exceptions here and/or "or" the retvals together... func( self.current_movie) return # == def __str__(self): if debug_flags.atom_debug: return "<Assembly of file %r" % self.filename + " (id = %r, _debug_name = %r)>" % (id(self), self._debug_name) #bruce 050429 return "<Assembly of " + self.filename + ">" def writemmpfile(self, filename, **options): #bruce 080326 revised _options = dict(addshelf = True) _options.update(options) writemmpfile_assy( self, filename, **_options) def get_cwd(self): """ Returns the current working directory for assy. """ if self.filename: cwd, file = os.path.split(self.filename) else: cwd = env.prefs[workingDirectory_prefs_key] return cwd # == #bruce 060407 zapped this, and the code can be removed soon ## def become_state(self, state, archive): #bruce 060117 kluge [will it still be needed?] ## from undo_archive import assy_become_state ## return assy_become_state(self, state, archive) # this subroutine will probably become a method of class Assembly def clear(self): #bruce 060117 kluge [will it still be needed?] return undo_archive.assy_clear(self) # this subroutine will probably become a method of class Assembly def editUndo(self): if self.undo_manager: self.undo_manager.editUndo() def editRedo(self): if self.undo_manager: self.undo_manager.editRedo() def undo_checkpoint_before_command(self, *args, **kws): ## moved into undo_manager: self.update_parts() #bruce 060127, precaution related to fixing bug 1406 if self.undo_manager: return self.undo_manager.undo_checkpoint_before_command(*args, **kws) def undo_checkpoint_after_command(self, *args, **kws): ## moved into undo_manager: self.update_parts() #bruce 060127, to fix bug 1406 ## #e [or should undo_manager use a callback, to do it even from ## # initial and clear checkpoints, and recursive-event ones??] if self.undo_manager: return self.undo_manager.undo_checkpoint_after_command(*args, **kws) def current_command_info(self, *args, **kws): #e (will this always go into undo system, or go into some more general current command object in env, instead?) if self.undo_manager: return self.undo_manager.current_command_info(*args, **kws) def clear_undo_stack(self, *args, **kws): if self.undo_manager: return self.undo_manager.clear_undo_stack(*args, **kws) def allNodes(self, class1 = None): #bruce 060224; use more widely? """ Return a new list (owned by caller) of all Nodes in self.tree or self.shelf (including Groups ###untested). If class1 is passed, limit them to the instances of that class. WARNING: self.shelf might be in the list, if it includes Groups. If this is bad we might revise the API to exclude it. """ res = [] def func(node): if not class1 or isinstance(node, class1): res.append(node) self.tree.apply2all(func) self.shelf.apply2all(func) return res def get_part_files_directory(self): # Mark 060703. """ Returns the Part Files directory for this Assembly, even if it doesn't exist. """ # Maybe find_or_make_part_files_directory() should call this to centralize name creation. Mark 060703. if self.filename: path_wo_ext, ext = os.path.splitext(self.filename) return 0, os.path.abspath(os.path.normpath(path_wo_ext + " Files")) else: return 1, "I cannot do this until this part is saved." def find_or_make_part_files_directory(self, make=True): """ Return the Part Files directory for this Assembly. Make it if it doesn't already exist. If <make> is False, return the Part Files directory if it already exists. If it doesn't exist, return None. Specifically, return: - on success, return (0, part files directory), or if <make> is False and the Part Files directory does not exist, return (0, None). - on error, return (1, errormsg). About the "Part Files" directory: The Part Files directory exists next to the current MMP file and has the same name as the MMP file (without the .mmp extension) but with the ' Files' suffix. For example, the MMP file "DNA Shape.mmp" will have "DNA Shape Files" as its Part Files directory. The Part Files directory contains all the associated subdirectories and files for this MMP part, such as POV-Ray Scene files (*.pov), movie files (*.dpb), GAMESS files (*.gms), etc. The Part Files directory currently supports: - POV-Ray Scene files (*.pov). To be implemented: - Movie files (*.dpb) - GAMESS files (*.gms) - ESP Image files (*.png) - Image files (*.png, *.bmp, etc) """ if self.filename: # The current file has been saved, so it is OK to make the Part Files directory. path_wo_ext, ext = os.path.splitext(self.filename) return find_or_make_any_directory(path_wo_ext + " Files", make = make) else: if make: # Cannot make the Part Files directory until the current file is saved. Return error. return 1, "I cannot do this until this part is saved." else: # The current file has not been saved, but since <make> = False, no error. return 0, None def find_or_make_pov_files_directory(self, make=True): """ Return the POV-Ray Scene Files directory for this Assembly. The POV-Ray Scene Files directory is a subdirectory under the current MMP file's Part Files directory and contains all the associated POV-Ray files for this Assembly. For any error, return (1, errortext); on success return (0, full_path_of_pov_files_dir). In other words, return (errorcode, path_or_errortext). """ errorcode, dir_or_errortext = self.find_or_make_part_files_directory(make = make) if errorcode: return errorcode, dir_or_errortext povfiles_dir = os.path.join(dir_or_errortext, "POV-Ray Scene Files") return find_or_make_any_directory(povfiles_dir, make = make) pass # end of class Assembly ## Assembly = assembly #bruce 060224 thinks this should become the preferred name for the class (and the only one, when practical) # == # specialized kinds of Groups: [bruce 050108/050109] # [moved from Utility.py since now only used here; # TODO: these Group subclasses could all be renamed as private. # bruce 071026] class PartGroup(Group): """ A specialized Group for holding the entire "main model" of an Assembly, with provisions for including the "assy.viewdata" elements as initial MT_kids, but not in self.members (which is a kluge, and hopefully can be removed reasonably soon, though perhaps not for Alpha). """ def __init__(self, name, assy, dad, members = (), editCommand = None): #bruce 080306 self._initialkids = [] #bruce 050302, bugfixed 080306 (was a mutable class variable! tho not used as such in its old code) Group.__init__(self, name, assy, dad, members = members, editCommand = editCommand) return # These revised definitions are the non-kluge reason we need this subclass: ###@@@ also some for menus... def is_top_of_selection_group(self): return True #bruce 050131 for Alpha def rename_enabled(self): return False def drag_move_ok(self): return False # ... but drag_copy is permitted! (someday, when copying groups is permitted) # drop methods should be the same as for any Group def permits_ungrouping(self): return False def _class_for_copies(self, mapping): #bruce 080314, preserving original behavior del mapping return Group def node_icon(self, display_prefs): # same whether closed or open return imagename_to_pixmap("modeltree/part.png") ## # And this temporary kluge makes it possible to use this subclass where it's ## # needed, without modifying assembly.py or files_mmp.py: ## def kluge_set_initial_nonmember_kids(self, lis): #bruce 050302 comment: no longer used, for now ## """ ## [This kluge lets the csys and datum plane model tree items ## show up in the PartGroup, without their nodes being in its members list, ## since other code wants their nodes to remain in assy.viewdata, but they can ## only have one .dad at a time. Use of it means you can't assume node.dad ## corresponds to model tree item parent!] ## """ ## lis = filter( lambda node: node.show_in_model_tree(), lis) ## # bruce 050127; for now this is the only place that honors node.show_in_model_tree()! ## self._initialkids = list(lis) def MT_kids(self, display_prefs = {}): # in PartGroup #bruce 080108 revised semantics """ overrides Group.MT_kids """ ## if not self.openable() or not display_prefs.get('open', False): ## return [] # (I think this is never called when not self.open and self.openable(), # so don't bother optimizing that case. [bruce 080306]) regularkids = Group.MT_kids(self, display_prefs) if 1: ## and self.open: #bruce 080306 test code, should clean up #bruce 081217 update: the self.open condition is ok as long as # the fake kids are never selectable, but that's fragile # and ought to be formalized if desired, so it's better # to remove that condition now that MT_kids is not supposed # to depend on self.open. from utilities.debug_prefs import debug_pref, Choice_boolean_False want_fake_kid = debug_pref("Model Tree: show fake initial kid?", Choice_boolean_False) have_fake_kid = not not self._initialkids if have_fake_kid and not want_fake_kid: self._initialkids = [] elif want_fake_kid and not have_fake_kid: dad = None # works... # Note, if you select it you can get messages like: # atom_debug: bug(?): change_current_selgroup_to_include_self on node with no selgroup; ignored # and that clicking elsewhere on MT doesn't deselect it. # # Note: if dad is self, making the Group apparently adds it # to our members list! This seems to be why it was appearing # twice, one in the fake top position and once at the # bottom (the same node, sharing selection/renaming state). _fake_kid = Group("fake initial kid", self.assy, dad) self._initialkids = [_fake_kid] pass return list(self._initialkids) + list(regularkids) def edit(self): cntl = PartProp(self.assy) #bruce comment 050420: PartProp is passed assy and gets its stats from assy.tree. # This needs revision if it should someday be available for Parts on the clipboard. cntl.exec_() self.assy.mt.mt_update() def description_for_history(self): """ [overridden from Group method] """ return "Part Name: [" + self.name +"]" pass class ClipboardShelfGroup(Group): """ A specialized Group for holding the Clipboard (aka Shelf). """ def postcopy_in_mapping(self, mapping): #bruce 050524 assert 0, "ClipboardShelfGroup.postcopy_in_mapping should never be called!" def pick(self): #bruce 050131 for Alpha msg = "Clipboard can't be selected or dragged. (Individual clipboard items can be.)" env.history.statusbar_msg( msg) def is_selection_group_container(self): return True #bruce 050131 for Alpha def rename_enabled(self): return False def drag_move_ok(self): return False def drag_copy_ok(self): return False def drop_on_should_autogroup(self, drag_type, nodes): #bruce 071025 """ [overrides Node method] """ # note: drop on clipboard makes a new clipboard item. return len(nodes) > 1 def permits_ungrouping(self): return False ##bruce 050316: does always being openable work around the bugs in which this node is not open when it should be? ###e btw we need to make sure it becomes open whenever it contains the current part. ####@@@@ ## def openable(self): # overrides Node.openable() ## "whether tree widgets should permit the user to open/close their view of this node" ## non_empty = (len(self.members) > 0) ## return non_empty def _class_for_copies(self, mapping): #bruce 080314, preserving original behavior; probably not needed del mapping print "why is %r being copied?" % self # since I think this should never be called return Group def node_icon(self, display_prefs): del display_prefs # unlike most Groups, we don't even care about 'open' non_empty = (len(self.members) > 0) if non_empty: kluge_pixmap = imagename_to_pixmap("modeltree/clipboard-full.png") res = imagename_to_pixmap("modeltree/clipboard-full.png") else: kluge_pixmap = imagename_to_pixmap("modeltree/clipboard-gray.png") res = imagename_to_pixmap("modeltree/clipboard-empty.png") # kluge: guess: makes paste tool look enabled or disabled ###@@@ clean this up somehow?? believe it or not, it might actually be ok... self.assy.w.editPasteAction.setIcon(QtGui.QIcon(kluge_pixmap)) return res def edit(self): return "The Clipboard does not yet provide a property-editing dialog." def editProperties_enabled(self): return False def description_for_history(self): """ [overridden from Group method] """ return "Clipboard" def getPastables(self): """ """ pastables = [] pastables = filter(is_pastable, self.members) return pastables pass class RootGroup(Group): """ A specialized Group for holding the entire model tree's toplevel nodes, which (by coincidence? probably more like a historical non-coincidence) imitates the assy.root member of the pre-050109 code. [This will be revised... ###@@@] [btw i don't know for sure that this is needed at all...] ###obs doc, but reuse some of it: This is what the pre-050108 code made or imitated in modelTree as a Group called ROOT. ###k i think This will be revised soon, because (1) the Assembly itself might as well be this Node, (2) the toplevel members of an Assembly will differ from what they are now. """ def postcopy_in_mapping(self, mapping): #bruce 050524 assert 0, "RootGroup.postcopy_in_mapping should never be called!" def pick(self): #bruce 050131 for Alpha self.redmsg( "Internal error: tried to select assy.root (ignored)" ) #e does this need to differ from a Group? maybe in some dnd/rename attrs... # or maybe not, since only its MT_kids are shown (not itself) ###@@@ # (we do use the fact that it differs in class from a Group # as a signal that we might need to replace it... not sure if this is needed) pass # end
NanoCAD-master
cad/src/model/assembly.py
# Copyright 2004-2008 Nanorex, Inc. See LICENSE file for details. """ jigs_motors.py -- Classes for motors. @version: $Id$ @copyright: 2004-2008 Nanorex, Inc. See LICENSE file for details. History: 050927. Split off Motor jigs from jigs.py into this file. Mark """ # imports from math vs. Numeric as discovered from running code on 2007/06/25. from math import asin, atan2 from Numeric import pi from Numeric import sqrt from Numeric import dot from Numeric import argmax from Numeric import reshape from OpenGL.GL import glPushMatrix from OpenGL.GL import glTranslatef from OpenGL.GL import glRotatef from OpenGL.GL import glPopMatrix import foundation.env as env from geometry.VQT import V, Q, A, norm, cross, vlen from graphics.drawing.CS_draw_primitives import drawcylinder from graphics.drawing.drawers import drawRotateSign from graphics.drawing.drawers import drawbrick from graphics.drawing.drawers import drawLinearSign from utilities.Log import orangemsg from utilities.Log import redmsg, greenmsg from graphics.rendering.povray.povheader import povpoint #bruce 050413 from utilities.debug import print_compact_stack, print_compact_traceback from model.jigs import Jig from utilities.constants import gray # == Motors class Motor(Jig): """ superclass for Motor jigs """ axis = V(0,0,0) #bruce 060120; redundant with some subclass inits; some code could handle None here, but I'm not sure it all could. # WARNING: this is added to copyable_attrs in subclasses, not here, and is not added to mutable_attrs (possible bug). ###@@@ # Also, self.center is not in mutable_attrs, but is modified by += , which is a likely bug. ####@@@@ # [bruce 060228 comment] is_movable = True #mark 060120 def __init__(self, assy, atomlist = []): #bruce 050526 added optional atomlist arg assert atomlist == [] # whether from default arg value or from caller -- for now Jig.__init__(self, assy, atomlist) self.quat = Q(1, 0, 0, 0) # is self.quat ever set to other values? if not, remove it; if so, add it to mutable_attrs. [bruce 060228 comment] #The motor is usually drawn as an opaque object. However when it is #being previewed, it is drawn as a transparent object - Ninad 2007-10-09 self.previewOpacity = 0.4 self.defaultOpacity = 1.0 self.opacity = self.defaultOpacity # == The following methods were moved from RotaryMotor to this class by bruce 050705, # since some were almost identical in LinearMotor (and those were removed from it, as well) # and others are wanted in it in order to implement "Recenter on atoms" in LinearMotor. # for a motor read from a file, the "shaft" record def setShaft(self, shaft): self.setAtoms(shaft) #bruce 041105 code cleanup self._initial_posns = None #bruce 050518; needed in RotaryMotor, harmless in others # for a motor created by the UI, center is average point and # axis is [as of 060120] computed as roughly normal to the shape of that set. def findCenterAndAxis(self, shaft, glpane): #bruce 060120 renamed this from findCenter, replaced los arg with glpane re bug 1344 self.setAtoms(shaft) #bruce 041105 code cleanup self.recompute_center_axis(glpane) return def recompute_center_axis(self, glpane): #bruce 060120 replaced los arg with glpane re bug 1344 # try to point in direction of prior axis, or along line of sight if no old axis (self.axis is V(0,0,0) then) nears = [self.axis, glpane.lineOfSight, glpane.down] pos = A( map( lambda a: a.posn(), self.atoms ) ) self.center = sum(pos)/len(pos) relpos = pos - self.center from geometry.geometryUtilities import compute_heuristic_axis axis = compute_heuristic_axis( relpos, 'normal', already_centered = True, nears = nears, dflt = None ) if not axis: #e warning? I think so... BTW we pass dflt = None to make the warning come out more often; # I don't know if we'd need to check for it here if we didn't. env.history.message( orangemsg( "Warning: motor axis chosen arbitrarily since atom arrangement doesn't suggest one." )) #k can this come out too often during movie-playing? No, because we don't recompute axis then at all. axis = glpane.lineOfSight self.axis = axis self.assy.changed() #bruce 060116 fix unreported bug analogous to bug 1331 self._initial_posns = None #bruce 050518; needed in RotaryMotor, harmless in others return def recenter_on_atoms(self): "called from model tree cmenu command" self.recompute_center_axis(self.assy.o) #bruce 060120 pass glpane for its "point of view" (re bug 1344) #e maybe return whether we moved?? return def __CM_Recenter_on_atoms(self): #bruce 050704 moved this from modelTree.py and made it use newer system for custom cmenu cmds """ Rotary or Linear Motor context menu command: "Recenter on atoms" """ ##e it might be nice to dim this menu item if the atoms haven't moved since this motor was made or recentered; # first we'd need to extend the __CM_ API to make that possible. [bruce 050704] cmd = greenmsg("Recenter on Atoms: ") self.recenter_on_atoms() info = "Recentered motor [%s] for current atom positions" % self.name env.history.message( cmd + info ) self.assy.w.win_update() # (glpane might be enough, but the other updates are fast so don't bother figuring it out) return def __CM_Align_to_chunk(self): """ Rotary or Linear Motor context menu command: "Align to chunk" This uses the chunk connected to the first atom of the motor. """ # I needed this when attempting to simulate the rotation of a long, skinny # chunk. The axis computed from the attached atoms was not close to the axis # of the chunk. I figured this would be a common feature that was easy to add. # ##e it might be nice to dim this menu item if the chunk's axis hasn't moved since this motor was made or recentered; # first we'd need to extend the __CM_ API to make that possible. [mark 050717] cmd = greenmsg("Align to Chunk: ") chunk = self.atoms[0].molecule # Get the chunk attached to the motor's first atom. # wware 060116 bug 1330 # The chunk's axis could have its direction exactly reversed and be equally valid. # We should choose between those two options for which one has the positive dot # product with the old axis, to avoid reversals of motor direction when going # between "align to chunk" and "recenter on atoms". #bruce 060116 modified this fix to avoid setting axis to V(0,0,0) if it's perpendicular to old axis. newAxis = chunk.getaxis() if dot(self.axis,newAxis) < 0: newAxis = - newAxis self.axis = newAxis self.assy.changed() # wware 060116 bug 1331 - assembly changed when axis changed info = "Aligned motor [%s] on chunk [%s]" % (self.name, chunk.name) env.history.message( cmd + info ) self.assy.w.win_update() return def __CM_Reverse_direction(self): #bruce 060116 new feature (experimental) """ Rotary or Linear Motor context menu command: "Reverse direction" """ cmd = greenmsg("Reverse direction: ") self.reverse_direction() info = "Reversed direction of motor [%s]" % self.name env.history.message( cmd + info ) self.assy.w.win_update() # (glpane might be enough, but the other updates are fast so don't bother figuring it out) return def reverse_direction(self): #bruce 060116 "Negate axis of this motor in order to reverse its direction." self.axis = - self.axis self.assy.changed() return def move(self, offset): ###k NEEDS REVIEW: does this conform to the new Node API method 'move', # or should it do more invalidations / change notifications / updates? [bruce 070501 question] self.center += offset def rot(self, q): self.axis = q.rot(self.axis) #mark 060120. def posn(self): return self.center def getaxis(self): # todo: merge somehow with getaxis methods on other Nodes return self.axis def axen(self): return self.axis def remove_atom(self, *args, **opts): self._initial_posns = None #bruce 050518; needed in RotaryMotor, harmless in others return Jig.remove_atom(self, *args, **opts) def make_selobj_cmenu_items(self, menu_spec): """ Add Motor-specific context menu items to <menu_spec> list when self is the selobj. """ Jig.make_selobj_cmenu_items(self, menu_spec) #bruce 060313 share this code (it is identical to the following commented out code) ## item = ('Hide', self.Hide) ## menu_spec.append(item) ## if self.disabled_by_user_choice: ## item = ('Disabled', self.toggleJigDisabled, 'checked') ## else: ## item = ('Disable', self.toggleJigDisabled, 'unchecked') ## menu_spec.append(item) ## menu_spec.append(None) # Separator ## item = ('Properties...', self.edit) ## menu_spec.append(item) item = ('Align to Chunk', self.__CM_Align_to_chunk) menu_spec.append(item) item = ('Recenter on Atoms', self.__CM_Recenter_on_atoms) menu_spec.append(item) item = ('Reverse Direction', self.__CM_Reverse_direction) menu_spec.append(item) def updateCosmeticProps(self, previewing = False): """ Update the cosmetic properties of motor """ if not previewing: try: self.opacity = self.defaultOpacity except: print_compact_traceback("Can't set properties for the Rotary"\ "Motor object. Ignoring exception.") else: self.opacity = self.previewOpacity pass # end of class Motor # == RotaryMotor class RotaryMotor(Motor): """ A Rotary Motor has an axis, represented as a point and a direction vector, a stall torque, a no-load speed, and a set of atoms connected to it To Be Done -- selecting & manipulation """ sym = "RotaryMotor" # Was "Rotary Motor" (removed space). Mark 2007-05-28 icon_names = ["modeltree/Rotary_Motor.png", "modeltree/Rotary_Motor-hide.png"] featurename = "Rotary Motor" #bruce 051203 _initial_posns = None #bruce 060310 added default values for _initial_* and added them to copyable_attrs, to fix bug 1656 _initial_quats = None copyable_attrs = Motor.copyable_attrs + ('torque', 'initial_speed', 'speed', 'enable_minimize', 'dampers_enabled', \ 'length', 'radius', 'sradius', \ 'center', 'axis', \ '_initial_posns', '_initial_quats' ) def __init__(self, assy, editCommand = None, atomlist = []): """ create a blank Rotary Motor not connected to anything """ # [note (bruce 071128): future copy-code cleanup will require either # that the atomlist argument comes before the editCommand argument, # or that _um_initargs is overridden.] assert atomlist == [] # whether from default arg value or from caller -- for now Motor.__init__(self, assy, atomlist) self.torque = 0.0 # in nN * nm self.initial_speed = 0.0 # in gHz self.speed = 0.0 # in gHz self.center = V(0,0,0) self.axis = V(0,0,0) self._initial_posns = None #bruce 050518 # We need to reset _initial_posns to None whenever we recompute # self.axis from scratch or change the atom list in any way (even reordering it). # For now, we do this everywhere it's needed "by hand", # rather than in some (not yet existing) systematic and general way. # set default color of new rotary motor to gray self.color = gray # This is the "draw" color. When selected, this will become highlighted red. self.normcolor = gray # This is the normal (unselected) color. self.length = 10.0 # default length of Rotary Motor cylinder self.radius = 1.0 # default cylinder radius self.sradius = 0.2 #default spoke radius # Should self.cancelled be in RotaryMotorProp.setup? - Mark 050109 self.cancelled = True # We will assume the user will cancel self.editCommand = editCommand def edit(self): """ Overrides jig.edit. """ commandSequencer = self.assy.w.commandSequencer commandSequencer.userEnterCommand('ROTARY_MOTOR', always_update = True) currentCommand = commandSequencer.currentCommand assert currentCommand.commandName == 'ROTARY_MOTOR' #When a Motor object read from an mmp file is edited, we need to assign #it an editCommand. So, when it is resized, the propMgr spinboxes #are properly updated. See also Plane.resizeGeometry. if self.editCommand is None: self.editCommand = currentCommand currentCommand.editStructure(self) if self is self.assy.o.selobj: self.assy.o.selobj = None ###e shouldn't we use set_selobj instead?? [bruce 060726 question] # If the Properties dialog was selected from the GLPane's context menu, set selobj = None # so that we can see the jig's real color, not the highlighted color. This is very important # when changing the jig's color from the properties dialog since it will remain highlighted # if we don't do this. mark 060312. def setProps(self, props): """ Set the Rotary Motor properties. It is called while reading a MMP file record or to restore the old properties if user cancels edit operation on an exsiting motor. @param props: The rotary motor properties to be set. @type props: tuple """ self.name, self.color, self.torque, \ self.speed, self.center, self.axis,\ self.length, self.radius, self.sradius = props self._initial_posns = None def getProps(self): """ Return the current properties of the Rotary motor. @return: The current properties of the rotary motor @rtype: tuple """ return (self.name, self.color, self.torque, self.speed, self.center, self.axis, self.length, self.radius, self.sradius) def _getinfo(self): return "[Object: Rotary Motor] [Name: " + str(self.name) + "] " + \ "[Torque = " + str(self.torque) + " nN-nm] " + \ "[Speed = " + str(self.speed) + " GHz]" def _getToolTipInfo(self): #ninad060825 "Return a string for display in Dynamic Tool tip " from platform_dependent.PlatformDependent import fix_plurals attachedAtomCount = fix_plurals("Attached to %d atom(s)"%(len(self.atoms))) return str(self.name) + "<br>" + "<font color=\"#0000FF\"> Jig Type:</font>Rotary Motor"\ + "<br>" + "<font color=\"#0000FF\">Torque: </font>" + str(self.torque) + " nN-nm " \ + "<br>" + "<font color=\"#0000FF\">Speed:</font> " + str(self.speed) + " GHz" \ + "<br>" + str(attachedAtomCount) def getstatistics(self, stats): stats.nrmotors += 1 def norm_project_posns(self, posns): """ [Private helper for getrotation] Given a Numeric array of position vectors relative to self.center, project them along self.axis and normalize them (and return that -- but we take ownership of posns passed to us, so we might or might not modify it and might or might not return the same (modified) object. """ axis = self.axis dots = dot(posns, axis) ## axis_times_dots = axis * dots # guess from this line: exceptions.ValueError: frames are not aligned axis_times_dots = A(len(dots) * [axis]) * reshape(dots,(len(dots),1)) #k would it be ok to just use axis * ... instead? posns -= axis_times_dots ##posns = norm(posns) # some exception from this posns = A(map(norm, posns)) # assumes no posns are right on the axis! now we think they are on a unit circle perp to the axis... # posns are now projected to a plane perp to axis and centered on self.center, and turned into unit-length vectors. return posns # (note: in this implem, we did modify the mutable argument posns, but are returning a different object anyway.) def getrotation(self): #bruce 050518 new feature for showing rotation of rmotor in its cap-arrow """ Return a rotation angle for the motor. This is arbitrary, but rotates smoothly with the atoms, averaging out their individual thermal motion. It is not history-dependent -- e.g. it will be consistent regardless of how you jump around among the frames of a movie. But if we ever implement remaking or revising the motor position, or if you delete some of the motor's atoms, this angle is forgotten and essentially resets to 0. (That could be fixed, and the angle even saved in the mmp file, if desired. See code comments for other possible improvements.) """ # possible future enhancements: # - might need to preserve rotation when we forget old posns, by setting an arb offset then; # - might need to preserve it in mmp file?? # - might need to draw it into PovRay file?? # - might need to preserve it when we translate or rotate entire jig with its atoms (doing which is NIM for now) # - could improve and generalize alg, and/or have sim do it (see comments below for details). # posns = A(map( lambda a: a.posn(), self.atoms )) posns -= self.center if self._initial_posns is None: # (we did this after -= center, so no need to forget posns if we translate the entire jig) self._initial_posns = posns # note, we're storing *relative* positions, in spite of the name! self._initial_quats = None # compute these the first time they're needed (since maybe never needed) return 0.0 # returning this now (rather than computing it below) is just an optim, in theory assert len(self._initial_posns) == len(posns), "bug in invalidating self._initial_posns when rmotor atoms change" if not (self._initial_posns != posns): # have to use not (x != y) rather than (x == y) due to Numeric semantics! # no (noticable) change in positions - return quickly # (but don't change stored posns, in case this misses tiny changes which could accumulate over time) # (we do this before the subsequent stuff, to not waste redraw time when posns don't change; # just re correctness, we could do it at a later stage) return 0.0 # now we know the posns are different, and we have the old ones to compare them to. posns = self.norm_project_posns( posns) # this might modify posns object, and might return same or different object quats = self._initial_quats if quats is None: # precompute a quat to rotate new posns into a standard coord system for comparison to old ones # (Q args must be orthonormal and right-handed) oldposns = + self._initial_posns # don't modify those stored initial posns # (though it probably wouldn't matter if we did -- from now on, # they are only compared to None and checked for length, as of 050518) oldposns = self.norm_project_posns( oldposns) axis = self.axis quats = self._initial_quats = [ Q(axis,pos1,cross(axis,pos1)) for pos1 in oldposns ] angs = [] for qq, pos2 in zip( self._initial_quats, posns): npos2 = qq.unrot(pos2) # now npos2 is in yz plane, and pos1 (if transformed) would just be the y axis in that plane; # just get its angle in that plane (defined so that if pos2 = pos1, ie npos2 = (0,1,0), then angle is 0) ang = angle(npos2[1], npos2[2]) # in degrees angs.append(ang) # now average these angles, paying attention to their being on a circle # (which means the average of 1 and 359 is 0, not 180!) angs.sort() # Warning: this sort is only correct since we know they're in the range [0,360] (inclusive range is ok). # It might be correct for any range that covers the circle exactly once, e.g. [-180,180] # (not fully analyzed for that), but it would definitely be wrong for e.g. [-0.001, 360.001]! # So be careful if you change how angle() works. angs = A(angs) gaps = angs[1:] - angs[:-1] gaps = [angs[0] - angs[-1] + 360] + list(gaps) i = argmax(gaps) ##e Someday we should check whether this largest gap is large enough for this to make sense (>>180); # we are treating the angles as "clustered together in the part of the circle other than this gap" # and averaging them within that cluster. It would also make sense to discard outliers, # but doing this without jittering the rotation angle (as individual points become closer # to being outliers) would be challenging. Maybe better to just give up unless gap is, say, >>340. ##e Before any of that, just get the sim to do this in a better way -- interpret the complete set of # atom motions as approximating some overall translation and rotation, and tell us this, so we can show # not only rotation, but axis wobble and misalignment, and so these can be plotted. angs = list(angs) angs = angs[i:] + angs[:i] # start with the one just after the largest gap relang0 = angs[0] angs = A(angs) - relang0 # be relative to that, when we average them # but let them all be in the range [0,360)! angs = (angs + 720) % 360 # We need to add 720 since Numeric's mod produces negative outputs # for negative inputs (unlike Python's native mod, which is correct)! # How amazingly ridiculous. ang = (sum(angs) / len(angs)) + relang0 ang = ang % 360 # this is Python mod, so it's safe return ang def _draw_jig(self, glpane, color, highlighted=False): """ Draw a Rotary Motor jig as a cylinder along the axis, with a thin cylinder (spoke) to each atom. If <highlighted> is True, the Rotary Motor is draw slightly larger. """ ## print "RMotor _draw_jig",env.redraw_counter # This confirms that Jigs are drawn more times than they ought to need to be, # possibly due to badly organized Jig hit-testing code -- 4 times on mouseenter that highlights them in Build mode # (even after I fixed a bug today in which it redrew the entire model twice each frame); # but it's hard to find something to compare it to for an objective test of whether being a Jig matters, # since atoms, bonds, and chunks all have special behavior of their own. BTW, the suspected bad Jig code might redraw # everything (not only Jigs) this often, even though all it cares about is seeing Jigs in glRenderMode output. # BTW2, on opening a file containing one jig, it was drawn something like 20 times. # [bruce 060724 comments] if highlighted: inc = 0.01 # tested. Fixes bug 1681. mark 060314. else: inc = 0.0 glPushMatrix() try: glTranslatef( self.center[0], self.center[1], self.center[2]) q = self.quat glRotatef( q.angle*180.0/pi, q.x, q.y, q.z) orig_center = V(0.0, 0.0, 0.0) bCenter = orig_center - (self.length / 2.0 + inc) * self.axis tCenter = orig_center + (self.length / 2.0 + inc) * self.axis drawcylinder(color, bCenter, tCenter, self.radius + inc, capped = 1, opacity = self.opacity ) for a in self.atoms: drawcylinder(color, orig_center, a.posn()-self.center, self.sradius + inc, opacity = self.opacity) rotby = self.getrotation() #bruce 050518 # if exception in getrotation, just don't draw the rotation sign # (safest now that people might believe what it shows about amount of rotation) drawRotateSign((0,0,0), bCenter, tCenter, self.radius, rotation = rotby) except: #bruce 060208 protect OpenGL stack from exception seen in bug 1445 print_compact_traceback("exception in RotaryMotor._draw, continuing: ") print " some info that might be related to that exception: natoms = %d" % len(self.atoms) ###@@@ might not keep this glPopMatrix() return # Write "rmotor" and "spoke" records to POV-Ray file in the format: # rmotor(<cap-point>, <base-point>, cylinder-radius, <r, g, b>) # spoke(<cap-point>, <base-point>, scylinder-radius, <r, g, b>) def writepov(self, file, dispdef): if self.hidden: return if self.is_disabled(): return #bruce 050421 c = self.posn() a = self.axen() file.write("rmotor(" + povpoint(c+(self.length / 2.0)*a) + "," + povpoint(c-(self.length / 2.0)*a) + "," + str (self.radius) + ",<" + str(self.color[0]) + "," + str(self.color[1]) + "," + str(self.color[2]) + ">)\n") for a in self.atoms: if vlen(c - a.posn()) > 0.001: #bruce 060808 add condition to see if this fixes bug 719 (two places in this file) file.write("spoke(" + povpoint(c) + "," + povpoint(a.posn()) + "," + str (self.sradius) + ",<" + str(self.color[0]) + "," + str(self.color[1]) + "," + str(self.color[2]) + ">)\n") # Returns the jig-specific mmp data for the current Rotary Motor as: # torque speed (cx, cy, cz) (ax, ay, az) length radius sradius \n shaft mmp_record_name = "rmotor" def mmp_record_jigspecific_midpart(self): cxyz = self.posn() * 1000 axyz = self.axen() * 1000 #bruce 060307 %.2f -> %.6f for params used by sim, %.2f -> %.3f for graphics-only params # (Note that for backwards compatibility we are constrained by files_mmp regexps which require these fields # to be 1 or more digits, '.', 1 or more digits. I'm more sure this is true of %.6f than of %f, though # in my tests these seemed equivalent. When someone has time they should check out python docs on this. [bruce 060307]) dataline = "%.6f %.6f (%d, %d, %d) (%d, %d, %d) %.3f %.3f %.3f" % \ (self.torque, self.speed, int(cxyz[0]), int(cxyz[1]), int(cxyz[2]), int(axyz[0]), int(axyz[1]), int(axyz[2]), self.length, self.radius, self.sradius ) return " " + dataline + "\n" + "shaft" def writemmp_info_leaf(self, mapping): #mark 060307 [bruce revised Jig -> Motor same day, should have no effect] "[extends superclass method]" Motor.writemmp_info_leaf(self, mapping) if self.initial_speed: # Note: info record not written if initial_speed = 0.0 (default). mapping.write("info leaf initial_speed = " + str(self.initial_speed) + "\n") # Note: this assumes all Python float formats (from str) can be read by the sim C code using atof(). # Whether this is true needs testing, by trying out lots of sizes of values of initial speed # (perhaps negative too, if cad UI permits that). Ints might also be possible here (not sure), # so the sim reading code should permit them too. [bruce 060307 comment] return def readmmp_info_leaf_setitem( self, key, val, interp ): #mark 060307 [bruce revised Jig -> Motor same day, should have no effect] "[extends superclass method]" if key == ['initial_speed']: self.initial_speed = float(val) #bruce 060307 added "float" (not sure if this really matters, since cad doesn't compute with it) else: Motor.readmmp_info_leaf_setitem( self, key, val, interp) return pass # end of class RotaryMotor def angle(x,y): #bruce 050518; see also atan2 (noticed used in VQT.py) which might do roughly the same thing """ Return the angle above the x axis of the line from 0,0 to x,y, in a numerically stable way, assuming vlen(V(x,y)) is very close to 1.0. """ if y < 0: return 360 - angle(x,-y) if x < 0: return 180 - angle(-x,y) if y > x: return 90 - angle(y,x) #e here we could normalize length if we felt like it, # and/or repair any glitches in continuity at exactly 45 degrees res = asin(y)*180/pi #print "angle(%r,%r) -> %r" % (x,y,res) if res < 0: return res + 360 # should never happen return res # == LinearMotor class LinearMotor(Motor): """ A Linear Motor has an axis, represented as a point and a direction vector, a force, a stiffness, and a set of atoms connected to it To Be Done -- selecting & manipulation """ sym = "LinearMotor" # Was "Linear Motor" (removed space). Mark 2007-05-28 icon_names = ["modeltree/Linear_Motor.png", "modeltree/Linear_Motor-hide.png"] featurename = "Linear Motor" #bruce 051203 copyable_attrs = Motor.copyable_attrs + ('force', 'stiffness', 'length', 'width', 'sradius', 'center', 'axis', \ 'enable_minimize', 'dampers_enabled') def __init__(self, assy, command = None, atomlist = []): """ create a blank Linear Motor not connected to anything """ # [note (bruce 071128): future copy-code cleanup will require either # that the atomlist argument comes before the command argument, # or that _um_initargs is overridden.] assert atomlist == [] # whether from default arg value or from caller -- for now Motor.__init__(self, assy, atomlist) self.force = 0.0 self.stiffness = 0.0 self.center = V(0,0,0) self.axis = V(0,0,0) # set default color of new linear motor to gray self.color = gray # This is the "draw" color. When selected, this will become highlighted red. self.normcolor = gray # This is the normal (unselected) color. self.length = 10.0 # default length of Linear Motor box self.width = 2.0 # default box width self.sradius = 0.2 #default spoke radius self.cancelled = True # We will assume the user will cancel self.command = command def edit(self): """ Overrides jig.edit. """ commandSequencer = self.assy.w.commandSequencer commandSequencer.userEnterCommand('LINEAR_MOTOR', always_update = True) currentCommand = commandSequencer.currentCommand assert currentCommand.commandName == 'LINEAR_MOTOR' #When a Motor object read from an mmp file is edited, we need to assign #it an command. So, when it is resized, the propMgr spinboxes #are properly updated. See also Plane.resizeGeometry. if self.command is None: self.command = currentCommand currentCommand.editStructure(self) if self is self.assy.o.selobj: self.assy.o.selobj = None ###e shouldn't we use set_selobj instead?? [bruce 060726 question] # If the Properties dialog was selected from the GLPane's context menu, set selobj = None # so that we can see the jig's real color, not the highlighted color. This is very important # when changing the jig's color from the properties dialog since it will remain highlighted # if we don't do this. mark 060312. def getProps(self): """ Return the current properties of the Rotary motor. @return: The current properties of the rotary motor @rtype: tuple """ return (self.name, self.color, self.force, self.stiffness, self.center, self.axis, self.length, self.width, self.sradius) # set the properties for a Linear Motor read from a (MMP) file def setProps(self, props): """ Set the Linear Motor properties. It is called while reading a MMP file record or to restore the old properties if user cancels edit operation on an exsiting motor. @param props: The linear motor properties to be set. @type props: tuple """ self.name, self.color, self.force, \ self.stiffness, self.center, \ self.axis, self.length, \ self.width, self.sradius = props def _getinfo_TEST(self): # please leave in for debugging POV-Ray lmotor macro. mark 060324 a = self.axen() xrot = -atan2(a[1], sqrt(1-a[1]*a[1]))*180/pi yrot = atan2(a[0], sqrt(1-a[0]*a[0]))*180/pi return "[Object: Linear Motor] [Name: " + str(self.name) + "] " + \ "[Force = " + str(self.force) + " pN] " + \ "[Stiffness = " + str(self.stiffness) + " N/m] " + \ "[Axis = " + str(self.axis[0]) + ", " + str(self.axis[1]) + ", " + str(self.axis[2]) + "]" + \ "[xRotation = " + str(xrot) + ", yRotation = " + str(yrot) + "]" def _getinfo(self): return "[Object: Linear Motor] [Name: " + str(self.name) + "] " + \ "[Force = " + str(self.force) + " pN] " + \ "[Stiffness = " + str(self.stiffness) + " N/m]" def _getToolTipInfo(self): #ninad060825 "Return a string for display in Dynamic Tool tip " from platform_dependent.PlatformDependent import fix_plurals attachedAtomCount = fix_plurals("Attached to %d atom(s)"%(len(self.atoms))) return str(self.name) + "<br>" + "<font color=\"#0000FF\"> Jig Type:</font>Linear Motor"\ + "<br>" + "<font color=\"#0000FF\">Force: </font>" + str(self.force) + " pN " \ + "<br>" + "<font color=\"#0000FF\">Stiffness:</font> " + str(self.stiffness) + " N/m" \ + "<br>" + str(attachedAtomCount) def getstatistics(self, stats): stats.nlmotors += 1 def _draw_jig(self, glpane, color, highlighted=False): """ Draw a linear motor as a long box along the axis, with a thin cylinder (spoke) to each atom. """ glPushMatrix() try: glTranslatef( self.center[0], self.center[1], self.center[2]) q = self.quat glRotatef( q.angle*180.0/pi, q.x, q.y, q.z) orig_center = V(0.0, 0.0, 0.0) drawbrick(color, orig_center, self.axis, self.length, self.width, self.width, opacity = self.opacity) drawLinearSign((0,0,0), orig_center, self.axis, self.length, self.width, self.width) # (note: drawLinearSign uses a small depth offset so that arrows are slightly in front of brick) # [bruce comment 060302, a guess from skimming drawLinearSign's code] for a in self.atoms[:]: drawcylinder(color, orig_center, a.posn()-self.center, self.sradius, opacity = self.opacity) except: #bruce 060208 protect OpenGL stack from exception analogous to that seen for RotaryMotor in bug 1445 print_compact_traceback("exception in LinearMotor._draw, continuing: ") glPopMatrix() # Write "lmotor" and "spoke" records to POV-Ray file in the format: # lmotor(<corner-point1>, <corner-point2>, <yrotate>, <yrotate>, <translate>, <r, g, b>) # spoke(<cap-point>, <base-point>, sbox-radius, <r, g, b>) def writepov(self, file, dispdef): if self.hidden: return if self.is_disabled(): return #bruce 050421 c = self.posn() a = self.axen() xrot = -atan2(a[1], sqrt(1-a[1]*a[1]))*180/pi yrot = atan2(a[0], sqrt(1-a[0]*a[0]))*180/pi file.write("lmotor(" \ + povpoint([self.width * 0.5, self.width * 0.5, self.length * 0.5]) + "," \ + povpoint([self.width * -0.5, self.width * -0.5, self.length * -0.5]) + "," \ + "<0.0, " + str(yrot) + ", 0.0>," \ + "<" + str(xrot) + ", 0.0, 0.0>," \ + povpoint(c) + "," \ + "<" + str(self.color[0]) + "," + str(self.color[1]) + "," + str(self.color[2]) + ">)\n") for a in self.atoms: if vlen(c - a.posn()) > 0.001: #bruce 060808 add condition to see if this fixes bug 719 (two places in this file) file.write("spoke(" + povpoint(c) + "," + povpoint(a.posn()) + "," + str (self.sradius) + ",<" + str(self.color[0]) + "," + str(self.color[1]) + "," + str(self.color[2]) + ">)\n") # Returns the jig-specific mmp data for the current Linear Motor as: # force stiffness (cx, cy, cz) (ax, ay, az) length width sradius \n shaft mmp_record_name = "lmotor" def mmp_record_jigspecific_midpart(self): cxyz = self.posn() * 1000 axyz = self.axen() * 1000 #bruce 060307 %.6f left as is for params used by sim, %.2f -> %.3f for graphics-only params # (see further comments in RotaryMotor method) dataline = "%.6f %.6f (%d, %d, %d) (%d, %d, %d) %.3f %.3f %.3f" % \ (self.force, self.stiffness, #bruce 050705 swapped force & stiffness order here, to fix bug 746; # since linear motors have never worked in sim in a released version, # and since this doesn't change the meaning of existing mmp files # (only the way the setup dialog generates them, making it more correct), # I'm guessing it's ok that this changes the actual mmp file-writing format # (to agree with the documented format and the reading-format) # and I'm guessing that no change to the format's required-date is needed. #bruce 050706 increased precision of force & stiffness from 0.01 to 0.000001 # after email discussion with josh. int(cxyz[0]), int(cxyz[1]), int(cxyz[2]), int(axyz[0]), int(axyz[1]), int(axyz[2]), self.length, self.width, self.sradius ) return " " + dataline + "\n" + "shaft" pass # end of class LinearMotor # end of module jigs_motors.py
NanoCAD-master
cad/src/model/jigs_motors.py
# Copyright 2004-2009 Nanorex, Inc. See LICENSE file for details. """ atomtypes.py -- AtomType object, knows about one bonding pattern for one element. @author: Josh, Bruce @version: $Id$ @copyright: 2004-2009 Nanorex, Inc. See LICENSE file for details. History: Bruce 050510 moved some code (originally by Josh) out of Elem.__init__ into new class AtomType.__init__ and added all the superstructure, as part of supporting atom types with variable bonding patterns (and higher-order bonds, though as of 050511 these atoms don't yet know anything directly about bond-orders and their .valence attribute is probably not yet used [later: now it's used].) bruce 050513 replaced some == with 'is' and != with 'is not', to avoid __getattr__ on __xxx__ attrs in python objects. """ # element.atomtypes -> list of atom types usable for that element # atom.atomtype -> current atomtype for that atom from geometry.VQT import Q from utilities.Log import redmsg from utilities import debug_flags from foundation.state_utils import IdentityCopyMixin import foundation.env as env from model.bond_constants import V_SINGLE, V_DOUBLE, V_TRIPLE, V_AROMATIC, V_GRAPHITE, V_CARBOMERIC class AtomType(IdentityCopyMixin): """ An atom type includes an element and its bonding pattern (and maybe more) -- enough info to know how to construct things in Build mode using this element in this bonding pattern, something about how the user wants to simulate them or minimize them (externally or wirthin Build mode), etc. This is designed more for the UI than for the simulator, which might need even finer distinctions to properly simulate atoms. The idea is to include in this class whatever the user needs for convenient building, and to later infer from the pattern of actual bonds and surrounding atoms (as well as the info in this object) how best to simulate an atom using this atomtype object. An atomtype object can be used alone to create a free or attached atom, and might also be kept around by the atom as its way of remembering its own type -- which might change. Or an atom might just remember the *name* of its atomtype (and grab this object from a list in the element) -- I don't know yet. ###obs, probably wrong: Note that (as far as is yet known) more than one identical atomtype object might exist -- so the object itself is not an ok place to store definitive mutable per-session info about how to treat that atom type. The name of an atomtype might be reused for more than one element (e.g. 'sp2') but the atomtype itself is element-specific. (Related atomtype objects might share code or data, of course.) """ def __init__(self, elem, name, formalCharge, electronsNeeded, electronsProvided, covalentRadius, bondvectors): """ #doc... Set some public members, including element, name, fullname, numbonds, valence, rcovalent, bondvectors, base, and quats. Also spX, openbond; and for some elements, num_lonepairs (etc), num_pi_electrons. """ self.element = elem # electronsProvided + formalCharge should equal group number # these are shared from another atom (half of an order 1 covalent bond) electronsShared = electronsNeeded - electronsProvided self.valence = electronsShared # total bond order for all bonds to this atomtype self.name = name = name or "?" # default name won't show up except for bugs, provided it's only used for elements with only one atomtype self.fullname = elem.name + '/' + self.name #ok? [see also self.fullname_for_msg()] self.openbond = (elem.eltnum == 0) if name.startswith("sp3") or name == "?": spX = 3 elif name.startswith("sp2"): # including sp2 and sp2(graphitic) spX = 2 elif name.startswith("sp") and (name == "sp" or not name[2].isdigit()): spX = 1 else: print "warning: bug: atomtype name in %r does not start with sp, sp2, or sp3; assuming sp3 in bonds code" % self.fullname spX = 3 self.spX = spX if 0 and debug_flags.atom_debug and (spX != 3 or self.openbond): print "atom_debug: fyi: %r has spX == %d" % (self.fullname, spX) self.rcovalent = covalentRadius self.base = None self.quats = [] # ends up one shorter than self.numbonds [bruce 041217] if (bondvectors): # number of distinct bonds to different other atoms (a # double bond is counted as 1) self.numbonds = len(bondvectors) s = bondvectors[0] self.base = s for v in bondvectors[1:]: self.quats += [Q(s,v)] else: self.numbonds = 0 self.bondvectors = bondvectors or [] # not sure if [] (in place of None) matters self.charge = formalCharge #self._init_electronic_structure() # this uses self.numbonds, so don't call it too early self._init_permitted_v6_list() return # from __init__ # def _init_electronic_structure(self): #bruce 050707 # """ # [private method] # Figure out situation with valence electrons, etc, and store it in # attributes. Only works for low-enough-atomic-number elements. # """ # # Figure out situation with valence electrons (available for pi orbitals), lone pairs, etc. # # This might be only supported for non-sp3 atomtypes (which presently go no higher than sulfur) so far. # # And for now it might be mostly hardcoded rather than principled. [bruce 050706] # _debug = 0 # if (self.element.eltnum == 15 or self.element.eltnum == 33 or self.element.eltnum == 34): # _debug = 1 # print "_init_electronic_structure(%d)" % self.element.eltnum # total_es = self.element.eltnum + self.charge # total number of electrons # # shell 1 is 1s, 2 es in all. shell 2 is 2s, 2px, 2py, 2pz, 8 electrons in all. shell 3 starts out 3s, 3px, 3py, 3pz... # unassigned_es = total_es # for shellsize in [2,8,8,-1]: # if shellsize < 0: # return # don't yet bother to figure out any of this for more than 18 electrons # # (should be ok, since this info is only needed for sp2 or sp atomtypes, # # and those don't yet go above Sulfur (elt 16) # if unassigned_es <= shellsize: # num_outer_shell_es = unassigned_es # break # # try the next shell # unassigned_es -= shellsize # del unassigned_es # if (_debug): print "num_outer_shell_es: %d" % num_outer_shell_es # if (_debug): print "shellsize: %d" % shellsize # self.total_es = total_es # not yet used for anything # self.num_outer_shell_es = num_outer_shell_es # (this might only be used in this routine) # if shellsize != 8: # return # don't go beyond this point for H or He. # # BTW, H is considered sp3 to simplify the bond-inference code, but technically that's nonsense. # spX = self.spX # numbonds = self.numbonds # we'll check this for consistency, or maybe use it to distinguish graphitic N from other sp2 N... # # now figure out number of lone pairs, available pi electrons # nlp = npi = 0 # num_spX_lonepairs (just those in spX orbitals, not p orbitals), num_pi_electrons # # 0 is default value for both, but following cases modify one or both values; # # then they're stored in attrs before we return. # nlp_p = 0 # num_p_lonepairs (number of lone pairs in p orbitals) # if spX == 3: # # There are 4 available bonding (or LP) positions or AOs (atomic orbitals), hybridized from s,p,p,p. # # The first 4 electrons just offer themselves for sigma bonds, one per orbital. # # Additional electrons pair up with those one by one to form lone pairs, reducing numbonds. # if num_outer_shell_es <= 4: # assert numbonds == num_outer_shell_es # else: # 5 thru 8 # if (numbonds != shellsize - num_outer_shell_es): # return # this is true for sp3(p) i.e. sp3(phosphate), #currently ok to bail, as none of this is actually #used. # nlp = num_outer_shell_es - 4 # elif spX == 2: # # There are 3 bonding (or LP) positions, # # plus one p orbital which might help form a pi bond or contain an LP or contain nothing. # # The first 3 electrons offer themselves for sigma bonds # # (I don't know what happens for fewer than 3, # # and we have no non-sp3 atomtypes for those anyway -- maybe they're impossible.) # assert 3 <= num_outer_shell_es <= 6 # (the upper limit of 6 is commented on implicitly below) # # The 4th electron offers itself for a pi bond (which is not counted in numbonds). # # The next one can either pair up with that one (e.g. in N/sp2(graphitic)) # # or with one of the "sigma electrons" (reducing numbonds). # # Likewise, for more electrons, 0 or 1 can pair with the "pi electron", # # and the rest reduce numbonds (down to 1 for Oxygen -- any more and I doubt sp2 is possible). # # (I don't know how many of those combinations are possible, # # but I don't need to know in this code, since numbonds tells me what happened.) # if num_outer_shell_es <= 3: # assert numbonds == num_outer_shell_es # else: # npi = 1 # the 4th electron (this value might be changed again below) # if num_outer_shell_es > 4: # # find out what happens to the 5th and optional 6th electrons # more_es = num_outer_shell_es - 4 # (1 or 2 of them) # # some of them (0 to 2, all or all but one) paired with sigma electrons to form lone pairs and reduce numbonds # nlp = 3 - numbonds # leftover = more_es - nlp # assert leftover in [0,1] # # the leftover electron (if any) paired with that 4th "pi electron" # # (forming another lone pair in the p orbital -- I'll store that separately to avoid confusion) # npi -= leftover # nlp_p += leftover # else: # assert spX == 1 # # There are two bonding (or LP) positions, plus 2 p orbitals. # # I'll use similar code to the above, though I think many combinations of values won't be possible. # # In fact, I think 4 <= num_outer_shell_es <= 6, so I won't worry much about correctness of the following outside of that. # if num_outer_shell_es <= 2: # assert numbonds == num_outer_shell_es # else: # more_es = min(2, num_outer_shell_es - 2) # no higher than 2 # # for C(sp), num_outer_shell_es == 4, and these 2 offer themselves for pi bonds # npi += more_es # # now if there are more than 4, what do they pair up with? # # I'm not sure, so figure it out from numbonds (though I suspect only one answer is ever possible). # if num_outer_shell_es > 4: # more_es = num_outer_shell_es - 4 # nlp = 2 - numbonds # lone pairs in the sp AOs # leftover = more_es - nlp # assert leftover in [0,1,2] # since only 2 p orbitals (occupied by 1 e each) they can go into # npi -= leftover # nlp_p += leftover # self.num_spX_lonepairs = nlp # self.num_p_lonepairs = nlp_p # self.num_lonepairs = nlp + nlp_p # more useful to the outside code, though not yet used as of 050707 # self.num_pi_electrons = npi # assert 2 * (nlp + nlp_p) + npi + numbonds == num_outer_shell_es # double check all this by counting the electrons # if 0 and debug_flags.atom_debug: # print "atom_debug: (%d) %s has %d bonds, and %d,%d,%d pi electrons, LPs in spX, LPs in p" % \ # (self.element.eltnum, self.fullname, numbonds, npi, nlp, nlp_p) # return # from _init_electronic_structure def potential_pi_bond(self): """ Returns true if atoms of this type can be involved in a pi bond. """ return self.spX < 3 def is_linear(self): """ Returns true if atoms of this type have two bonds in a linear arrangement. """ return self.spX == 1 def is_planar(self): """ Returns true if atoms of this type have three bonds in a planar arrangement. """ return self.spX == 2 def apply_to(self, atom): # how is this used? do we transmute the elt too? (why not? why? when would that be called?) """ change atom to have this atomtype (or emit history warning saying why you can't) """ ###e need to split out the check for transmute being legal and do it first # (so our caller, making menu, can disable illegal cmds) ##print "apply_to for self = %r" % self atom.Transmute( self.element, atomtype = self) if atom.atomtype is not self: # it didn't work for some reason (clean up way of finding history, and/or get Transmute to say why it failed #e) env.history.message( redmsg( "Can't change %r to %s" % (atom, self.fullname_for_msg()))) #e say why not def ok_to_apply_to(self, atom): return True # stub, see comments above for one way to fix; # but it's better to wait til bond valence code is more designed and filled-out # and then it'll be transmute calling this method instead of us calling a split out part of it! ###@@@ def __repr__(self): return "<%s %r at %#x>" % (self.__class__.__name__, self.fullname, id(self)) def fullname_for_msg(self): ####@@@@ use this in more places -- check all uses of fullname or of len(elt.atomtypes) if len(self.element.atomtypes) > 1: # this changes at runtime, thus this is a method and not a constant return "%s(%s)" % (self.element.name, self.name) # not sure good for Nitrogen(sp2(graphitic)) ###e else: return self.element.name pass def permits_v6(self, v6): ###@@@ see also bond_utils.possible_bond_types; maybe they should share some common knowledge """ Is it permissible for a bond of the given v6 to connect to this atomtype, ignoring valence issues? Note: this method should be fast -- it's called (at least) for every non-single bond of every changed atom. BTW [#obs, WRONG], an order of bond types from most to least permissible is (ignoring special rules for graphite, and sp2 O or S): single, double, aromatic/graphite, triple, carbomeric. [See also the constant tuple most_permissible_v6_first.] If a type in that list is not permitted for some atomtype, neither are all types beyond it (again excepting special recognition-rules for graphite, and sp2 O or S not permitting single bonds). [This is wrong because for N(sp) we only permit single (bad valence) and triple, not double. That could change if necessary. ###@@@] Note: sp2 O and S disallow single bonds only because they have exactly one bond and a valence requirement of 2 (at least that's one way of thinking about it). So this function permits single bonds for them, so that the error in e.g. H-O(sp2) can be considered a valence error on the O rather than a bond-type error. This way, the calling code is simpler, since all bonds have legal types just given the elements/atomtypes on them; valence errors can be handled separately at a later stage. (Similarly, this function would permit both S-S and S=S for diatomic S(sp2), though at later stages, neither is error-free, S-S due to valence errors and S=S due to extreme instability. BTW, for code simplicity I've decided that both those errors are "permitted but with warnings" (and the warnings might be NIM). That has nothing to do with this function specifically, it's just FYI.) If this function is used to populate menus of possible bond types, 'single' should probably be disallowed or deprecated for sp2 O and S (as a special case, or based on some other attr of this atomtype (#e nim)). """ return (v6 in self.permitted_v6_list) permitted_v6_list = (V_SINGLE,) # default value of instance attribute; correct value for most atomtypes # permitted_v6_list is a public instance attribute, I guess def _init_permitted_v6_list(self): #e not yet correct for charged atomtypes (which is ok since we don't yet have any)... # the hardcoded element lists would need revision # set some public attrs which help with some warnings by external code; # some of them are because numbonds == 1 means atom valence determines bond order for the only bond self.is_S_sp2 = (self.element.symbol == 'S' and self.spX == 2) self.is_O_sp2 = (self.element.symbol == 'O' and self.spX == 2) self.bond1_is_bad = (self.is_S_sp2 or self.is_O_sp2) self.is_N_sp = (self.element.symbol == 'N' and self.spX == 1) # used for a special case, below res = [] # build a list of bond types to allow spX = self.spX if (spX == 3): if (self.valence > 4): res.append(V_DOUBLE) res.append(V_AROMATIC) res.append(V_GRAPHITE) if (self.valence > 5): res.append(V_TRIPLE) res.append(V_CARBOMERIC) else: return # only single bonds are allowed for sp3 with 4 or fewer bonds if (spX == 2): # currently C, N, O, S if (self.valence > 1): res.append(V_AROMATIC) res.append(V_GRAPHITE) if (self.valence > 1.9): res.append(V_DOUBLE) if (spX == 1): # currently X, C, N if (self.element.symbol == "X"): res.append(V_DOUBLE) res.append(V_AROMATIC) res.append(V_GRAPHITE) res.append(V_TRIPLE) res.append(V_CARBOMERIC) elif (self.element.symbol == "N"): res.append(V_TRIPLE) elif (self.valence > 1): res.append(V_AROMATIC) res.append(V_GRAPHITE) if (self.valence > 1.9): res.append(V_DOUBLE) if (self.valence > 2.1): res.append(V_CARBOMERIC) if (self.valence > 2.9): res.append(V_TRIPLE) if not res: return if 0 and debug_flags.atom_debug: print "atom_debug: (%d) %s permits these v6's besides single(6): %r" % (self.element.eltnum, self.fullname, res) res.append(V_SINGLE) # Note: we do this even for O(sp2) and S(sp2), even though a bond1 as their sole bond is always a valence error. # Valence errors have to be treated separately anyway, so it's probably ok to not catch these special cases here. # See also the docstring for a comment about this. See also the function bond_type_warning. res.sort() self.permitted_v6_list = tuple(res) # in case tuple can be searched faster return def _classify(self): #bruce 080502 """ [private helper for can_bond_to] @return: one of the following strings, as appropriate for self. - 'bondpoint' - 'Pl' - 'sugar' (not including Pl) - 'axis' - 'unpaired-base' - 'chem' @note: it would be better if our legal return values were int-valued named constants for fast lookup in a table of legal pairs, and if the classification of self was an attribute of self. """ if self.element.symbol == 'X': # kluge return 'bondpoint' elif self.element.role == 'strand': if self.element.symbol == 'Pl5': return 'Pl' return 'sugar' else: return self.element.role or 'chem' # 'axis' or 'unpaired-base' or 'chem' pass def can_bond_to(self, atom, bondpoint = None, auto = False): #bruce 080502 """ Some tool in the UI wants to bond a new atom of atomtype self to the given existing atom, in place of the given bondpoint if one is provided. If auto is true, this is an "autobonding" (just due to nearness of a new atom to an existing bondpoint); otherwise it's an explicit bonding attempt by the user. Return True if this should be allowed, False if not. @note: it would be desirable to improve this API so that the reason why not could also be returned. """ # note: this is not yet modular; and it is partly redundant with # _fix_atom_or_return_error_info in fix_bond_directions.py. del bondpoint, auto # not yet used def check_by_class1(class1, class2): # Note: pairs of _classify return values can be made illegal # by making this function return false for them in either order. # The outer function only returns true if this function # accepts a pair in both orders. if class1 == 'chem': return class2 in ('chem', 'bondpoint') elif class1 == 'Pl': return class2 in ('sugar', 'bondpoint') elif class1 == 'bondpoint': return class2 != 'bondpoint' return True class1 = self._classify() class2 = atom.atomtype._classify() if not check_by_class1(class1, class2): return False if not check_by_class1(class2, class1): return False return True pass # end of class AtomType # end """ ... the maximal sets of end-elements for A6 will be: aromatic, graphite: C, N, B (B depends on how Damian answers some Qs) (carbomeric, if we have it, only C -- probably not for A6; if I didn't make it clear, this only exists in chains of C(sp) alternating with bonda, where the bond orders are 1.5, 2.5, 1.5, etc) double: C, N, O, S triple: C, N """
NanoCAD-master
cad/src/model/atomtypes.py
# Copyright 2004-2008 Nanorex, Inc. See LICENSE file for details. """ NamedView.py -- a named view (including coordinate system for viewing) @author: Mark @version: $Id$ @copyright: 2004-2008 Nanorex, Inc. See LICENSE file for details. History: Mark wrote this in Utility.py. bruce 071026 moved it from Utility into a new file. Mark renamed Csys to NamedView, on or after 2008-02-03. Bruce 080303 simplified NamedView.__init__ arg signature and some calling code. """ from utilities.constants import gensym from geometry.VQT import V, Q, vlen from utilities.icon_utilities import imagename_to_pixmap from foundation.Utility import SimpleCopyMixin from foundation.Utility import Node from utilities import debug_flags import foundation.env as env from utilities.Log import greenmsg class NamedView(SimpleCopyMixin, Node): """ The NamedView is used to store all the parameters needed to save and restore a view. It is used in several distinct ways: 1) as a Named View created by the user and visible as a node in the model tree 2) internal use for storing the LastView and HomeView for every part 3) internal use by Undo for saving the view that was current when a change was made """ sym = "View" featurename = "Named View" copyable_attrs = Node.copyable_attrs + ('scale', 'pov', 'zoomFactor', 'quat') # (note: for copy, this is redundant with _um_initargs (that's ok), # but for Undo, it's important to list these here or give them _s_attr decls. # This fixes a presumed bug (perhaps unreported -- now bug 1942) in Undo of Set_to_Current_View. # Bug 1369 (copy) is fixed by _um_initargs and SimpleCopyMixin, not by this.) scale = pov = zoomFactor = quat = None # Undo might require these to have default values (not sure) [bruce 060523] def __init__(self, assy, name, scale, pov, zoomFactor, wxyz): """ @param pov: the inverse of the "center of view" in model coordinates @type pov: position vector (Numeric.array of 3 ints or floats, as made by V(x,y,z)) @param wxyz: orientation of view @type wxyz: a Quaternion (class VQT.Q), or a sequence of 4 floats which can be passed to that class to make one, e.g. Q(W, x, y, z) is the quaternion with axis vector x,y,z and sin(theta/2) = W """ self.const_pixmap = imagename_to_pixmap("modeltree/NamedView.png") if not name: name = gensym("%s" % self.sym, assy) Node.__init__(self, assy, name) self.scale = scale assert type(pov) is type(V(1, 0, 0)) self.pov = V(pov[0], pov[1], pov[2]) self.zoomFactor = zoomFactor self.quat = Q(wxyz) #bruce 050518/080303 comment: wxyz is passed as an array of 4 floats # (in same order as in mmp file's csys record), when parsing # csys mmp records, or with wxyz a quat in other places. return def _um_initargs(self): #bruce 060523 to help make it copyable from the UI (fixes bug 1369 along with SimpleCopyMixin) """ #doc @warning: see comment where this is called in this class -- it has to do more than its general spec requires """ # (split out of self.copy) if "a kluge is ok since I'm in a hurry": # the data in this NamedView might not be up-to-date, since the glpane "caches it" # (if we're the Home or Last View of its current Part) # and doesn't write it back after every user event! # probably it should... but until it does, do it now, before copying it! self.assy.o.saveLastView() return (self.assy, self.name, self.scale, self.pov, self.zoomFactor, self.quat), {} def show_in_model_tree(self): #bruce 050128; nothing's wrong with showing them, except that they are unselectable # and useless for anything except being renamed by dblclick (which can lead to bugs # if the names are still used when files_mmp reads the mmp file again). For Beta we plan # to make them useful and safe, and then make them showable again. """ [overrides Node method] """ return True # changed retval to True to support Named Views. mark 060124. def writemmp(self, mapping): v = (self.quat.w, self.quat.x, self.quat.y, self.quat.z, self.scale, self.pov[0], self.pov[1], self.pov[2], self.zoomFactor) mapping.write("csys (" + mapping.encode_name(self.name) + ") (%f, %f, %f, %f) (%f) (%f, %f, %f) (%f)\n" % v) self.writemmp_info_leaf(mapping) #bruce 050421 (only matters once these are present in main tree) def copy(self, dad = None): #bruce 060523 revised this (should be equivalent) #bruce 050420 -- revise this (it was a stub) for sake of Part view propogation upon topnode ungrouping; # note that various Node.copy methods are not yet consistent, and I'm not fixing this now. # (When I do, I think they will not accept "dad" but will accept a "mapping", and will never rename the copy.) # The data copied is the same as what can be passed to init and what writemmp writes. # Note that the copy needs to have the same exact name, not a variant (since the name # is meaningful for the internal uses of this object, in the present implem). assert dad is None args, kws = self._um_initargs() # note: we depend on our own _um_initargs returning enough info for a full copy, # though it doesn't have to in general. if 0 and debug_flags.atom_debug: print "atom_debug: copying namedView:", self return NamedView( *args, **kws ) def __str__(self): #bruce 050420 comment: this is inadequate, but before revising it # I'd have to verify it's not used internally, like Jig.__repr__ used to be!! return "<namedView " + self.name + ">" def ModelTree_plain_left_click(self): #bruce 080213 bugfix: override this new API method, not Node.pick. """ [overrides Node method] Change to self's view, if not animating. """ # Precaution. Don't change view if we're animating. if self.assy.o.is_animating: return self.change_view() return def ModelTree_context_menu_section(self): #bruce 080225, for Mark to review and revise """ Return a menu_spec list to be included in the Model Tree's context menu for this node, when this is the only selected node (which implies the context menu is specifically for this node). [extends superclass implementation] """ # start with superclass version menu_spec = Node.ModelTree_context_menu_section(self) # then add more items to it, in order: # Change to this view text = "Change to '%s' (left click)" % (self.name,) command = self.ModelTree_plain_left_click disabled = self.sameAsCurrentView() menu_spec.append( (text, command, disabled and 'disabled' or None) ) # Replace saved view with current view text = "Replace '%s' with the current view" % (self.name,) # (fyi, I don't know how to include bold text here, or whether it's possible) command = self._replace_saved_view_with_current_view disabled = self.sameAsCurrentView() menu_spec.append( (text, command, disabled and 'disabled' or None) ) # Return to previous view (NIM) [mark 060122] # @note: This is very helpful when the user accidentally clicks # a Named View node and needs an easy way to restore the previous view. if 0: text = "Return to previous View" command = self.restore_previous_view disabled = True # should be: disabled if no previous view is available menu_spec.append( (text, command, disabled and 'disabled' or None) ) # Note: we could also add other items here instead of defining them in __CM methods. # If they never need to be disabled, just use menu_spec.append( (text, command) ). return menu_spec def change_view(self): #mark 060122 """ Change the view to self. """ self.assy.o.animateToView(self.quat, self.scale, self.pov, self.zoomFactor, animate=True) cmd = greenmsg("Change View: ") msg = 'Current view is "%s".' % (self.name) env.history.message( cmd + msg ) def _replace_saved_view_with_current_view(self): #bruce 080225 split this out """ Replace self's saved view with the current view, if they differ. """ if not self.sameAsCurrentView(): self._set_to_current_view() return def restore_previous_view(self): """ Restores the previous view. @warning: Not implemented yet. Mark 2008-02-14 """ print "Not implemented yet." return def _set_to_current_view(self): #mark 060122 """ Set self to current view, marks self.assy as changed, and emits a history message. Intended for use on user-visible Named View objects in the model tree. Does not check whether self is already the current view (for that, see self.sameAsCurrentView()). @see: setToCurrentView, for use on internal view objects. """ #bruce 080225 revised this to remove duplicated code, # made it private, revised related docstrings self.setToCurrentView( self.assy.glpane) self.assy.changed() # maybe: make this check whether it really changed (or will Undo do that?) cmd = greenmsg("Set View: ") msg = 'View "%s" now set to the current view.' % (self.name) env.history.message( cmd + msg ) def move(self, offset): # in class NamedView [bruce 070501, used when these are deposited from partlib] """ [properly implements Node API method] """ self.pov = self.pov - offset # minus, because what we move is the center of view, defined as -1 * self.pov self.changed() return def setToCurrentView(self, glpane): """ Save the current view in self, but don't mark self.assy as changed or emit any history messages. Can be called directly on internal view objects (e.g. glpane.HomeView), or as part of the implementation of replacing self with the current view for user-visible Named View objects in the model tree. @param glpane: the 3D graphics area. @type glpane: L{GLPane) """ assert glpane self.quat = Q(glpane.quat) self.scale = glpane.scale self.pov = V(glpane.pov[0], glpane.pov[1], glpane.pov[2]) self.zoomFactor = glpane.zoomFactor def sameAsCurrentView(self, view = None): """ Tests if self is the same as I{view}, or the current view if I{view} is None (the default). @param view: A named view to compare with self. If None (the default), self is compared to the current view (i.e. the 3D graphics area). @type view: L{NamedView} @return: True if they are the same. Otherwise, returns False. @rtype: boolean """ # Note: I'm guessing this could be rewritten to be more # efficient/concise. For example, it seems possible to implement # this using a simple conditional like this: # # if self == view: # return True # else: # return False # # It occurs to me that the GPLane class should use a NamedView attr # along with (or in place of) quat, scale, pov and zoomFactor attrs. # That would make this method (and possibly other code) easier to # write and understand. # # Ask Bruce about all this. # # BTW, this code was originally copied/borrowed from # GLPane.animateToView(). Mark 2008-02-03. # Make copies of self parameters. q1 = Q(self.quat) s1 = self.scale p1 = V(self.pov[0], self.pov[1], self.pov[2]) z1 = self.zoomFactor if view is None: # use the graphics area in which self is displayed # (usually the main 3D graphics area; code in this class # has not been reviewed for working in other GLPane_minimal instances) view = self.assy.glpane # Copy the parameters of view for comparison q2 = Q(view.quat) s2 = view.scale p2 = V(view.pov[0], view.pov[1], view.pov[2]) z2 = view.zoomFactor # Compute the deltas deltaq = q2 - q1 deltap = vlen(p2 - p1) deltas = abs(s2 - s1) deltaz = abs(z2 - z1) if deltaq.angle + deltap + deltas + deltaz == 0: return True else: return False pass # end of class NamedView # bruce 050417: commenting out class Datum (and ignoring its mmp record "datum"), # since it has no useful effect. # bruce 060523: removing the commented out code. In case it's useful for # Datum Planes, it can be found in cvs rev 1.149 or earlier of Utility.py, # and commented out # references to it remain in other files. It referred to cad/images/datumplane.png. # end
NanoCAD-master
cad/src/model/NamedView.py
# Copyright 2004-2009 Nanorex, Inc. See LICENSE file for details. """ Chunk_mmp_methods.py -- Chunk mixin for methods related to mmp format (reading or writing) @author: Josh, Bruce @version; $Id$ @copyright: 2004-2009 Nanorex, Inc. See LICENSE file for details. History: Written over several years as part of chunk.py. Bruce 090123 split these methods out of class Chunk in chunk.py. (For prior svn history, see chunk.py -- this is too small to be worth dragging along all that history via svn copy.) TODO: Someday, refactor into a separate chunk-mmp-handling object. Also review whether atoms_in_mmp_file_order belongs here, and/or should be renamed to not be mmp-specific. Also review whether two private methods defined in Chunk_Dna_methods, and used only here, belong here (they are _readmmp_info_chunk_setitem_Dna and _writemmp_info_chunk_before_atoms_Dna, and are specific to both dna code for chunk, and mmp code). """ from utilities import debug_flags class Chunk_mmp_methods: """ Mixin (meant only for use by class Chunk) with all mmp-related methods for class Chunk. """ # Note: we can't inherit Chunk's main superclass here, even though doing # so would make pylint much happier; see comment near beginning of class # Chunk_Dna_methods for why. [bruce 090123 comment] def readmmp_info_chunk_setitem( self, key, val, interp ): #bruce 050217, renamed 050421 """ This is called when reading an mmp file, for each "info chunk" record. Key is a list of words, val a string; the entire record format is presently [050217] "info chunk <key> = <val>". Interp is an object to help us translate references in <val> into other objects read from the same mmp file or referred to by it. See the calls of this method from files_mmp for the doc of interp methods. If key is recognized, set the attribute or property it refers to to val; otherwise do nothing. (An unrecognized key, even if longer than any recognized key, is not an error. Someday it would be ok to warn about an mmp file containing unrecognized info records or keys, but not too verbosely (at most once per file per type of info).) """ didit = self._readmmp_info_chunk_setitem_Dna( key, val, interp) if didit: pass # e.g. for display_as_pam, save_as_pam elif key == ['hotspot']: # val should be a string containing an atom number referring to # the hotspot to be set for this chunk (which is being read from # an mmp file) (hs_num,) = val.split() hs = interp.atom(hs_num) self.set_hotspot(hs) # this assertfails if hotspot is invalid # [review: does caller handle that?] elif key == ['color']: #bruce 050505 # val should be 3 decimal ints from 0-255; # colors of None are not saved since they're the default r, g, b = map(int, val.split()) color = r/255.0, g/255.0, b/255.0 self.setcolor(color, repaint_in_MT = False) else: if debug_flags.atom_debug: print "atom_debug: fyi: info chunk with unrecognized key %r" % (key,) return def atoms_in_mmp_file_order(self, mapping = None): """ Return a list of our atoms, in the same order as they would be written to an mmp file produced for the given mapping (none by default) (which is the same order in which they occurred in one, *if* they were just read from one, at least for this class's implem of this method). We know it's the same order as they'd be written, since self.writemmp() calls this method. (Subclasses are permitted to override this method in order to revise the order. This can help optimize mmp writing and reading. It does have effects in the code when the atoms are read, but these are usually unimportant.) We know it's the same order they were just read in (if they were just read), since it's the order of atom.key, which is assigned successive values (guaranteed to sort in order) as atoms are read from the file and created for use in this session. @param mapping: writemmp_mapping being used for the writing process, or None if this is not being used for mmp writing. This can affect the set of atoms (and in principle, their order) due to conversions requested by the mapping, e.g. PAM3 -> PAM5. @type mapping: an instance of class writemmp_mapping, or None. [subclasses can override this, as described above] @note: this method is also used for non-mmp (but file-format- related) uses, but is still here in the mmp-specific mixin class because it has an mmp-related argument and is overridden by the mmp code of a subclass of Chunk. """ #bruce 050228; revised docstring and added mapping arg, 080321 del mapping # as of 060308 atlist is also sorted (so equals res), but we don't want # to recompute it and atpos and basepos just due to calling this. Maybe # that's silly and this should just return self.atlist, # or at least optim by doing that when it's in self.__dict__. ##e pairs = self.atoms.items() # key, val pairs; keys are atom.key, # which is an int which counts from 1 as atoms are created in one # session, and which is (as of now, 050228) specified to sort in # order of creation even if we later change the kind of value it # produces. pairs.sort() res = [atom for key, atom in pairs] return res def writemmp(self, mapping): #bruce 050322 revised interface to use mapping """ [overrides Node.writemmp] """ disp = mapping.dispname(self.display) mapping.write("mol (" + mapping.encode_name(self.name) + ") " + disp + "\n") self.writemmp_info_leaf(mapping) self.writemmp_info_chunk_before_atoms(mapping) #bruce 050228: write atoms in the same order they were created in, # so as to preserve atom order when an mmp file is read and written # with no atoms created or destroyed and no chunks reordered, thus # making previously-saved movies more likely to retain their validity. # (Due to the .dpb format not storing its own info about atom identity.) #bruce 080327 update: # Note: these "atoms" can be of class Atom or class Fake_Pl. #bruce 080328: for some of the atoms, let subclasses write all # their bonds separately, in a more compact form. compact_bond_atoms = \ self.write_bonds_compactly_for_these_atoms(mapping) for atom in self.atoms_in_mmp_file_order(mapping): atom.writemmp(mapping, dont_write_bonds_for_these_atoms = compact_bond_atoms) # note: this writes internal and/or external bonds, # after their 2nd atom is written, unless both their # atoms are in compact_bond_atoms. It also writes # bond_directions records as needed for the bonds # it writes. if compact_bond_atoms: # (this test is required) self.write_bonds_compactly(mapping) self.writemmp_info_chunk_after_atoms(mapping) return def writemmp_info_chunk_before_atoms(self, mapping): #bruce 080321 """ Write whatever info chunk records need to be written before our atoms (since their value, during mmp read, might be needed when reading the atoms or their bonds). [subclasses should extend this as needed] """ self._writemmp_info_chunk_before_atoms_Dna( mapping) return def write_bonds_compactly_for_these_atoms(self, mapping): #bruce 080328 """ If self plans to write some of its atoms' bonds compactly when self.write_bonds_compactly is called (possibly based on options in mapping), then return a dictionary of atom.key -> atom for those atoms. Otherwise return {}. [subclasses that can do this should override this method and write_bonds_compactly in corresponding ways.] """ del mapping return {} def writemmp_info_chunk_after_atoms(self, mapping): #bruce 080321 split this out """ Write whatever info chunk records should be written after our atoms and our internal bonds, or any other info chunk records not written by writemmp_info_chunk_before_atoms. [subclasses should override this as needed] """ #bruce 050217 new feature [see also a comment added to files_mmp.py]: # also write the hotspot, if there is one. hs = self.hotspot # uses getattr to validate it if hs: # hs is a valid hotspot in this chunk, and was therefore one of the # atoms just written by the caller, and therefore should have an # encoding already assigned for the current mmp file: hs_num = mapping.encode_atom(hs) assert hs_num is not None mapping.write("info chunk hotspot = %s\n" % hs_num) if self.color: r = int(self.color[0]*255 + 0.5) g = int(self.color[1]*255 + 0.5) b = int(self.color[2]*255 + 0.5) mapping.write("info chunk color = %d %d %d\n" % (r, g, b)) return def write_bonds_compactly(self, mapping): #bruce 080328 """ If self returned (or would return) some atoms from self.write_bonds_compactly_for_these_atoms(mapping), then write all bonds between atoms in that set into mapping in a compact form. @note: this should only be called if self did, or would, return a nonempty set of atoms from that method, self.write_bonds_compactly_for_these_atoms(mapping). [subclasses that can do this should override this method and write_bonds_compactly_for_these_atoms in corresponding ways.] """ assert 0, "subclasses which need this must override it" pass # end of class Chunk_mmp_methods # end
NanoCAD-master
cad/src/model/Chunk_mmp_methods.py
# Copyright 2004-2009 Nanorex, Inc. See LICENSE file for details. """ part.py -- class Part, for all chunks and jigs in a single physical space, together with their selection state and grouping structure (shown in the model tree). @version: $Id$ @copyright: 2004-2009 Nanorex, Inc. See LICENSE file for details. see assembly.py docstring, some of which is really about this module. ###@@@ revise == This module also contains a lot of code for specific operations on sets of molecules, which are all in the current part. Some of this code might ideally be moved to some other file. [As of 050507, much of that has now been moved.] == History: Split out of assembly.py (the file, and more importantly the class) by bruce 050222. The Part/assembly distinction was introduced by bruce 050222 (though some of its functionality was anticipated by the "current selection group" introduced earlier, just before Alpha-1). [I also rewrote this entire docstring then.] The Part/assembly distinction is unfinished, particularly in how it relates to some modes and to movie files. Prior history of assembly.py (and thus of much code in this file) unclear; assembly.py was almost certainly originated by Josh. bruce 050507 moved various methods out of this file, into more appropriate smaller files, some existing (jigs.py) and some new (ops_*.py). bruce 050513 replaced some == with 'is' and != with 'is not', to avoid __getattr__ on __xxx__ attrs in python objects. """ from utilities import debug_flags from utilities.debug import print_compact_traceback, print_compact_stack from utilities.Log import redmsg from utilities.constants import diINVISIBLE from utilities.constants import diDEFAULT from utilities.constants import SELWHAT_CHUNKS, SELWHAT_ATOMS from utilities.prefs_constants import levelOfDetail_prefs_key from utilities.prefs_constants import startup_GLPane_scale_prefs_key from geometry.VQT import V, Q from geometry.BoundingBox import BBox from foundation.Utility import Node from foundation.Group import Group from foundation.Assembly_API import Assembly_API from foundation.node_indices import fix_one_or_complain from foundation.inval import InvalMixin from foundation.state_utils import StateMixin from foundation.state_constants import S_REF, S_DATA, S_PARENT, S_CHILD import foundation.env as env from model.NamedView import NamedView from model.chunk import Chunk from model.jigs import Jig from model.Part_drawing_frame import Part_drawing_frame from model.Part_drawing_frame import fake_Part_drawing_frame from model.elements import PeriodicTable from operations.jigmakers_Mixin import jigmakers_Mixin from operations.ops_atoms import ops_atoms_Mixin from operations.ops_connected import ops_connected_Mixin from operations.ops_copy import ops_copy_Mixin from operations.ops_motion import ops_motion_Mixin from operations.ops_rechunk import ops_rechunk_Mixin from operations.ops_select import ops_select_Mixin from dna.operations.ops_pam import ops_pam_Mixin # == # number of atoms for detail level 0 HUGE_MODEL = 40000 # number of atoms for detail level 1 LARGE_MODEL = 5000 debug_parts = False # set this to True in a debugger, to enable some print statements, etc debug_1855 = False # DO NOT COMMIT WITH TRUE [bruce 060415] # == class Part( jigmakers_Mixin, InvalMixin, StateMixin, ops_atoms_Mixin, ops_pam_Mixin, ops_connected_Mixin, ops_copy_Mixin, ops_motion_Mixin, ops_rechunk_Mixin, ops_select_Mixin, object # fyi; redundant with InstanceLike inherited via StateMixin ): """ One Part object is created to hold any set of chunks and jigs whose coordinates are intended to lie in the same physical space. When new clipboard items come into being, new Parts are created as needed to hold them; and they should be destroyed when those clipboard items no longer exist as such (even if the chunks inside them still exist in some other Part). Note that parts are not Nodes (or at least, they are not part of the same node-tree as the chunks/jigs they contain); each Part has a toplevel node self.topnode, and a reference to its assy, used for (e.g.) finding a reference to the shared (per-assy) clipboard to use, self.shelf. """ # default values for some instance variables name = "" #bruce 060227 moved this into class and made it "" rather than None, for simplicity of _s_attr defaultval code # this is [someday? now?] set to any name autogenerated for our topnode, # so it can be reused if necessary (if our topnode changes a couple times in a row) # rather than autogenerating another name. # It would also be useful if there was a Part Tree Widget... alive = False # set to True at end of __init__, and again to False if we're destroyed(??#k) # state decls (for attrs set in __init__) [bruce 060224] _s_attr_name = S_DATA _s_attr_topnode = S_PARENT _s_attr_nodecount = S_DATA _s_attr_homeView = S_CHILD _s_attr_lastView = S_CHILD ## not true, i think: _s_categorize_homeView = 'view' # [bruce 060227] _s_categorize_lastView = 'view' # [bruce 060227] _s_attr_ppa2 = S_REF _s_attr_ppa3 = S_REF _s_attr_ppm = S_REF _s_attr_alive = S_DATA # needed since the part can be destroyed, which sets alive to False def _undo_update_always(self): #bruce 060224 """ This is run on every Part still around after an Undo or Redo op, whether or not it was modified by that op. """ # (though to be honest, that's due to a kluge, as of 060224 -- it won't yet run this on any other class!) attrs = self.invalidatable_attrs() if debug_1855: print "debug_1855: part %r _undo_update_always will inval %r" % (self, attrs,) # this looks ok self.invalidate_attrs( attrs) # especially selmols, selatoms, and molecules, but i guess all of them matter ###e should InvalMixin *always* do this? (unless overridden somehow?) guess: not quite. # don't call this, it can't be allowed to exist (I think): ## StateMixin._undo_update_always(self) return def __init__(self, assy, topnode): self.init_InvalMixin() self.assy = assy self.topnode = topnode # some old code refers to topnode as tree or root, but that's deprecated # since it doesn't work for setting the value (it causes bugs we won't detect) # so change all uses of that... maybe I have by now? ###k self.nodecount = 0 # doesn't yet include topnode until we self.add it, below prior_part = topnode.part if prior_part is None: prior_part = topnode.prior_part #bruce 050527 new feature; also might be None if prior_part is not None: # topnode.part might be destroyed when we add topnode to ourselves, # so we'd better first salvage from it whatever might be useful # (copying its view attributes fixes bug 556 [bruce 050420]) # [now we can also get these from topnode.prior_part if necessary; # it is like .part but doesn't modify part's nodecount or stats; # this is added to nodes made by copying other nodes, or Groups containing those, # so that view info can generally be preserved for copies -- bruce 050527] self.homeView = prior_part.homeView.copy() self.lastView = prior_part.lastView.copy() # (copying its name, if we were the first ones to get to it and if it doesn't # any longer need its name (since it has no topnode), might be enough # to make ungroup/regroup of a clipboard item preserve an autogenerated name; # I'm not 100% sure it's always a good idea, but it's worth a try, I guess; # if it's bad it'll be because the part still wanted its name for some reason. [bruce 050420]) if prior_part.name and prior_part.topnode is None: # steal its name self.name = prior_part.name prior_part.name = None del prior_part.name # save RAM (in undo archives, until undo does this itself) (not important, mainly a test, 060227) else: # HomeView and LastView -- these are per-part, are switched into # GLPane when its current part changes (i.e. very soon after our # assy's current part changes), and are written into mmp file for # main part, and in future for all parts. ###e bruce 050527 comment: would it ever be better to set these to # fit the content? If so, we'd have to just inval them here, since # most of the content is probably in nodes other than topnode, # which are not yet added (and we don't want to assume topnode's # kids will all be added, though for now this might be true -- # not sure). #Default scale is usually = 10.0-- obtained from the preference #value for startup_GLPane_scale_prefs_key #@see: GLPane.__init__, #@see:GLPane._adjust_GLPane_scale_if_needed() default_scale = float(env.prefs[startup_GLPane_scale_prefs_key]) self.homeView = NamedView(self.assy, "HomeView", default_scale, V(0,0,0), 1.0, Q(1.0, 0.0, 0.0, 0.0)) self.lastView = NamedView(self.assy, "LastView", default_scale, V(0,0,0), 1.0, Q(1.0, 0.0, 0.0, 0.0)) self.add(topnode) # for now: assert isinstance(assy, Assembly_API) assert isinstance(topnode, Node) # self._modified?? not yet needed for individual parts, but will be later. ##bruce 050417 zapping all Datum objects, since this will have no important effect, ## even when old code reads our mmp files. ## More info about this can be found in other comments/emails. ## self.xy = Datum(self.assy, "XY", "plane", V(0,0,0), V(0,0,1)) ## self.yz = Datum(self.assy, "YZ", "plane", V(0,0,0), V(1,0,0)) ## self.zx = Datum(self.assy, "ZX", "plane", V(0,0,0), V(0,1,0)) ##bruce 050418 replacing this with viewdata_members method and its caller in assy: ## grpl1 = [self.homeView, self.lastView] ## , self.xy, self.yz, self.zx] # [note: only use of .xy, .yz, .zx as of 050417] ## self.viewdata = Group("View Data", self.assy, None, grpl1) #bruce 050418 renamed this; not a user-visible change ## self.viewdata.open = False # some attrs are recomputed as needed (see below for their _recompute_ or _get_ methods): # e.g. molecules, bbox, center, drawLevel, alist, selatoms, selmols # movie ID, for future use. [bruce 050324 commenting out movieID until it's used; strategy for this will change, anyway.] ## self.movieID = 0 # ppa = previous picked atoms. ###@@@ not sure these are per-part; should reset when change mode or part self.ppa2 = self.ppa3 = self.ppm = None self.alive = True # we're not yet destroyed if debug_parts: print "debug_parts: fyi: created Part:", self return # from Part.__init__ def viewdata_members(self, i): #bruce 050418: this helps replace old assy.data for writing mmp files #bruce 050421: patch names for sake of saving per-Part views; # should be ok since names not otherwise used (I hope); # if not (someday), we can make copies and patch their names suffix = i and str(i) or "" self.homeView.name = "HomeView" + suffix self.lastView.name = "LastView" + suffix return [self.homeView, self.lastView] def __repr__(self): classname = self.__class__.__name__ try: topnodename = "%r" % self.topnode.name except: topnodename = "<topnode??>" try: return "<%s %#x %s (%d nodes)>" % (classname, id(self), topnodename, self.nodecount) except: return "<some part, exception in its __repr__>" #bruce 050425 # == updaters (###e refile??) def gl_update(self): """ update whatever glpane is showing this part (more than one, if necessary) """ self.assy.o.gl_update() # == membership maintenance # Note about selection of nodes moving between parts: # when nodes are removed from or added to parts, we ensure they (or their atoms) are not picked, # so that we needn't worry about updating selatoms, selmols, or current selection group; # this also seems best in terms of the UI. But note that it's not enough, if .part revision # follows tree revision, since picked nodes control selection group using tree structure alone. def add(self, node): if node.part is self: # this is normal, e.g. in ensure_one_part, so don't complain return if node.part is not None: if debug_parts: # this will be common print "debug_parts: fyi: node added to new part so removed from old part first:", node, self, node.part node.part.remove(node) assert node.part is None # this is a desired assertion, but make it a debug print # so as not to cause worse bugs: [bruce 080314] ## assert not node.picked # since remove did it, or it was not in a part and could not have been picked (I think!) if node.picked: msg = "\n***BUG: node.picked in %r.add(%r); clearing it to avoid more bugs" % \ (self, node) print_compact_stack( msg + ": ") node.picked = False # too dangerous to use node.unpick() here # Review: could we just make this legal, by doing # self.selmols_append(node) if node is a chunk? # (For now, instead, just have new nodes call .inherit_part # before .pick. This fixed a bug in DnaLadderRailChunk.) # [bruce 080314 comment] pass #e should assert a mol's atoms not picked too (too slow to do it routinely; bugs in this are likely to be noticed) node.part = node.prior_part = self #bruce 050527 comment: I hope and guess this is the only place node.part is set to anything except None; need to check ###k self.nodecount += 1 if isinstance(node, Chunk): ###@@@ #e better if we let the node add itself to our stats and lists, i think... self.invalidate_attrs(['molecules'], skip = ['natoms']) # this also invals bbox, center #e or we could append node to self.molecules... but I doubt that's worthwhile ###@@@ self.adjust_natoms( len(node.atoms)) # note that node is not added to any comprehensive list of nodes; in fact, we don't have one. # presumably this function is only called when node was just, or is about to be, # added to a nodetree in a place which puts it into this part's tree. # Therefore, in the absence of bugs and at the start of any user event handler, # self.topnode should serve as a comprehensive tree of this part's nodes. return def remove(self, node): """ Remove node (a member of this part) from this part's lists and stats; reset node.part; DON'T look for interspace bonds yet (since this node and some of its neighbors might be moving to the same new part). Node (and its atoms, if it's a chunk) will be unpicked before the removal. """ assert node.part is self node.unpick() # this maintains selmols if necessary if isinstance(node, Chunk): # need to unpick the atoms? [would be better to let the node itself have a method for this] ###@@@ (fix atom.unpick to not remake selatoms if missing, or to let this part maintain it) if (not self.__dict__.has_key('selatoms')) or self.selatoms: for atm in node.atoms.itervalues(): atm.unpick(filtered = False) #bruce 060331 precaution: added filtered = False, to fix potential serious bugs (unconfirmed) #e should optimize this by inlining and keeping selatoms test outside of loop self.invalidate_attrs(['molecules'], skip = ['natoms']) # this also invals bbox, center self.adjust_natoms(- len(node.atoms)) self.nodecount -= 1 node.part = None if self.topnode is node: self.topnode = None #k can this happen when any nodes are left??? if so, is it bad? if debug_parts: print "debug_parts: fyi: topnode leaves part, %d nodes remain" % self.nodecount # it can happen when I drag a Group out of clipboard: "debug_parts: fyi: topnode leaves part, 2 nodes remain" # and it doesn't seem to be bad (the other 2 nodes were pulled out soon). if self.nodecount <= 0: assert self.nodecount == 0 assert not self.topnode self.destroy() # NOTE: since Node.part is undoable, a destroyed Part can come back # to life after Undo. I don't know if this is related to a newly found bug: # make duplex with dna updater on, undo to before that, redo, nodecount is wrong. # For more info see today's comment in assembly.py. # [bruce 080325] return def destroy_with_topnode(self): #bruce 050927; consider renaming this to destroy, and destroy to something else """ destroy self.topnode and then self; assertionerror if self still has nodes after topnode is destroyed WARNING [060322]: This probably doesn't follow the semantics of other destroy methods (the issue is unreviewed). ###@@@ """ if self.topnode is not None: self.topnode.kill() # use kill, since Node.destroy is NIM [#e this should be fixed, might cause memory leaks] self.destroy() return def destroy(self): #bruce 050428 making this much more conservative for Alpha5 release and to fix bug 573 """ forget enough to prevent memory leaks; only valid if we have no nodes left; MUST NOT forget views! WARNING [060322]: This doesn't follow the semantics of other destroy methods; in particular, destroyed Parts might be revived later by Undo. This should be fixed by renaming this method (perhaps to kill), so we can add a real destroy method. ###@@@ """ #bruce 050527 added requirement (already true in current implem) that this not forget views, # so node.prior_part needn't prevent destroy, but can be used to retrieve default initial views for node. if debug_parts: print "debug_parts: fyi: destroying part", self assert self.nodecount == 0, "can't destroy a Part which still has nodes" # esp. since it doesn't have a list of them! # actually it could scan self.assy.root to find them... but for now, we'll enforce this anyway. if self.assy and self.assy.o: #e someday change this to self.glpane?? self.assy.o.forget_part(self) # just in case we're its current part ## self.invalidate_all_attrs() # not needed self.alive = False # do this one first ###@@@ see if this can help a Movie who knows us see if we're safe... [050420] if "be conservative for now, though memory leaks might result": #bruce 050428 return # bruce 050428 removed the rest for now. In fact, even what we had was probably not enough to # prevent memory leaks, since we've never paid attention to that, so the Nodes might have them # (in the topnode tree, deleted earlier, or the View nodes we still have, which might get into # temporary Groups in writemmp_file code and not get properly removed from those groups). ## BTW, bug 573 came from self.assy = None followed by __getattr__ wanting attrs from self.assy ## such as 'w' or 'current_selgroup_iff_valid'. ## # set all attrs to None, including self.alive (which is otherwise True to indicate we're not yet destroyed) ## for attr in self.__dict__.keys(): ## if not attr.startswith('_'): ## #bruce 050420 see if this 'if' prevents Python interpreter hang ## # when this object is later passed as argument to other code ## # in bug 519 (though it probably won't fix the bug); ## # before this we were perhaps deleting Python-internal attrs too, ## # such as __dict__ and __class__! ## if 0 and debug_flags.atom_debug: ## print "atom_debug: destroying part - deleting i mean resetting attr:",attr ## ## still causes hang in movie mode: ## ## delattr(self,attr) # is this safe, in arb order of attrs?? ## setattr(self, attr, None) return # incremental update methods def selmols_append(self, mol): if self.__dict__.has_key('selmols'): assert mol not in self.selmols self.selmols.append(mol) return def selmols_remove(self, mol): if self.__dict__.has_key('selmols'): ## might not always be true in current code, though it should be: ## assert mol in self.selmols try: self.selmols.remove(mol) except ValueError: # not in the list if debug_flags.atom_debug: print_compact_traceback("selmols_remove finds mol not in selmols (might not be a bug): ") return def adjust_natoms(self, delta): """ adjust the number of atoms, if known. Useful since drawLevel depends on this and is often recomputed. """ if self.__dict__.has_key('natoms'): self.natoms += delta return # == compatibility methods ###@@@ find and fix all sets of .tree or .root or .data (old name, should all be renamed now) or .viewdata (new name) or .shelf def _get_tree(self): #k this would run for part.tree; does that ever happen? print_compact_stack("_get_tree is deprecated: ") return self.topnode def _get_root(self): #k needed? print_compact_stack("_get_root is deprecated: ") return self.topnode # == properties that might be overridden by subclasses def immortal(self): """ Should this Part be undeletable from the UI (by cut or delete operations)? When true, delete will delete its members (leaving it empty but with its topnode still present), and cut will cut its members and move them into a copy of its topnode, which is left still present and empty. [can be overridden in subclasses] """ return False # simplest value used as default # == attributes which should be delegated to self.assy # attrnames to delegate to self.assy (ideally for writing as well as reading, until all using-code is upgraded) assy_attrs = ['w','o','mt','selwhat','win'] #bruce 071008 added 'win' ### TODO: add glpane, once we have it in assy and verify not already used here [bruce 071008 comment] # 050308: selwhat will be an official assy attribute; # some external code assigns to assy.selwhat directly, # and for now can keep doing that. Within the Part, perhaps we should # use a set_selwhat method if we need one, but for now we just assign # directly to self.assy.selwhat. assy_attrs_temporary = ['changed'] # tolerable, but might be better to track per-part changes, esp. re movies ###@@@ assy_attrs_review = ['shelf', 'current_movie'] #e in future, we'll split out our own methods for some of these, incl .changed #e and for others we'll edit our own methods' code to not call them on self but on self.assy (incl selwhat). assy_attrs_all = assy_attrs + assy_attrs_temporary + assy_attrs_review def __getattr__(self, attr): # in class Part """ [overrides InvalMixin.__getattr__] """ if attr.startswith('_'): # common case, be fast (even though it's done redundantly by InvalMixin.__getattr__) raise AttributeError, attr if attr in self.assy_attrs_all: # delegate to self.assy return getattr(self.assy, attr) ###@@@ detect error of infrecur, since assy getattr delegates to here?? return InvalMixin.__getattr__(self, attr) # uses _get_xxx and _recompute_xxx methods # == attributes which should be invalidated and recomputed as needed (both inval and recompute methods follow) _inputs_for_molecules = [] # only invalidated directly ###@@@ need to do it in any other places too? def _recompute_molecules(self): """ recompute self.molecules as a list of this part's chunks, IN ARBITRARY AND NONDETERMINISTIC ORDER. """ self.molecules = 333 # not a sequence - detect bug of touching or using this during this method seen = {} # values will be new list of mols def func(n): "run this exactly once on all molecules that properly belong in this assy" if isinstance(n, Chunk): # check for duplicates (mol at two places in tree) using a dict, whose values accumulate our mols list if seen.get(id(n)): print "bug: some chunk occurs twice in this part's topnode tree; semi-tolerated but not fixed" msg = " that chunk is %r, and this part is %r, in assy %r, with topnode %r" % \ (n, self, self.assy, self.topnode) #bruce 080403, since this happened to tom print_compact_stack(msg + ": ") return # from func only seen[id(n)] = n return # from func only self.topnode.apply2all( func) self.molecules = seen.values() # warning: not in the same order as they are in the tree! # even if it was, it might elsewhere be incrementally updated. return def nodes_in_mmpfile_order(self, nodeclass = None): """ Return a list of leaf nodes in this part (only of the given class, if provided) in the same order as they appear in its nodetree (depth first), which should be the same order they'd be written into an mmp file, unless something reorders them first (as happens for certain jigs in workaround_for_bug_296, as of 050325, but maybe not as of 051115 since workaround_for_bug_296 was removed some time ago). See also _recompute_alist. """ res = [] def func(n): if not nodeclass or isinstance(n, nodeclass): res.append(n) return # from func only self.topnode.apply2all( func) return res _inputs_for_natoms = ['molecules'] def _recompute_natoms(self): #e we might not bother to inval this for indiv atom changes in mols -- not sure yet #e should we do it incrly? should we do it on every node, and do other stats too? num = 0 for mol in self.molecules: num += len(mol.atoms) return num _inputs_for_drawLevel = ['natoms'] def _recompute_drawLevel(self): """ Recompute and set the value of self.drawLevel, which controls the detail level of spheres used to draw atoms (when shaders are not being used). @see: GLPane_minimal.get_drawLevel """ num = self.natoms # note: self.natoms must be accessed whether or not # its value is needed, due to limitations in InvalMixin. # Review: it might be good to optimize by not using InvalMixin # so we don't need to recompute self.natoms when it's not needed. lod = env.prefs[ levelOfDetail_prefs_key ] # added by mark, revised by bruce, 060215 lod = int(lod) if lod > 2: # presume we're running old code (e.g. A7) # using a prefs db written by newer code (e.g. A8) lod = 2 # max LOD current code can handle # (see _NUM_SPHERE_SIZES, len(drawing_globals.sphereList)) # now set self.drawLevel from lod if lod < 0: # -1 means "Variable based on the number of atoms in the part." # [bruce 060215 changed that from 3, so we can expand number of # LOD levels in the future.] self.drawLevel = 2 if num > LARGE_MODEL: self.drawLevel = 1 if num > HUGE_MODEL: self.drawLevel = 0 else: # High (2), medium (1) or low (0) self.drawLevel = lod return # == scanners (maybe not all of them?) def enforce_permitted_members_in_groups(self, **opts): #bruce 080319 """ Intended to be called after self has just been read, either before or after update_parts and/or the dna updater has first run (with appropriate options passed to distinguish those cases). Make sure all our groups that only permit some kinds of members (e.g. DnaStrandOrSegment groups) only have that kind of members, by ejecting non-permitted members to higher groups, making a new toplevel group if necessary. FYI: As of 080319 this just means we make sure the only members of a DnaStrand or DnaSegment (i.e. a DnaStrandOrSegment) are chunks (any subclass) and DnaMarker jigs. The dna updater, run later, will make sure there is a 1-1 correspondence between controlling markers and DnaStrandOrSegments, and (nim?) that only DnaLadderRailChunks are left inside DnaStrandOrSegments. (It may have a bug in which a DnaStrandOrSegment containing only an ordinary chunk with non-PAM atoms would be left in that state.) @param opts: options to pass to group API methods permit_as_member and _f_wants_to_be_killed. As of 080319, only pre_updaters is recognized, default True, saying whether we're running before updaters (especially the dna updater) have first been run. @warning: implementation is mostly in friend methods in class Node and/or Group, and is intended to be simple and safe, *not* fast. Therefore this is not suitable to run within the dna updater, only after mmp read. @warning: this does not check self.topnode._f_wants_to_be_killed since that is nontrivial to do safely and is probably not needed at present. @note: this method's only purpose (and that of the friend methods it calls) is to clean up incorrect mmp files whose UI ops were not properly enforcing these rules. """ assert self.topnode orig_topnode = self.topnode ejected_anything = self.topnode.is_group() and \ self.topnode._f_move_nonpermitted_members(**opts) # if it ejected anything, then as a special case for being at the top, # ensure_toplevel_group created a group to wrap the old topnode, # which is what contains the ejected nodes. # Verify this, and if it happened, repeat once, and then # ungroup if it has one or no members. if ejected_anything != (orig_topnode is not self.topnode): if ejected_anything: print "\n***BUG: sanitize_dnagroups ejected from topnode %r " \ "but didn't replace it" % orig_topnode else: print "\n***BUG: sanitize_dnagroups replaced topnode %r " \ "with %r but didn't eject anything" % \ (orig_topnode, self.topnode) pass else: # no bug, safe to proceed if orig_topnode is not self.topnode: # repeat, but only once (all new activity should be confined # within the new topnode, presumably an ordinary Group # made by ensure_toplevel_part) ejected_anything = self.topnode.is_group() and \ self.topnode._f_move_nonpermitted_members(**opts) if ejected_anything: print "\n***BUG: sanitize_dnagroups ejected from new topnode in %r" % self # don't print new topnode, we don't know whether or not it changed -- # if this ever happens, revise to print more info elif not self.topnode.is_group(): print "\n***BUG: sanitize_dnagroups replaced topnode with a non-Group in %r" % self else: # still no bug, safe to proceed if len(self.topnode) <= 1: self.topnode.ungroup() #k pass pass pass return # == Bounding box methods ### BUG: these only consider chunks (self.molecules) -- # they would miss other model objects such as Jigs. [bruce 070919 comment] # # REVIEW: is self.bbox (which these recompute) still used for anything? # Could it have been superceded by the one recalculated in glpane.setViewFitToWindow? # (Note, it's used in glpane.setViewRecenter, but only after an explicit recomputation # done by self.computeBoundingBox(), so its "auto-maintained" aspect is not being used # by that.) # [bruce 070919 question] def computeBoundingBox(self): """ Compute the bounding box for this Part. This should be called whenever the geometry model has been changed, like new parts added, parts/atoms deleted, parts moved/rotated(not view move/rotation), etc.""" self.invalidate_attrs(['bbox','center']) self.bbox, self.center return _inputs_for_bbox = ['molecules'] # in principle, this should also be invalidated directly by a lot more than does it now def _recompute_bbox(self): self.bbox = BBox() for mol in self.molecules: self.bbox.merge(mol.bbox) self.center = self.bbox.center() _inputs_for_center = ['molecules'] _recompute_center = _recompute_bbox # more bounding box methods [split out of GLPane methods by bruce 070919] def bbox_for_viewing_model(self): #bruce 070919 split this out of a GLPane method """ Return a BBox object suitable for choosing a view which shows the entire model (visible objects only). BUGS: - considers only chunks. - rectilinear bbox, not screen-aligned, is a poor approximation to the model volume for choosing the view. (Fixing this would require some changes in the caller as well.) """ bbox = BBox() for mol in self.molecules: if mol.hidden or mol.display == diINVISIBLE: continue bbox.merge(mol.bbox) return bbox def bbox_for_viewing_selection(self): #bruce 070919 split this out of a GLPane method """ Return a BBox object suitable for choosing a view which shows all currently selected objects in the model. BUGS: - considers only visible objects, even though some invisible objects, when selected, are indirectly visible (and all ought to be). (If this is fixed, comments and message strings in the caller will need revision.) - rectilinear bbox, not screen-aligned, is a poor approximation to the model volume for choosing the view. (Fixing this would also require some changes in the caller.) """ movables = self.getSelectedMovables() #We will compute a Bbox with a point list. #Approach to fix bug 2250. ninad060905 pointList = [] selatoms_list = self.selatoms_list() if selatoms_list: for atm in selatoms_list: if atm.display == diINVISIBLE: #ninad 060903 may not be necessary. #@@@ Could be buggy because user is probably seeing the selection wireframe around invisible atom #and you are now allowing zoom to selection. Same is true for invisible chunks. continue pointList.append(atm.posn()) if movables: for obj in movables: if obj.hidden: continue if not isinstance(obj, Jig): if obj.display == diINVISIBLE: continue if isinstance(obj, Chunk): for a in obj.atoms.itervalues(): pointList.append(a.posn()) elif isinstance(obj, Jig): pointList.append(obj.center) else: if not selatoms_list: return None bbox = BBox(pointList) return bbox # == _inputs_for_alist = [] # only invalidated directly. Not sure if we'll inval this whenever we should, or before uses. ###@@@ def _recompute_alist(self): """ Recompute self.alist, a list of all atoms in this Part, in the same order in which they were read from, or would be written to, an mmp file -- namely, tree order for chunks, atom.key order within chunks. See also nodes_in_mmpfile_order. """ #bruce 050228 changed chunk.writemmp to make this possible, # by writing atoms in order of atom.key, # which is also the order they're created in when read from an mmp file. # Note that just after reading an mmp file, all atoms in alist are ordered by .key, # but this is no longer true in general after chunks are reordered, separated, merged, # or atoms are created or destroyed. What does remain true is that newly written mmp files # would have atoms (and the assy.alist computed by the old mmp-writing code) # in the same order as this function computes. # (#e Warning: if we revise mmp file format, this might no longer be correct. # For example, if we wanted movies to remain valid when chunks were reordered in the MT # and even when atoms were divided into chunks differently, # we could store an array of atoms followed by chunking and grouping info, instead of # using tree order at all to determine the atom order in the file. Or, we could change # the movie file format to not depend so strongly on atom order.) self.alist = 333 # not a valid Python sequence alist = [] def func_alist(nn): """ run this exactly once on all molecules (or other nodes) in this part, in tree order """ if isinstance(nn, Chunk): alist.extend(nn.atoms_in_mmp_file_order()) ### REVIEW for PAM3+5: do we need to pass a mapping to # atoms_in_mmp_file_order so it will include conversion atoms? # If so, does caller need to pass it in, to determine conversion options? # If so, do we replace the pseudo-invalidation of this list with # a get method for it, or with passing the option to the mapping # to tell it to collect the atoms actually written? (guess: the latter) # [bruce 080321/080327 questions] return # from func_alist only self.topnode.apply2all( func_alist) self.alist = alist return # == do the selmols and selatoms recomputers belong in ops_select?? _inputs_for_selmols = [] # only inval directly, since often stays the same when molecules changes, and might be incrly updated def _recompute_selmols(self): #e not worth optimizing for selwhat... but assert it was consistent, below. self.selmols = 333 # not a valid Python sequence res = [] def func_selmols(nn): """ run this exactly once on all molecules (or other nodes) in this part (in any order) """ if isinstance(nn, Chunk) and nn.picked: res.append(nn) return # from func_selmols only self.topnode.apply2all( func_selmols) self.selmols = res if self.selmols: if self.selwhat != SELWHAT_CHUNKS: msg = "bug: part has selmols but selwhat != SELWHAT_CHUNKS" if debug_flags.atom_debug: print_compact_stack(msg) else: print msg return _inputs_for_selatoms = [] # only inval directly (same reasons as selmols; this one is *usually* updated incrementally, for speed) def _recompute_selatoms(self): if debug_1855: print "debug_1855: part %r _recompute_selatoms, self.selwhat is %r, so we %s assume result is {} without checking" % \ ( self, self.selwhat, {False:"WON'T",True:"WILL (not anymore)"}[self.selwhat != SELWHAT_ATOMS] ) # Note: this optim (below, now removed) was wrong after undo in that bug... # I don't trust it to be always right even aside from Undo, so I'll remove it for A7. # For A8 maybe we should replace it with an optim based on an accurate per-part count of picked atoms? # Killed nodes might fail to get uncounted, but that would be ok. ##e #bruce 060415 zapping this to fix bug 1855... # but if we find selatoms and this would have said not to, should we fix selwhat?? # For now we just complain (debug only) but don't fix it. ###@@@ ## if self.selwhat != SELWHAT_ATOMS: ## # optimize, by trusting selwhat to be correct. ## # This is slightly dangerous until changes to assy's current selgroup/part ## # also fix up selatoms, and perhaps even verify no atoms selected in new part. ## # But it's likely that there are no such bugs, so we can try it this way for now. ## # BTW, someday we might permit selecting atoms and chunks at same time, ## # and this will need revision -- perhaps we'll have a selection-enabled boolean ## # for each type of selectable thing; perhaps we'll keep selatoms at {} when they're ## # known to be unselectable. ## # [bruce 050308] ## return {} # caller (InvalMixin.__getattr__) will store this into self.selatoms self.selatoms = 333 # not a valid dictlike thing res = {} def func_selatoms(nn): "run this exactly once on all molecules (or other nodes) in this part (in any order)" if isinstance(nn, Chunk): for atm in nn.atoms.itervalues(): if atm.picked: res[atm.key] = atm return # from func_selatoms only self.topnode.apply2all( func_selatoms) self.selatoms = res if debug_1855: print "debug_1855: part %r _recompute_selatoms did so, stores %r" % (self, res,) # guess: maybe this runs too early, before enough is updated, due to smth asking for it, maybe for incr update purposes if res and self.selwhat != SELWHAT_ATOMS and debug_flags.atom_debug: #bruce 060415; this prints, even after fix (or mitigation to nothing but debug prints) of bug 1855, # and I don't yet see an easy way to avoid that, so making it debug-only for A7. print "debug: bug: part %r found %d selatoms, even though self.selwhat != SELWHAT_ATOMS (not fixed)" % (self,len(res)) return def selatoms_list(self): #bruce 051031 """ Return the current list of selected atoms, in order of selection (whenever that makes sense), earliest first. This list is recomputed whenever requested, since order can change even when set of selected atoms doesn't change; therefore its API looks like a method rather than like an attribute. Intended usage: use .selatoms_list() instead of .selatoms.values() for anything which might care about atom order. """ items = [(atm.pick_order(), atm) for atm in self.selatoms.itervalues()] items.sort() return [pair[1] for pair in items] def selected_atoms_list(self, include_atoms_in_selected_chunks = False): #bruce 070508 """ Return a list of all selected atoms. If the option says to, also include real (i.e. selectable, ignoring selection filter) atoms in selected chunks. Atoms are in arbitrary order, except that if only atoms were selected (not chunks), then they're in order of selection. """ res = self.selatoms_list() # use some private knowledge: we now own this mutable list. if include_atoms_in_selected_chunks: #e [someday it might be that chunks too will have a pick_order; # then we could sort them with the atoms before expanding them into atoms, # and change our spec to return all atoms in order of selection # (using arb or mmp file order within picked chunks)] for chunk in self.selmols: for atom in chunk.atoms.itervalues(): if not atom.is_singlet(): res.append(atom) return res # == def addmol(self, mol): # searching for "def addnode" should also find this """ [Public method; the name addmol is DEPRECATED, use addnode instead:] Add any kind of Node to this Part (usually the "current Part"), at the end of the top level of its node tree (so it will be visible as the last node in this Part's section of the Model Tree, when this Part is visible). Invalidate part attributes which summarize part content (e.g. bbox, drawLevel). @param mol: the Node to add to self @type mol: Node @note: The method name addmol is deprecated. New code should use its alias, addnode. """ #bruce 050228 revised this for Part (was on assy) and for inval/update of part-summary attrs. ## not needed since done in changed_members: ## self.changed() #bruce 041118 self.ensure_toplevel_group() # needed if, e.g., we use Build mode to add to a clipboard item self.topnode.addchild(mol) #bruce 050202 comment: if you don't want this location for the added mol, # just call mol.moveto when you're done, like [some other code] does. ## done in addchild->changed_dad->inherit_part->Part.add: ## self.invalidate_attrs(['natoms','molecules']) # this also invals bbox and center, via molecules #bruce 050321 disabling the following debug code, since not yet ok for all uses of _readmmp; # btw does readmmp even need to call addmol anymore?? #bruce 050322 now readmmp doesn't call addmol so I'll try reenabling this debug code: if debug_flags.atom_debug: self.assy.checkparts() addnode = addmol #bruce 060604/080318; should make addnode the fundamental one, and clean up above comments def ensure_toplevel_group(self): #bruce 080318 revised so unopenables like DnaStrand don't count """ Make sure this Part's toplevel node is a Group (of a kind which does not mind having arbitrary new members added to it), by Grouping it if not. @note: most operations which create new nodes and want to add them needn't call this directly, since they can call self.addnode or assy.addnode instead. """ topnode = self.topnode assert topnode is not None if not topnode.is_group() or not topnode.MT_DND_can_drop_inside(): # REVIEW: is that the best condition? Do we need an argument # to help us know what kinds of groups are acceptable here? # And if the current one is not, what kind to create? # [bruce 080318 comment, and revised condition] self.create_new_toplevel_group() return def create_new_toplevel_group(self): """ #doc; return newly made toplevel group """ ###e should assert we're a clipboard item part # to do this correctly, I think we have to know that we're a "clipboard item part"; # this implem might work even if we permit Groups of clipboard items someday old_top = self.topnode #bruce 050420 keep autogen names in self as well as in topnode name = self.name or self.assy.name_autogrouped_nodes_for_clipboard( [old_top]) self.name = name # beginning of section during which assy's Part structure is invalid self.topnode = Group(name, self.assy, None) self.add(self.topnode) # now put the new Group into the node tree in place of old_top old_top.addsibling(self.topnode) self.topnode.addchild(old_top) # do this last, since it makes old_top forget its old location # now fix our assy's current selection group if it used to be old_top, # but without any of the usual effects from "selgroup changed" # (since in a sense it didn't -- at least the selgroup's part didn't change). self.assy.fyi_part_topnode_changed(old_top, self.topnode) # end of section during which assy's Part structure is invalid if debug_flags.atom_debug: self.assy.checkparts() return self.topnode def get_topmost_subnodes_of_class(self, clas): #Ninad 2008-08-06, revised by bruce 080807 """ Return a list of the topmost (direct or indirect) children of self.topnode (Nodes or Groups), or self.topnode itself, which are instances of the given class (or of a subclass). That is, scanning depth-first into self's tree of nodes, for each node we include in our return value, we won't include any of its children. @param clas: a class. @note: to avoid import cycles, it's often desirable to specify the class as an attribute of a convenient Assembly object (e.g. xxx.assy.DnaSegment) rather than as a global value that needs to be imported (e.g. DnaSegment, after "from xxx import DnaSegment"). @see: same-named method on class Group. """ node = self.topnode # not necessarily a Group if isinstance( node, clas): return node elif node.is_group(): return node.get_topmost_subnodes_of_class( clas) else: return [] # == # self.drawing_frame and related methods [bruce 090218/090219] _drawing_frame = None # allocated on demand _drawing_frame_class = fake_Part_drawing_frame # Note: this attribute is modified dynamically. # This default value is appropriate for drawing which does not # occur between matched calls of before/after_drawing_model, since # drawing then is deprecated but needs to work, # so this class will work, but warn when created. # Its "normal" value is used between matched calls # of before/after_drawing_model. def __get_drawing_frame(self): """ get method for self.drawing_frame property: Initialize self._drawing_frame if necessary, and return it. """ if not self._drawing_frame: self._drawing_frame = self._drawing_frame_class() # note: self._drawing_frame_class changes dynamically return self._drawing_frame def __set_drawing_frame(self): """ set method for self.drawing_frame property; should never be called """ assert 0 def __del_drawing_frame(self): """ del method for self.drawing_frame property """ self._drawing_frame = None drawing_frame = property(__get_drawing_frame, __set_drawing_frame, __del_drawing_frame) def _has_drawing_frame(self): """ @return: whether we presently have an allocated drawing frame (which would be returned by self.drawing_frame). @rtype: boolean """ return self._drawing_frame is not None def draw(self, glpane): """ Draw all of self's visible model objects using the given GLPane, whose OpenGL context must already be current. """ self.invalidate_attr('natoms') #bruce 060215, so that natoms and drawLevel are recomputed every time # (needed to fix bugs caused by lack of inval of natoms when atoms die or are born; # also means no need for prefs change to inval drawLevel, provided it gl_updates) # (could optim by only invalling drawLevel itself if the prefs value is not 'variable', I think, # but recomputing natoms should be fast compared to drawing, anyway) self.before_drawing_model() error = True try: # draw all visible model objects in self self.topnode.draw(glpane, glpane.displayMode) error = False finally: self.after_drawing_model(error) return def general_appearance_prefs_summary(self, glpane): #bruce 090306 """ Summarize the prefs values that affect the appearance of most or all atoms and bonds (that can be drawn when self is drawn), using the graphics prefs values in glpane.glprefs and for drawing in glpane. Note about how this is used: when what we return changes, all Chunk & ExternalBondSet display lists (to be drawn in self) will be considered invalid (when next drawn in self). @note: we don't include glpane.displayMode, because it only affects some display lists (not the ones for which locally set display styles determine their appearance). @see: GLPane._general_appearance_change_indicator (related) @see: GLPane._whole_model_drawingset_change_indicator (not directly related) @see: GLPane._cached_bg_image_comparison_data (not directly related) """ eltprefs = (PeriodicTable.color_change_counter, PeriodicTable.rvdw_change_counter ) matprefs = glpane.glprefs.materialprefs_summary() #bruce 051126 drawLevel = glpane.get_drawLevel(self) # ok to pass assy or part #bruce 060215 added drawLevel (when this was in Chunk.draw) # review: does this drawLevel kluge belong inside # GLPrefs.materialprefs_summary? return (eltprefs, matprefs, drawLevel,) def before_drawing_model(self): #bruce 070928; revised 090219 ### maybe: rename _model -> _part? """ Whenever self's model, or part of it, is drawn, that should be bracketed by calls of self.before_drawing_model() and self.after_drawing_model() (using try/finally to guarantee the latter call). This is already done by self.draw, but must be done explicitly if something draws a portion of self's model in some other way. (For examples, see our other calls.) Specifically, the caller must do (in this order): * call self.before_drawing_model() * call node.draw() (with proper arguments, and exception protection) on some subset of the nodes of self (not drawing any node twice); during these calls, reference can be made to attributes of self.drawing_frame (which is allocated on demand if/when first used after this method is called) * call self.after_drawing_model() (with proper arguments) Nesting of these pairs of before_drawing_model/after_drawing_model calls is not permitted and will cause bugs. This API will need revision when the model can contain repeated parts, since each repetition will need to be bracketed by matched calls of before_drawing_model and after_drawing_model, but they will need to behave differently to permit nesting (e.g. have a stack of prior values of the variables they reset). Nesting would not be needed to support "multiple views of one whole Part" or "views of multiple Parts" (but each Part-view would need to be bracketed by before/after calls); but nesting would be needed to support multiple views of "part of one Part" within a larger view of the "whole Part", if they were implemented by drawing "part of one Part" multiple times (due to repeated drawing of bonds being legitimate then). If the repetition was implemented at a graphical level (e.g. by reusing a DrawingSet), nesting of this bracketing would not be needed, and that would be faster too. """ del self.drawing_frame self._drawing_frame_class = Part_drawing_frame # instantiated the first time self.drawing_frame is accessed return def after_drawing_model(self, error = False): #bruce 070928; revised 090219 """ @see: before_drawing_model @param error: if the caller knows, it can pass an error flag to indicate whether drawing succeeded or failed. If it's known to have failed, we might not do some things we normally do. Default value is False since most calls don't pass anything. (#REVIEW: good?) """ del self.drawing_frame del self._drawing_frame_class # expose class default value return def glpane_label_text(self): #bruce 090219 renamed from glpane_text return "" # default implem, subclasses might override this def writepov(self, f, dispdef): # revised, bruce 090219 """ Draw self's visible model objects into an open povray file (which already has whatever headers & macros it needs), using the given display mode by default. """ self.before_drawing_model() # This is needed at least for its setting up of # self.drawing_frame.repeated_bonds_dict, and using its # "full version" will help permit future draw methods that # work for either OpenGL or POV-Ray. # (It might also be desirable to use GLPane._before_drawing_csdls # at that time.) error = True try: self.topnode.writepov(f, dispdef) error = False finally: self.after_drawing_model(error) return # == def break_interpart_bonds(self): ###@@@ move elsewhere in method order? review, implem for jigs """ Break all bonds between nodes in this part and nodes in other parts; jig-atom connections count as bonds [but might not be handled correctly as of 050308]. #e In future we might optimize this and only do it for specific node-trees. """ # Note: this implem assumes that the nodes in self are exactly the node-tree under self.topnode. # As of 050309 this is always true (after update_parts runs), but might not be required except here. self.topnode.apply2all( lambda node: node.break_interpart_bonds() ) return # == these are event handlers which do their own full UI updates at the end # bruce 050201 for Alpha: # Like I did to fix bug 370 for Delete (and cut and copy), # make Hide and Unhide work on jigs even when in selatoms mode. def Hide(self): """ Hide all selected chunks and jigs """ self.topnode.apply2picked(lambda x: x.hide()) self.w.win_update() def Unhide(self): """ Unhide all selected chunks and jigs """ self.topnode.apply2picked(lambda x: x.unhide()) self.w.win_update() # == def place_new_geometry(self, plane): self.ensure_toplevel_group() self.addnode(plane) # note: fix_one_or_complain will do nothing # (and return 0) as long as plane has no atoms, # which I think is true for all ref. geometry, for now anyway # [bruce 071214 comment] def errfunc(msg): "local function for error message output" # I think this will never happen [bruce 071214] env.history.message( redmsg( "Internal error making new geometry: " + msg)) fix_one_or_complain( plane, self.topnode, errfunc) self.assy.changed() self.w.win_update() return def place_new_jig(self, jig): #bruce 050415, split from all jig makers, extended, bugfixed """ Place a new jig (created by user, from atoms which must all be in this Part) into a good place in this Part's model tree. """ atoms = jig.atoms # public attribute of the jig assert atoms, "bug: new jig has no atoms: %r" % jig for atm in atoms: assert atm.molecule.part is self, \ "bug: new jig %r's atoms are not all in the current Part %r (e.g. %r is in %r)" % \ ( jig, self, atm, atm.molecule.part ) # First just put it after any atom's chunk (as old code did); then fix that place below. self.ensure_toplevel_group() #bruce 050415 fix bug 452 item 17 mol = atoms[0].molecule # arbitrary chunk involved with this jig mol.dad.addchild(jig) assert jig.part is self, "bug in place_new_jig's way of setting correct .part for jig %r" % jig # Now put it in the right place in the tree, if it didn't happen to end up there in addchild. # BTW, this is probably still good to do, even though it's no longer necessary to do # whenever we save the file (by workaround_for_bug_296, now removed), # i.e. even though the mmp format now permits forward refs to jigs. [bruce 051115 revised comment] def errfunc(msg): "local function for error message output" # I think this should never happen [bruce ca. 050415] env.history.message( redmsg( "Internal error making new jig: " + msg)) fix_one_or_complain( jig, self.topnode, errfunc) # now it's after all the atoms in it, but we also need to move it # outside of any group it doesn't belong in (and after that group # so that it remains after all its atoms). [bruce 080515 bugfix] move_after_this_group = None for group in jig.containing_groups(): if not 1: ## group.allow_this_node_inside(jig): # IMPLEM, to the extent we need it aside from permit_as_member move_after_this_group = group else: location = move_after_this_group or jig if group is location.dad and not group.permit_as_member( jig, pre_updaters = False ): ###doc: explain why this option pre_updaters = False makes sense # review: use the other code that calls permit_as_member instead of # calling it directly? move_after_this_group = group pass continue if move_after_this_group is not None: move_after_this_group.addsibling(jig) return # == def resetAtomsDisplay(self): """ Resets the display mode for each atom in the selected chunks to default display mode. Returns the total number of atoms that had their display setting reset. """ n = 0 for chunk in self.selmols: n += chunk.set_atoms_display(diDEFAULT) if n: self.changed() return n def showInvisibleAtoms(self): """ Resets the display mode for each invisible (diINVISIBLE) atom in the selected chunks to default display mode. Returns the total number of invisible atoms that had their display setting reset. """ n = 0 for chunk in self.selmols: n += chunk.show_invisible_atoms() if n: self.changed() return n ###e refile these new methods: def writemmpfile(self, filename, **mapping_options): #bruce 051209 added **mapping_options # as of 050412 this didn't yet turn singlets into H; # but as of long before 051115 it does (for all calls -- so it would not be good to use for Save Selection!) #bruce 051209 -- now it only does that if **mapping_options ask it to. from files.mmp.files_mmp_writing import writemmpfile_part writemmpfile_part( self, filename, **mapping_options) pass # end of class Part # == subclasses of Part class MainPart(Part): def immortal(self): return True def location_name(self): return "main part" def movie_suffix(self): """ what suffix should we use in movie filenames? None means don't permit making them. """ return "" pass class ClipboardItemPart(Part): def glpane_label_text(self): #e abbreviate long names... return "%s (%s)" % (self.topnode.name, self.location_name()) def location_name(self): """ [used in history messages and on glpane] """ # bruce 050418 change: ## return "clipboard item %d" % ( self.clipboard_item_number(), ) return "on Clipboard" #e might be better to rename that to Shelf, so only the current # pastable (someday also in OS clipboard) can be said to be "on the Clipboard"! def clipboard_item_number(self): """ this can be different every time... """ return self.assy.shelf.members.index(self.topnode) + 1 def movie_suffix(self): """ what suffix should we use in movie filenames? None means don't permit making them. """ ###e stub -- not a good choice, since it changes and thus is reused... # it might be better to assign serial numbers to each newly made Part that needs one for this purpose... # actually I should store part numbers in the file, and assign new ones as 1 + max of existing ones in shelf. # then use them in dflt topnode name and in glpane text (unless redundant) and in this movie suffix. # but this stub will work for now. Would it be better to just return ""? Not sure. Probably not. return "-%d" % ( self.clipboard_item_number(), ) pass # end
NanoCAD-master
cad/src/model/part.py
# Copyright 2007-2009 Nanorex, Inc. See LICENSE file for details. """ @author: Ninad @version: $Id$ @copyright: 2007-2009 Nanorex, Inc. See LICENSE file for details. History: ninad 2007-05-21: Created. ninad 2007-06-03: Implemented Plane Property Manager piotr 2008-06-13: Added image reading from MMP file. This file also used to contain DirectionArrow and ResizeHandle classes. Those were moved to their own module on Aug 20 and Oct 17, 2007 respt. """ import foundation.env as env from math import pi, atan, cos, sin from Numeric import add, dot from OpenGL.GL import glPushMatrix from OpenGL.GL import glPopMatrix from OpenGL.GL import glTranslatef from OpenGL.GL import glRotatef from OpenGL.GL import glPushName, glPopName # piotr 080527 # added texture-related imports from OpenGL.GL import glBindTexture from OpenGL.GL import glDeleteTextures from OpenGL.GL import GL_TEXTURE_2D from graphics.drawing.drawers import drawLineLoop from graphics.drawing.drawers import drawPlane from graphics.drawing.draw_grid_lines import drawGPGridForPlane from graphics.drawing.drawers import drawHeightfield from utilities.constants import black, orange, yellow, brown from geometry.VQT import V, Q, A, cross, planeXline, vlen, norm, ptonline from geometry.BoundingBox import BBox from utilities.debug import print_compact_traceback import foundation.env as env from utilities.Log import redmsg from model.ReferenceGeometry import ReferenceGeometry from graphics.drawables.DirectionArrow import DirectionArrow from graphics.drawables.ResizeHandle import ResizeHandle from utilities.constants import PLANE_ORIGIN_LOWER_LEFT, LABELS_ALONG_ORIGIN from graphics.drawing.texture_helpers import load_image_into_new_texture_name try: #bruce 080701 revised this (and related code far below); # Derrick may revise further, along with several other imports from PIL # or its submodules, in this and other files (search separately for PIL and # Image to find them all). import Image # from PIL except ImportError: from PIL import Image from utilities.prefs_constants import PlanePM_showGridLabels_prefs_key, PlanePM_showGrid_prefs_key ONE_RADIAN = 180.0 / pi # One radian = 57.29577951 degrees # This is for optimization since this computation occurs repeatedly # in very tight drawning loops. --Mark 2007-08-14 def checkIfValidImagePath(imagePath): try: im = Image.open(imagePath) except IOError: return 0 return 1 class Plane(ReferenceGeometry): """ The Plane class provides a reference plane on which to construct other 2D or 3D structures. """ sym = "Plane" is_movable = True mutable_attrs = ('center', 'quat', 'gridColor', 'gridLineType', 'gridXSpacing', 'gridYSpacing') icon_names = ["modeltree/Plane.png", "modeltree/Plane-hide.png"] copyable_attrs = ReferenceGeometry.copyable_attrs + mutable_attrs cmdname = 'Plane' mmp_record_name = "plane" logMessage = "" default_opacity = 0.1 preview_opacity = 0.0 default_fill_color = orange preview_fill_color = yellow default_border_color = orange preview_border_color = yellow def __init__(self, win, editCommand = None, atomList = None, READ_FROM_MMP = False): """ Constructs a plane. @param win: The NE1 main window. @type win: L{MainWindow} @param editCommand: The Plane Edit Controller object. If this is None, it means the Plane is created by reading the data from the MMP file and it doesn't have an EditCommand assigned. The EditCommand may be created at a later stage in this case. See L{self.edit} for an example. @type editCommand: B{Plane_EditCommand} or None @param atomList: List of atoms. @type atomList: list @param READ_FROM_MMP: True if the plane is read from a MMP file. @type READ_FROM_MMP: bool """ self.win = win ReferenceGeometry.__init__(self, win) self.fill_color = self.default_fill_color self.border_color = self.default_border_color self.opacity = self.default_opacity self.handles = [] self.directionArrow = None # This is used to notify drawing code if it's just for picking purpose # [copied from class ESPImage ] self.pickCheckOnly = False ### REVIEW/TODO: understanding how self.pickCheckOnly might be # left over from one drawing call to another (potentially causing # bugs) is a mess. It needs to be refactored so that it's just an # argument to all methods it's passed through. This involves some # superclass methods; maybe they can be overridden so the argument # is only needed in local methods, I don't know. This is done in # several Node classes, so I added this comment to all of them. # [bruce 090310 comment] self.editCommand = editCommand self.imagePath = "" self.heightfield = None self.heightfield_scale = 1.0 self.heightfield_use_texture = True # piotr 080528 # added tex_image attribute for texture image self.tex_coords = [[0.0, 0.0], [0.0, 1.0], [1.0, 1.0], [1.0, 0.0]] self.display_image = False self.display_heightfield = False self.heightfield_hq = False self.tex_image = None self.image = None #related to grid self.gridColor = yellow self.gridLineType = 3 self.gridXSpacing = 4.0 self.gridYSpacing = 4.0 self.originLocation = PLANE_ORIGIN_LOWER_LEFT self.displayLabelStyle = LABELS_ALONG_ORIGIN if not READ_FROM_MMP: self.width = 16.0 # piotr 080605 - change default dimensions to square self.height = 16.0 self.normcolor = black self.setup_quat_center(atomList) self.directionArrow = DirectionArrow(self, self.glpane, self.center, self.getaxis()) def __getattr__(self, attr): """ Recomputes attrs. @param attr: The attribute to recompute. @type attr: str """ if attr == 'bbox': return self.__computeBBox() if attr == 'planeNorm': return self.quat.rot(V(0.0, 0.0, 1.0)) if attr == 'members': return None # Mark 2007-08-15 else: raise AttributeError, 'Plane has no attr "%s"' % attr def __computeBBox(self): """ Compute the plane's current bounding box. """ # The move absolute method moveAbsolute() in Move_Command relies on a # 'bbox' attribute for the movables. This attribute is really useless # for Planes otherwise. Instead of modifying that method, I added the # attribute bbox here to fix BUG 2473. # -- ninad 2007-06-27. hw = self.width * 0.5 hh = self.height * 0.5 corners_pos = [V(-hw, hh, 0.0), V(-hw, -hh, 0.0), V( hw, -hh, 0.0), V( hw, hh, 0.0)] abs_pos = [] for pos in corners_pos: abs_pos += [self.quat.rot(pos) + self.center] return BBox(abs_pos) def setProps(self, props): """ Set the Plane properties. It is called while reading a MMP file record. @param props: The plane's properties. @type props: tuple @see: files_mmp._readmmp_state._read_plane for a comment about grid related attrs in the <props> """ name, border_color, width, height, center, wxyz, \ gridColor, gridLineType, gridXSpacing, gridYSpacing, \ originLocation, displayLabelStyle = props self.name = name self.color = self.normcolor = border_color self.width = width self.height = height self.center = center self.quat = Q(wxyz[0], wxyz[1], wxyz[2], wxyz[3]) #see files_mmp._readmmp_state._read_plane for a comment which #explains when the following attrs can be 'None' -- 2008-06-25 if gridColor is not None: self.gridColor = gridColor if gridLineType is not None: self.gridLineType = gridLineType if gridXSpacing is not None: self.gridXSpacing = gridXSpacing if gridYSpacing is not None: self.gridYSpacing = gridYSpacing if originLocation is not None: self.originLocation = originLocation if displayLabelStyle is not None: self.displayLabelStyle = displayLabelStyle if not self.directionArrow: self.directionArrow = DirectionArrow(self, self.glpane, self.center, self.getaxis()) def updateCosmeticProps(self, previewing = False): """ Update the Cosmetic properties for the Plane. The properties such as bordercolor and fill color are different when the Plane is being 'Previewed'. @param previewing: Set to True only when previewing. Otherwise, should be False. @type previewing: bool """ if not previewing: try: self.fill_color = self.default_fill_color self.border_color = self.default_border_color self.opacity = self.default_opacity except: print_compact_traceback("Can't set properties for the Plane"\ "object. Ignoring exception.") else: self.fill_color = self.preview_fill_color self.opacity = self.preview_opacity self.border_color = self.preview_border_color def getProps(self): """ Return the current properties of the Plane. @return: The plane's properties. @rtype: tuple """ # Used in preview method. If an existing structure is changed, and # the user clicks "Preview" and then clicks "Cancel", then it restores # the old properties of the plane returned by this function. props = (self.name, self.color, self.width, self.height, self.center, self.quat, self.gridColor, self.gridLineType, self.gridXSpacing, self.gridYSpacing, self.originLocation, self.displayLabelStyle) return props def mmp_record_jigspecific_midpart(self): """ Returns the "midpart" of the Plane's MMP record in the format: - width height (cx, cy, cz) (w, x, y, z) @return: The midpart of the Plane's MMP record @rtype: str """ gridColor = map(int, A(self.gridColor)*255) #This value is used in method mmp_record of class Jig dataline = "%.2f %.2f (%f, %f, %f) (%f, %f, %f, %f) " %\ (self.width, self.height, self.center[0], self.center[1], self.center[2], self.quat.w, self.quat.x, self.quat.y, self.quat.z) return " " + dataline def _draw_geometry(self, glpane, color, highlighted = False): """ Draw the Plane. @param glpane: The 3D graphics area to draw it in. @type glpane: L{GLPane} @param color: The color of the plane. @type color: tuple @param highlighted: This argument determines if the plane is drawn in the highlighted color. @type highlighted: bool @see: self.draw_after_highlighting() which draws things like filled plane, grids etc after the main drawing code is finished. """ #IMPORTANT NOTE: self.draw_after_highlighting makes sure that #plane get selected even when you click #on the filled portion of it. -- Ninad 2008-06-20 glPushMatrix() glTranslatef( self.center[0], self.center[1], self.center[2]) q = self.quat glRotatef( q.angle * ONE_RADIAN, q.x, q.y, q.z) hw = self.width * 0.5 hh = self.height * 0.5 bottom_left = V(- hw, - hh, 0.0) bottom_right = V(+ hw, - hh, 0.0) top_right = V(+ hw, + hh, 0.0) top_left = V(- hw, + hh, 0.0) corners_pos = [bottom_left, bottom_right, top_right, top_left] if self.picked: drawLineLoop(self.color, corners_pos) if highlighted: drawLineLoop(color, corners_pos, width = 2) pass self._draw_handles(corners_pos) else: if highlighted: drawLineLoop(color, corners_pos, width = 2) else: #Following draws the border of the plane in orange color #for its front side (side that was in front #when the plane was created) and a brown border for the backside. if dot(self.getaxis(), glpane.lineOfSight) < 0: bordercolor = brown #backside else: bordercolor = self.border_color #frontside drawLineLoop(bordercolor, corners_pos) if self.directionArrow.isDrawRequested(): self.directionArrow.draw() glPopMatrix() return def draw_after_highlighting(self, glpane, dispdef, pickCheckOnly = False): """ Things to draw after highlighting. Subclasses can override this method. This API method ensures that, when user clicks on the filled area of a plane, the plane gets selected. @param pickCheckOnly: This flag in conjunction with this API method allows selection of the plane when you click inside the plane (i.e. not along the highlighted plane borders) . (Note: flag copied over from the old implementation before 2008-06-20) @type pickCheckOnly: boolean @return: A boolean flag 'anythingDrawn' that tells whether this method drew something. @rtype: boolean @see: Node.draw_after_highlighting() which is overridden here """ #This implementation fixes bug 2900 anythingDrawn = False if self.hidden: return anythingDrawn self.pickCheckOnly = pickCheckOnly try: anythingDrawn = True glPushName(self.glname) glPushMatrix() glTranslatef( self.center[0], self.center[1], self.center[2]) q = self.quat glRotatef( q.angle * ONE_RADIAN, q.x, q.y, q.z) if dot(self.getaxis(), glpane.lineOfSight) < 0: fill_color = brown #backside else: fill_color = self.fill_color # Urmi-20080613: display grid lines on the plane if env.prefs[PlanePM_showGrid_prefs_key]: drawGPGridForPlane(self.glpane, self.gridColor, self.gridLineType, self.width, self.height, self.gridXSpacing, self.gridYSpacing, self.quat.unrot(self.glpane.up), self.quat.unrot(self.glpane.right), env.prefs[PlanePM_showGridLabels_prefs_key], self.originLocation, self.displayLabelStyle) textureReady = False if self.display_image and \ self.tex_image: textureReady = True glBindTexture(GL_TEXTURE_2D, self.tex_image) fill_color = [1.0,1.0,1.0] if self.display_heightfield: if self.heightfield and \ self.image: if not self.heightfield_use_texture: textureReady = False drawHeightfield(fill_color, self.width, self.height, textureReady, self.opacity, SOLID = True, pickCheckOnly = self.pickCheckOnly, hf = self.heightfield) else: drawPlane(fill_color, self.width, self.height, textureReady, self.opacity, SOLID = True, pickCheckOnly = self.pickCheckOnly, tex_coords = self.tex_coords) glPopMatrix() except: anythingDrawn = False glPopName() print_compact_traceback( "ignoring exception when drawing Plane %r: " % self) else: glPopName() return anythingDrawn def setWidth(self, newWidth): """ Set the height of the plane. @param newWidth: The new width. @type newWidth: float """ self.width = newWidth def setHeight(self, newHeight): """ Set the height of the plane. @param newHeight: The new height. @type newHeight: float """ self.height = newHeight def getWidth(self): """ Get the plane's width. """ return self.width def getHeight(self): """ Get the plane's height. """ return self.height def getaxis(self): """ Get the plane axis, which is its normal. """ # todo: merge somehow with getaxis methods on other Nodes return self.planeNorm def move(self, offset): """ Move the plane by I{offset}. @param offset: The XYZ offset. @type offset: L{V} """ self.center += offset #Following makes sure that handles move as the geometry moves. #@@ do not call Plane.move method during the Plane resizing. #call recomputeCenter method instead. -- ninad 20070522 if len(self.handles) == 8: for hdl in self.handles: assert isinstance(hdl, ResizeHandle) hdl.move(offset) def rot(self, q): """ Rotate plane by quat I{q}. @param q: The rotation quat. @type q: L{Q} """ self.quat += q def _getPlaneOrientation(self, atomPos): """ """ assert len(atomPos) >= 3 v1 = atomPos[-2] - atomPos[-1] v2 = atomPos[-3] - atomPos[-1] return cross(v1, v2) def _draw_handles(self, cornerPoints): """ Draw the handles that permit the geometry resizing. Example: For a plane, there will be 8 small squares along the border... 4 at plane corners and remaining in the middle of each side of the plane. The handles will be displayed only when the geometry is selected. @param cornerPoints: List of 4 corner points(V). The handles will be drawn at these corners PLUS in the middle of each side of the Plane. @type cornerPoints: list of 4 L{V} """ handleCenters = list(cornerPoints) cornerHandleCenters = list(cornerPoints) midBtm = (handleCenters[0] + handleCenters[1]) * 0.5 midRt = (handleCenters[1] + handleCenters[2]) * 0.5 midTop = (handleCenters[2] + handleCenters[3]) * 0.5 midLft = (handleCenters[3] + handleCenters[0]) * 0.5 for midpt in [midBtm, midRt, midTop, midLft]: handleCenters.append(midpt) if len(self.handles) == 8: assert len(self.handles) == len(handleCenters) i = 0 for i in range(len(self.handles)): self.handles[i].draw(hCenter = handleCenters[i]) else: hdlIndex = 0 for hCenter in handleCenters: handle = ResizeHandle(self, self.glpane, hCenter) handle.draw() if handle not in self.handles: self.handles.append(handle) #handleIndex = 0, 1, 2, 3 --> #--> bottomLeft, bottomRight, topRight, topLeft corners respt #handleIndex = 4, 5, 6, 7 --> #-->midBottom, midRight, midTop, midLeft Handles respt. if hdlIndex == 5 or hdlIndex == 7: handle.setType('Width-Handle') elif hdlIndex == 4 or hdlIndex == 6: handle.setType('Height-Handle') else: handle.setType('Corner') hdlIndex +=1 def recomputeCenter(self, handleOffset): """ Recompute the center of the Plane based on the handleOffset This is needed during resizing. """ ##self.move(handleOffset / 2.0) self.center += handleOffset / 2.0 def getHandlePoint(self, hdl, event): #First compute the intersection point of the mouseray with the plane #This will be our first self.handle_MovePt upon left down. #This value is further used in handleLeftDrag. -- Ninad 20070531 p1, p2 = self.glpane.mousepoints(event) linePoint = p2 lineVector = norm(p2 - p1) planeAxis = self.getaxis() planeNorm = norm(planeAxis) planePoint = self.center #Find out intersection of the mouseray with the plane. intersection = planeXline(planePoint, planeNorm, linePoint, lineVector) if intersection is None: intersection = ptonline(planePoint, linePoint, lineVector) handlePoint = intersection return handlePoint def resizeGeometry(self, movedHandle, event): """ Resizes the plane's width, height or both depending upon the handle type. @param movedHandle: The handle being moved. @type movedHandle: L{ResizeHandle} @param event: The mouse event. @type event: QEvent @see: PlanePropertyManager._update_UI_do_updates() @see: PlanePropertyManager.update_spinboxes() @see: Plane_EditCommand.command_update_internal_state() """ #NOTE: mouseray contains all the points #that a 'mouseray' will travel , between points p1 and p2 . # The intersection of mouseray with the Plane (this was suggested #by Bruce in an email) is our new handle point. #obtained in left drag. #The first vector (vec_v1) is the vector obtained by using #plane.quat.rot(handle center) #The handle_NewPt is used to find the second vector #between the plane center and this point. # -- Ninad 20070531, (updated 20070615) handle_NewPt = self.getHandlePoint(movedHandle, event) #ninad 20070615 : Fixed the resize geometry bug 2438. Thanks to Bruce #for help with the formula that finds the right vector! (vec_v1) vec_v1 = self.quat.rot(movedHandle.center) vec_v2 = V(handle_NewPt[0] - self.center[0], handle_NewPt[1] - self.center[1], handle_NewPt[2] - self.center[2]) #Orthogonal projection of Vector V2 over V1 call it vec_P. #See Plane.resizeGeometry for further details -- ninad 20070615 #@@@ need to document this further. vec_P = vec_v1 * (dot(vec_v2, vec_v1) / dot(vec_v1,vec_v1)) #The folllowing puts 'stoppers' so that if the mouse goes beyond the #opposite face while dragging, the plane resizing is stopped. #This fixes bug 2447. (It still has a bug where fast mouse movements #make resizing stop early (need a bug report) ..minor bug , workaround #is to #do the mousemotion slowly. -- ninad 20070615 if dot(vec_v1, vec_P) < 0: return #ninad 20070515: vec_P is the orthogonal projection of vec_v2 over #vec_v1 #(see selectMode.handleLeftDrag for definition of vec_v2). #The total handle movement is by the following offset. So, for instance #the fragged handle was a 'Width-Handle' , the original width of the #plane is changed by the vlen(totalOffset). Since we want to keep the #opposite side of the plane fixed during resizing, we need to offset the #plane center , along the direction of the following totalOffsetVector #(Remember that the totalOffsetVector is along vec_v1. #i.e. the angle is either 0 or 180), and , by a distance equal to #half the length of the totalOffset. Before moving the center #by this amount we need to recompute the new width or height #or both of the plane because those new values will be used in #the Plane drawing code totalOffset = vec_P - vec_v1 if vlen(vec_P) > vlen(vec_v1): new_dimension = 2 * vlen(vec_v1) + vlen(totalOffset) else: new_dimension = 2 * vlen(vec_v1) - vlen(totalOffset) if movedHandle.getType() == 'Width-Handle' : new_w = new_dimension self.setWidth(new_w) elif movedHandle.getType() == 'Height-Handle' : new_h = new_dimension self.setHeight(new_h) elif movedHandle.getType() == 'Corner': wh = 0.5 * self.getWidth() hh = 0.5 * self.getHeight() theta = atan(hh / wh) new_w = (new_dimension) * cos(theta) new_h = (new_dimension) * sin(theta) self.setWidth(new_w) self.setHeight(new_h) self.recomputeCenter(totalOffset) #assy.changed() required to make sure that the PM.update_UI() gets #called (because model is changed) and the spinboxes (or other UI #elements in the PM) get updated. self.assy.changed() def edit(self): """ Overrides node.edit and shows the property manager. """ commandSequencer = self.win.commandSequencer commandSequencer.userEnterCommand('REFERENCE_PLANE', always_update = True) currentCommand = commandSequencer.currentCommand assert currentCommand.commandName == 'REFERENCE_PLANE' #When a Plane object read from an mmp file is edited, we need to assign #it an editCommand. So, when it is resized, the propMgr spinboxes #are properly updated. See self.resizeGeometry. if self.editCommand is None: self.editCommand = currentCommand currentCommand.editStructure(self) def setup_quat_center(self, atomList = None): """ Setup the plane's quat using a list of atoms. If no atom list is supplied, the plane is centered in the glpane and parallel to the screen. @param atomList: A list of atoms. @type atomList: list """ if atomList: self.atomPos = [] for a in atomList: self.atomPos += [a.posn()] planeNorm = self._getPlaneOrientation(self.atomPos) if dot(planeNorm, self.glpane.lineOfSight) < 0: planeNorm = -planeNorm self.center = add.reduce(self.atomPos) / len(self.atomPos) self.quat = Q(V(0.0, 0.0, 1.0), planeNorm) else: self.center = V(0.0, 0.0, 0.0) # Following makes sure that Plane edges are parallel to # the 3D workspace borders. Fixes bug 2448 x, y ,z = self.glpane.right, self.glpane.up, self.glpane.out self.quat = Q(x, y, z) self.quat += Q(self.glpane.right, pi) def placePlaneParallelToScreen(self): """ Orient this plane such that it is placed parallel to the screen """ self.setup_quat_center() self.glpane.gl_update() def placePlaneThroughAtoms(self): """ Orient this plane such that its center is same as the common center of three or more selected atoms. """ atmList = self.win.assy.selatoms_list() if not atmList: msg = redmsg("Select 3 or more atoms to create a Plane.") self.logMessage = msg return # Make sure more than three atoms are selected. if len(atmList) < 3: msg = redmsg("Select 3 or more atoms to create a Plane.") self.logMessage = msg return self.setup_quat_center(atomList = atmList) self.glpane.gl_update() def placePlaneOffsetToAnother(self): """ Orient the plane such that it is parallel to a selected plane , with an offset. """ cmd = self.editCommand.cmd jigList = self.win.assy.getSelectedJigs() if jigList: planeList = [] for j in jigList: if isinstance(j, Plane) and (j is not self): planeList.append(j) #First, clear all the direction arrow drawings if any in #the existing Plane objectes in the part if not self.assy.part.topnode.members: msg = redmsg("Select a different plane first to place the" " current plane offset to it") env.history.message(cmd + msg) return for p in self.assy.part.topnode.members: if isinstance(p, Plane): if p.directionArrow: p.directionArrow.setDrawRequested(False) if len(planeList) == 1: self.offsetParentGeometry = planeList[0] self.offsetParentGeometry.directionArrow.setDrawRequested(True) if self.offsetParentGeometry.directionArrow.flipDirection: offset = 2 * norm(self.offsetParentGeometry.getaxis()) else: offset = -2 * norm(self.offsetParentGeometry.getaxis()) self.center = self.offsetParentGeometry.center + offset self.quat = Q(self.offsetParentGeometry.quat) else: msg = redmsg("Select exactly one plane to\ create a plane offset to it.") env.history.message(cmd + msg) return else: msg = redmsg("Select an existing plane first to\ create a plane offset to it.") env.history.message(cmd + msg) return self.glpane.gl_update() def loadImage(self, file_name): """ Loads an image to be displayed on the plane as a texture. Displays a warning message if the image format is not supported or the file cannot be open. This method should be extened to support basic image operations (resizing, flipping, cropping). @param file_name: The name of the image file. """ # piotr 080528 self.deleteImage() try: mipmaps, image = load_image_into_new_texture_name(file_name) self.imagePath = file_name # piotr 080624 self.tex_image = image # this gl_update may not be enough to show the image immediately self.glpane.gl_update() except: msg = redmsg("Cannot load plane image " + file_name) env.history.message(msg) self.tex_image = None def computeHeightfield(self): """ Computes a pseudo-3D "relief" mesh from image data. The result is a tuple including vertex, normal, and texture coordinates. These arrays are used by drawers.drawHeighfield method. """ # calculate heightfield data try: #bruce 080701 revised this; UNTESTED; # Derrick may revise further; see related comment above. # Also, this probably ought to be done as a toplevel import, # unless it can fail on some systems where import Image works. from Image import ANTIALIAS except: from PIL.Image import ANTIALIAS self.heightfield = None if self.display_heightfield: if self.image: self.heightfield = [] wi, he = self.image.size new_size = self.image.size # resize if too large (max. 300 pixels (HQ) or 100 pixels) if self.heightfield_hq: if wi > 300 or \ he > 300: new_size = (300, (300 * wi) / he) else: if wi > 100 or \ he > 100: new_size = (100, (100 * wi) / he) im = self.image.resize(new_size, ANTIALIAS) # resize im = im.convert("L") # compute luminance == convert to grayscale pix = im.load() wi, he = im.size scale = -self.heightfield_scale/256.0 nz = -1.0/float(he + 1) # generate triangle strips for y in range(0, he-1): tstrip_vert = [] tstrip_norm = [] tstrip_tex = [] for x in range(0, wi): for t in [0, 1]: x0 = float(x) / float(wi - 1) y0 = float(y+t) / float(he - 1) # get data point (the image is converted to grayscale) r0 = scale * pix[x, y+t] # append a vertex tstrip_vert.append([x0 - 0.5, y0 - 0.5, r0]) # append a 2D texture coordinate tstrip_tex.append([x0 , 1.0 - y0]) # compute normal for lighting if x > 0 and \ y > 0 and \ x < wi - 1 and \ y < he - 2: r1 = scale * pix[x-1, y+t] r2 = scale * pix[x+1, y+t] r3 = scale * pix[x, y-1+t] r4 = scale * pix[x, y+1+t] tstrip_norm.append(norm(V(r2-r1, r4-r3, nz))) else: tstrip_norm.append(V(0.0, 0.0, -1.0)) self.heightfield.append((tstrip_vert, tstrip_norm, tstrip_tex)) def rotateImage(self, direction): """ Rotates plane image texture coordinates clockwise (direction==0) or counterclockwise (direction==1) by 90 degrees. """ if direction == 0: tmp = self.tex_coords[0] self.tex_coords[0] = self.tex_coords[3] self.tex_coords[3] = self.tex_coords[2] self.tex_coords[2] = self.tex_coords[1] self.tex_coords[1] = tmp else: tmp = self.tex_coords[0] self.tex_coords[0] = self.tex_coords[1] self.tex_coords[1] = self.tex_coords[2] self.tex_coords[2] = self.tex_coords[3] self.tex_coords[3] = tmp if self.display_heightfield: self.computeHeightfield() self.glpane.gl_update() def mirrorImage(self, direction): """ Mirrors image texture coordinates horizontally (direction==0) or vertically (direction==1). """ if direction == 0: tmp = self.tex_coords[3] self.tex_coords[3] = self.tex_coords[0] self.tex_coords[0] = tmp tmp = self.tex_coords[2] self.tex_coords[2] = self.tex_coords[1] self.tex_coords[1] = tmp else: tmp = self.tex_coords[3] self.tex_coords[3] = self.tex_coords[2] self.tex_coords[2] = tmp tmp = self.tex_coords[0] self.tex_coords[0] = self.tex_coords[1] self.tex_coords[1] = tmp if self.display_heightfield: self.computeHeightfield() self.glpane.gl_update() def deleteImage(self): """ Deletes a texture. """ if self.tex_image: glDeleteTextures(self.tex_image) self.tex_image = None def writemmp(self, mapping): """ [extends ReferenceGeometry method] """ # piotr 080613 added this method super = ReferenceGeometry super.writemmp(self, mapping) # Write plane "info" record. # Ninad 2008-06-25: Added support for various grid attrs. gridColor = map(int, A(self.gridColor)*255) gridColorString = "%d %d %d"%(gridColor[0] , gridColor[1] , gridColor[2]) line = "info plane gridColor = " + gridColorString + "\n" mapping.write(line) line = "info plane gridLineType = %d\n" %(self.gridLineType) mapping.write(line) line = "info plane gridXSpacing = %0.2f\n" %(self.gridXSpacing) mapping.write(line) line = "info plane gridYSpacing = %0.2f\n" %(self.gridYSpacing) mapping.write(line) line = "info plane originLocation = %d\n" %(self.originLocation) mapping.write(line) line = "info plane displayLabelStyle = %d\n" %(self.displayLabelStyle) mapping.write(line) line = "info plane image_file = %s\n" %(self.imagePath) mapping.write(line) line = "info plane image_settings = %d\n" % (self.display_image) mapping.write(line) return def readmmp_info_plane_setitem( self, key, val, interp ): """ Read mmp file info record. """ if key[0] == "gridColor": gridColorString = val gridColor = gridColorString.split() self.gridColor = map(lambda (x): int(x) / 255.0, [int(gridColor[0]), int(gridColor[1]), int(gridColor[2])] ) elif key[0] == "gridLineType": self.gridLineType = int(val) elif key[0] == "gridXSpacing": self.gridXSpacing = float(val) elif key[0] == "gridYSpacing": self.gridYSpacing = float(val) elif key[0] == "originLocation": self.originLocation = int(val) elif key[0] == "displayLabelStyle": self.displayLabelStyle = int(val) elif key[0] == "image_file": self.imagePath = val if self.imagePath: self.image = Image.open(self.imagePath) self.loadImage(self.imagePath) elif key[0] == "image_settings": self.display_image = int(val) return
NanoCAD-master
cad/src/model/Plane.py
# Copyright 2004-2009 Nanorex, Inc. See LICENSE file for details. """ jigs.py -- Classes for motors and other jigs, and their superclass, Jig. @version: $Id$ @copyright: 2004-2009 Nanorex, Inc. See LICENSE file for details. History: Mostly written as gadgets.py (I'm not sure by whom); renamed to jigs.py by bruce 050414; jigs.py 1.1 should be an exact copy of gadgets.py rev 1.72, except for this module-docstring and a few blank lines and comments. bruce 050507 pulled in the jig-making methods from class Part. bruce 050513 replaced some == with 'is' and != with 'is not', to avoid __getattr__ on __xxx__ attrs in python objects. bruce circa 050518 made rmotor arrow rotate along with the atoms. 050927 moved motor classes to jigs_motors.py and plane classes to jigs_planes.py mark 051104 Changed named of Ground jig to Anchor. bruce 080305 changed Jig superclass from Node to NodeWith3DContents """ from OpenGL.GL import glLineStipple from OpenGL.GL import GL_LINE_STIPPLE from OpenGL.GL import glEnable from OpenGL.GL import GL_FRONT from OpenGL.GL import GL_LINE from OpenGL.GL import glPolygonMode from OpenGL.GL import GL_BACK from OpenGL.GL import GL_LIGHTING from OpenGL.GL import glDisable from OpenGL.GL import GL_CULL_FACE from OpenGL.GL import glPushName from OpenGL.GL import glPopName from OpenGL.GL import GL_FILL from utilities import debug_flags from utilities.icon_utilities import imagename_to_pixmap from utilities.prefs_constants import hoverHighlightingColor_prefs_key from utilities.prefs_constants import selectionColor_prefs_key from utilities.constants import gensym from utilities.constants import blue from utilities.constants import darkred from utilities.constants import black from utilities.Log import orangemsg from utilities.debug import print_compact_stack, print_compact_traceback from geometry.VQT import A import foundation.env as env from foundation.Utility import NodeWith3DContents from foundation.state_constants import S_REFS from graphics.rendering.povray.povheader import povpoint from graphics.drawing.drawers import drawwirecube from graphics.drawing.patterned_drawing import isPatternedDrawing from graphics.drawing.patterned_drawing import startPatternedDrawing from graphics.drawing.patterned_drawing import endPatternedDrawing from graphics.drawables.Selobj import Selobj_API from commands.ThermostatProperties.StatProp import StatProp from commands.ThermometerProperties.ThermoProp import ThermoProp # == _superclass = NodeWith3DContents #bruce 080305 revised this class Jig(NodeWith3DContents, Selobj_API): """ Abstract superclass for all jigs. @note: some jigs refer to atoms, but no jigs *contain* atoms. @note: most jigs don't really have "3D content", since they derive this implicitly from their atoms. But some do, so as long as they are all inheriting one class, that class needs to inherit NodeWith3DContents rather than just Node. """ # Each Jig subclass must define the class variables: # - icon_names -- a list of two icon basenames (one normal and one "hidden") # to be passed to imagename_to_pixmap # (unless that Jig subclass overrides node_icon) icon_names = ("missing", "missing-hidden") # will show up as blank icons if not overridden # (see also: "modeltree/junk.png", which exists, but has no hidden form) # # and the class constants: # - mmp_record_name (if it's ever written to an mmp file) mmp_record_name = "#" # if not redefined, this means it's just a comment in an mmp file # # and can optionally redefine some of the following class constants: sym = "Jig" # affects name-making code in __init__ featurename = "" # wiki help featurename for each Jig (or Node) subclass, or "" if it doesn't have one yet [bruce 051201] # (Each Jig subclass should override featurename with a carefully chosen name; for a few jigs it should end in "Jig".) _affects_atom_structure = True # whether adding or removing this jig # to/from an atom should record a structural change to that atom # (in _changed_structure_Atoms) for purposes of undo and updaters. # Unclear whether it ever needs to be True, but for historical # compatibility, it's True except on certain new jig classes. # (For more info see comments where this is used in class Atom.) # OTOH it's also possible this is needed on all jigs, even internal ones, # to prevent undo bugs (when undoing changes to a jig's atoms). # Until that's reviewed, it should not be overridden on any jig. # [bruce 071128] # class constants used as default values of instance variables: #e we should sometime clean up the normcolor and color attributes, but it's hard, # since they're used strangly in the *Prop.py files and in our pick and unpick methods. # But at least we'll give them default values for the sake of new jig subclasses. [bruce 050425] color = normcolor = (0.5, 0.5, 0.5) # "Enable in Minimize" is only supported for motors. Otherwise, it is ignored. Mark 051006. # [I suspect the cad code supports it for all jigs, but only provides a UI to set it for motors. -- bruce 051102] enable_minimize = False # whether a jig should apply forces to atoms during Minimize # [should be renamed 'enable_in_minimize', but I'm putting this off since it affects lots of files -- bruce 051102] # WARNING: this is added to copyable_attrs in some subclasses, rather than here # (which is bad style, IMHO, but I won't change it for now). [bruce 060228 comment] # (update, bruce 060421: it may be bad style, but in current copy & undo code it also saves memory & time # if there are lots of jigs. I don't know if there can yet be lots of jigs in practice, in ways that affect those things, # since I forget the details of pi_bond_sp_chain jigs.) dampers_enabled = True # whether a jig which can have dampers should actually have them (default True in cad and sim) # (only used in rotary motor sim & UI so far, but supported for read & write for all jigs, # and for copy for rotary and linear motors) [bruce 060421 for A7] atoms = None cntl = None # see set_cntl method (creation of these deferred until first needed, by bruce 050526) propmgr = None # see set_propmgr method in RotaryMotor class. Mark 2007-05-28. copyable_attrs = _superclass.copyable_attrs + ('normcolor', 'color') # added in some subclasses: 'enable_minimize', 'dampers_enabled' # most Jig subclasses need to extend this further _s_attr_atoms = S_REFS #bruce 060228 fix bug 1592 [untested] def __init__(self, assy, atomlist): """ Each subclass needs to call this, either in its own __init__ method or at least sometime before it's used as a Node. @warning: any subclass which overrides this and changes the argument signature may need to override _um_initargs as well. [extends superclass method] """ # Warning: some Jig subclasses require atomlist in __init__ to equal [] [revised circa 050526] _superclass.__init__(self, assy, gensym("%s" % self.sym, assy)) self.setAtoms(atomlist) #bruce 050526 revised this; this matters since some subclasses now override setAtoms # Note: the atomlist fed to __init__ is always [] for some subclasses # (with the real one being fed separately, later, to self.setAtoms) # but is apparently required to be always nonempty for other subclasses. #e should we split this jig if attached to more than one mol?? # not necessarily, tho the code to update its appearance # when one of the atoms move is not yet present. [bruce 041202] #e it might make sense to init other attrs here too, like color ## this is now the default for all Nodes [050505]: self.disabled_by_user_choice = False #bruce 050421 # Huaicai 7/15/05: support jig graphically select self.glname = self.assy.alloc_my_glselect_name( self) #bruce 080917 revised ### REVIEW: is this ok or fixed if this chunk is moved to a new assy # (if that's possible)? [bruce 080917 Q] return def _um_initargs(self): """ Return args and kws suitable for __init__. [Overrides an undo-related superclass method; see its docstring for details.] """ # [as of 060209 this is probably well-defined and correct (for most Jig subclasses), ...] # [as of 071128 it looks like it's only used in nodes that inherit SimpleCopyMixin, # but is slated to become used more widely when copy code is cleaned up. # It is also not currently correct for RotaryMotor and LinearMotor.] return (self.assy, self.atoms), {} # This should be good enough for most Jig subclasses. def node_icon(self, display_prefs): """ a subclass should override this if it needs to choose its icons differently """ return imagename_to_pixmap( self.icon_names[self.hidden] ) def setAtoms(self, atomList): """ Set self's atoms to the atoms in atomList, and append self to atom.jigs for each such atom, doing proper invalidations on self and those atoms. If self already has atoms when this is called, first remove them (which includes removing self from atom.jigs for each such atom, doing proper invalidations on that atom). Report errors if self's membership in atom.jigs lists is not as expected. Subclasses can override this if they need to take special action when their atomlist is initialized. (It's called in Jig.__init__ and in Jig._copy_fixup_at_end.) @param atomList: List of atoms to which this jig needs to be attached. @type atomList: list @see: L{self._remove_all_atoms} @see: L{RotaryMotor_EditCommand._modifyStructure} for an example use @see: L{self.setShaft} (for certain subclasses) """ if self.atoms: # intended to fix bug 2561 more safely than the prior change [bruce 071010] self._remove_all_atoms() self.atoms = list(atomList) # copy the list for atom in atomList: if self in atom.jigs: print "bug: %r is already in %r.jigs, just before we want" \ " to add it" % (self, atom) else: atom._f_jigs_append(self, changed_structure = self._affects_atom_structure ) return def is_glpane_content_itself(self): #bruce 080319 # note: some code which tests for "Chunk or Jig" might do better # to test for this method's return value. """ @see: For documentation, see Node method docstring. @rtype: boolean [overrides Node method, but as of 080319 has same implem] """ # Note: we may want this False return value even if self *is* shown # and if this does get called in practice (see Node docstring # for context of this comment). The effect of this being False # for things visible in GLPane is that in some cases they # would be picked automatically due to things in the same Groups # being picked. If we don't decide to revise this behavior for most Jigs, # and if it matters due to this being called for normal Groups # (not just inside special Dna groups of various kinds), # it probably means this method is misnamed or misdescribed. # [bruce 080319] return False def needs_atoms_to_survive(self): return True # for most Jigs def _draw(self, glpane, dispdef): """ Draws the jig in the normal way. """ # russ 080530: Support for patterned selection drawing modes. selected = self.picked and not self.is_disabled() patterned = isPatternedDrawing(select = selected) if patterned: # Patterned selection drawing needs the normal drawing first. self._draw_jig(glpane, self.normcolor) startPatternedDrawing(select = True) pass # Draw solid color (unpatterned) or overlay pattern in the selection color. self._draw_jig(glpane, (selected and env.prefs[selectionColor_prefs_key] or self.color)) if patterned: # Reset from patterned drawing mode. endPatternedDrawing(select = True) pass return def draw_in_abs_coords(self, glpane, color): """ Draws the jig in the highlighted way. """ # russ 080530: Support for patterned highlighting drawing modes. patterned = isPatternedDrawing(highlight = True) if patterned: # Patterned highlighting drawing needs the normal drawing first. self._draw_jig(glpane, self.normcolor, 1) startPatternedDrawing(highlight = True) self._draw_jig(glpane, env.prefs[hoverHighlightingColor_prefs_key], 1) endPatternedDrawing(highlight = True) else: self._draw_jig(glpane, color, 1) pass return def _draw_jig(self, glpane, color, highlighted = False): """ This is the main drawing method for a jig, which Jig subclasses may want to override. (The public methods which call it, draw -> _draw -> _draw_jig and draw_in_abs_coords -> _draw_jig, do useful things that should be common to most jig drawing.) Note that the current code [080118] is a mess in terms of exactly which drawing methods are overridden by various jigs. I don't know if this is justified by the "common code" being harmful in some cases, or just carelessness. Either way, it needs cleanup. By default, this method draws a wireframe box around each of the jig's atoms. This method should be overridden by subclasses that want to do more than simply draw wireframe boxes around each of the jig's atoms. For a good example, see the MeasureAngle._draw_jig(). """ for a in self.atoms: # Using dispdef of the atom's chunk instead of the glpane's dispdef fixes bug 373. mark 060122. chunk = a.molecule dispdef = chunk.get_dispdef(glpane) disp, rad = a.howdraw(dispdef) # wware 060203 selected bounding box bigger, bug 756 if self.picked: rad *= 1.01 drawwirecube(color, a.posn(), rad) # == copy methods [default values or common implems for Jigs, # == when these differ from Node methods] [bruce 050526 revised these] def will_copy_if_selected(self, sel, realCopy): """ [overrides Node method] """ # Copy this jig if asked, provided the copy will refer to atoms if necessary. # Whether it's disabled (here and/or in the copy, and why) doesn't matter. if not self.needs_atoms_to_survive(): return True for atom in self.atoms: if sel.picks_atom(atom): return True if realCopy: # Tell user reason why not. Mark 060125. # [bruce 060329 revised this, to make use of wware's realCopy arg. # See also bugs 1186, 1665, and associated email. msg = "Didn't copy [%s] since none of its atoms were copied." % (self.name) env.history.message(orangemsg(msg)) return False def will_partly_copy_due_to_selatoms(self, sel): """ [overrides Node method] """ return True # this is correct for jigs that say yes to jig.confers_properties_on(atom), and doesn't matter for others. def copy_full_in_mapping(self, mapping): #bruce 070430 revised to honor mapping.assy clas = self.__class__ new = clas(mapping.assy, []) # don't pass any atoms yet (maybe not all of them are yet copied) # [Note: as of about 050526, passing atomlist of [] is permitted for motors, but they assert it's []. # Before that, they didn't even accept the arg.] # Now, how to copy all the desired state? We could wait til fixup stage, then use mmp write/read methods! # But I'd rather do this cleanly and have the mmp methods use these, instead... # by declaring copyable attrs, or so. new._orig = self new._mapping = mapping new.name = "[being copied]" # should never be seen mapping.do_at_end( new._copy_fixup_at_end) #k any need to call mapping.record_copy?? # [bruce comment 050704: if we could easily tell here that none of our atoms would get copied, # and if self.needs_atoms_to_survive() is true, then we should return None (to fix bug 743) here; # but since we can't easily tell that, we instead kill the copy # in _copy_fixup_at_end if it has no atoms when that func is done.] return new def _copy_fixup_at_end(self): # warning [bruce 050704]: some of this code is copied in jig_Gamess.py's Gamess.cm_duplicate method. """ [Private method] This runs at the end of a copy operation to copy attributes from the old jig (which could have been done at the start but might as well be done now for most of them) and copy atom refs (which has to be done now in case some atoms were not copied when the jig itself was). Self is the copy, self._orig is the original. """ orig = self._orig del self._orig mapping = self._mapping del self._mapping copy = self orig.copy_copyable_attrs_to(copy) # replaces .name set by __init__ self.own_mutable_copyable_attrs() # eliminate unwanted sharing of mutable copyable_attrs if orig.picked: # clean up weird color attribute situation (since copy is not picked) # by modifying color attrs as if we unpicked the copy self.color = self.normcolor nuats = [] for atom in orig.atoms: nuat = mapping.mapper(atom) if nuat is not None: nuats.append(nuat) if len(nuats) < len(orig.atoms) and not self.name.endswith('-frag'): # similar code is in chunk, both need improving self.name += '-frag' if nuats or not self.needs_atoms_to_survive(): self.setAtoms(nuats) else: #bruce 050704 to fix bug 743 self.kill() #e jig classes with atom-specific info would have to do more now... we could call a 2nd method here... # or use list of classnames to search for more and more specific methods to call... # or just let subclasses extend this method in the usual way (maybe not doing those dels above). return # == def _remove_all_atoms(self): #bruce 071010 """ Remove all of self's atoms, but don't kill self even if that would normally happen then. (For internal use, when new atoms are about to be added.) @see: L{self.setAtoms} """ # TODO: could be optimized by inlining remove_atom for atom in list(self.atoms): self.remove_atom(atom, _kill_if_no_atoms_left_but_needs_them = False) return def remove_atom(self, atom, _kill_if_no_atoms_left_but_needs_them = True): """ Remove atom from self, and remove self from atom [called from Atom.kill] Also kill self if it loses all its atoms but it needs them to survive, unless the private option to prevent that is passed. WARNING: extended by some subclasses to call Node.kill (not Jig.kill) on self. WARNING: extended by some subclasses to do invalidations on attrs of self that depend on the atoms list. TODO: A better way would be for this to call an optional _changed_atoms method on self. See also: methods self.moved_atom and self.changed_structure, which are passed an atom and tell us it changed in some way. See also: self._remove_all_atoms method """ #bruce 071127 renamed this Jig API method, rematom -> remove_atom self.atoms.remove(atom) # also remove self from atom's list of jigs atom._f_jigs_remove(self, changed_structure = self._affects_atom_structure ) if _kill_if_no_atoms_left_but_needs_them: if not self.atoms and self.needs_atoms_to_survive(): self.kill() return def kill(self): """ [extends superclass method] """ # bruce 050215 modified this to remove self from our atoms' jiglists, via remove_atom for atom in self.atoms[:]: #bruce 050316: copy the list (presumably a bugfix) self.remove_atom(atom) # the last one removed kills the jig recursively! _superclass.kill(self) # might happen twice, that's ok def destroy(self): #bruce 050718, for bonds code # not sure if this ever needs to differ from kill -- probably not; in fact, you should probably override kill, not destroy self.kill() # bruce 050125 centralized pick and unpick (they were identical on all Jig # subclasses -- with identical bugs!), added comments; didn't yet fix the bugs. #bruce 050131 for Alpha: more changes to it (still needs review after Alpha is out) def pick(self): """ select the Jig [extends superclass method] """ from utilities.debug_prefs import debug_pref_History_print_every_selected_object if debug_pref_History_print_every_selected_object(): #bruce 070504 added this condition env.history.message(self.getinfo()) #bruce 050901 revised this; now done even if jig is killed (might affect fixed bug 451-9) if not self.picked: _superclass.pick(self) self.normcolor = self.color # bug if this is done twice in a row! [bruce 050131 maybe fixed now due to the 'if'] self.color = env.prefs[selectionColor_prefs_key] # russ 080603: pref. return def unpick(self): """ unselect the Jig [extends superclass method] """ if self.picked: _superclass.unpick(self) # bruce 050126 -- required now self.color = self.normcolor # see also a copy method which has to use the same statement to compensate for this kluge def rot(self, quat): pass def moved_atom(self, atom): #bruce 050718, for bonds code """ FYI (caller is saying to this jig), we have just changed atom.posn() for one of your atoms. [Subclasses should override this as needed.] """ pass def changed_structure(self, atom): #bruce 050718, for bonds code """ FYI (caller is saying to this jig), we have just changed the element, atomtype, or bonds for one of your atoms. [Subclasses should override this as needed.] """ pass def break_interpart_bonds(self): #bruce 050316 fix the jig analog of bug 371; 050421 undo that change for Alpha5 (see below) """ [overrides Node method] """ #e this should be a "last resort", i.e. it's often better if interpart bonds # could split the jig in two, or pull it into a new Part. # But that's NIM (as of 050316) so this is needed to prevent some old bugs. #bruce 050421 for Alpha5 decided to permit all Jig-atom interpart bonds, but just let them # make the Jig disabled. That way you can drag Jigs out and back into a Part w/o losing their atoms. # (And we avoid bugs from removing Jigs and perhaps their clipboard-item Parts at inconvenient times.) #bruce 050513 as long as the following code does nothing, let's speed it up ("is not") and also comment it out. ## for atom in self.atoms[:]: ## if self.part is not atom.molecule.part and 0: ###@@@ try out not doing this; jigs will draw and save inappropriately at first... ## self.remove_atom(atom) # this might kill self, if we remove them all return def anchors_atom(self, atom): #bruce 050321, renamed 050404 """ does this jig hold this atom fixed in space? [should be overridden by subclasses as needed, but only Anchor needs to] """ return False # for most jigs def node_must_follow_what_nodes(self): #bruce 050422 made Node and Jig implems of this from function of same name """ [overrides Node method] """ mols = {} # maps id(mol) to mol [bruce 050422 optim: use dict, not list] for atom in self.atoms: mol = atom.molecule if id(mol) not in mols: mols[id(mol)] = mol return mols.values() def writemmp(self, mapping): #bruce 050322 revised interface to use mapping """ [extends Node.writemmp; could be overridden by Jig subclasses, but isn't (as of 050322)] """ #bruce 050322 made this from old Node.writemmp, but replaced nonstandard use of __repr__ line, wroteleaf = self.mmp_record(mapping) # includes '\n' at end if line: mapping.write(line) if wroteleaf: self.writemmp_info_leaf(mapping) # only in this case, since other case means no node was actually written [bruce 050421] else: _superclass.writemmp(self, mapping) # just writes comment into file and atom_debug msg onto stdout return def writemmp_info_leaf(self, mapping): #bruce 051102 """ [extends superclass method] """ _superclass.writemmp_info_leaf(self, mapping) if self.enable_minimize: mapping.write("info leaf enable_in_minimize = True\n") #bruce 051102 if not self.dampers_enabled: mapping.write("info leaf dampers_enabled = False\n") #bruce 060421 return def readmmp_info_leaf_setitem( self, key, val, interp ): #bruce 051102 """ [extends superclass method] """ if key == ['enable_in_minimize']: # val should be "True" or "False" (unrecognized vals are treated as False) val = (val == 'True') self.enable_minimize = val elif key == ['dampers_enabled']: # val should be "True" or "False" (unrecognized vals are treated as True) val = (val != 'False') self.dampers_enabled = val else: _superclass.readmmp_info_leaf_setitem( self, key, val, interp) return def _mmp_record_front_part(self, mapping): # [Huaicai 9/21/05: split mmp_record into front-middle-last 3 parts, so each part can be different for a different jig. if mapping is not None: name = mapping.encode_name(self.name) #bruce 050729 help fix some Jig.__repr__ tracebacks (e.g. part of bug 792-1) else: name = self.name if self.picked: c = self.normcolor # [bruce 050422 comment: this code looks weird, but i guess it undoes pick effect on color] else: c = self.color color = map(int, A(c)*255) mmprectype_name_color = "%s (%s) (%d, %d, %d)" % (self.mmp_record_name, name, color[0], color[1], color[2]) return mmprectype_name_color def _mmp_record_last_part(self, mapping): """ Last part of the mmp record. By default, this lists self's atoms, encoded by mapping. In some cases it lists a subset of self's atoms. Subclass can override this method if needed. As of long before 080317, some subclasses do that to work around bugs or kluges in class Jig methods which cause problems when they have no atoms. @note: If this returns anything other than empty, make sure to put one extra space character at the front. [As of long before 080317, it is likely that this is done by caller and therefore no longer needed in this method. ###review] """ #Huaicai 9/21/05: split this from mmp_record, so the last part # can be different for a jig like ESP Image, which has no atoms. if mapping is not None: ndix = mapping.atnums minflag = mapping.min # writing this record for Minimize? [bruce 051031] else: ndix = None minflag = False nums = self.atnums_or_None( ndix, return_partial_list = minflag ) assert nums is not None # bruce 080317 # caller must ensure this by calling this with mapping.min set # or when all atoms are encodable. [bruce comment 080317] return " " + " ".join(map(str, nums)) def mmp_record(self, mapping = None): #bruce 050422 factored this out of all the existing Jig subclasses, changed arg from ndix to mapping #e could factor some code from here into mapping methods #bruce 050718 made this check for mapping is not None (2 places), as a bugfix in __repr__ #bruce 051031 revised forward ref code, used mapping.min """ Returns a pair (line, wroteleaf) where line is the standard MMP record for any jig (one string containing one or more lines including their \ns): jigtype (name) (r, g, b) ... [atnums-list]\n where ... is defined by a jig-specific submethod, and (as a special kluge) might contain \n and start another mmp record to hold the atnums-list! And, where wroteleaf is True iff this line creates a leaf node (susceptible to "info leaf") when read. Warning: the mmp file parser for most jigs cares that the data fields are separated by exactly one blank space. Using two spaces makes it fail! If mapping is supplied, then mapping.ndix maps atom keys to atom numbers (atnums) for use only in this writemmp event; if not supplied, just use atom keys as atnums, since we're being called by Jig.__repr__. [Subclasses could override this to return their mmp record, which must consist of 1 or more lines (all in one string which we return) each ending in '\n', including the last line; or return None to force caller to use some default value; but they shouldn't, because we've pulled all the common code for Jigs into here, so all they need to override is mmp_record_jigspecific_midpart.] """ if mapping is not None: ndix = mapping.atnums name = mapping.encode_name(self.name) # flags related to what we can do about atoms on this jig which have no encoding in mapping permit_fwd_ref = not mapping.min #bruce 051031 (kluge, mapping should say this more directly) permit_missing_jig_atoms = mapping.min #bruce 051031 (ditto on kluge) assert not (permit_fwd_ref and permit_missing_jig_atoms) # otherwise wouldn't know which one to do with missing atoms! else: ndix = None name = self.name permit_fwd_ref = False #bruce 051031 permit_missing_jig_atoms = False # guess [bruce 051031] want_fwd_ref = False # might be modified below if mapping is not None and mapping.not_yet_past_where_sim_stops_reading_the_file() and self.is_disabled(): # forward ref needed due to self being disabled if permit_fwd_ref: want_fwd_ref = True else: return "# disabled jig skipped for minimize\n", False else: # see if forward ref needed due to not all atoms being written yet if permit_fwd_ref: # assume this means that missing atoms should result in a forward ref nums = self.atnums_or_None( ndix) # nums is used only to see if all atoms have yet been written, so we never pass return_partial_list flag to it want_fwd_ref = (nums is None) del nums else: pass # just let missing atoms not get written del ndix if want_fwd_ref: assert mapping # implied by above code # We need to return a forward ref record now, and set up mapping object to write us out for real, later. # This means figuring out when to write us... and rather than ask atnums_or_None for more help on that, # we use a variant of the code that used to actually move us before writing the file (since that's easiest for now). # But at least we can get mapping to do most of the work for us, if we tell it which nodes we need to come after, # and whether we insist on being invisible to the simulator even if we don't have to be # (since all our atoms are visible to it). ref_id = mapping.node_ref_id(self) #e should this only be known to a mapping method which gives us the fwdref record?? mmprectype_name = "%s (%s)" % (self.mmp_record_name, name) fwd_ref_to_return_now = "forward_ref (%s) # %s\n" % (str(ref_id), mmprectype_name) # the stuff after '#' is just a comment after_these = self.node_must_follow_what_nodes() assert after_these # but this alone does not assert that they # weren't all already written out! The next method should # do that. [### need to assert they are not killed??] mapping.write_forwarded_node_after_nodes( self, after_these, force_disabled_for_sim = self.is_disabled() ) return fwd_ref_to_return_now , False frontpart = self._mmp_record_front_part(mapping) midpart = self.mmp_record_jigspecific_midpart() lastpart = self._mmp_record_last_part(mapping) # note: this also calls atnums_or_None if lastpart == " ": # bruce 051102 for "enable in minimize" # kluge! should return a flag instead. # this happens during "minimize selection" if a jig is enabled # for minimize but none of its atoms are being minimized. if not self.atoms: #bruce 080317 add this case as a bugfix; # this might mean some of the existing subclass overrides of # _mmp_record_last_part are no longer needed (###review). # KLUGE, to work around older kluge which was causing bugs: # this value of lastpart is normal in this case. # But warn in the file if this looks like a bug. if self.needs_atoms_to_survive(): # untested? print "bug? %r being written with no atoms, but needs them" % self lastpart += "# bug? no atoms, but needs them" # now use lastpart in return value as usual pass else: # (before bruce 080317 bugfix, this was what we did # even when not self.atoms) # return a comment instead of the entire mmp record: return "# jig with no selected atoms skipped for minimize\n", False pass return frontpart + midpart + lastpart + "\n" , True def mmp_record_jigspecific_midpart(self): """ #doc (see rmotor's version's docstring for details) [some subclasses need to override this] Note: If it returns anything other than empty, make sure add one more extra 'space' at the front. """ return "" # Added "return_partial_list" after a discussion with Bruce about "enable in minimize" jigs. # This would allow a partial atom list to be returned. # [Mark 051006 defined return_partial_list API; bruce 051031 revised docstring and added implem, # here and in one subclass.] def atnums_or_None(self, ndix, return_partial_list = False): """ Return list of atnums to write, as ints(??) (using ndix to encode them), or None if some atoms were not yet written to the file and return_partial_list is False. (If return_partial_list is True, then missing atoms are just left out of the returned list. Callers should check whether the resulting list is [] if that matters.) (If ndix not supplied, as when we're called by __repr__, use atom keys for atnums; return_partial_list doesn't matter in this case since all atoms have keys.) [Jig method; overridden by some subclasses] """ res = [] for atom in self.atoms: key = atom.key if ndix: code = ndix.get(key, None) # None means don't add it, and sometimes also means return early if code is None and not return_partial_list: # typical situation (as we're called as of 051031): # too soon to write this jig -- would require forward ref to an atom, which mmp format doesn't support return None if code is not None: res.append(code) else: res.append(key) return res def __repr__(self): #bruce 050322 compatibility method, probably not needed, but affects debugging try: line, wroteleaf = None, None # for debug print, in case not assigned line, wroteleaf = self.mmp_record() assert wroteleaf # BTW, is wroteleaf false for jigs whose mmp line is a comment? Does it need to be? [bruce 071205 Q] except: #bruce 050422 msg = "bug in Jig.__repr__ call of self.mmp_record() ignored, " \ "which returned (%r, %r)" % (line, wroteleaf) print_compact_traceback( msg + ": " ) line = None if line: return line # review: is this precise retval still required # by mmp writing code? I hope not... if not, change it # to be a better version of __repr__. [bruce 071205 comment] else: return "<%s at %#x>" % (self.__class__.__name__, id(self)) pass def is_disabled(self): #bruce 050421 experiment related to bug 451-9 """ [overrides Node method] """ return self.disabled_by_user_choice or self.disabled_by_atoms() def disabled_by_atoms(self): #e rename? """ is this jig necessarily disabled (due to some atoms being in a different part)? """ part = self.part for atom in self.atoms: if part is not atom.molecule.part: return True # disabled (or partly disabled??) due to some atoms not being in the same Part #e We might want to loosen this for an Anchor/Ground (and only disable the atoms in a different Part), # but for initial bugfixing, let's treat all atoms the same for all jigs and see how that works. return False def getinfo(self): #bruce 050421 added this wrapper method and renamed the subclass methods it calls. sub = self._getinfo() disablers = [] if self.disabled_by_user_choice: disablers.append("by choice") if self.disabled_by_atoms(): if self.part.topnode is self.assy.tree: why = "some atoms on clipboard" else: why = "some atoms in a different Part" disablers.append(why) if len(disablers) == 2: why = disablers[0] + ", and by " + disablers[1] elif len(disablers) == 1: why = disablers[0] else: assert not disablers why = "" if why: sub += " [DISABLED (%s)]" % why return sub def _getinfo(self):#ninad060825 """ Return a string for display in history or Properties [subclasses should override this] """ return "[%s: %s]" % (self.sym, self.name) def getToolTipInfo(self): """ public method that returns a string for display in Dynamic Tool tip """ return self._getToolTipInfo() def _getToolTipInfo(self): """ Return a string for display in Dynamic Tool tip [subclasses should override this] """ return "%s <br><font color=\"#0000FF\"> Jig Type:</font> %s" % (self.name, self.sym) def draw(self, glpane, dispdef): #bruce 050421 added this wrapper method and renamed the subclass methods it calls. ###@@@writepov too if self.hidden: return disabled = self.is_disabled() if disabled: # use dashed line (see drawer.py's drawline for related code) glLineStipple(1, 0xE3C7) # 0xAAAA dots are too small; 0x3F07 assymetrical; try dashes len 4,6, gaps len 3, start mid-6 glEnable(GL_LINE_STIPPLE) # and display polys as their edges (see drawer.py's drawwirecube for related code) glPolygonMode(GL_FRONT, GL_LINE) glPolygonMode(GL_BACK, GL_LINE) glDisable(GL_LIGHTING) glDisable(GL_CULL_FACE) # this makes motors look too busy, but without it, they look too weird (which seems worse) try: glPushName(self.glname) self._draw(glpane, dispdef) except: glPopName() print_compact_traceback("ignoring exception when drawing Jig %r: " % self) else: glPopName() if disabled: glEnable(GL_CULL_FACE) glEnable(GL_LIGHTING) glPolygonMode(GL_FRONT, GL_FILL) glPolygonMode(GL_BACK, GL_FILL) #bruce 050729 precaution related to bug 835; could probably use GL_FRONT_AND_BACK glDisable(GL_LINE_STIPPLE) return def edit(self): #bruce 050526 moved this from each subclass into Jig, and let it handle missing cntl if self.cntl is None: #bruce 050526: had to defer this until first needed, so I can let some jigs temporarily be in a state # where it doesn't work, during copy. (The Stat & Thermo controls need the jig to have an atom during their init.) self.set_cntl() assert self.cntl is not None if self is self.assy.o.selobj: self.assy.o.selobj = None # If the Properties dialog was selected from the GLPane's context # menu, selobj will typically be self and the jig will appear # highlighted. That is inconvenient if we want to change its color # from the Properties dialog, since we can't see the color we're # changing, either before or after we change it. So reset selobj # to None here to avoid this problem. # [mark 060312 revision; comment rewritten by bruce 090106] self.cntl.setup() self.cntl.exec_() def toggleJigDisabled(self): """ Enable/Disable jig. """ # this is wrong, doesn't do self.changed(): ## self.disabled_by_user_choice = not self.disabled_by_user_choice self.set_disabled_by_user_choice( not self.disabled_by_user_choice ) #bruce 060313 use correct call, to fix bug 1671 (and related unreported bugs) if self is self.assy.o.selobj: # Without this, self will remain highlighted until the mouse moves. self.assy.o.selobj = None ###e shouldn't we use set_selobj instead?? [bruce 060726 question] self.assy.w.win_update() def mouseover_statusbar_message(self): # Fixes bug 1642. mark 060312 return self.name def make_selobj_cmenu_items(self, menu_spec): """ Add jig specific context menu items to <menu_spec> list when self is the selobj. This method should be overridden by subclasses that want to add more/different menu items. For a good example, see the Motor.make_selobj_cmenu_items(). """ item = ('Hide', self.Hide) menu_spec.append(item) if self.disabled_by_user_choice: item = ('Disabled', self.toggleJigDisabled, 'checked') else: item = ('Disable', self.toggleJigDisabled, 'unchecked') menu_spec.append(item) menu_spec.append(None) # Separator item = ('Edit Properties...', self.edit) menu_spec.append(item) def nodes_containing_selobj(self): #bruce 080507 """ @see: interface class Selobj_API for documentation """ # safety check in case of calls on out of date selobj: if self.killed(): return [] return self.containing_nodes() #e there might be other common methods to pull into here pass # end of class Jig # == Anchor (was Ground) class Anchor(Jig): """ an Anchor (Ground) just has a list of atoms that are anchored in space """ sym = "Anchor" icon_names = ["modeltree/anchor.png", "modeltree/anchor-hide.png"] featurename = "Anchor" # wiki help featurename [bruce 051201; note that for a few jigs this should end in "Jig"] # create a blank Anchor with the given list of atoms def __init__(self, assy, list): Jig.__init__(self, assy, list) # set default color of new anchor to black self.color = black # This is the "draw" color. When selected, this will become highlighted red. self.normcolor = black # This is the normal (unselected) color. def set_cntl(self): #bruce 050526 split this out of __init__ (in all Jig subclasses) # Changed from GroundProp to more general JigProp, which can be used for any simple jig # that has only a name and a color attribute changable by the user. JigProp supersedes GroundProp. # Mark 050928. from command_support.JigProp import JigProp self.cntl = JigProp(self, self.assy.o) # Write "anchor" record to POV-Ray file in the format: # anchor(<box-center>,box-radius,<r, g, b>) def writepov(self, file, dispdef): if self.hidden: return if self.is_disabled(): return if self.picked: c = self.normcolor else: c = self.color for a in self.atoms: disp, rad = a.howdraw(dispdef) grec = "anchor(" + povpoint(a.posn()) + "," + str(rad) + ",<" + str(c[0]) + "," + str(c[1]) + "," + str(c[2]) + ">)\n" file.write(grec) def _getinfo(self): return "[Object: Anchor] [Name: " + str(self.name) + "] [Total Anchors: " + str(len(self.atoms)) + "]" def _getToolTipInfo(self): #ninad060825 """ Return a string for display in Dynamic Tool tip """ attachedAtomCount = "<font color=\"#0000FF\"> Total Anchors:</font> %d "%(len(self.atoms)) return str(self.name) + "<br>" + "<font color=\"#0000FF\"> Jig Type:</font>Anchor"\ + "<br>" + str(attachedAtomCount) def getstatistics(self, stats): stats.nanchors += len(self.atoms) mmp_record_name = "ground" # Will change to "anchor" for A7. Mark 051104. def mmp_record_jigspecific_midpart(self): # see also fake_Anchor_mmp_record [bruce 050404] return "" def anchors_atom(self, atom): #bruce 050321; revised 050423 (warning: quadratic time for large anchor jigs in Minimize) """ does this jig hold this atom fixed in space? [overrides Jig method] """ return (atom in self.atoms) and not self.is_disabled() def confers_properties_on(self, atom): # Anchor method """ [overrides Node method] Should this jig be partly copied (even if not selected) when this atom is individually selected and copied? (It's ok to assume without checking that atom is one of this jig's atoms.) """ return True pass # end of class Anchor def fake_Anchor_mmp_record(atoms, mapping): #bruce 050404 utility for Minimize Selection """ Return an mmp record (one or more lines with \n at end) for a fake Anchor (Ground) jig for use in an mmp file meant only for simulator input. @note: unlike creating and writing out a new real Anchor (Ground) object, which adds itself to each involved atom's .jigs list (perhaps just temporarily), perhaps causing unwanted side effects (like calling some .changed() method), this function has no side effects. """ ndix = mapping.atnums c = black color = map(int,A(c)*255) # Change to "anchor" for A7. Mark 051104. s = "ground (%s) (%d, %d, %d) " % ("name", color[0], color[1], color[2]) nums = map((lambda a: ndix[a.key]), atoms) return s + " ".join(map(str,nums)) + "\n" # == Stat and Thermo class Jig_onChunk_by1atom(Jig): """ Subclass for Stat and Thermo, which are on one atom in cad code, but on its whole chunk in simulator, by means of being written into mmp file as the min and max atnums in that chunk (whose atoms always occupy a contiguous range of atnums, since those are remade per writemmp event), plus the atnum of their one user-visible atom. """ def setAtoms(self, atomlist): """ [Overrides Jig method; called by Jig.__init__] """ # old comment: # ideally len(list) should be 1, but in case code in files_mmp uses more # when supporting old Stat records, all I assert here is that it's at # least 1, but I only store the first atom [bruce 050210] # addendum, bruce 050526: can't assert that anymore due to copying code for this jig. ## assert len(atomlist) >= 1 atomlist = atomlist[0:1] # store at most one atom super = Jig super.setAtoms(self, atomlist) def atnums_or_None(self, ndix, return_partial_list = False): #bruce 051031 added return_partial_list implem """ return list of atnums to write, or None if some atoms not yet written [overrides Jig method] """ assert len(self.atoms) == 1 atom = self.atoms[0] if ndix: # for mmp file -- return numbers of first, last, and defining atom atomkeys = [atom.key] + atom.molecule.atoms.keys() # arbitrary order except first list element # first key occurs twice, that's ok (but that it's first matters) # (this is just a kluge so we don't have to process it thru ndix separately) try: nums = map((lambda ak: ndix[ak]), atomkeys) except KeyError: # too soon to write this jig -- would require forward ref to an atom, which mmp format doesn't support if return_partial_list: return [] # kluge; should be safe since chunk atoms are written all at once [bruce 051031] return None nums = [min(nums), max(nums), nums[0]] # assumes ndix contains numbers, not number-strings [bruce 051031 comment] else: # for __repr__ -- in this case include only our defining atom, and return key rather than atnum nums = map((lambda a: a.key), self.atoms) return nums pass class Stat( Jig_onChunk_by1atom ): """ A Stat is a Langevin thermostat, which sets a chunk to a specific temperature during a simulation. A Stat is defined and drawn on a single atom, but its record in an mmp file includes 3 atoms: - first_atom: the first atom of the chunk to which it is attached. - last_atom: the last atom of the chunk to which it is attached. - boxed_atom: the atom in the chunk the user selected. A box is drawn around this atom. Note that the simulator applies the Stat to all atoms in the entire chunk to which it is attached, but in case of merging or joining chunks, the atoms in this chunk might be different each time the mmp file is written; even the atom order in one chunk might vary, so the first and last atoms can be different even when the set of atoms in the chunk has not changed. Only the boxed_atom is constant (and only it is saved, as self.atoms[0]). """ #bruce 050210 for Alpha-2: fix bug in Stat record reported by Josh to ne1-users sym = "Stat" icon_names = ["modeltree/Thermostat.png", "modeltree/Thermostat-hide.png"] featurename = "Thermostat" #bruce 051203 copyable_attrs = Jig_onChunk_by1atom.copyable_attrs + ('temp',) # create a blank Stat with the given list of atoms, set to 300K def __init__(self, assy, list): Jig.__init__(self, assy, list) # note: this calls Jig_onChunk_by1atom.setAtoms method # set default color of new stat to blue self.color = blue # This is the "draw" color. When selected, this will become highlighted red. self.normcolor = blue # This is the normal (unselected) color. self.temp = 300 def set_cntl(self): #bruce 050526 split this out of __init__ (in all Jig subclasses) self.cntl = StatProp(self, self.assy.o) ## self.cntl = None #bruce 050526 do this later since it needs at least one atom to be present # Write "stat" record to POV-Ray file in the format: # stat(<box-center>,box-radius,<r, g, b>) def writepov(self, file, dispdef): if self.hidden: return if self.is_disabled(): return if self.picked: c = self.normcolor else: c = self.color for a in self.atoms: disp, rad = a.howdraw(dispdef) srec = "stat(" + povpoint(a.posn()) + "," + str(rad) + ",<" + str(c[0]) + "," + str(c[1]) + "," + str(c[2]) + ">)\n" file.write(srec) def _getinfo(self): return "[Object: Thermostat] "\ "[Name: " + str(self.name) + "] "\ "[Temp = " + str(self.temp) + "K]" + "] "\ "[Attached to: " + str(self.atoms[0].molecule.name) + "] " def _getToolTipInfo(self): #ninad060825 "Return a string for display in Dynamic Tool tip " #ninad060825 We know that stat has only one atom May be we should use try - except to be safer? attachedChunkInfo = ("<font color=\"#0000FF\">Attached to chunk </font>[%s]") %(self.atoms[0].molecule.name) return str(self.name) + "<br>" + "<font color=\"#0000FF\"> Jig Type:</font>Thermostat"\ + "<br>" + "<font color=\"#0000FF\"> Temperature:</font>" + str(self.temp) + " K"\ + "<br>" + str(attachedChunkInfo) def getstatistics(self, stats): stats.nstats += len(self.atoms) mmp_record_name = "stat" def mmp_record_jigspecific_midpart(self): return " " + "(%d)" % int(self.temp) pass # end of class Stat # == Thermo class Thermo(Jig_onChunk_by1atom): """ A Thermo is a thermometer which measures the temperature of a chunk during a simulation. A Thermo is defined and drawn on a single atom, but its record in an mmp file includes 3 atoms and applies to all atoms in the same chunk; for details see Stat docstring. """ #bruce 050210 for Alpha-2: fixed same bug as in Stat. sym = "Thermo" icon_names = ["modeltree/Thermometer.png", "modeltree/Thermometer-hide.png"] featurename = "Thermometer" #bruce 051203 # creates a thermometer for a specific atom. "list" contains only one atom. def __init__(self, assy, list): Jig.__init__(self, assy, list) # note: this calls Jig_onChunk_by1atom.setAtoms method # set default color of new thermo to dark red self.color = darkred # This is the "draw" color. When selected, this will become highlighted red. self.normcolor = darkred # This is the normal (unselected) color. def set_cntl(self): #bruce 050526 split this out of __init__ (in all Jig subclasses) self.cntl = ThermoProp(self, self.assy.o) # Write "thermo" record to POV-Ray file in the format: # thermo(<box-center>,box-radius,<r, g, b>) def writepov(self, file, dispdef): if self.hidden: return if self.is_disabled(): return if self.picked: c = self.normcolor else: c = self.color for a in self.atoms: disp, rad = a.howdraw(dispdef) srec = "thermo(" + povpoint(a.posn()) + "," + str(rad) + ",<" + str(c[0]) + "," + str(c[1]) + "," + str(c[2]) + ">)\n" file.write(srec) def _getinfo(self): return "[Object: Thermometer] "\ "[Name: " + str(self.name) + "] "\ "[Attached to: " + str(self.atoms[0].molecule.name) + "] " def _getToolTipInfo(self): #ninad060825 """ Return a string for display in Dynamic Tool tip """ attachedChunkInfo = ("<font color=\"#0000FF\">Attached to chunk </font>[%s]") %(self.atoms[0].molecule.name) #ninad060825 We know that stat has only one atom... Maybe we should use try/except to be safer? return str(self.name) + "<br>" + "<font color=\"#0000FF\"> Jig Type:</font>Thermometer"\ + "<br>" + str(attachedChunkInfo) def getstatistics(self, stats): stats.nthermos += len(self.atoms) mmp_record_name = "thermo" def mmp_record_jigspecific_midpart(self): return "" pass # end of class Thermo # == AtomSet class AtomSet(Jig): """ An Atom Set just has a list of atoms that can be easily selected by the user. """ sym = "AtomSet" # Was "Atom Set" (removed space). Mark 2007-05-28 icon_names = ["modeltree/Atom_Set.png", "modeltree/Atom_Set-hide.png"] featurename = "Atom Set" #bruce 051203 # create a blank AtomSet with the given list of atoms def __init__(self, assy, list): Jig.__init__(self, assy, list) # set default color of new set atom to black self.color = black # This is the "draw" color. When selected, this will become highlighted red. self.normcolor = black # This is the normal (unselected) color. def set_cntl(self): # Fixed bug 1011. Mark 050927. from command_support.JigProp import JigProp self.cntl = JigProp(self, self.assy.o) # it's drawn as a wire cube around each atom (default color = black) def _draw(self, glpane, dispdef): """ Draws a red wire frame cube around each atom, only if the jig is select. """ if not self.picked: return for a in self.atoms: # Using dispdef of the atom's chunk instead of the glpane's dispdef fixes bug 373. mark 060122. chunk = a.molecule dispdef = chunk.get_dispdef(glpane) disp, rad = a.howdraw(dispdef) # wware 060203 selected bounding box bigger, bug 756 if self.picked: rad *= 1.01 drawwirecube(self.color, a.posn(), rad) def _getinfo(self): return "[Object: Atom Set] [Name: " + str(self.name) + "] [Total Atoms: " + str(len(self.atoms)) + "]" def _getToolTipInfo(self): #ninad060825 """ Return a string for display in Dynamic Tool tip """ attachedAtomCount ="<font color=\"#0000FF\">Total Atoms: </font>%d"%(len(self.atoms)) return str(self.name) + "<br>" + "<font color=\"#0000FF\"> Jig Type:</font>Atom Set"\ + "<br>" + str(attachedAtomCount) def getstatistics(self, stats): stats.natoms += 1 # Count only the atom set itself, not the number of atoms in the set. mmp_record_name = "atomset" def mmp_record_jigspecific_midpart(self): return "" pass # end of class AtomSet # end
NanoCAD-master
cad/src/model/jigs.py
# Copyright 2004-2007 Nanorex, Inc. See LICENSE file for details. """ jigs_planes.py -- Classes for Plane jigs, including RectGadget, GridPlane, and (in its own module) ESPImage. @author: Huaicai (I think), Ninad (I think), maybe others @version: $Id$ @copyright: 2004-2007 Nanorex, Inc. See LICENSE file for details. History: 050927. Split off Plane jigs from jigs.py into this file. Mark bruce 071215 split class ESPImage into its own file. TODO: Split more. Perhaps merge GridPlane with Plane (reference plane). """ import math from Numeric import size, add from OpenGL.GL import glPushMatrix from OpenGL.GL import glTranslatef from OpenGL.GL import glRotatef from OpenGL.GL import glPopMatrix from graphics.drawing.drawers import drawLineLoop from graphics.drawing.draw_grid_lines import drawGPGrid from graphics.drawing.draw_grid_lines import drawSiCGrid from geometry.VQT import V, Q, A, cross from graphics.rendering.povray.povheader import povpoint from model.jigs import Jig from utilities.constants import black from utilities.constants import gray from utilities.prefs_constants import SQUARE_GRID from utilities.prefs_constants import SOLID_LINE from geometry.BoundingBox import BBox from commands.GridPlaneProperties.GridPlaneProp import GridPlaneProp # == RectGadget class RectGadget(Jig): """ Abstract superclass for GridPlane and ESPImage. """ is_movable = True #mark 060120 mutable_attrs = ('center', 'quat') copyable_attrs = Jig.copyable_attrs + ('width', 'height') + mutable_attrs def __init__(self, assy, list, READ_FROM_MMP): Jig.__init__(self, assy, list) self.width = 20 self.height = 20 self.assy = assy self.cancelled = True # We will assume the user will cancel self.atomPos = [] if not READ_FROM_MMP: self.__init_quat_center(list) def _um_initargs(self): #bruce 051013 [as of 060209 this is probably well-defined and correct # (for most Jig subclasses), but not presently used] """ Return args and kws suitable for __init__. [Overrides Jig._um_initargs; see its docstring.] """ return (self.assy, self.atoms, True), {} def setAtoms(self, atomlist): """ Override the version from Jig. Removed adding jig to atoms """ if self.atoms: print "fyi: bug? setAtoms overwrites existing atoms on %r" % self self.atoms = list(atomlist) def __init_quat_center(self, list): for a in list:#[:3]: self.atomPos += [a.posn()] planeNorm = self._getPlaneOrientation(self.atomPos) self.quat = Q(V(0.0, 0.0, 1.0), planeNorm) self.center = add.reduce(self.atomPos)/len(self.atomPos) def __computeBBox(self): """ Compute current bounding box. """ hw = self.width/2.0; hh = self.height/2.0 corners_pos = [V(-hw, hh, 0.0), V(-hw, -hh, 0.0), V(hw, -hh, 0.0), V(hw, hh, 0.0)] abs_pos = [] for pos in corners_pos: abs_pos += [self.quat.rot(pos) + self.center] return BBox(abs_pos) def __getattr__(self, name): # in class RectGadget if name == 'bbox': return self.__computeBBox() elif name == 'planeNorm': return self.quat.rot(V(0.0, 0.0, 1.0)) elif name == 'right': return self.quat.rot(V(1.0, 0.0, 0.0)) elif name == 'up': return self.quat.rot(V(0.0, 1.0, 0.0)) else: raise AttributeError, 'RectGadget has no "%s"' % name #bruce 060209 revised text def getaxis(self): # todo: merge somehow with getaxis methods on other Nodes return self.planeNorm # axis is normal to plane of RectGadget. Mark 060120 def move(self, offset): """ Move the plane by <offset>, which is a 'V' object. """ ###k NEEDS REVIEW: does this conform to the new Node API method 'move', # or should it do more invalidations / change notifications / updates? # [bruce 070501 question] self.center += offset def rot(self, q): self.quat += q def needs_atoms_to_survive(self): # [Huaicai 9/30/05] """ Overrided method inherited from Jig. This is used to tell if the jig can be copied even if it doesn't have atoms. """ return False def _getPlaneOrientation(self, atomPos): assert len(atomPos) >= 3 v1 = atomPos[-2] - atomPos[-1] v2 = atomPos[-3] - atomPos[-1] return cross(v1, v2) def _mmp_record_last_part(self, mapping): return "" ## def is_disabled(self): ## """ ## """ ## return False ###[Huaicai 9/29/05: The following two methods are temporarily copied here, this is try to fix jig copy related bugs ### not fully analyzed how the copy works yet. It fixed some problems, but not sure if it's completely right. def copy_full_in_mapping(self, mapping): #bruce 070430 revised to honor mapping.assy clas = self.__class__ new = clas(mapping.assy, [], True) # don't pass any atoms yet (maybe not all of them are yet copied) # [Note: as of about 050526, passing atomlist of [] is permitted for motors, but they assert it's []. # Before that, they didn't even accept the arg.] # Now, how to copy all the desired state? We could wait til fixup stage, then use mmp write/read methods! # But I'd rather do this cleanly and have the mmp methods use these, instead... # by declaring copyable attrs, or so. new._orig = self new._mapping = mapping new.name = "[being copied]" # should never be seen mapping.do_at_end( new._copy_fixup_at_end) #k any need to call mapping.record_copy?? # [bruce comment 050704: if we could easily tell here that none of our atoms would get copied, # and if self.needs_atoms_to_survive() is true, then we should return None (to fix bug 743) here; # but since we can't easily tell that, we instead kill the copy # in _copy_fixup_at_end if it has no atoms when that func is done.] return new def _copy_fixup_at_end(self): # warning [bruce 050704]: some of this code is copied in jig_Gamess.py's Gamess.cm_duplicate method. """ [Private method] This runs at the end of a copy operation to copy attributes from the old jig (which could have been done at the start but might as well be done now for most of them) and copy atom refs (which has to be done now in case some atoms were not copied when the jig itself was). Self is the copy, self._orig is the original. """ orig = self._orig del self._orig mapping = self._mapping del self._mapping copy = self orig.copy_copyable_attrs_to(copy) # replaces .name set by __init__ self.own_mutable_copyable_attrs() # eliminate unwanted sharing of mutable copyable_attrs if orig.picked: # clean up weird color attribute situation (since copy is not picked) # by modifying color attrs as if we unpicked the copy self.color = self.normcolor #nuats = [] #for atom in orig.atoms: #nuat = mapping.mapper(atom) #if nuat is not None: #nuats.append(nuat) #if len(nuats) < len(orig.atoms) and not self.name.endswith('-frag'): # similar code is in chunk, both need improving #self.name += '-frag' #if nuats or not self.needs_atoms_to_survive(): #self.setAtoms(nuats) #else: ##bruce 050704 to fix bug 743 #self.kill() #e jig classes with atom-specific info would have to do more now... we could call a 2nd method here... # or use list of classnames to search for more and more specific methods to call... # or just let subclasses extend this method in the usual way (maybe not doing those dels above). return pass # end of class RectGadget # == GridPlane class GridPlane(RectGadget): """ """ #bruce 060212 include superclass mutables (might fix some bugs); see analogous ESPImage comments for more info own_mutable_attrs = ('grid_color', ) mutable_attrs = own_mutable_attrs + RectGadget.mutable_attrs copyable_attrs = RectGadget.copyable_attrs + ('line_type', 'grid_type', 'x_spacing', 'y_spacing') + own_mutable_attrs sym = "GridPlane" #bruce 070604 removed space (per Mark decision) icon_names = ["modeltree/Grid_Plane.png", "modeltree/Grid_Plane-hide.png"] # Added gridplane icons. Mark 050915. mmp_record_name = "gridplane" featurename = "Grid Plane" #bruce 051203 def __init__(self, assy, list, READ_FROM_MMP = False): RectGadget.__init__(self, assy, list, READ_FROM_MMP) self.color = black # Border color self.normcolor = black self.grid_color = gray self.grid_type = SQUARE_GRID # Grid patterns: "SQUARE_GRID" or "SiC_GRID" # Grid line types: "NO_LINE", "SOLID_LINE", "DASHED_LINE" or "DOTTED_LINE" self.line_type = SOLID_LINE # Changed the spacing to 2 to 1. Mark 050923. self.x_spacing = 5.0 # 5 Angstroms self.y_spacing = 5.0 # 5 Angstroms def setProps(self, name, border_color, width, height, center, wxyz, grid_type, \ line_type, x_space, y_space, grid_color): self.name = name; self.color = self.normcolor = border_color; self.width = width; self.height = height; self.center = center; self.quat = Q(wxyz[0], wxyz[1], wxyz[2], wxyz[3]) self.grid_type = grid_type; self.line_type = line_type; self.x_spacing = x_space; self.y_spacing = y_space; self.grid_color = grid_color def _getinfo(self): return "[Object: Grid Plane] [Name: " + str(self.name) + "] " def getstatistics(self, stats): stats.num_gridplane += 1 def set_cntl(self): self.cntl = GridPlaneProp(self, self.assy.o) def make_selobj_cmenu_items(self, menu_spec): """ Add GridPlane specific context menu items to the <menu_spec> list when self is the selobj (i.e. the selected object under the cursor when the context menu is displayed). @param menu_spec: A list of context menu items, where each member is a tuple (menu item string, method). @type menu_spec: list @note: This only works in "Build Atoms" (depositAtoms) mode. """ item = ('Hide', self.Hide) menu_spec.append(item) menu_spec.append(None) # Separator item = ('Edit Properties...', self.edit) menu_spec.append(item) def _draw_jig(self, glpane, color, highlighted = False): """ Draw a Grid Plane jig as a set of grid lines. """ glPushMatrix() glTranslatef( self.center[0], self.center[1], self.center[2]) q = self.quat glRotatef( q.angle*180.0/math.pi, q.x, q.y, q.z) hw = self.width/2.0; hh = self.height/2.0 corners_pos = [V(-hw, hh, 0.0), V(-hw, -hh, 0.0), V(hw, -hh, 0.0), V(hw, hh, 0.0)] if highlighted: grid_color = color else: grid_color = self.grid_color if self.picked: drawLineLoop(self.color, corners_pos) else: drawLineLoop(color, corners_pos) if self.grid_type == SQUARE_GRID: drawGPGrid(glpane, grid_color, self.line_type, self.width, self.height, self.x_spacing, self.y_spacing, q.unrot(self.assy.o.up), q.unrot(self.assy.o.right)) else: drawSiCGrid(grid_color, self.line_type, self.width, self.height, q.unrot(self.assy.o.up), q.unrot(self.assy.o.right)) glPopMatrix() def mmp_record_jigspecific_midpart(self): """ format: width height (cx, cy, cz) (w, x, y, z) grid_type line_type x_space y_space (gr, gg, gb) """ color = map(int, A(self.grid_color)*255) dataline = "%.2f %.2f (%f, %f, %f) (%f, %f, %f, %f) %d %d %.2f %.2f (%d, %d, %d)" % \ (self.width, self.height, self.center[0], self.center[1], self.center[2], self.quat.w, self.quat.x, self.quat.y, self.quat.z, self.grid_type, self.line_type, self.x_spacing, self.y_spacing, color[0], color[1], color[2]) return " " + dataline def writepov(self, file, dispdef): if self.hidden: return if self.is_disabled(): return #bruce 050421 hw = self.width/2.0; hh = self.height/2.0 corners_pos = [V(-hw, hh, 0.0), V(-hw, -hh, 0.0), V(hw, -hh, 0.0), V(hw, hh, 0.0)] povPlaneCorners = [] for v in corners_pos: povPlaneCorners += [self.quat.rot(v) + self.center] strPts = ' %s, %s, %s, %s ' % tuple(map(povpoint, povPlaneCorners)) color = '%s>' % (povStrVec(self.color),) file.write('grid_plane(' + strPts + color + ') \n') pass # end of class GridPlane # == def povStrVec(va): # review: refile in povheader or so? [bruce 071215 comment] # used in other modules too rstr = '<' for ii in range(size(va)): rstr += str(va[ii]) + ', ' return rstr #end
NanoCAD-master
cad/src/model/jigs_planes.py
# Copyright 2008-2009 Nanorex, Inc. See LICENSE file for details. """ ExternalBondSet.py - keep track of external bonds, to optimize redraw @author: Bruce @version: $Id$ @copyright: 2008-2009 Nanorex, Inc. See LICENSE file for details. History: bruce 080702 created bruce 090211 making compatible with TransformNode, though that is unfinished and not yet actually used. (Update: as of 090225 TransformNode is abandoned. However, I'm leaving some comments that refer to TransformNode in place (in still-active files), since they also help point out the code which any other attempt to optimize rigid drags would need to modify. In those comments, dt and st refer to dynamic transform and static transform, as used in scratch/TransformNode.py.) """ # plan: # # initial test implem: do all bond drawing through this object, # but do it just as often as right now, in the same way. # # see chunk._draw_external_bonds # for now, we just maintain them but do nothing else with them, # as of 080702 noon PT. update 080707: a debug_pref draws with them, # false by default since predicted to be a slowdown for now. # Retesting this 090126, it seems to work. Put drawing code into # ExternalBondSetDrawer, but not yet doing any caching there (CSDLs). # When we do, not yet known how much inval/update code goes there vs. here. from geometry.VQT import V, vlen from graphics.model_drawing.ExternalBondSetDrawer import ExternalBondSetDrawer # todo: this import shouldn't be needed once we have the right # GraphicsRule architecture _DEBUG_EBSET = False # ok to commit with True, until the debug_pref # that calls us is on by default class ExternalBondSet(object): """ Know about all external bonds between two specific chunks, and cache info to speed their redrawing, including display lists. When the appearance or set of bonds change, we might be invalidated, or destroyed and remade, depending on client code. """ def __init__(self, chunk1, chunk2): self.chunks = (chunk1, chunk2) # note: not private # note: our chunks are also called "our nodes", # since some of this code would work for them being any TransformNodes # WARNING: KLUGE: self.chunks might be reordered inside self.draw. # The order has no effect on anything except drawing, # and need not remain constant or relate to atom order in our bonds. # maybe todo: rename: _f_bonds self._bonds = {} self._drawer = ExternalBondSetDrawer(self) # review: make on demand? GL context not current now... # hopefully ok, since it will only make DL on demand during .draw. return def __repr__(self): res = "<%s at %#x with %d bonds for %r>" % \ (self.__class__.__name__.split('.')[-1], id(self), len(self._bonds), self.chunks # this is () if self is destroyed ) return res def is_currently_bridging_dynamic_transforms(self): """ @return: whether not all of our nodes share the same dynamic transform object (counting None as such as object) @rtype: boolean """ dt1 = self.chunks[0].dynamic_transform for chunk in self.chunks: if chunk.dynamic_transform is not dt1: return True return False def invalidate_distortion(self): """ Called when any of our nodes' (chunks') dynamic transforms changes transform value (thus moving that node in space), if not all of our nodes share the same dynamic transform object, or when any of our nodes gets distorted internally (i.e. some of its atoms move, other than by all of them moving rigidly). """ self.invalidate_display_lists() return def invalidate_display_lists(self): self._drawer.invalidate_display_lists() return def invalidate_display_lists_for_style(self, style): #bruce 090217 """ @see: documentation of same method in class Chunk """ self._drawer.invalidate_display_lists_for_style(style) def other_chunk(self, chunk): """ @see: Bond.other_chunk """ c1, c2 = self.chunks if chunk is c1: return c2 elif chunk is c2: return c1 assert 0 return def add_bond(self, bond): """ Add this bond to self, if not already there. It must be a bond between our two chunks (not checked). Do appropriate invals within self. """ # removed for speed: assert self._correct_bond(bond) if not self._bonds.has_key(id(bond)): # test is to avoid needless invalidation (important optim) self.invalidate_display_lists() self._bonds[id(bond)] = bond if _DEBUG_EBSET: print "added bond %r to %r" % (bond, self) return def empty(self): # todo: rename to is_empty return not self._bonds def remove_incorrect_bonds(self): """ Some of our bonds may have been killed, or their atoms have changed, or their atom parents (chunks) have changed, so they are no longer correctly our members. Remove any such bonds, and do appropriate invals within self. """ bad = [] for bond in self._bonds.itervalues(): if not self._correct_bond(bond): bad.append(bond) if bad: self.invalidate_display_lists() for bond in bad: del self._bonds[id(bond)] if _DEBUG_EBSET: print "removed bond %r from %r" % (bond, self) return def _correct_bond(self, bond): # REVIEW: might need to speed this up. """ Is bond, which once belonged in self, still ok to have in self? If not, it's because it was killed, or its atoms are not in both of self's chunks. """ # bond must not be killed if bond.killed(): return False if bond not in bond.atom1.bonds: # This ought to be checked by bond.killed, but isn't yet! # See comment therein. # REVIEW: Hopefully it works now and bond.killed can be fixed to # check it. Conversely, if it doesn't work right, this routine # will probably have bugs of its own. # (Note: it'd be nice if that was faster, but there might be old # code that relies on looking at atoms of a killed bond, so we # can't just set the atoms to None. OTOH we don't want to waste # Undo time & space with a "killed flag" (for now).) return False # bond's atoms must (still) point to both of our chunks c1 = bond.atom1.molecule c2 = bond.atom2.molecule return (c1, c2) == self.chunks or (c2, c1) == self.chunks # REVIEW: too slow due to == ? # todo: optimize by sorting these when making bond? # (see also the kluge in draw, which can reverse them) # [bruce 090126] def destroy(self): if not self.chunks: return # permit repeated destroy if _DEBUG_EBSET: print "destroying %r" % self if self._drawer: self._drawer.destroy() # deallocate displists self._drawer = None for chunk in self.chunks: chunk._f_remove_ExternalBondSet(self) self.chunks = () self._bonds = () # make len() still work ### TODO: other deallocations, e.g. of display lists return # == # methods needed only for drawing def bounding_lozenge(self): #bruce 090306 unstubbed this # note: return this in abs coords, even after we have a # display list and permit relative motion. # todo: if this takes time to compute, cache it when # we redraw the display list, then # transform here into abs coords. chunk1, chunk2 = self.chunks c1, r1 = chunk1.bounding_sphere() c2, r2 = chunk2.bounding_sphere() return c1, c2, max(r1, r2) def bounding_sphere(self): #bruce 090306 unstubbed this; maybe never called # see comments in bounding_lozenge c1, c2, r = self.bounding_lozenge() return (c1 + c2)/2.0, r + vlen(c2 - c1)/2.0 def should_draw_as_picked(self): """ Should all the bonds in self be drawn as looking selected? @see: same named method in class Bond """ # note: same-named method in class Bond has equivalent code # (after implem revised 090227) # warning: ChunkDrawer has an optim which depends on this # method's semantics; see its selColor assignment. return self.chunks[0].picked and self.chunks[1].picked def bondcolor(self): #bruce 090227 """ Return the color in which to draw all our bonds. """ return self.chunks[0].drawing_color() # Note: this choice of bondcolor is flawed, because it depends # on which chunk is drawn first of the two that are connected. # (The reason it depends on that is because of a kluge in which # we reorder the chunks to match that order, in self.draw(). # It would be better if it depended more directly on model tree # order (the same, provided the chunks actually get drawn), # or on something else (e.g. axis vs strand chunks).) # I'm leaving this behavior in place, but revising how it works # in order to avoid color changes or DL remake when highlighting # external bonds within ChunkDrawer.draw_highlighted. # [bruce 090227] def get_dispdef(self, glpane): #bruce 090227 """ Return the display style in which to draw all our bonds. """ # [see comments in def bondcolor about choice of self.chunks[0]] # Note: if we ever decide to draw our bonds in both styles, # when our chunks disagree, we should revise this method's API # to return both disps to overdraw. (Or we might let it return # an opacity for each one, and also let users set a style like # that directly.) return self.chunks[0].get_dispdef(glpane) def draw(self, glpane, chunk, drawLevel, highlight_color = None): # todo: this method (and perhaps even our self._drawer attribute) # won't be needed once we have the right GraphicsRule architecture) if not self.chunks: # we've been destroyed (should not happen) return if chunk is not self.chunks[0] and highlight_color is None: # KLUGE; see self.bondcolor() comment for explanation. # This should happen at most once each time the model tree is # reordered (or the first time we're drawn), provided we don't # do it during ChunkDrawer.draw_highlighted (as we ensure by # testing highlight_color). Note that self (and therefore the # state of which chunk comes first) lasts as long as both chunks # remain alive. [bruce 090227] assert chunk is self.chunks[1] self.chunks = (self.chunks[1], self.chunks[0]) pass self._drawer.draw(glpane, drawLevel, highlight_color) pass # end of class ExternalBondSet # end
NanoCAD-master
cad/src/model/ExternalBondSet.py
NanoCAD-master
cad/src/history/__init__.py
# Copyright 2004-2008 Nanorex, Inc. See LICENSE file for details. """ HistoryWidget.py -- provides a Qt "megawidget" supporting our history/status area. @author: Bruce @version: $Id$ @copyright: 2004-2008 Nanorex, Inc. See LICENSE file for details. TODO: This file ought to be extensively revised or reorganized, possibly along with all code that calls it (e.g. any code that generates status messages). The history code itself (as opposed to the UI code in the megawidget) should be split into a separate module when it gets complicated. In fact, it should be split into a few cooperating objects (archive, widget, file io, storage ops), in separate files. [bruce 080104 comment] Terminology: A "megawidget" is an object, not itself a widget, which controls one or more widgets so as to act like a single more complex widget. I got the term from "Python Megawidgets" (which are implemented in Tk rather than Qt). """ import sys, os, time from PyQt4 import QtCore from PyQt4.Qt import Qt from PyQt4.Qt import QTextEdit, QTextOption from utilities import debug_flags from platform_dependent.PlatformDependent import mkdirs_in_filename from widgets.DebugMenuMixin import DebugMenuMixin import foundation.env as env from utilities.prefs_constants import historyMsgTimestamp_prefs_key from utilities.prefs_constants import historyMsgSerialNumber_prefs_key from utilities.prefs_constants import historyHeight_prefs_key from utilities.Log import graymsg, quote_html, greenmsg, redmsg, orangemsg from platform_dependent.PlatformDependent import fix_plurals class message: """ Stores one message for a history. """ #e this will get more complicated (and its existence will be justified) # once messages can be html-formatted, include links to what they're about, # etc; and it may also gain search or filter methods for the display. def __init__(self, text, timestamp_as_seconds = None, serno = None, hist = None): self.text = text # plain text for now; should not normally have \n at start or end if not timestamp_as_seconds: timestamp_as_seconds = time.time() # floating point number self.time = timestamp_as_seconds if not serno: try: serno = hist.next_serno() except: serno = -1 self.serno = serno self.hist = hist # mark added this def timestamp_text(self): #e should inherit the method from the display env if env.prefs[historyMsgTimestamp_prefs_key]: timetuple = time.localtime(self.time) # mark pulled the format string into this method return "[%s] " % (time.asctime(timetuple).split()[3]) ###stub; i hope this is hh:mm:ss else: return '' def serial_number_text(self): if env.prefs[historyMsgSerialNumber_prefs_key]: # mark pulled the format string into this method return "%d. " % (self.serno) else: return '' def widget_text_header(self): # mark revised the subrs, so this can now be "". return self.serial_number_text() + self.timestamp_text() def widget_text(self): return self.widget_text_header() + self.text def widget_html(self): ###@@@ experimental. This sort of works... ###e also escape < > and & ? not appropriate when self.text contains html, as it sometimes does! # maybe it's best in the long run to just require the source messages to escape these if they need to. # if not, we'll need some sort of hueristic to escape them except when part of well-formatted tags. return graymsg(self.widget_text_header()) + self.text #e could remove graymsg when what's inside it is "" def xml_text(self): assert 0, "nim" # same fields as widget text, but in xml, and not affected by display prefs pass # hte_super = QTextEdit # also works (sort of) with QTextBrowser [bruce 050914] # Switching to QTextBrowser also removes some misleading things from the HistoryWidget's context # menu, since a user isn't allowed to put text in it. (E.g. "Insert Unicode control character") #hte_super = QTextBrowser hte_super = QTextEdit m_super = DebugMenuMixin class History_QTextEdit(hte_super, m_super): def __init__(self, parent):#050304 hte_super.__init__(self, parent) m_super._init1(self) # provides self.debug_event() # note: as of 071010 this calls DebugMenuMixin._init1 def focusInEvent(self, event): ## print "fyi: hte focus in" # debug return hte_super.focusInEvent(self, event) def focusOutEvent(self, event): ## print "fyi: hte focus out" # debug return hte_super.focusOutEvent(self, event) def event(self, event): # this is getting called for various events, but of the ones in the QTextEdit, not for any mouse events, # but is called for KeyEvents (2 each, presumably one press res T, and one release res F). # Could this be a difference in PyQt and Qt? Or, is it because we're outside the scrollview? # I should try overriding contentsEvent instead... ###e debug = debug_flags.atom_debug and 0 if debug: try: after = event.stateAfter() except: after = "<no stateAfter>" # needed for Wheel events, at least [code copied from GLPane.py] print "fyi: hte event %r; stateAfter = %r" % (event, after) res = hte_super.event(self, event) if debug: print " (event done, res = %r)" % res #e now if it was a paintevent, try painting something else over it... or try implementing the method for catching those... #e watch out for being outside the scrollview. return res def contentsMousePressEvent(self, event):#050304 # note, bruce 090119: pylint claims this method no longer exists in QTextEdit if self.debug_event(event, 'mousePressEvent', permit_debug_menu_popup = 1): return return hte_super.contentsMousePressEvent(self, event) def repaint(self, *args): print "repaint, %r" % args # this is not being called, even though we're getting PaintEvents above. return hte_super.repaint(*args) def debug_menu_items(self): """ [overrides method from m_super (DebugMenuMixin)] """ usual = m_super.debug_menu_items(self) # list of (text, callable) pairs, None for separator ours = [ ## ("reload modules and remake widget", self._reload_and_remake), ## ("(treewidget instance created %s)" % self._init_time, lambda x:None, 'disabled'), ## ("history widget debug menu", noop, 'disabled'), ] ## ours.append(None) ours.extend(usual) #e more new ones on bottom? ## [not yet working:] ## ours.append(("last colored text", self._debug_find_last_colored_text)) return ours def _debug_find_last_colored_text(self): #bruce 050509 experiment; not yet working """ search backwards for the last item of colored text """ case_sensitive = True word_only = False forward = False lookfor = "<span style=\"color:#" # limit this to error or warning? problem: this even finds "gray" timestamps. # that is, it *should* find them, but in fact it doesn't seem to work at all -- it doesn't move the cursor. # Could it be that it's not looking in the html, only in the main text? Yes -- it finds this if it's in main text! # So I should have it look for something recognizable other than color, maybe "] error" or "] warning". ###e # first back up a bit?? self.find( lookfor, case_sensitive, word_only, forward) # modifies cursor position; could pass and return para/index(??) pass # end of class History_QTextEdit # == class HistoryWidget: # - Someday we're likely to turn this widget into a frame with buttons. # - Note that we're assuming there is only one of these per program run -- # not necessarily one per window, if we someday have more than one window. # If we decide more than one window displays the status, sharing one history, # we'll have to figure out how to do that at the time. def __init__(self, parent, header_line = None, filename = None, mkdirs = 0): """ ###doc this; optional arg header_line should be a string, generally not ending in '\n' """ if 1: #bruce 060301 (in two places) env.last_history_serno = self.last_serno self._deferred_summary_messages = {} ###### User Preference initialization ############################## # Get history related settings from prefs db. # If they are not found, set default values here. # The keys are located in constants.py # Mark 050716 # [revised by bruce 050810; comment above is now no longer up to date] #ninad 060904 modified this Still a partial implementation of NFR 843 self.history_height = env.prefs[historyHeight_prefs_key] ###### End of User Preference initialization ########################## if header_line == None: ## header_line_1 = "(running from [%s])" % os.path.dirname(os.path.abspath(sys.argv[0])) #bruce 050516 ## header_line_2 = "session history, started at: %s" % time.asctime() #stub ## header_line = header_line_1 + '<br>' + header_line_2 # <br> is now tested and works [bruce 050516] timestr = time.asctime() # do this first path = os.path.dirname(os.path.abspath(sys.argv[0])) #bruce 050516 added "running from" path to this message # (if this proves to be too long, we can shorten it or make it only come out when atom_debug is set) header_line = "session history (running from %s), started at: %s" % (path, timestr) #stub self._init_widget(parent) file_msg = self._init_file(filename, mkdirs = mkdirs) self._append(header_line) # appends to both widget and file # most output should pass through self._print_msg, not just self._append if debug_flags.atom_debug: self._debug_init() self._print_msg(file_msg) return def _init_widget(self, parent): """ [private] set up self.widget """ self.widget = History_QTextEdit(parent) # public member, private value (except that it's a Qt widget) self.widget.setFocusPolicy(QtCore.Qt.ClickFocus) ##e StrongFocus also can be tabbed to, might be better # not needed on Mac [bruce], but needed on Windows [mark], # to support copy/paste command sequences, etc # Partial implem for NFR 843. Need a method for updating the height of the widget. Mark 050729 # The minimum height of the history widget. This attr is useful # if self's widget-owner needs to compute its own minimum height. self.minimumHeight = \ self.widget.fontMetrics().lineSpacing() * \ self.history_height + 2 # Plus 2 pixels self.widget.setMinimumHeight(int(self.minimumHeight)) # Initialize the variable used in expanding / collapsing # the history widget. self._previousWidgetHeight = self.minimumHeight self.widget.setWordWrapMode(QTextOption.WordWrap) self.widget.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.widget.ensureCursorVisible() return def collapseWidget(self): """ Collapse the history widget. """ #Store the earlier history widget height (to be used in # self.expandWidget) self._previousWidgetHeight = self.widget.height() self.widget.setMaximumHeight(0) def expandWidget(self): """ Expand the history widget """ self.widget.setMaximumHeight(self._previousWidgetHeight) file = None filename = "" def _init_file(self, filename, mkdirs = 0): """ Set up optional file. Call this even if filename is None, so debug code can run. Don't output a history message naming the file -- but return one, so caller can do that later if it wants to. """ if filename: # user wants history saved; save it or print it. try: if mkdirs: # this is optional, for safety mkdirs_in_filename(filename) ff = open(filename, "a") except: print "bug warning: couldn't make history file %r; printing to sys.__stderr__ instead" % filename self.filename = "sys.__stderr__" self.file = sys.__stderr__ else: self.filename = filename self.file = ff elif debug_flags.atom_debug: # developer wants it saved, but program thinks user doesn't print "atom_debug: printing history to sys.__stderr__" self.filename = "sys.__stderr__" self.file = sys.__stderr__ else: pass # make sure print output says what's happening, one way or another if self.file: # even if it's __stderr__ self.file.write("# nanorex history file, format version 050104\n") self.file.flush() file_msg = "(saving history in file \"%s\")" % self.filename else: file_msg = "(history is not being saved in any file)" print file_msg #e remove this soon return file_msg def _debug_init(self): """ record initial info useful for debugging """ # record modtime of this module try: ff = "\"%s\"" % __file__ our_mtime = os.stat(__file__).st_mtime tt = time.asctime(time.localtime(our_mtime)) except: ff = "this module's" tt = "<exception discarded>" self._print_msg("atom_debug: %s modtime is %s" % (ff,tt)) def _append(self, something): ###e perhaps split into append_text, append_html, and append_msg """ [private method] Append some text to the widget and the optional history file. The text is not processed except to add newlines as needed. We assume the given text does not normally start or end with a newline. """ ## something = str(something) # usually something should already be a string if self.file: self.file.write(something.encode("utf_8")) self.file.write('\n') # file gets \n after each line, not before if debug_flags.atom_debug: # (we also flush in self.h_update(), whether or not debugging) self.file.flush() self.widget.append(something) # apparently prepends a newline if needed self.widget.ensureCursorVisible() #e Someday we need a checkbox or heuristic to turn off this # autoscrolling, in case user wants to read or copy something # while new status messages keep pouring in. # main print method for one message def _print_msg(self, msg): """ Format and print one message (a string, usually not starting or ending with newline). Precede it with a timestamp. Most printing should go though this method. Client code should call a higher-level method which uses this one. [Someday we might also #e: - compress redundant messages which would otherwise be too verbose. - add html or xml formatting, differently for different kinds of messages, as indicated by optional args (not yet designed). - when debugging, print info about the call stack at the time the message is printed [this is now implemented by a debug_pref, 060720].] """ ###e in debug_stack mode, walk stack and compare to stored stack and print exit of old frames and enter of (some) new ones m1 = message(msg, hist = self) msg = m1.widget_html() # widget_text() or widget_html() self._append(msg) ##e need to pass the message object, since also puts it into the file, but text might be different! ###@@@ if 0 and debug_flags.atom_debug: # this is redundant with __stderr__ in _append, so we no longer do it. print "(history:)", msg return # helpers for the message objects inside us last_serno = 0 def next_serno(self): self.last_serno += 1 if 1: #bruce 060301 (in two places) env.last_history_serno = self.last_serno return self.last_serno saved_msg = saved_options = saved_transient_id = None saved_norepeat_id = None # the main public method, typically accessed in new code as env.history.message(), # or in older code via the MainWindow object (e.g. win.history or w.history or self.history): def message(self, msg, transient_id = None, repaint = 0, norepeat_id = None, **options): """ Compatibility method -- pretend we're a statusbar and this is its "set text" call. [The following is not yet implemented as of the initial commit:] In reality, make sure the new end of the history looks basically like the given text, but use semi-heuristics to decide how to combine this text with previous "status text" so that the recorded history is not too full of redundant messages. Soon, we might add options to help tune this, or switch to separate methods. [Some of these features might be in _print_msg rather than in this method directly.] If transient_id is supplied, then for successive messages for which it's the same, put them all in the conventional statusbar, but only print the last one into the widget. (This can only be done when the next message comes. To permit this to be forced to occur by client code, a msg of None or "" is permitted and ignored. [#e also clear statusbar then?]) When transient_id is supplied, repaint = 1 tries to repaint the statusbar after modifying it. Presently this doesn't yet work, so it prints the msg instead, to be sure it's seen. This option should be used during a long computation containing no Qt event processing. (Which should ideally never be allowed to occur, but that's a separate issue.) If norepeat_id is supplied (assumed not to co-occur with transient_id), print the first message normally (out of several in a row with the same norepeat_id) but discard the others. If quote_html is True, replace the html-active chars '<', '>', '&' in msg with forms that will print as themselves. Note that this is not compatible with text returned by functions such as greenmsg; for that, you have to use quote_html(text) on appropriate portions of the message text. See also message_no_html. When quote_html is combined with transient_id, (I hope) it only affects the message printed to the history widget, not to the statusbar. If color is provided, it should be one of a fixed list of supported colors (see code for details), and it's applied after quote_html, and (I hope) only in the widget, not in the statusbar (so it should be compatible with transient_id). """ self.emit_all_deferred_summary_messages() # bruce 080130 new feature # REVIEW: should this be done here even if not msg? # The goals of doing it are to make sure it happens even for # commands that end by emitting only that message. # The side effect of printing it before transients # is probably bad rather than good. A better scheme might be # to call this as a side effect of internally ending a command # if we have any way to do that (e.g. related to the code that # automatically calls undo checkpoints then, or actually inside # the calling of some undo checkpoints). # (quote_html and color are implemented as one of the **options, not directly in this method. [bruce 060126]) # first emit a saved_up message, if necessary if self.saved_transient_id and self.saved_transient_id != transient_id: self.widget_msg( self.saved_msg, self.saved_options) self.saved_msg = self.saved_options = self.saved_transient_id = None # just an optim self.statusbar_msg("") # no longer show it in true statusbar # (this might clear someone else's message from there; no way to avoid this # that I know of; not too bad, since lots of events beyond our control do it too) # "call env.in_op() from code that runs soon after missing env.begin_op() calls" [bruce 050908] # (##fix: we do this after the saved-up message, but that's cheating, # since non-missing begin_ops need some other way to handle that, # namely, saving up a message object, which grabs some current-op info # when created rather than when printed.) env.in_op('(history message)') # note, this is also called for transient_id messages which get initially put into sbar... # is it ok if env.in_op recursively calls this method, self.message?? # I think so, at least if subcall doesn't use transient_id option. ##k [bruce 050909] # never save or emit a null msg (whether or not it came with a transient_id) if not msg: return # now handle the present msg: save (and show transiently) or emit from utilities.debug_prefs import debug_pref, Choice_boolean_False if debug_pref("print history.message() call stacks?", Choice_boolean_False): #bruce 060720 from utilities.debug import compact_stack options['compact_stack'] = compact_stack(skip_innermost_n = 1) # skips compact_stack itself, and this line that calls it if transient_id: self.statusbar_msg(msg, repaint = repaint) # (no html allowed in msg!) # (Actually we should make a message object now, so the timestamp is # made when the message was generated (not when emitted, if that's delayed), # and then show its plain text version transiently (including a text # timestamp), and save the same message object for later addition to the # widget and file. Should be straightforward, but I'll commit it separately # since it requires message objects to be created higher up, and # ideally passed lower down, than they are now. ###@@@) self.saved_msg = msg self.saved_options = options self.saved_transient_id = transient_id else: if norepeat_id and norepeat_id == self.saved_norepeat_id: return self.saved_norepeat_id = norepeat_id # whether supplied or None self.widget_msg( msg, options) return def message_no_html(self, msg, **kws): #bruce 050727; revised 060126 (should now be more correct when combined with transient_id) ## msg = quote_html(msg) ## self.message( msg, **kws) opts = dict(quote_html = True) # different default than message, but still permit explicit caller option to override opts.update(kws) return self.message( msg, **opts) def redmsg(self, msg, **kws): #bruce 080201 """ Shorthand for self.message(redmsg(msg), <options>). """ self.message(redmsg(msg), **kws) return def orangemsg(self, msg, **kws): #bruce 080201 """ Shorthand for self.message(orangemsg(msg), <options>). """ self.message(orangemsg(msg), **kws) return def greenmsg(self, msg, **kws): #bruce 080201 """ Shorthand for self.message(greenmsg(msg), <options>). """ self.message(greenmsg(msg), **kws) return def graymsg(self, msg, **kws): #bruce 080201 """ Shorthand for self.message(graymsg(msg), <options>). """ self.message(graymsg(msg), **kws) return # == def flush_saved_transients(self): """ make sure a saved-up transient message, if there is one, is put into the history now """ self.message(None) # [passing None is a private implem -- outsiders should not do this!] # == def deferred_summary_message(self, format, count = 1): #bruce 080130 """ Store a summary message to be emitted near the end of the current operation (in the current implem this is approximated as before the next history message of any kind), with '[N]' in the format string replaced with the number of calls of this method since the last time summary messages were emitted. @param format: message format string, containing optional '[N]'. @type format: string (possibly containing HTML if that is compatible with fix_plurals()). @param count: if provided, pretend we were called that many times, i.e. count up that many occurrences. Default 1. Passing 0 causes this summary message to be printed later even if the total count remains 0. @type count: nonnegative int. """ # todo: message types should be classes, and the formatting using '[N]' # and fix_plurals (done elsewhere), as well as metainfo like whether # they are errors or warnings or neither, should be done by methods # and attrs of those classes. (True for both regular and deferred messages.) assert count >= 0 # 0 is permitted, but does have an effect # other code may also assume count is an int (not e.g. a float) self._deferred_summary_messages.setdefault( format, 0) self._deferred_summary_messages[ format] += count return def emit_deferred_summary_message(self, format, even_if_none = False): """ Emit the specified deferred summary message, if any have been recorded (or even if not, if the option requests that). """ assert 0, "nim" def emit_all_deferred_summary_messages(self): """ Emit all deferred summary messages which have been stored, in the sort order of their format strings, once each with their counts appropriately inserted. Clear the set of stored messages before emitting any messages. (If more are added during this call, that's probably a bug, but this is not checked for or treated specially.) This is called internally before other messages are emitted (in the present implem of this deferred summary message scheme), and can also be called externally at any time. """ items = self._deferred_summary_messages.items() # (format, count) pairs self._deferred_summary_messages = {} items.sort() # use format string as sorting key. # TODO: use order in which messages first arrived (since last emitted). # possible todo: let message provider specify a different sorting key. for format, count in items: self._emit_one_summary_message(format, count) return def _emit_one_summary_message(self, format, count): msg = format.replace("[N]", "%s" % count) # note: not an error if format doesn't contain "[N]" # assume msg contains '(s)' -- could check this instead to avoid debug print msg = fix_plurals(msg, between = 3) # kluge: if a large between option is generally safe, # it ought to be made the default in fix_plurals # # todo: review for safety in case msg contains HTML (e.g. colors) # todo: ideally format would be a class instance which knew warning status, etc, # rather than containing html self.message( msg) return # == def statusbar_msg(self, msg_text, repaint = False): """ Show the message I{msg_text} (which must be plain text and short) in the main window's status bar. (This method is the main public way of doing that.) This only works for plain text messages, not html. If the message is too long, it might make the window become too wide, perhaps off the screen! Thus use this with care. Also, the message might be erased right away by events beyond our control. Thus this is best used only indirectly by self.message with transient_id option, and only for messages coming out almost continuously for some period, e.g. during a drag. @param msg_text: The message for the status bar. @type msg_text: string @param repaint: Forces a repaint of the status bar with the new message. This doesn't work (see comments in code). @param repaint: boolean """ win = env.mainwindow() sbar = win.statusBar() if msg_text: sbar.showMessage(msg_text) else: sbar.clearMessage() if repaint: ## this didn't work, so don't do it until I know why it didn't work: ## sbar.repaint() ## #k will this help extrude show its transient msgs upon entry? # so do this instead: print msg_text return def progress_msg(self, msg_text): # Bug 1343, wware 060310 """ Display and/or record a progress message in an appropriate place. @note: for now, the place is always a dedicated label in the statusbar, and these messages are never recorded. In the future this might be revised based on user prefs. """ win = env.mainwindow() statusBar = win.statusBar() statusBar._f_progress_msg(msg_text) #bruce 081229 refactoring def widget_msg(self, msg, options): #e improved timestamp? #e use html for color etc? [some callers put this directly in the msg, for now] _quote_html = options.pop('quote_html', False) #bruce 060126 new feature, improving on message_no_html interface ##k if _quote_html: msg = quote_html(msg) _color = options.pop('color', None) if _color: #bruce 060126 new feature; for now only permits 4 fixed color name strings; # should someday permit any color name (in any format) or object (of any kind) #e funcs = {'green':greenmsg, 'orange':orangemsg, 'red':redmsg, 'gray':graymsg} func = funcs[_color] # any colorname not in this dict is an exception (ok for now) msg = func(msg) _compact_stack = options.pop('compact_stack', "") #bruce 060720 if _compact_stack: msg += graymsg("; history.message() call stack: %s" % quote_html(_compact_stack)) # any unrecognized options are warned about below self._print_msg(msg) if options: msg2 = "fyi: bug: widget_msg got unsupported options: %r" % options print msg2 # too important to only print in the history file -- # could indicate that not enough info is being saved there self._print_msg(msg2) return def debug_print(self, fmt, *args): """ Any code that wants to print debug-only notes, properly timestamped and intermixed with other history, and included in the history file, can use this method. """ if not debug_flags.atom_debug: return msg = ("debug: " + fmt) % args self._print_msg(msg) # inval/update methods def h_update(self): # bruce 050107 renamed this from 'update' """ (should be called at the end of most user events) [no longer named update, since that conflicts with QWidget.update -- technically this doesn't matter since we are not a QWidget subclass, but even so it's good to avoid this confusion.] """ if self.file: self.file.flush() #k is this too slow, e.g. for bareMotion or keystrokes? # if so, don't call it for those, or make it check whether it's needed. #k is this often enough, in case of bugs? Maybe not, # so we also flush every msg when atom_debug (in another method). # nothing for widget is yet needed here, since changes to QTextEdit cause it to be # invalidated and later updated (repainted) by internal Qt code, # using a separate update event coming after other Qt events are processed, # but maybe something will be needed later. [bruce 041228] return def h_update_experimental_dont_call_me(self): self.widget.update() # http://doc.trolltech.com/3.3/qwidget.html#update ###@@@ try calling this from win.win_update to see if that fixes the repaint bugs after leaving extrude! ### it was not enough. guess: it is not updated because it does not have the focus... # so try an explicit repaint call. self.widget.repaint() # also not enough. what's up with it?? did it not yet get passed correct geometry info? does repaint need a rect? # ###@@@ pass # end of class HistoryWidget # end
NanoCAD-master
cad/src/history/HistoryWidget.py
NanoCAD-master
cad/src/files/__init__.py
# Copyright 2004-2009 Nanorex, Inc. See LICENSE file for details. """ files_mmp_writing.py -- overall control of writing MMP files; provides class writemmp_mapping and functions writemmpfile_assy and writemmpfile_part. @author: Josh, Bruce @version: $Id$ @copyright: 2004-2009 Nanorex, Inc. See LICENSE file for details. History: bruce 080304 split this out of files_mmp.py. bruce 080328 split mmpformat_versions.py out of this file. Note: A lot of mmp writing code is defined in other files, notably (but not only) for the classes Chunk, Atom, and Jig. For notes about mmp file format version strings, including when to change them and a list of all that have existed, see other files in this package. """ from files.mmp.mmpformat_versions import MMP_FORMAT_VERSION_TO_WRITE from files.mmp.mmpformat_versions import MMP_FORMAT_VERSION_TO_WRITE__WITH_NEW_DISPLAY_NAMES # temporary definition from files.mmp.mmpformat_versions import MMP_FORMAT_VERSION_TO_WRITE__WITH_COMPACT_BONDS_AND_NEW_DISPLAY_NAMES # temporary definition from files.mmp.mmp_dispnames import get_dispName_for_writemmp from utilities import debug_flags from utilities.debug import print_compact_traceback from utilities.constants import intRound from utilities.constants import PAM_MODELS # == class writemmp_mapping: #bruce 050322, to help with minimize selection and other things """ Provides an object for accumulating data while writing an mmp file. Specifically, the object stores options which affect what's written [any option is allowed, so specific mmp writing methods can check it w/o this class needing to know about it], accumulates an encoding of atoms as numbers, has helper methods for using that encoding, writing some parts of the file; in future this will be able to write forward refs for jigs and save the unwritten jigs they refer to until they're written at the end. """ fp = None def __init__(self, assy, **options): """ #doc; assy is used for some side effects (hopefully that can be cleaned up). """ self._memos = {} self.assy = assy self.atnums = atnums = {} atnums['NUM'] = 0 # kluge from old code, kept for now #e soon change atnums to store strings, and keep 'NUM' as separate instvar self.options = options # as of 050422, one of them is 'leave_out_sim_disabled_nodes'; # as of 051209 one is 'dict_for_stats'; # as of 080325 one is add_atomids_to_dict self.sim = options.get('sim', False) # simpler file just for the simulator? self.min = options.get('min', False) # even more simple, just for minimize? self.add_atomids_to_dict = options.get('add_atomids_to_dict', None) self.convert_to_pam = options.get('convert_to_pam') or "" # which PAM model to convert chunks to when saving, # or any false value for not converting them. # By default, do no conversion either way. # For convenient debug prints, self.convert_to_pam is always a string. assert not self.convert_to_pam or self.convert_to_pam in PAM_MODELS self.honor_save_as_pam = not not options.get('honor_save_as_pam') # Whether to let chunk.save_as_pam override self.convert_to_pam # when set (to a value in PAM_MODELS). By default, don't honor it. self.write_bonds_compactly = options.get('write_bonds_compactly') or False if self.min: self.sim = True self.for_undo = options.get('for_undo', False) if self.for_undo: # Writemmp methods should work differently in several ways when we're using self to record "undo state"; # they can also store info into the following attributes to help the corresponding reading methods. # (We might revise this to use a mapping subclass, but for now, I'm guessing the init arg support might be useful.) # (Later we're likely to split this into more than one flag, to support writing binary mmp files, # differential mmp files, and/or files containing more info such as selection.) # [bruce 060130] self.aux_list = [] self.aux_dict = {} self.forwarded_nodes_after_opengroup = {} self.forwarded_nodes_after_child = {} return def set_fp(self, fp): """ set file pointer to write to (don't forget to call write_header after this!) """ self.fp = fp return def write(self, lines): """ write one or more \n-terminates lines (passed as a single string) to our file pointer """ #e future versions might also hash these lines, to help make a movie id self.fp.write(lines) return def encode_name(self, name): #bruce 050618 to fix part of bug 474 (by supporting ')' in node names) """ encode name suitable for being terminated by ')', as it is in the current mmp format """ #e could extend to encode unicode chars as well #e could extend to encode newlines, tho we don't generally want to allow newlines in names anyway # The encoding used is %xx for xx the 2-digit hex ASCII code of the encoded character (like in URLs). # E.g. "%#x" % ord("%") => 0x25 name = name.replace('%','%25') # this has to be done first; the other chars can be in any order name = name.replace('(', '%28') # not needed except to let parens in mmp files be balanced (for the sake of text editors) name = name.replace(')', '%29') # needed return name def close(self, error = False): if error: try: self.write("\n# error while writing file; stopping here, might be incomplete\n") #e maybe should include an optional error message from the caller #e maybe should write something formal and/or incorrect so file can't be read w/o noticing this error except: print_compact_traceback("exception writing to mmp file, ignored: ") self.fp.close() self.destroy() #k ok to do this this soon? return def destroy(self): #bruce 080326; NEEDS TESTING or analysis for each use of this class that uses self._memos """ Remove all cyclic refs in self and in objects it owns, assuming self needn't continue to be used but might be destroyed again. """ memos = self._memos self._memos = {} for memo in memos.itervalues(): memo.destroy() # need exception protection? #e more? return def write_header(self): assy = self.assy # The MMP File Format is initialized here, just before we write the file. # Mark 050130 # [see also the general notes and history of the mmpformat, # in a comment or docstring near the top of this file -- bruce 050217] from utilities.GlobalPreferences import debug_pref_write_new_display_names if self.write_bonds_compactly: # soon, this will become the usual case, I hope mmpformat = MMP_FORMAT_VERSION_TO_WRITE__WITH_COMPACT_BONDS_AND_NEW_DISPLAY_NAMES elif debug_pref_write_new_display_names(): # this is what will be used by default in NE1 1.0.0, # as it turned on by default as of now, for writing to all mmp files # (whether intended for NE1 or NV1; doesn't affect files for ND1) # [bruce 080410] mmpformat = MMP_FORMAT_VERSION_TO_WRITE__WITH_NEW_DISPLAY_NAMES else: # this case is needed as long as some readers don't yet support # the new display names (an incompatible change), or if we want # to retain the ability to write files for older reading code # such as A9.1 or prior releases. mmpformat = MMP_FORMAT_VERSION_TO_WRITE if not (self.sim or self.min): #bruce 050322 comment: this side effect is questionable when # self.sim or self.min is True. #bruce 080328: don't do it then (since it's possible we might soon # write a different version of this record then). assy.mmpformat = mmpformat self.fp.write("mmpformat %s\n" % mmpformat) if self.min: self.fp.write("# mmp file written by Adjust or Minimize; can't be read before Alpha5\n") elif self.sim: self.fp.write("# mmp file written by Simulate; can't be read before Alpha5\n") if not self.min: self.fp.write("kelvin %d\n" % assy.temperature) # To be added for Beta. Mark 05-01-16 ## f.write("movie_id %d\n" % assy.movieID) return def encode_next_atom(self, atom): """ Assign the next sequential number (for use only in this writing of this mmp file) to the given atom; return the number AS A STRING and also store it herein for later use. Error if this atom was already assigned a number. """ # code moved here from old Atom.writemmp in chem.py atnums = self.atnums assert atom.key not in atnums, \ "bug: %r encoded twice in %r" % (atom, self) # new assertion, bruce 030522 # (that date looks too early to be correct -- probably it's from 050322); # assertion message added, bruce 080516 atnums['NUM'] += 1 # old kluge, to be removed num = atnums['NUM'] atnums[atom.key] = num if self.add_atomids_to_dict is not None: self.add_atomids_to_dict[atom.key] = num assert str(num) == self.encode_atom(atom) return str(num) def encode_atom(self, atom): """ Return an encoded reference to this atom (a short string, actually a printed int as of 050322, guaranteed true i.e. not "") for use only in the mmp file contents we're presently creating, or None if no encoding has yet been assigned to this atom for this file-writing event. This has no side effects -- to allocate new encodings, use encode_next_atom instead. Note: encoding is valid only for one file-writing-event, *not* for the same filename if it's written to again later (in principle, not even if the file contents are unchanged, though in practice, for other reasons, we try to make the encoding deterministic). """ if atom.key in self.atnums: return str(self.atnums[atom.key]) else: return None pass def encode_atom_written(self, atom): # bruce 080328 """ Like encode_atom, but require that atom has already been written (KeyError exception if not). """ return str(self.atnums[atom.key]) def dispname(self, display): """ (replaces disp = dispNames[self.display] in older code) """ if self.sim: disp = "-" # assume sim ignores this field else: ## disp = dispNames[display] disp = get_dispName_for_writemmp(display) #bruce 080324 revised return disp def encode_atom_coordinates( self, posn ): #bruce 080521 """ Return a sequence of three strings which encode the three coordinates of the given atom position, suitably for use in the atom record of an mmp file (in the traditional format as of 080521). These strings include no separators; not all callers will necessarily add the same separators. """ x, y, z = posn return map( self.encode_atom_coordinate, (x, y, z)) def encode_atom_coordinate( self, angstroms ): """ Encode a single atom coordinate as a string (which includes no separators) suitable for use in the atom record of an mmp file (in the traditional format as of 080521). @see: encode_atom_coordinates @see: decode_atom_coordinate in another class [nim] """ #bruce 080521 split this out of Atom.writemmp coord = angstroms * 1000 number = intRound(coord) #bruce 080521 bugfix # (before 080521 this was int(coord + 0.5) since 080327, # which is wrong for negative coords; # before 080327 it was int(coord), which may be wrong # for many coord values (full effect untested).) return str(number) # bruce 050422: support for writing forward-refs to nodes, and later writing the nodes at the right time # (to be used for jigs which occur before their atoms in the model tree ordering) # 1. methods for when the node first wishes it could be written out past_sim_part_of_file = False # set to True by external code (kluge?) def not_yet_past_where_sim_stops_reading_the_file(self): return not self.past_sim_part_of_file def node_ref_id(self, node): return id(node) def write_forwarded_node_after_nodes( self, node, after_these, force_disabled_for_sim = False ): """ Due to the mmp file format, node says it must come after the given nodes in the file, and optionally also after where the sim stops reading the file. Write it out in a nice place in the tree (for sake of old code which doesn't know it should be moved back into its original place), as soon in the file as is consistent with these conditions. In principle this might be "now", but that's an error -- that is, caller is required to only call us if it has to. (We might find a way to relax that condition, but that's harder than it sounds.) """ # It seems too hard to put it in as nice a place as the old code did, # and be sure it's also a safe place... so let's just put it after the last node in after_these, # or in some cases right after where the sim stops reading (but in a legal place re shelf group structure). from foundation.node_indices import node_position, node_at root = self.assy.root # one group containing everything in the entire file # this should be ok even if "too high" (as when writing a single part), # but probably only due to how we're called ... not sure. if force_disabled_for_sim: if self.options.get('leave_out_sim_disabled_nodes', False): return # best to never write it in this case! # assume we're writing the whole assy, so in this case, write it no sooner than just inside the shelf group. after_these = list(after_these) + [self.assy.shelf] # for a group, being after it means being after its "begin record" try: afterposns = map( lambda node1: node_position(node1, root), after_these) except: #bruce 080325 msg = "ignoring exception in map of node_position; won't write forwarded %r: " % node print_compact_traceback(msg) return after_this_pos = max(afterposns) after_this_node = node_at(root, after_this_pos) if after_this_node.is_group(): assert after_this_node is self.assy.shelf, \ "forwarding to after end of a group is not yet properly implemented: %r" % after_this_node # (not even if we now skipped to end of that group (by pushing to 'child' not 'opengroup'), # since ends aren't ordered like starts, so max was wrong in that case.) self.push_node(node, self.forwarded_nodes_after_opengroup, after_this_node) else: self.push_node(node, self.forwarded_nodes_after_child, after_this_node) return def push_node(self, node, dict1, key): list1 = dict1.setdefault(key, []) #k syntax #k whether pyobjs ok as keys list1.append(node) return # 2. methods for actually writing it out, when it finally can be def pop_forwarded_nodes_after_opengroup(self, og): return self.pop_nodes( self.forwarded_nodes_after_opengroup, og) def pop_forwarded_nodes_after_child(self, ch): return self.pop_nodes( self.forwarded_nodes_after_child, ch) def pop_nodes( self, dict1, key): list1 = dict1.pop(key, []) return list1 def write_forwarded_node_for_real(self, node): self.write_node(node) #e also write some forward anchor... not sure if before or after... probably "after child" or "after node" (or leaf if is one) assert not node.is_group() # for now; true since we're only used on jigs; desirable since "info leaf" only works in this case self.write_info_leaf( 'forwarded', self.node_ref_id(node) ) return def write_info_leaf( self, key, val): """ write an info leaf record for key and val. @warning: writes str(val) for any python type of val. """ val = str(val) assert '\n' not in val self.write( "info leaf %s = %s\n" % (key, val) ) return def write_node(self, node): node.writemmp(self) return # == def get_memo_for(self, obj): #bruce 080326 """ #doc """ try: res = self._memos[id(obj)] except KeyError: res = self._make_memo_for(obj) self._memos[id(obj)] = res return res def _make_memo_for(self, obj): #bruce 080326 # maybe: need exception protection? return obj._f_make_writemmp_mapping_memo(self) pass # end of class writemmp_mapping # == def writemmpfile_assy(assy, filename, addshelf = True, **mapping_options): """ Write everything in this assy (chunks, jigs, Groups, for both tree and shelf unless addshelf = False) into a new MMP file of the given filename. Should be called via the assy method writemmpfile. Should properly save entire file regardless of current part and without changing current part. """ #e maybe: should merge with writemmpfile_part # Note: only called by Assembly.writemmpfile as of long before 080326. # See also writemmpfile_part, called by Part.writemmpfile. ##Huaicai 1/27/05, save the last view before mmp file saving #bruce 050419 revised to save into glpane's current part assy.o.saveLastView() assy.update_parts() #bruce 050325 precaution fp = open(filename, "w") mapping = writemmp_mapping(assy, **mapping_options) ###e should pass sim or min options when used that way... mapping.set_fp(fp) try: mapping.write_header() assy.construct_viewdata().writemmp(mapping) assy.tree.writemmp(mapping) mapping.write("end1\n") mapping.past_sim_part_of_file = True if addshelf: assy.shelf.writemmp(mapping) mapping.write("end molecular machine part " + assy.name + "\n") except: mapping.close(error = True) raise else: mapping.close() return # from writemmpfile_assy # == def writemmpfile_part(part, filename, **mapping_options): """ Write an mmp file for a single Part. """ # todo: should merge with writemmpfile_assy # and/or with def writemmpfile in class sim_aspect #bruce 051209 added mapping_options # as of 050412 this didn't yet turn singlets into H; # but as of long before 051115 it does (for all calls -- so it would not be good to use for Save Selection!) part.assy.o.saveLastView() ###e should change to part.glpane? not sure... [bruce 050419 comment] # this updates assy.part namedView records, but we don't currently write them out below node = part.topnode assert part is node.part part.assy.update_parts() #bruce 050325 precaution if part is not node.part and debug_flags.atom_debug: print "atom_debug: bug?: part changed during writemmpfile_part, using new one" part = node.part assy = part.assy #e assert node is tree or shelf member? is there a method for that already? is_topnode? fp = open(filename, "w") mapping = writemmp_mapping(assy, **mapping_options) mapping.set_fp(fp) try: mapping.write_header() ###e header should differ in this case ##e header or end comment or both should say which Part we wrote node.writemmp(mapping) mapping.write("end molecular machine part " + assy.name + "\n") except: mapping.close(error = True) raise else: mapping.close() return # from writemmpfile_part # end
NanoCAD-master
cad/src/files/mmp/files_mmp_writing.py
# Copyright 2007-2008 Nanorex, Inc. See LICENSE file for details. """ files_mmp_registration.py - registration scheme for helper functions for parsing mmp record lines which start with specific recordnames. @author: Bruce @version: $Id$ @copyright: 2007-2008 Nanorex, Inc. See LICENSE file for details. History: bruce 080304 split this out of files_mmp.py, to avoid import cycles, since anything should be able to import this module, but the main reading code (which remains in files_mmp) needs to import a variety of model classes for constructing them (since not everything uses the registration scheme or should have to). """ # == class MMP_RecordParser(object): #bruce 071018 """ Public superclass for parsers for reading specific kinds of mmp records. Concrete subclasses should be registered with the global default mmp grammar using register_MMP_RecordParser('recordname', recordParser) for one or more recordnames which that parser subclass can support. Typically, each subclass knows how to parse just one kind of record, and is registered with only one recordname. Instance creation is only done by the mmp parser module, at least once per assembly (the instance will know which assembly it's for in self.assy, a per-instance constant), and perhaps as often as once per mmp file read (or conceivably even once per mmp record read -- REVIEW whether to rule that out in order to permit instances to remember things between records while one file is being read, e.g. whether they've emitted certain warnings, and similarly whether to promise they're instantiated once per file, as opposed to less often, for the same reason). Concrete subclasses need to define method read_record, which will be called with one line of text (including the final newline) whose first word is one of the record names for which that subclass was registered. ### REVIEW: will they also be called for subsequent lines in some cases? motors, atoms/bonds, info records... The public methods in this superclass can be called by the subclass to help it work; their docstrings contain essential info about how to write concrete subclasses. """ def __init__(self, readmmp_state, recordname): """ @param readmmp_state: object which tracks state of one mmp reading operation. @type readmmp_state: class _readmmp_state (implem is private to files_mmp.py). @param recordname: mmp record name for which this instance is registered. @type recordname: string (containing no whitespace) """ self.readmmp_state = readmmp_state self.recordname = recordname self.assy = readmmp_state.assy return def get_name(self, card, default): """ [see docstring of same method in class _readmmp_state] """ return self.readmmp_state.get_name(card, default) def get_decoded_name_and_rest(self, card, default = None): """ [see docstring of same method in class _readmmp_state] """ return self.readmmp_state.get_decoded_name_and_rest(card, default) def decode_name(self, name): """ [see docstring of same method in class _readmmp_state] """ return self.readmmp_state.decode_name(name) def addmember(self, model_component): """ [see docstring of same method in class _readmmp_state] """ self.readmmp_state.addmember(model_component) def set_info_object(self, kind, model_component): """ [see docstring of same method in class _readmmp_state] """ self.readmmp_state.set_info_object(kind, model_component) def read_new_jig(self, card, constructor): """ [see docstring of same method in class _readmmp_state] """ self.readmmp_state.read_new_jig(card, constructor) def read_record(self, card): msg = "subclass %r for recordname %r must implement method read_record" % \ (self.__class__, self.recordname) self.readmmp_state.bug_error(msg) pass # end of class MMP_RecordParser class _fake_MMP_RecordParser(MMP_RecordParser): """ Use this as an initial registered RecordParser for a known mmp recordname, to detect the error of the real one not being registered soon enough when that kind of mmp record is first read. """ def read_record(self, card): msg = "init code has not registered " \ "an mmp record parser for recordname %r " \ "to parse this mmp line:\n%r" % (self.recordname, card,) self.readmmp_state.bug_error(msg) pass # == class _MMP_Grammar(object): """ An mmp file grammar (for reading only), not including the hardcoded part. Presently just a set of registered mmp-recordname-specific parser classes, typically subclasses of MMP_RecordParser. Note: as of 071019 there is only one of these, a global singleton _The_MMP_Grammar, private to this module (though it could be made public if desired). But nothing in principle prevents this class from being instantiated multiple times with different record parsers in each one. """ def __init__(self): self._registered_record_parsers = {} def register_MMP_RecordParser(self, recordname, recordParser): assert issubclass(recordParser, MMP_RecordParser) ### not a valid requirement eventually, but good for catching errors # in initial uses of this system. self._registered_record_parsers[ recordname] = recordParser def get_registered_MMP_RecordParser(self, recordname): return self._registered_record_parsers.get( recordname, None) pass _The_MMP_Grammar = _MMP_Grammar() # private grammar for registering record parsers # Note: nothing prevents this _MMP_Grammar from being public, # except that for now we're just making public a static function # for registering into it, register_MMP_RecordParser, # and one for accessing it for reading, find_registered_parser_class, # so to avoid initial confusion I'm only making those # static functions public. [bruce 071019/080304] # == def register_MMP_RecordParser(recordname, recordParser): """ Public function for registering RecordParsers with specific recordnames in the default grammar for reading MMP files. RecordParsers are typically subclasses of class MMP_RecordParser, whose docstring describes the interface they must satisfy to be registered here. """ if recordname not in _RECORDNAMES_THAT_MUST_BE_REGISTERED: # probably too early for a history warning, for now print "\n*** Warning: a developer forgot to add %r "\ "to _RECORDNAMES_THAT_MUST_BE_REGISTERED" % (recordname,) assert type(recordname) is type("") _The_MMP_Grammar.register_MMP_RecordParser( recordname, recordParser) return # Now register some fake recordparsers for all documented mmp recordnames # whose parsers are not hardcoded into class _readmmp_state, # so if other code forgets to register the real ones before we first read # an mmp file containing them, we'll detect the error instead of just # ignoring those records as we intentionally ignore unrecognized records. # We do this directly on import, to be sure it's not done after the real ones # are registered, and since doing so should not cause any trouble. _RECORDNAMES_THAT_MUST_BE_REGISTERED = [ 'comment', 'gamess', 'povrayscene', 'DnaSegmentMarker', 'DnaStrandMarker', ] ### TODO: extend this list as more parsers are moved out of files_mmp.py for recordname in _RECORDNAMES_THAT_MUST_BE_REGISTERED: register_MMP_RecordParser( recordname, _fake_MMP_RecordParser) # == def find_registered_parser_class(recordname): #bruce 071019 """ Return the class registered for parsing mmp lines which start with recordname (a string), or None if no class was registered (yet) for that recordname. (Such a class is typically a subclass of MMP_RecordParser.) [note: intended to be used only by the main mmp reading code.] """ ### REVIEW: if we return None, should we warn about a subsequent # registration for the same name, since it's too late for it to help? # That would be wrong if the user added a plugin and then read another # mmp file that required it, but right if we have startup order errors # in registering standard readers vs. reading built-in mmp files. # Ideally, we'd behave differently during or after startup. # For now, we ignore this issue, except for the _fake_MMP_RecordParsers # registered for _RECORDNAMES_THAT_MUST_BE_REGISTERED above. return _The_MMP_Grammar.get_registered_MMP_RecordParser( recordname) # end
NanoCAD-master
cad/src/files/mmp/files_mmp_registration.py
# Copyright 2005-2008 Nanorex, Inc. See LICENSE file for details. """ mmpformat_versions.py -- list of all mmpformat versions ever used, and related parsing and testing code, and definitions of currently written versions. @author: Bruce @version: $Id$ @copyright: 2005-2008 Nanorex, Inc. See LICENSE file for details. History: bruce 080328 split this out of files_mmp_writing.py, which was earlier split out of files_mmp.py, which may have been called fileIO.py when this list was first started. bruce 080328 added reader code (not in this file) to warn if the mmpformat being read appears to be too new. bruce 080410 added a long string comment about the mmpformat situation for the upcoming release of NE1 1.0.0. TODO: - fix the logic bug in "info leaf", described below. """ # == # imports are lower down _RAW_LIST_OF_KNOWN_MMPFORMAT_VERSIONS = \ """ Notes by bruce 050217 about mmp file format version strings, and a list of all that have been used so far. Developers -- please maintain this list! For general notes about when and how to change the mmp format version, see a separate file, files_mmp_format_version.txt, which may be in the same directory as this source file. WARNING: THIS LONG STRING LITERAL IS PARSED TO OBTAIN THE LIST OF KNOWN VERSIONS. Any line in it which starts with "'" (a single quote) must look like the lines below which present an mmpformat version string that has been used. The testing code in this module extracts this list and makes sure each version string can be parsed by the mmp reader's code for doing that, and makes sure they are presented here in chronological order, and fit other rules described with that code. === There was no mmpformat record before 050130 (shortly before Alpha-1 was released), though the format had several versions before then, not all of which were upward-compatible. At some points, new elements were added, but this was not listed here as a new required format (though it should have been), since it was not noticed that this broke the reading of new files by old code due to exceptions for unrecognized elements. === '050130' -- the mmpformat record, using this format-version "050130", was introduced just before Alpha-1 release, at or shortly after the format was changed so that two (rather than one) NamedView (Csys) records were stored, one for Home View and one for Last View '050130 required; 050217 optional' -- introduced by bruce on 050217, when the info record was added, for info chunk hotspot. (The optional part needs incrementing whenever more kinds of info records are interpretable, at least once per "release".) '050130 required; 050421 optional' -- bruce, adding new info records, namely "info leaf hidden" and "info opengroup open"; and adding "per-part views" in the initial data group, whose names are HomeView%d and LastView%d. All these changes are backward-compatible -- old code will ignore the new records. '050130 required; 050422 optional' -- bruce, adding forward_ref, info leaf forwarded, and info leaf disabled. '050502 required' -- bruce, now writing bond2, bond3, bonda, bondg for higher-valence bonds appearing in the model (if any). (The code that actually writes these is not in this file.) Actually, "required" is conservative -- these are only "required" if higher-valence bonds are present in the model being written. Unfortunately, we don't yet have any way to say that to old code reading the file. (This would require declaring these new bond records in the file, using a "declare" record known by older reading-code, and telling it (as part of the declaration, something formal that meant) "if you see these new record types and don't understand them, then you miss some essential bond info of the kind carried by bond1 which you do understand". In other words, "error if you see bond2 (etc), don't understand it, but do understand (and care about) bond1".) '050502 required; 050505 optional' -- bruce, adding "info chunk color". '050502 required; 050511 optional' -- bruce, adding "info atom atomtype". Strictly speaking, these are required in the sense that the atoms in the file will seem to have the wrong number of bonds if these are not understood. But since the file would still be usable to old code, and no altered file would be better for old code, we call these new records optional. '050502 required; 050618 preferred' -- bruce, adding url-encoding of '(', ')', and '%' in node names (so ')' is legal in them, fixing part of bug 474). I'm calling it optional, since old code could read new files with only the harmless cosmetic issue of the users seeing the encoded node-names. I also decided that "preferred" is more understandable than "optional". Nothing yet uses that word (except the user who sees this format in the Part Properties dialog), so no harm is caused by changing it. '050502 required; 050701 preferred' -- bruce, adding gamess jig and info gamess records. '050502 required; 050706 preferred' -- bruce, increased precision of Linear Motor force & stiffness '050920 required' -- bruce, save carbomeric bonds as their own bond type bondc, not bonda as before '050920 required; 051102 preferred' -- bruce, adding "info leaf enable_in_minimize" '050920 required; 051103 preferred' -- this value existed for some time; unknown whether the prior one actually existed or not '050920 required; 060421 preferred' -- bruce, adding "info leaf dampers_enabled" '050920 required; 060522 preferred' -- bruce, adding "comment" and "info leaf commentline <encoding>" [will be in Alpha8] '050920 required; 070415 preferred' -- bruce, adding "bond_direction" record '050920 required; 080115 preferred' -- bruce, adding group classifications DnaGroup, DnaSegment, DnaStrand, Block '050920 required; 080321 preferred' -- bruce, adding info chunk display_as_pam, save_as_pam '080327 required' -- bruce, ADDED AFTER THE FACT to cover new display style names but not new "write_bonds_compactly" records '080327 required; 080412 preferred' -- bruce, to cover mark's "info opengroup nanotube-parameters" record, added today (it should be ok that 080412 > 080328, since the pair of dates are compared independently, *but* the preferred date defaults to the required date, therefore we also have to upgrade '080328 required' to '080328 required; 080412 preferred') '080327 required; 080523 preferred' -- bruce, adding "info atom +5data" for saving PAM3+5 data on Ss3 pseudoatoms '080327 required; 080529 preferred' -- bruce, adding "info atom ghost" for marking placeholder bases aka ghost bases '080328 required' -- bruce, adding new records bond_chain, directional_bond_chain, and dna_rung_bonds (all enabled for writing by the option write_bonds_compactly in the present code), and also using new display style names '080328 required; 080412 preferred' -- bruce, see comment for '080327 required; 080412 preferred' '080328 required; 080523 preferred' -- bruce, see comment for '080327 required; 080523 preferred' '080328 required; 080529 preferred' -- bruce, see comment for '080327 required; 080529 preferred' """ # == # comment about status for NE1 1.0.0, to be released soon: [bruce 080410] """ This describes the mmp format situation as it's being revised today [080410] to prepare for releasing NE1 1.0.0 in the near future. It covers two incompatible changes (write_bonds_compactly and new display style names), one being written by default, one not. (It's edited email, but ought to be rewritten from scratch to be more useful as a comment in this file.) == We will not enable the write_bonds_compactly optimized mmp format by default, for NE1 1.0.0. The risk is small, the work is small, the testing is small, but they are all nonzero, and the gain is at most a 20-30% savings in disk space (and some in runtime for file open or save, perhaps, but less than that) (never yet measured, FYI), and at this late stage (shortly before the release, 080410) that gain doesn't really justify any nonzero risk or extra work. (One of the work and/or risk items is that there are loose ends in the writing code for certain cases where strands leave one corner of a dna ladder and reenter another corner of the same ladder -- rare, but theoretically possible; easy to fix, but not yet fixed; only a writing code bug, not needing any change in format or reading code. I'd forgotten I still needed to fix those writing bugs when I was discussing this on today's call.) We should still (and I just did) enable the new display style names, which *are* worth enabling now for all mmp writing. Those have essentially zero risk, and are a confusion-reduction rather than just an optimization. These changes were both part of a single new "mmpformat version". The code before now was conservative -- if either change was enabled, it wrote the new mmpformat version, to warn reading code about both changes being potentially present. To avoid needless worry by reading code that understands new display names but not new bond records (as we are writing now), I'll add an intermediate mmpformat version "after the fact" for that, dated one day before the one that includes both changes: '080327 required'. This won't matter for NE1 reading code (since if it's new enough to care about the mmpformat version record, it can also read both revisions to the mmp format itself), but will allow other code to rely on that record to know that compact bonds are not present even though new display style names are present. == The debug_pref we have now controls write_bonds_compactly for NE1 save, only. It will remain available but off by default. In current code, there is no way to turn it on for mmp writing meant for ND1 or NV1. If time permits, we'll add 2 other debug_prefs to enable write_bonds_compactly for writing files for ND1 and for NV1, so we can easily test it for them later. (ND1 has code to read it but this is untested. NV1 doesn't read it and no work on making it read it is urgent -- unlike for its reading new display style codes, now required but trivial.) == It is worth noting here that there are two known compatibility bugs not covered by the mmpformat version record value: - New element numbers cause crashes when read by old code, or turn into the wrong element (I think) in fairly recent code. (Ideally, we'd read them as special atoms which permitted any number of bonds and could be written out again with the same "unrecognized element number".) - There is a logic bug in the "info leaf" record, or in any info kind which can apply to more mmp recordnames in newer writing code ("leaf" is the only one). Old readers will ignore the new mmp recordnames it applies to, but will recognize "info leaf" and will associate it with the wrong record (whichever prior one it can apply to which they *did* recognize and read). This bug won't matter for this release, even though it adds a DnaMarker record to the set which can use info leaf, since that record can't occur without new element numbers (for PAM DNA elements), and those cause all older released reading code to crash. But it will matter for the next subsequent release in which we add any jigs applicable to not-just-added element numbers. (It even affects this release, for a debugging-only jig which can mark any kind of atom, but that can be ignored since it's undocumented and only useful for debugging.) The solution is to close off the set of mmprecords info leaf can apply to, after this upcoming release of NE1 1.0.0, and revise that scheme somehow for any new mmp recordname that needs it, by adding a new info kind just for that mmp recordname (which can be isomorphic to info leaf). == Update, 080521: I fixed a bug in Atom.writemmp's rounding of negative atom position coordinates. I didn't modify the mmpformat version for this, since it would cause old code to warn when reading new files, even though these are *more* compatible with that reader code than older-written files are (since their atom coordinates were written by buggy code). This forgoes a chance to record in the file whether the writing bug was fixed, but there will very soon be a new preferred mmpformat version for other reasons, so it's not important. """ # == # When you revise these, also revise (if necessary) the body of # def _mmp_format_version_we_can_read() in files_mmp.py. MMP_FORMAT_VERSION_TO_WRITE = '050920 required; 080321 preferred' # this semi-formally indicates required & ideal reader versions... # for notes about when/how to revise this, see general notes referred to # at end of module docstring. MMP_FORMAT_VERSION_TO_WRITE__WITH_NEW_DISPLAY_NAMES = '080327 required; 080529 preferred' # For NE1 1.0.0 we will write new display names but not (by default) # the new bond records enabled in current code by 'write_bonds_compactly'. MMP_FORMAT_VERSION_TO_WRITE__WITH_COMPACT_BONDS_AND_NEW_DISPLAY_NAMES = '080328 required; 080529 preferred' # Soon after NE1 1.0.0, this can become the usually-written version, I hope, # and these separately named constants can go away. (Or, the oldest one # might be retained, so we can offer the ability to write mmp files for # old reading code, if there is any reason for that.) _version_being_written_by_default = MMP_FORMAT_VERSION_TO_WRITE__WITH_NEW_DISPLAY_NAMES # used locally, only for startup prints, but still it ought to be # kept in sync with reality as determined by files_mmp_writing.py # and by the default values of certain debug_prefs # == from utilities.debug import print_compact_traceback # == def _extract(raw_list): lines = raw_list.split('\n') res = [] for line in lines: if line.startswith("'"): res.append( line.split("'")[1] ) continue return res KNOWN_MMPFORMAT_VERSIONS = _extract(_RAW_LIST_OF_KNOWN_MMPFORMAT_VERSIONS) assert MMP_FORMAT_VERSION_TO_WRITE in KNOWN_MMPFORMAT_VERSIONS assert MMP_FORMAT_VERSION_TO_WRITE__WITH_NEW_DISPLAY_NAMES in KNOWN_MMPFORMAT_VERSIONS assert MMP_FORMAT_VERSION_TO_WRITE__WITH_COMPACT_BONDS_AND_NEW_DISPLAY_NAMES in KNOWN_MMPFORMAT_VERSIONS if _version_being_written_by_default != KNOWN_MMPFORMAT_VERSIONS[-1]: # warn, since this situation should be temporary; warning will be wrong # if these constants are not kept up to date with the actual writing code print "note: KNOWN_MMPFORMAT_VERSIONS contains more recent versions " \ "than the one we're writing by default, %r" % _version_being_written_by_default pass # == def parse_mmpformat(mmpformat): #bruce 080328 """ Parse an mmpformat value string of the syntax which can presently be used in an mmpformat mmp record, or any syntax which has been used previously. @return: a tuple of (ok, required_date, preferred_date) (containing types boolean, string (if ok), string (if ok), where the dates are raw date strings from the mmpformat record, understandable only to functions in this module, namely mmp_date_newer) @note: never raises exceptions for syntax errors, just returns ok == false """ mmpformat = mmpformat.strip() try: sections = mmpformat.split(';') assert len(sections) in (1, 2) def parse_section(section, allowed_descriptive_words): """ parse a section of the mmpformat record, such as "050502 required" or "050701 preferred", verifying the word is ok, and returning the date string. """ words = section.strip().split() if len(words) == 1: assert words[0] == '050130' # kluge, special case else: assert len(words) == 2 and words[1] in allowed_descriptive_words return words[0] required_date = parse_section(sections[0], ["required"]) if len(sections) == 1: preferred_date = required_date else: preferred_date = parse_section(sections[1], ["optional", "preferred"]) return True, required_date, preferred_date except: msg = "syntax error in mmpformat (or bug) [%s]" % (mmpformat,) print_compact_traceback(msg + ": ") return False, None, None pass def mmp_date_newer(date1, date2): #bruce 080328 """ """ date1 = _normalize_mmp_date(date1) date2 = _normalize_mmp_date(date2) return (date1 > date2) def _normalize_mmp_date(date): #bruce 080328 """ [private helper for mmp_date_newer] @note: raises exceptions for some mmp file syntax errors """ assert type(date) == type('080328') and date.isdigit() if len(date) == 6: date = '20' + date assert len(date) == 8 assert int(date) >= 20050130, "too early: %r" % (date,) assert date >= '20050130', "too early : %r" % (date,) # date of earliest mmpformat record, compared two equivalent ways return int(date) def _mmp_format_newer( (required1, preferred1), (required2, preferred2) ): return mmp_date_newer( required1, required2) or \ ( required1 == required2 and mmp_date_newer( preferred1, preferred2) ) # == def _test(): """ Make sure the parsing code can handle all the format versions, and (same thing) that newly defined format versions can be parsed. Also verify the versions occur in the right order. """ last_version = None last_version_data = None for version in KNOWN_MMPFORMAT_VERSIONS: ok, required, preferred = parse_mmpformat(version) assert ok, "parse failure or error in %r" % (version,) assert not mmp_date_newer( required, preferred), "invalid dates in %r" % (version,) if last_version: assert _mmp_format_newer( (required, preferred), last_version_data ), \ "wrong order: %r comes after %r" % \ (version, last_version) last_version = version last_version_data = (required, preferred) continue # print "fyi: all %d mmpformat versions passed the test" % len(KNOWN_MMPFORMAT_VERSIONS) return # always test, once at startup (since it takes less than 0.01 second) _test() # end
NanoCAD-master
cad/src/files/mmp/mmpformat_versions.py
NanoCAD-master
cad/src/files/mmp/__init__.py
# Copyright 2008-2009 Nanorex, Inc. See LICENSE file for details. """ mmp_dispnames.py @author: Bruce @version: $Id$ @copyright: 2008-2009 Nanorex, Inc. See LICENSE file for details. History: bruce 090116 split this out of constants.py """ from utilities.GlobalPreferences import debug_pref_write_new_display_names from utilities.GlobalPreferences import debug_pref_read_new_display_names ### TODO: refile these global variables: from utilities.constants import new_dispNames, dispNames, remap_atom_dispdefs from utilities.constants import diDEFAULT, diTUBES # our use of diTUBES under that name is a KLUGE def get_dispName_for_writemmp(display): #bruce 080324, revised 080328 """ Turn a display-style code integer (e.g. diDEFAULT; as stored in Atom.display or Chunk.display) into a display-style code string as used in the current writing format for mmp files. """ if debug_pref_write_new_display_names(): return new_dispNames[display] return dispNames[display] def interpret_dispName(dispname, defaultValue = diDEFAULT, atom = True): """ Turn a display-style code string (a short string constant used in mmp files for encoding atom and chunk display styles) into the corresponding display-style code integer (its index in dispNames, as extended at runtime). If dispname is not a valid display-style code string, return defaultValue, which is diDEFAULT by default. If atom is true (the default), only consider "atom display styles" to be valid; otherwise, also permit "chunk display styles". """ #bruce 080324 def _return(res): "(how to return res from interpret_dispName)" if res > diTUBES and atom and remap_atom_dispdefs.has_key(res): # note: the initial res > diTUBES is an optimization kluge return defaultValue return res try: res = dispNames.index(dispname) except ValueError: # not found, in first array (the one with old names, # i.e. the one which gets extended) pass else: return _return(res) if debug_pref_read_new_display_names(): try: res = new_dispNames.index(dispname) except ValueError: # not found, in 2nd array (the one with new names, # which are aliases for old ones) pass else: return _return(res) return defaultValue # from interpret_dispName # end
NanoCAD-master
cad/src/files/mmp/mmp_dispnames.py
# Copyright 2004-2009 Nanorex, Inc. See LICENSE file for details. """ files_mmp.py -- reading MMP files See also: files_mmp_writing.py, files_mmp_registration.py @author: Josh, others @version: $Id$ @copyright: 2004-2009 Nanorex, Inc. See LICENSE file for details. History: bruce 050414 pulled this out of fileIO.py, cvs rev. 1.97 (of which it was the major part), since I am splitting that into separate modules for each file format. bruce 080304 split out the mmp writing part into its own file, files_mmp_writing.py. That also contains the definition of MMP_FORMAT_VERSION_TO_WRITE and the history of its values and refers to the documentation for when to change it. [Later that stuff was moved to mmpformat_versions.py.] bruce 080304 split out the registration code, to avoid import cycles, since anything should be able to import that, but the main reading code (remaining in this file) needs to import a variety of model classes for constructing them (since not everything uses the registration scheme or should have to). """ import re, time import foundation.env as env from utilities import debug_flags from model.chem import Atom from model.jigs import AtomSet from model.jigs import Anchor from model.jigs import Stat from model.jigs import Thermo from model.jigs_motors import RotaryMotor from model.jigs_motors import LinearMotor from model.jigs_planes import GridPlane from analysis.ESP.ESPImage import ESPImage from model.jigs_measurements import MeasureAngle from model.jigs_measurements import MeasureDihedral from geometry.VQT import V, Q, A from utilities.Log import redmsg, orangemsg, quote_html from model.elements import PeriodicTable from model.elements import Pl5 from model.bonds import bond_atoms from model.chunk import Chunk from foundation.Utility import Node from foundation.Group import Group from model.NamedView import NamedView # for reading one, and for isinstance from utilities.debug import print_compact_traceback from utilities.debug import print_compact_stack from utilities.constants import gensym from utilities.constants import SUCCESS, ABORTED, READ_ERROR from model.bond_constants import find_bond from model.bond_constants import V_SINGLE from model.bond_constants import V_DOUBLE from model.bond_constants import V_TRIPLE from model.bond_constants import V_AROMATIC from model.bond_constants import V_GRAPHITE from model.bond_constants import V_CARBOMERIC from model.Plane import Plane from files.mmp.files_mmp_registration import find_registered_parser_class from files.mmp.mmpformat_versions import parse_mmpformat, mmp_date_newer from files.mmp.mmp_dispnames import interpret_dispName # the following imports and the assignment they're used in # should be replaced by some registration scheme # (not urgent) [bruce 080115] from dna.model.DnaGroup import DnaGroup from dna.model.DnaSegment import DnaSegment from dna.model.DnaStrand import DnaStrand from cnt.model.NanotubeSegment import NanotubeSegment from dna.updater.fix_after_readmmp import will_special_updates_after_readmmp_do_anything # == # KNOWN_INFO_KINDS lists the legal "kinds" of info encodable in info records. # (Note: an "info kind" is a way of finding which object the info is about; # it's not related to the data type of the encoded info.) # # This is declared here, and checked in set_info_object, # to make sure that the known info kinds are centrally listed, # so that that aspect of the mmp format remains documented in this file. # # We also include comments about who & when added a specific info kind. # (The dates might later be turned into code and used for some form of mmp file # version compatibility checking.) # # [bruce 071023] KNOWN_INFO_KINDS = ( 'chunk', #bruce 050217 'opengroup', #bruce 050421 'leaf', #bruce 050421 'atom', #bruce 050511 'gamess', #bruce 050701 'espimage', #mark 060108 'povrayscene', #mark 060613 'plane', ) # == # GROUP_CLASSIFICATIONS maps a "group classification identifier" # (a string containing no whitespace) usable in the group mmp record # (as of 080115) to a constructor function (typically a subclass of Group) # whose API is the same as that of Group (when used as a constructor). # # THIS MUST BE KEPT CONSISTENT with the class constant assignments # of _mmp_group_classifications in subclasses of Group. # # This assignment and the imports that support it ought to be replaced # by a registration scheme. Not urgent. Alternatively, we could let these # values depend on the assy being read into (a good thing to do in principle) # and ask the assy to map these names to classes). [bruce 080115/080310] _GROUP_CLASSIFICATIONS = { 'DnaGroup' : DnaGroup, 'DnaSegment' : DnaSegment, 'DnaStrand' : DnaStrand, 'Block' : Group, #bruce 080331 changed this from Block -> Group, since Block is # deprecated; it should remain in this list indefinitely so reading # old mmp files continues to work. 'NanotubeSegment' : NanotubeSegment, } # == patterns for reading mmp files #bruce 050414 comment: these pat constants are not presently used in any other files. _name_pattern = re.compile(r"\(([^)]*)\)") # this has a single pattern group which matches a parenthesized string old_csyspat = re.compile("csys \((.+)\) \((-?\d+\.\d+), (-?\d+\.\d+), (-?\d+\.\d+), (-?\d+\.\d+)\) \((-?\d+\.\d+)\)") new_csyspat = re.compile("csys \((.+)\) \((-?\d+\.\d+), (-?\d+\.\d+), (-?\d+\.\d+), (-?\d+\.\d+)\) \((-?\d+\.\d+)\) \((-?\d+\.\d+), (-?\d+\.\d+), (-?\d+\.\d+)\) \((-?\d+\.\d+)\)") namedviewpat = re.compile("namedview \((.+)\) \((-?\d+\.\d+), (-?\d+\.\d+), (-?\d+\.\d+), (-?\d+\.\d+)\) \((-?\d+\.\d+)\) \((-?\d+\.\d+), (-?\d+\.\d+), (-?\d+\.\d+)\) \((-?\d+\.\d+)\)") datumpat = re.compile("datum \((.+)\) \((\d+), (\d+), (\d+)\) (.*) \((-?\d+\.\d+), (-?\d+\.\d+), (-?\d+\.\d+)\) \((-?\d+\.\d+), (-?\d+\.\d+), (-?\d+\.\d+)\) \((-?\d+\.\d+), (-?\d+\.\d+), (-?\d+\.\d+)\)") keypat = re.compile("\S+") ## molpat = re.compile("mol \(.*\) (\S\S\S)") molpat = re.compile("mol \(.*\) (\w+)") atom1pat = re.compile("atom (\d+) \((\d+)\) \((-?\d+), (-?\d+), (-?\d+)\)") ##atom2pat = re.compile("atom \d+ \(\d+\) \(.*\) (\S\S\S)") atom2pat = re.compile("atom \d+ \(\d+\) \(.*\) (\w+)") # \w == [a-zA-Z0-9_] # Old Rotary Motor record format: # rmotor (name) (r, g, b) torque speed (cx, cy, cz) (ax, ay, az) old_rmotpat = re.compile("rmotor \((.+)\) \((\d+), (\d+), (\d+)\) (-?\d+\.\d+) (-?\d+\.\d+) \((-?\d+), (-?\d+), (-?\d+)\) \((-?\d+), (-?\d+), (-?\d+)\)") # New Rotary Motor record format: # rmotor (name) (r, g, b) torque speed (cx, cy, cz) (ax, ay, az) length radius spoke_radius new_rmotpat = re.compile("rmotor \((.+)\) \((\d+), (\d+), (\d+)\) (-?\d+\.\d+) (-?\d+\.\d+) \((-?\d+), (-?\d+), (-?\d+)\) \((-?\d+), (-?\d+), (-?\d+)\) (-?\d+\.\d+) (-?\d+\.\d+) (-?\d+\.\d+)") # Old Linear Motor record format: # lmotor (name) (r, g, b) force stiffness (cx, cy, cz) (ax, ay, az) old_lmotpat = re.compile("lmotor \((.+)\) \((\d+), (\d+), (\d+)\) (-?\d+\.\d+) (-?\d+\.\d+) \((-?\d+), (-?\d+), (-?\d+)\) \((-?\d+), (-?\d+), (-?\d+)\)") # New Linear Motor record format: # lmotor (name) (r, g, b) force stiffness (cx, cy, cz) (ax, ay, az) length width spoke_radius new_lmotpat = re.compile("lmotor \((.+)\) \((\d+), (\d+), (\d+)\) (-?\d+\.\d+) (-?\d+\.\d+) \((-?\d+), (-?\d+), (-?\d+)\) \((-?\d+), (-?\d+), (-?\d+)\) (-?\d+\.\d+) (-?\d+\.\d+) (-?\d+\.\d+)") #Grid Plane record format: #gridplane (name) (r, g, b) width height (cx, cy, cz) (w, x, y, z) grid_type line_type x_space y_space (gr, gg, gb) gridplane_pat = re.compile("gridplane \((.+)\) \((\d+), (\d+), (\d+)\) (-?\d+\.\d+) (-?\d+\.\d+) \((-?\d+\.\d+), (-?\d+\.\d+), (-?\d+\.\d+)\) \((-?\d+\.\d+), (-?\d+\.\d+), (-?\d+\.\d+), (-?\d+\.\d+)\) (\d+) (\d+) (-?\d+\.\d+) (-?\d+\.\d+) \((\d+), (\d+), (\d+)\)") #Plane record format: #plane (name) (r, g, b) width height (cx, cy, cz) (w, x, y, z) plane_pat = re.compile("plane \((.+)\) \((\d+), (\d+), (\d+)\) (-?\d+\.\d+) (-?\d+\.\d+) \((-?\d+\.\d+), (-?\d+\.\d+), (-?\d+\.\d+)\) \((-?\d+\.\d+), (-?\d+\.\d+), (-?\d+\.\d+), (-?\d+\.\d+)\)") # ESP Image record format: # espimage (name) (r, g, b) width height resolution (cx, cy, cz) (w, x, y, z) trans (fr, fg, fb) show_bbox win_offset edge_offset ## esppat = re.compile("espimage \((.+)\) \((\d+), (\d+), (\d+)\) (-?\d+\.\d+) (-?\d+\.\d+) (\d+) \((-?\d+\.\d+), (-?\d+\.\d+), (-?\d+\.\d+)\) \((-?\d+\.\d+), (-?\d+\.\d+), (-?\d+\.\d+), (-?\d+\.\d+)\) (-?\d+\.\d+) \((\d+), (\d+), (\d+)\) (\d+) (-?\d+\.\d+) (-?\d+\.\d+)") #bruce 060207 generalize pattern so espwindow is also accepted (to help fix bug 1357); safe forever, but can be removed after A7 esppat = re.compile("[a-z]* \((.+)\) \((\d+), (\d+), (\d+)\) (-?\d+\.\d+) (-?\d+\.\d+) (\d+) \((-?\d+\.\d+), (-?\d+\.\d+), (-?\d+\.\d+)\) \((-?\d+\.\d+), (-?\d+\.\d+), (-?\d+\.\d+), (-?\d+\.\d+)\) (-?\d+\.\d+) \((\d+), (\d+), (\d+)\) (\d+) (-?\d+\.\d+) (-?\d+\.\d+)") # atomset (name) (r, g, b) atom1 atom2 ... atom25 {up to 25} atomsetpat = re.compile("atomset \((.+)\) \((\d+), (\d+), (\d+)\)") # ground (name) (r, g, b) atom1 atom2 ... atom25 {up to 25} #bruce 060228 generalize pattern so "anchor" is also accepted; see also _read_anchor groundpat = re.compile("[a-z]* \((.+)\) \((\d+), (\d+), (\d+)\)") # stat (name) (r, g, b) (temp) first_atom last_atom boxed_atom statpat = re.compile("stat \((.+)\) \((\d+), (\d+), (\d+)\) \((\d+)\)" ) # thermo (name) (r, g, b) first_atom last_atom boxed_atom thermopat = re.compile("thermo \((.+)\) \((\d+), (\d+), (\d+)\)" ) # general jig pattern #bruce 050701 jigpat = re.compile("\((.+)\) \((\d+), (\d+), (\d+)\)") # more readable regexps, wware 051103 # font names NEVER have parentheses in them, ala Postscript nameRgbFontnameFontsize = ("\((.+)\) " + # (name) "\((\d+), (\d+), (\d+)\) " + # (r, g, b) "\((.+)\) " + # (font_name) "(\d+)") # font_size _oneAtompat = " (\d+)" # mdistance (name) (r, g, b) (font_name) font_size a1 a2 mdistancepat = re.compile("mdistance " + nameRgbFontnameFontsize + _oneAtompat + _oneAtompat) # mangle (name) (r, g, b) (font_name) font_size a1 a2 a3 manglepat = re.compile("mangle " + nameRgbFontnameFontsize + _oneAtompat + _oneAtompat + _oneAtompat) # mdihedral (name) (r, g, b) (font_name) font_size a1 a2 a3 a4 mdihedralpat = re.compile("mdihedral " + nameRgbFontnameFontsize + _oneAtompat + _oneAtompat + _oneAtompat + _oneAtompat) # == reading mmp files _MMP_FORMAT_VERSION_WE_CAN_READ__MOST_CONSERVATIVE = '050920 required; 080321 preferred' # ideally, this should be identical to MMP_FORMAT_VERSION_TO_WRITE, # and should just be called _MMP_FORMAT_VERSION_WE_CAN_READ, # but sometimes it can temporarily differ (in either direction), # so we don't use the same constant. # # Note: this value is based on all the code that contributes to mmp reading, # not only the code in this file. That includes methods on model objects # for parsing info records, and registered mmp record parsers. # [bruce 080328 new feature and comment] def _mmp_format_version_we_can_read(): # bruce 080328, revised 080410 (should it be a method?) from utilities.GlobalPreferences import debug_pref_read_bonds_compactly from utilities.GlobalPreferences import debug_pref_read_new_display_names if debug_pref_read_bonds_compactly() and debug_pref_read_new_display_names(): # this is the default, as of 080328, still true 080410 and for upcoming # release of NE1 1.0.0; revised to a newer one, 080523, 080529 res = '080328 required; 080529 preferred' # i.e. MMP_FORMAT_VERSION_TO_WRITE__WITH_COMPACT_BONDS_AND_NEW_DISPLAY_NAMES elif debug_pref_read_new_display_names(): # this is the default which we *write*, as of 080410 and for upcoming # release of NE1 1.0.0; revised to a newer one, 080523, 080529 # note: setting prefs to only read this high is only useful for testing res = '080327 required; 080529 preferred' # i.e. MMP_FORMAT_VERSION_TO_WRITE__WITH_NEW_DISPLAY_NAMES else: # setting prefs to only read this high is only useful for testing res = _MMP_FORMAT_VERSION_WE_CAN_READ__MOST_CONSERVATIVE return res # == def decode_atom_coordinate(coord_string): #bruce 080521 """ Decode an atom coordinate string as used in the atom record of an mmp file (in the traditional format as of 080521). Return a float, in Angstroms. """ # note: this is inlined in decode_atom_coordinates return float(coord_string) / 1000.0 # in Angstroms def decode_atom_coordinates(xs, ys, zs): #bruce 080521 """ Decode three atom coordinate strings as used in the atom record of an mmp file (in the traditional format as of 080521). Interpret them as x, y, z coordinates respectively. Return a Numeric array of three floats, in Angstroms (which is the NE1 internal standard for representing a model space position). """ # this would be correct (untested): ## return A(map( decode_atom_coordinate, [xs, ys, zs])) # but it's better to optimize by inlining decode_atom_coordinate: return V(float(xs), float(ys), float(zs)) / 1000.0 # == class _readmmp_state: """ Hold the state needed by _readmmp between lines; and provide some methods to help with reading the lines. [See also the classes mmp_interp (another read-helper) and writemmp_mapping.] """ #bruce 050405 made this class from most of _readmmp to help generalize it # (e.g. for reading sim input files for minimize selection) # initial values of instance variables # TODO: some or all of these are private -- rename them to indicate that [bruce 071023 comment] prevatom = None # the last atom read, if any prevcard = None # used in reading atoms and bonds [TODO: doc, make private] prevchunk = None # the current Chunk being built, if any [renamed from self.mol, bruce 071023] prevmotor = None # the last motor jig read, if any (used by shaft record) def __init__(self, assy, isInsert): self.assy = assy #bruce 060117 comment: self.assy is only used to pass to Node constructors (including _MarkerNode), # and to set assy.temperature and assy.mmpformat (only done if not isInsert, which looks like only use of isInsert here). self.isInsert = isInsert #bruce 050405 made the following from old _readmmp localvars, and revised their comments self.ndix = {} topgroup = Group("__opengroup__", assy, None) #bruce 050405 topgroup holds toplevel groups (or other items) as members; replaces old code's grouplist self.groupstack = [topgroup] #bruce 050405 revised this -- no longer stores names separately, and current group is now at end # stack (top at end) to store all unclosed groups # (the only group which can accept children, as we read the file, is always self.groupstack[-1]; # in the old code this was called opengroup [bruce 050405]) self.sim_input_badnesses_so_far = {} # helps warn about sim-input files self.markers = {} #bruce 050422 for forward_ref records self._info_objects = {} #bruce 071017 for info records # (replacing attributes of self named by the specific kinds) self._registered_parser_objects = {} #bruce 071017 self.listOfAtomsInFileOrder = [] return def destroy(self): self.assy = self.ndix = self.groupstack = self.markers = None self.prevatom = None self.prevcard = None self.prevchunk = None self.prevmotor = None self.sim_input_badnesses_so_far = None self._info_objects = None self._registered_parser_objects = None self.listOfAtomsInFileOrder = None return def extract_toplevel_items(self): """ for use only when done: extract the list of toplevel items (removing them from our artificial Group if any); but don't verify they are Groups or alter them, that's up to the caller. """ for marker in self.markers.values(): marker.kill() #bruce 050422; semi-guess self.markers = None if len(self.groupstack) > 1: self.warning("mmp file had %d unclosed groups" % (len(self.groupstack) - 1)) topgroup = self.groupstack[0] self.groupstack = "error if you keep reading after this" res = topgroup.members[:] for m in res: topgroup.delmember(m) return res def warning(self, msg): msg = quote_html(msg) env.history.message( redmsg( "Warning: " + msg)) def format_error(self, msg): ###e use this more widely? msg = quote_html(msg) env.history.message( redmsg( "Warning: mmp format error: " + msg)) ###e and say what we'll do? review calls; syntax error def bug_error(self, msg): msg = quote_html(msg) env.history.message( redmsg( "Bug: " + msg)) def readmmp_line(self, card): """ returns None, or error msg(#k), or raises exception on bugs or maybe some syntax errors """ key_m = keypat.match(card) if not key_m: # ignore blank lines (does this also ignore some erroneous lines??) #k return recordname = key_m.group(0) # recordname should now be the mmp record type, e.g. "group" or "mol" linemethod, errmsg = self._find_linemethod(recordname) if errmsg or not linemethod: return errmsg # if linemethod itself has an exception, best to let the caller handle it # (only it knows whether the line passed to us was made up or really in the file) return linemethod(card) def _find_linemethod(self, recordname): """ [private] Look for a method for parsing one mmp file line which starts with recordname. @return: the tuple (linemethod, errmsg), where linemethod is a callable which takes one argument (the entire line ### with \n or not??) and returns None or an error message string, and errmsg is None or an error message string from the process of looking for the linemethod. """ errmsg = None # will be changed below if an error message is needed linemethod = None # will be changed below when an mmp-line parser method is found # first look for a registered parser for this recordname parser = self._find_registered_parser_object(recordname) if parser: linemethod = parser.read_record # probably this is never None, but this code supports it being None if linemethod: return linemethod, errmsg # if there was no registered record parser, look for a built-in method to do it, # as a specially-named method of self, based on the recordname # (this is safe, since the prefix means arbitrary input can't find unintended methods) methodname = "_read_" + recordname # e.g. _read_group, _read_mol, ... try: linemethod = getattr(self, methodname, None) except: # I don't know if an exception can happen (e.g. from non-identifier chars in recordname), # and if it can, whether it would always be an AttributeError. ###e TODO: print_compact_traceback until i know linemethod = None errmsg = "syntax error or bug" ###e improve message else: if linemethod is None: # unrecognized mmp recordname -- not an error, # but [bruce 050217 new debug feature] # print a debug-only warning except for a comment line # (TODO: maybe only do this the first time we see it?) if debug_flags.atom_debug and recordname != '#': print "atom_debug: fyi: unrecognized mmp record type ignored (not an error): %r" % recordname pass return linemethod, errmsg def _find_registered_parser_object(self, recordname): """ Return an instance of the registered record-parser class for this recordname (cached for reuse while reading the one mmp file self will be used for), or None if no parser was registered for this recordname. """ try: return self._registered_parser_objects[recordname] except KeyError: clas = find_registered_parser_class(recordname) # just one global registry, for now if clas: instance = clas(self, recordname) else: instance = None # cache None too -- the query might be repeated # just as much as if we had a parser for it self._registered_parser_objects[recordname] = instance return instance pass def get_name(self, card, default): """ Get the object name from an mmp record line which represents the name in the usual way (as a parenthesized string immediately after the recordname), but don't decode it (see decode_name for that). @return: name @rtype: string @see: get_decoded_name_and_rest """ # note: code also used in get_decoded_name_and_rest x = _name_pattern.search(card) if x: return x.group(1) print "warning: mmp record without a valid name field: %r" % (card,) #bruce 071019 return gensym(default) # Note: I'm not sure it's safe/good to pass an assy argument # to this gensym, and I also think this probably never happens, # so it's best to be safe and not pass one. [bruce 080407 comment] def get_decoded_name_and_rest(self, card, default = None): #bruce 080115 """ Get the object name from an mmp record line which represents the name in the usual way (as an encoded parenthesized string immediately after the recordname). Return the tuple ( decoded name, stripped rest of record), or ( default, "" ) if the record line has the wrong format. @param card: the entire mmp record @type card: string @param default: what to return for the name (or pass to gensym if a string) if the record line has the wrong format; default value is None (typically an error in later stages of the caller) @type default: anything, usually string or None @return: ( decoded name, stripped rest of record ) @rtype: tuple of (string, string) @see: get_name """ # note: copies some code from get_name x = _name_pattern.search(card) if x: # match succeeded name = self.decode_name( x.group(1) ) rest = card.split(')', 1)[1] rest = rest.strip() else: # format error print "warning: mmp record without a valid name field: %r" % (card,) #bruce 071019 if type(default) == type(""): name = gensym(default) # Note: I'm not sure it's safe/good to pass an assy argument # to this gensym, so I won't. [bruce 080407 comment] else: name = default rest = "" return ( name, rest) def decode_name(self, name): #bruce 050618 part of fixing part of bug 474 """ Invert the transformation done by the writer's encode_name method. """ name = name.replace("%28",'(') # most of these replacements can be done in any order... name = name.replace("%29",')') name = name.replace("%25",'%') # ... but this one must be done last. return name # the remaining methods are parsers for specific records (soon to be split out # and registered -- bruce 071017), mixed with helper functions for their use def _read_group(self, card): # group: begins any kind of Group """ Read the mmp record which indicates the beginning of a Group object (for Group or any of its specialized subclasses). Subsequent mmp records (including nested groups) will be read as members of this group, until a matching egroup record is read. @see: self._read_egroup """ #bruce 080115 generalized this to use or save group classifications name, rest = self.get_decoded_name_and_rest(card, "Grp") assert name is not None old_opengroup = self.groupstack[-1] constructor = Group extra_classifications = [] for classification in rest.split(): # from general to specific if classification in _GROUP_CLASSIFICATIONS: constructor = _GROUP_CLASSIFICATIONS[ classification ] # assume this will always write out a classification # sufficient to regenerate it; if that's ever not true # we should save classification into extra_classifications # here extra_classifications = [] else: extra_classifications.append( classification ) continue # use the last one we recognize; save and rewrite the extra ones new_opengroup = constructor(name, self.assy, old_opengroup) # this includes addchild of new group to old_opengroup (so don't call self.addmember) if extra_classifications: # make sure they can get written out again new_opengroup.set_extra_classifications( extra_classifications ) self.groupstack.append(new_opengroup) def _read_egroup(self, card): # egroup: ends any kind of Group """ Read the mmp record which indicates the end of a Group object (for Group or any of its specialized subclasses). @see: self._read_group """ name = self.get_name(card, "Grp") assert name is not None name = self.decode_name(name) if len(self.groupstack) == 1: return "egroup %r when no groups remain unclosed" % (name,) curgroup = self.groupstack.pop() curname = curgroup.name if name != curname: # note, unlike old code we've already popped a group; shouldn't matter [bruce 050405] return "mismatched group records: egroup %r tried to match group %r" % (name, curname) return None # success def _read_mol(self, card): # mol: start a Chunk name = self.get_name(card, "Mole") name = self.decode_name(name) mol = Chunk(self.assy, name) self.prevchunk = mol # so its atoms, etc, can find it (might not be needed if they'd search for it) [bruce 050405 comment] # now that I removed _addMolecule, this is less often reset to None, # so we'd detect more errors if they did search for it [bruce 050405] disp = molpat.match(card) if disp: mol.setDisplayStyle(interpret_dispName(disp.group(1), atom = False)) #bruce 080324 revised self.addmember(mol) #bruce 050405; removes need for _addMolecule def _read_atom(self, card): m = atom1pat.match(card) if not m: print card n = int(m.group(1)) try: element = PeriodicTable.getElement(int(m.group(2))) sym = element.symbol except: # catch unsupported element error [bruce 080115] [untested?] # todo: improve getElement so we can narrow down exception type, # or turn this into a special return value; or perhaps better, # permit creating an atom of an unknown element # (by transparently extending getElement to create one) sym = "C" errmsg = "unsupported element in this mmp line; using %s: %s" % (sym, card,) self.format_error(errmsg) ## xyz = A(map(float, [m.group(3), m.group(4), m.group(5)])) / 1000.0 xyz = decode_atom_coordinates( m.group(3), m.group(4), m.group(5) ) #bruce 080521 if self.prevchunk is None: #bruce 050405 new feature for reading new bare sim-input mmp files self.guess_sim_input('missing_group_or_chunk') self.prevchunk = Chunk(self.assy, "sim chunk") self.addmember(self.prevchunk) a = Atom(sym, xyz, self.prevchunk) # sets default atomtype for the element [behavior of that was revised by bruce 050707] self.listOfAtomsInFileOrder.append(a) a.unset_atomtype() # let it guess atomtype later from the bonds read from subsequent mmp records [bruce 050707] disp = atom2pat.match(card) if disp: a.setDisplayStyle(interpret_dispName(disp.group(1))) #bruce 080324 revised self.ndix[n] = a self.prevatom = a self.prevcard = card return def _read_bond1(self, card): return self.read_bond_record(card, V_SINGLE) def _read_bond2(self, card): return self.read_bond_record(card, V_DOUBLE) def _read_bond3(self, card): return self.read_bond_record(card, V_TRIPLE) def _read_bonda(self, card): return self.read_bond_record(card, V_AROMATIC) def _read_bondg(self, card): return self.read_bond_record(card, V_GRAPHITE) def _read_bondc(self, card): #bruce 050920 added this return self.read_bond_record(card, V_CARBOMERIC) def read_bond_record(self, card, valence): list1 = map(int, re.findall("\d+", card[5:])) # note: this assumes all bond mmp-record-names are the same length, 5 chars. try: for a in map((lambda n: self.ndix[n]), list1): bond_atoms( self.prevatom, a, valence, no_corrections = True) # bruce 050502 revised this except KeyError: print "error in MMP file: atom ", self.prevcard print card #e better error action, like some exception? def _read_bond_direction(self, card): #bruce 070415 atomcodes = card.strip().split()[1:] # note: these are strings, but self.ndix needs ints assert len(atomcodes) >= 2 atoms = map((lambda nstr: self.ndix[int(nstr)]), atomcodes) for atom1, atom2 in zip(atoms[:-1], atoms[1:]): bond = find_bond(atom1, atom2) bond.set_bond_direction_from(atom1, 1) return def _read_bond_chain(self, card): #bruce 080328 from utilities.GlobalPreferences import debug_pref_read_bonds_compactly if not debug_pref_read_bonds_compactly(): summary_format = "Error: input file contains [N] bond_chain record(s) we can't read" env.history.deferred_summary_message( redmsg(summary_format)) return fields = card.strip().split()[1:] assert len(fields) >= 2 # beginning and ending atom code # (ignore extra fields for upwards compatibility) # note: following code is similar in two methods atoms_in_range = self.atoms_in_range(fields[0], fields[1]) if len(atoms_in_range) > 1: # not sure if this test is required for correctness for atom1, atom2 in zip( atoms_in_range[:-1], atoms_in_range[1:] ): bond_atoms( atom1, atom2, V_SINGLE, no_corrections = True) pass return def _read_directional_bond_chain(self, card): #bruce 080328 from utilities.GlobalPreferences import debug_pref_read_bonds_compactly if not debug_pref_read_bonds_compactly(): summary_format = "Error: input file contains [N] directional_bond_chain record(s) we can't read" env.history.deferred_summary_message( redmsg(summary_format)) return fields = card.strip().split()[1:] assert len(fields) >= 3 # beginning and ending atom code, and bond direction # (ignore extra fields for upwards compatibility; # optional 4th field might be sequence info [nim], default 'X') # note: following code is similar in two methods atoms_in_range = self.atoms_in_range(fields[0], fields[1]) bond_dir = int(fields[2]) assert bond_dir in (1, -1) if len(atoms_in_range) > 1: # not sure if this test is required for correctness for atom1, atom2 in zip( atoms_in_range[:-1], atoms_in_range[1:] ): bond = bond_atoms( atom1, atom2, V_SINGLE, no_corrections = True) bond.set_bond_direction_from(atom1, bond_dir) pass if len(fields) >= 4: # store optional dna base sequence info # (allowed to be shorter than needed, but not longer; # X or missing letter is not stored, so it won't override # an earlier per-atom info record specifying the dnaBaseName) sequence = fields[3] assert sequence.isalpha() pointer = 0 # to next unused character within sequence for atom in atoms_in_range: if pointer >= len(sequence): break if atom.element.role == 'strand' and not atom.element is Pl5: # atom is a strand_sugar letter = sequence[pointer] pointer += 1 if letter != 'X': atom.setDnaBaseName(letter) continue if pointer < len(sequence): assert 0, "extra sequence info: only %d of %d chars were assigned from %r" % \ (pointer, len(sequence), card) pass return def _read_dna_rung_bonds(self, card): #bruce 080328 from utilities.GlobalPreferences import debug_pref_read_bonds_compactly if not debug_pref_read_bonds_compactly(): summary_format = "Error: input file contains [N] dna_rung_bonds record(s) we can't read" env.history.deferred_summary_message( redmsg(summary_format)) return fields = card.strip().split()[1:] assert len(fields) >= 4 # beginning and ending atom codes, for chunk1 and chunk2 # (ignore extra fields for upwards compatibility) atoms_in_range1 = self.atoms_in_range(fields[0], fields[1]) atoms_in_range2 = self.atoms_in_range(fields[2], fields[3]) def ok(atom): assert isinstance(atom, Atom) return atom.element.role == 'axis' or \ (atom.element.role == 'strand' and not atom.element is Pl5) atoms1 = filter(ok, atoms_in_range1) atoms2 = filter(ok, atoms_in_range2) assert len(atoms1) == len(atoms2), \ "qualifying atom counts %d and %d don't match in %r" % \ (len(atoms1), len(atoms2), card) for atom1, atom2 in zip(atoms1, atoms2): bond_atoms( atom1, atom2, V_SINGLE, no_corrections = True) return def atoms_in_range(self, start, end): #bruce 080328 """ Return all the atoms whose atomcodes in self are between start and end, inclusive. Start and end can be equal, meaning return one atom. """ start = int(start) end = int(end) assert 1 <= start <= end res = [self.ndix[code] for code in range(start, end+1)] # that will fail if any atom in that range wasn't yet read return res # == jig reading methods. # Note that there are at least three different ways various jigs handle # reading their atom list: in a separate shaft record which occurs after # their main mmp record, whose atoms are passed to jig.setShaft; # or in the same record, passed to the constructor; # or in the same record, but passed to setProps after the jig is made. # This ought to be cleaned up sometime. # See also self.read_new_jig, which is the beginning of a partial cleanup. # [bruce 080227 comment] # Read the MMP record for a Rotary Motor as either: # rmotor (name) (r, g, b) torque speed (cx, cy, cz) (ax, ay, az) length, radius, spoke_radius # rmotor (name) (r, g, b) torque speed (cx, cy, cz) (ax, ay, az) # (note: the atoms are read separately from a subsequent shaft record) def _read_rmotor(self, card): m = new_rmotpat.match(card) # Try to read card with new format if not m: m = old_rmotpat.match(card) # If that didn't work, read card with old format ngroups = len(m.groups()) # ngroups = number of fields found (12 = old, 15 = new) name = m.group(1) name = self.decode_name(name) col = map(lambda (x): int(x) / 255.0, [m.group(2), m.group(3), m.group(4)] ) torq = float(m.group(5)) sped = float(m.group(6)) cxyz = A(map(float, [m.group(7), m.group(8), m.group(9)])) / 1000.0 axyz = A(map(float, [m.group(10), m.group(11), m.group(12)])) / 1000.0 if ngroups == 15: # if we have 15 fields, we have the length, radius and spoke radius. length = float(m.group(13)) radius = float(m.group(14)) sradius = float(m.group(15)) else: # if not, set the default values for length, radius and spoke radius. length = 10.0 radius = 2.0 sradius = 0.5 motor = RotaryMotor(self.assy) props = name, col, torq, sped, cxyz, axyz, length, radius, sradius motor.setProps(props) self.addmotor(motor) def addmotor(self, motor): #bruce 050405 split this out self.addmember(motor) self.prevmotor = motor # might not be needed if we just looked for it when we need it [bruce 050405 comment] def _read_shaft(self, card): list1 = map(int, re.findall("\d+", card[6:])) list1 = map((lambda n: self.ndix[n]), list1) self.prevmotor.setShaft(list1) # Read the MMP record for a Linear Motor as: # lmotor (name) (r, g, b) force stiffness (cx, cy, cz) (ax, ay, az) length, width, spoke_radius # lmotor (name) (r, g, b) force stiffness (cx, cy, cz) (ax, ay, az) # (note: the atoms are read separately from a subsequent shaft record) def _read_lmotor(self, card): m = new_lmotpat.match(card) # Try to read card with new format if not m: m = old_lmotpat.match(card) # If that didn't work, read card with old format ngroups = len(m.groups()) # ngroups = number of fields found (12 = old, 15 = new) name = m.group(1) name = self.decode_name(name) col = map(lambda (x): int(x) / 255.0, [m.group(2), m.group(3), m.group(4)] ) force = float(m.group(5)) stiffness = float(m.group(6)) cxyz = A(map(float, [m.group(7), m.group(8), m.group(9)])) / 1000.0 axyz = A(map(float, [m.group(10), m.group(11), m.group(12)])) / 1000.0 if ngroups == 15: # if we have 15 fields, we have the length, width and spoke radius. length = float(m.group(13)) width = float(m.group(14)) sradius = float(m.group(15)) else: # if not, set the default values for length, width and spoke radius. length = 10.0 width = 2.0 sradius = 0.5 motor = LinearMotor(self.assy) props = name, col, force, stiffness, cxyz, axyz, length, width, sradius motor.setProps(props) self.addmotor(motor) def _read_gridplane(self, card): """ Read the MMP record for a Grid Plane jig as: gridplane (name) (r, g, b) width height (cx, cy, cz) (w, x, y, z) grid_type line_type x_space y_space (gr, gg, gb) """ m = gridplane_pat.match(card) name = m.group(1) name = self.decode_name(name) border_color = map(lambda (x): int(x) / 255.0, [m.group(2), m.group(3), m.group(4)]) width = float(m.group(5)); height = float(m.group(6)); center = A(map(float, [m.group(7), m.group(8), m.group(9)])) quat = A(map(float, [m.group(10), m.group(11), m.group(12), m.group(13)])) grid_type = int(m.group(14)); line_type = int(m.group(15)); x_space = float(m.group(16)); y_space = float(m.group(17)) grid_color = map(lambda (x): int(x) / 255.0, [m.group(18), m.group(19), m.group(20)]) gridPlane = GridPlane(self.assy, [], READ_FROM_MMP = True) gridPlane.setProps(name, border_color, width, height, center, quat, grid_type, \ line_type, x_space, y_space, grid_color) self.addmember(gridPlane) #Read mmp record for a Reference Plane def _read_plane(self, card): """ Read the MMP record for a Reference Plane as: plane (name) (r, g, b) width height (cx, cy, cz) (w, x, y, z) """ m = plane_pat.match(card) name = m.group(1) name = self.decode_name(name) #border_color = color of the border for front side of the reference plane. #user can't set it for now. -- ninad 20070104 border_color = map(lambda (x): int(x) / 255.0, [m.group(2), m.group(3), m.group(4)]) width = float(m.group(5)); height = float(m.group(6)); center = A(map(float, [m.group(7), m.group(8), m.group(9)])) quat = A(map(float, [m.group(10), m.group(11), m.group(12), m.group(13)])) #@@HACK: Plane.setProps() accepts a tuple that must also contain values #for the grid related attrs such as gridColor, gridLineType etc. #But as of 2008-06-25 those (new) attrs are set using self.set_info_object #(see Plane.readmmp_info_plane_setitem) because they are a part of #'info' record (which allows upward and backword compatibility for reading #mmp files of different versions.) There is a spacial (old) code # to handle those info records. To satisfy that code as well as the #Plane.setProps() API method, we do the following -- 1. We pass 'None' #for the items, in the 'props' tuple that are a part of info record #2. Note that the info record will be read afterwords in this method #3. Plane.setProps takes extra precaution to check if the passed #parameter is None (and set its attrs only when that param is not None) # -- Ninad 2008-06-25 gridColor = None gridLineType = None gridXSpacing = None gridYSpacing = None originLocation = None displayLabelStyle = None plane = Plane(self.assy.w, READ_FROM_MMP = True) props = (name, border_color, width, height, center, quat, gridColor, gridLineType, gridXSpacing, gridYSpacing, originLocation, displayLabelStyle) plane.setProps(props) self.addmember(plane) #This sets the Plane attrs such as gridColor, gridLineType etc. self.set_info_object('plane', plane) # Read the MMP record for a Atom Set as: # atomset (name) atom1 atom2 ... atom_n {no limit} def _read_atomset(self, card): m = atomsetpat.match(card) name = m.group(1) name = self.decode_name(name) col = map(lambda (x): int(x) / 255.0, [m.group(2), m.group(3), m.group(4)] ) # Read in the list of atoms card = card[card.index(")") + 1:] # skip past the color field list1 = map(int, re.findall("\d+", card[card.index(")") + 1:])) list1 = map((lambda n: self.ndix[n]), list1) atomset = AtomSet(self.assy, list1) # create atom set and set props atomset.name = name atomset.color = col self.addmember(atomset) def _read_espimage(self, card): """ Read the MMP record for an ESP Image jig as: espimage (name) (r, g, b) width height resolution (cx, cy, cz) (w, x, y, z) trans (fr, fg, fb) show_bbox win_offset edge_offset. """ m = esppat.match(card) name = m.group(1) name = self.decode_name(name) border_color = map(lambda (x): int(x) / 255.0, [m.group(2), m.group(3), m.group(4)]) width = float(m.group(5)); height = float(m.group(6)); resolution = int(m.group(7)) center = A(map(float, [m.group(8), m.group(9), m.group(10)])) quat = A(map(float, [m.group(11), m.group(12), m.group(13), m.group(14)])) trans = float(m.group(15)) fill_color = map(lambda (x): int(x) / 255.0, [m.group(16), m.group(17), m.group(18)]) show_bbox = int(m.group(19)) win_offset = float(m.group(20)); edge_offset = float(m.group(21)) espImage = ESPImage(self.assy, [], READ_FROM_MMP = True) espImage.setProps(name, border_color, width, height, resolution, center, quat, trans, fill_color, show_bbox, win_offset, edge_offset) self.addmember(espImage) # for interpreting "info espimage" records: self.set_info_object('espimage', espImage) return _read_espwindow = _read_espimage #bruce 060207 help fix bug 1357 (read older mmprecord for ESP Image, for compatibility with older bug report attachments) # (the fix also required a change to esppat) # (this can be removed after A7 is released, but for now it's convenient to have it so old bug reports remain useful) # Read the MMP record for a Ground (Anchor) as: # ground (name) (r, g, b) atom1 atom2 ... atom25 {up to 25} def _read_ground(self, card): # see also _read_anchor m = groundpat.match(card) name = m.group(1) name = self.decode_name(name) col = map(lambda (x): int(x) / 255.0, [m.group(2), m.group(3), m.group(4)] ) # Read in the list of atoms card = card[card.index(")") + 1 :] # skip past the color field list1 = map(int, re.findall("\d+", card[card.index(")") + 1 :])) list1 = map((lambda n: self.ndix[n]), list1) gr = Anchor(self.assy, list1) # create ground and set props gr.name = name gr.color = col self.addmember(gr) _read_anchor = _read_ground #bruce 060228 (part of making anchor work when reading future mmp files, before prerelease snapshots) # Read the MMP record for a MeasureDistance, wware 051103 # mdistance (name) (r, g, b) (font_name) font_size a1 a2 # no longer modeled on motor, wware 051103 def _read_mdistance(self, card): from model.jigs_measurements import MeasureDistance m = mdistancepat.match(card) # Try to read card assert len(m.groups()) == 8 name = m.group(1) name = self.decode_name(name) col = map(lambda (x): int(x) / 255.0, [m.group(2), m.group(3), m.group(4)] ) font_name = m.group(5) font_size = int(m.group(6)) atomlist = map(int, [m.group(7), m.group(8)]) lst = map(lambda n: self.ndix[n], atomlist) mdist = MeasureDistance(self.assy, [ ]) mdist.setProps(name, col, font_name, font_size, lst) self.addmember(mdist) # Read the MMP record for a MeasureAngle, wware 051103 # mangle (name) (r, g, b) (font_name) font_size a1 a2 a3 # no longer modeled on motor, wware 051103 def _read_mangle(self, card): m = manglepat.match(card) # Try to read card assert len(m.groups()) == 9 name = m.group(1) name = self.decode_name(name) col = map(lambda (x): int(x) / 255.0, [m.group(2), m.group(3), m.group(4)] ) font_name = m.group(5) font_size = int(m.group(6)) atomlist = map(int, [m.group(7), m.group(8), m.group(9)]) lst = map(lambda n: self.ndix[n], atomlist) mang = MeasureAngle(self.assy, [ ]) mang.setProps(name, col, font_name, font_size, lst) self.addmember(mang) # Read the MMP record for a MeasureDistance, wware 051103 # mdihedral (name) (r, g, b) (font_name) font_size a1 a2 a3 a4 # no longer modeled on motor, wware 051103 def _read_mdihedral(self, card): m = mdihedralpat.match(card) # Try to read card assert len(m.groups()) == 10 name = m.group(1) name = self.decode_name(name) col = map(lambda (x): int(x) / 255.0, [m.group(2), m.group(3), m.group(4)] ) font_name = m.group(5) font_size = int(m.group(6)) atomlist = map(int, [m.group(7), m.group(8), m.group(9), m.group(10)]) lst = map(lambda n: self.ndix[n], atomlist) mdih = MeasureDihedral(self.assy, [ ]) mdih.setProps(name, col, font_name, font_size, lst) self.addmember(mdih) def read_new_jig(self, card, constructor): #bruce 050701 """ Helper method to read any sort of sufficiently new jig from an mmp file and add it to self.assy using self.addmember. Args are: card - the mmp file line. constructor - function that takes assy and atomlist and makes a new jig, without putting up any dialog. """ # this method will give one place to fix things in the future (for new jig types), # like the max number of atoms per jig. recordname, rest = card.split(None, 1) del recordname card = rest m = jigpat.match(card) name = m.group(1) name = self.decode_name(name) col = map(lambda (x): int(x) / 255.0, [m.group(2), m.group(3), m.group(4)] ) # Read in the list of atoms # [max number of atoms used to be limited by max mmp-line length # of 511 bytes; I think that limit was removed long ago # but this should be verified (in cad and sim readers) # [bruce 080227 comment]] card = card[card.index(")") + 1:] # skip past the color field list1 = map(int, re.findall("\d+", card[card.index(")") + 1:])) list1 = map((lambda n: self.ndix[n]), list1) jig = constructor(self.assy, list1) # create jig and set some properties -- constructor must not put up a dialog jig.name = name jig.color = col # (other properties, if any, should be specified later in the file by some kind of "info" records) self.addmember(jig) return jig # Read the MMP record for a Thermostat as: # stat (name) (r, g, b) (temp) first_atom last_atom box_atom def _read_stat(self, card): m = statpat.match(card) name = m.group(1) name = self.decode_name(name) col = map(lambda (x): int(x) / 255.0, [m.group(2), m.group(3), m.group(4)] ) temp = m.group(5) # Read in the list of atoms card = card[card.index(")") + 1:] # skip past the color field card = card[card.index(")") + 1:] # skip past the temp field list1 = map(int, re.findall("\d+", card[card.index(")") + 1:])) # We want "list1" to contain only the 3rd item, so let's remove # first_atom (1st item) and last_atom (2nd item) in list1. # They will get regenerated in the Thermo constructor. # Mark 050129 if len(list1) > 2: del list1[0:2] # Now remove everything else from list1 except for the boxed_atom. # This would happen if we loaded an old part with more than 3 atoms listed. if len(list1) > 1: del list1[1:] msg = "a thermostat record was found (" + name + ") in the part which contained extra atoms. They will be ignored." self.warning(msg) list1 = map((lambda n: self.ndix[n]), list1) sr = Stat(self.assy, list1) # create stat and set props sr.name = name sr.color = col sr.temp = temp self.addmember(sr) # Read the MMP record for a Thermometer as: # thermo (name) (r, g, b) first_atom last_atom box_atom def _read_thermo(self, card): m = thermopat.match(card) name = m.group(1) name = self.decode_name(name) col = map(lambda (x): int(x) / 255.0, [m.group(2), m.group(3), m.group(4)] ) # Read in the list of atoms card = card[card.index(")") + 1:] # skip past the color field list1 = map(int, re.findall("\d+", card[card.index(")") + 1:])) # We want "list1" to contain only the 3rd item, so let's remove # first_atom (1st item) and last_atom (2nd item) in list1. # They will get regenerated in the Thermo constructor. # Mark 050129 if len(list1) > 2: del list1[0:2] # Now remove everything else from list1 except for the boxed_atom. # This would happen if we loaded an old part with more than 3 atoms listed. if len(list1) > 1: del list1[1:] msg = "a thermometer record was found in the part which contained extra atoms. They will be ignored." self.warning(msg) list1 = map((lambda n: self.ndix[n]), list1) sr = Thermo(self.assy, list1) # create stat and set props sr.name = name sr.color = col self.addmember(sr) def _read_namedview(self, card): """ Read the MMP record for a I{namedview} as: namedview (name) (quat.w, quat.x, quat.y, quat.z) (scale) (pov.x, pov.y, pov.z) (zoom factor) @note: Currently, "namedview" records are treated as an alias for the "csys" record. The writer NamedView.writemmp() will switch to writing "namedview" records (instead of "csys") soon. Mark 2008-02-07. """ #bruce 050418 revising this to not have side effects on assy. # Instead, caller can do that by scanning the group these are read into. # This means we can now ignore the isInsert flag and always return # these records. Finally, I'll return them all, not just the ones with # special names we recognize (the prior code only called self.addmember # if the namedview name was HomeView or LastView); caller can detect # those special names when it needs to. m = namedviewpat.match(card) name = m.group(1) name = self.decode_name(name) wxyz = A(map(float, [m.group(2), m.group(3), m.group(4), m.group(5)])) scale = float(m.group(6)) pov = A(map(float, [m.group(7), m.group(8), m.group(9)])) zoomFactor = float(m.group(10)) namedView = NamedView(self.assy, name, scale, pov, zoomFactor, wxyz) self.addmember(namedView) # regardless of name; no side effects on assy (yet) for any name, # though later code will recognize the names HomeView and LastView # and treat them specially. # (050421 extension: also some related names, for Part views) def _read_csys(self, card): # csys -- really a named view. """ Read the MMP record for a I{csys} as: csys (name) (quat.w, quat.x, quat.y, quat.z) (scale) (pov.x, pov.y, pov.z) (zoom factor) @note: Currently, "namedview" records are treated as an alias for the "csys" record. The writer NamedView.writemmp() will switch to writing "namedview" records (instead of "csys") soon. Mark 2008-02-07. """ #bruce 050418 revising this to not have side effects on assy. # Instead, caller can do that by scanning the group these are read into. # This means we can now ignore the isInsert flag and always return # these records. Finally, I'll return them all, not just the ones with # special names we recognize (the prior code only called self.addmember # if the csys name was HomeView or LastView); caller can detect those # special names when it needs to. ## if not self.isInsert: #Skip this record if inserting ###Huaicai 1/27/05, new file format with home view ### and last view information m = new_csyspat.match(card) if m: name = m.group(1) name = self.decode_name(name) wxyz = A(map(float, [m.group(2), m.group(3), m.group(4), m.group(5)] )) scale = float(m.group(6)) pov = A(map(float, [m.group(7), m.group(8), m.group(9)])) zoomFactor = float(m.group(10)) namedView = NamedView(self.assy, name, scale, pov, zoomFactor, wxyz) self.addmember(namedView) # regardless of name; no side effects on assy (yet) for any # name, though later code will recognize the names HomeView and # LastView and treat them specially # (050421 extension: also some related names, for Part views) else: m = old_csyspat.match(card) if m: name = m.group(1) name = self.decode_name(name) wxyz = A(map(float, [m.group(2), m.group(3), m.group(4), m.group(5)] )) scale = float(m.group(6)) homeView = NamedView(self.assy, "OldVersion", scale, V(0,0,0), 1.0, wxyz) #bruce 050417 comment # (about Huaicai's preexisting code, some of which I moved into this file 050418): # this name "OldVersion" is detected in fix_assy_and_glpane_views_after_readmmp # (called from MWsemantics.fileOpen, one of our callers) # and changed to "HomeView", also triggering other side effects on glpane at that time. lastView = NamedView(self.assy, "LastView", scale, V(0,0,0), 1.0, A([0.0, 1.0, 0.0, 0.0]) ) self.addmember(homeView) self.addmember(lastView) else: print "bad format in csys record, ignored:", card return def _read_datum(self, card): # datum -- Datum object -- old version deprecated by bruce 050417 pass # don't warn about an unrecognized mmp record, even when atom_debug def addmember(self, thing): #bruce 050405 split this out self.groupstack[-1].addchild(thing) def _read_waals(self, card): # waals -- van der Waals Interactions pass # code was wrong -- to be implemented later def _read_kelvin(self, card): # kelvin -- Temperature in Kelvin (simulation parameter) if not self.isInsert: # Skip this record if inserting m = re.match("kelvin (\d+)", card) n = int(m.group(1)) self.assy.temperature = n def _read_mmpformat(self, card): # mmpformat -- MMP File Format. Mark 050130 # revised by bruce 080328 m = re.match("mmpformat (.*)", card) mmpformat = m.group(1) if not self.isInsert: # Skip this side effect if inserting self.assy.mmpformat = mmpformat # warn if format might be too new, or if we can't understand # mmpformat record at all [new feature, bruce 080328] okjunk, can_read_required, can_read_preferred = parse_mmpformat( _mmp_format_version_we_can_read() ) assert okjunk msg = "" wrapper = None try: ok, required, preferred = parse_mmpformat(mmpformat) except: print_compact_traceback("exception or syntax error while parsing [%s]: " % card.strip()) msg = "Error: bug or syntax error in mmpformat record, file corrupt or too new: [%s]" % \ quote_html(card.strip()) wrapper = redmsg else: if not ok: msg = "Warning: can't parse mmpformat record, file might be too new: [%s]" % \ quote_html(card.strip()) wrapper = redmsg # intentional, not a typo: a red "Warning" elif mmp_date_newer(required, can_read_required): msg = "Warning: mmpformat requires newer reading code; essential data might be unreadable: [%s]" % \ quote_html(card.strip()) wrapper = redmsg elif mmp_date_newer(preferred, can_read_preferred): msg = "Note: mmpformat prefers newer reading code for some data: [%s]" % \ quote_html(card.strip()) wrapper = orangemsg pass if wrapper: msg = wrapper(msg) if msg: env.history.message(msg) return def _read_end1(self, card): # end1 -- End of main tree pass def _read_end(self, card): # end -- end of file pass def _read_info(self, card): #bruce 050217 new mmp record, for optional info about # various types of objects which occur earlier in the file # (what I mean by "optional" is that it's never an error for the # specified type of thing or type of info to not be recognized, # as can happen when a new file is read by older code) # Find current chunk -- how we do this depends on details of # the other mmp-record readers in this big if/elif statement, # and is likely to need changing sometime. It's self.prevchunk. # Now make dict of all current items that info record might refer to. currents = dict( chunk = self.prevchunk, opengroup = self.groupstack[-1], #bruce 050421 leaf = ([None] + self.groupstack[-1].members)[-1], #bruce 050421 atom = self.prevatom, #bruce 050511 ) currents.update( self._info_objects) #bruce 071017 interp = mmp_interp(self.ndix, self.markers) #e could optim by using the same object each time [like 'self'] readmmp_info(card, currents, interp) # has side effect on object referred to by card return def set_info_object(self, kind, model_component): #bruce 071017 if kind not in KNOWN_INFO_KINDS: # for motivation, see comment next to definition of KNOWN_INFO_KINDS # [bruce 071023] print_compact_stack( "warning: unrecognized info kind, %r: " % (kind,) ) self._info_objects[kind] = model_component return def _read_forward_ref(self, card): """ forward_ref (%s) ... """ # add a marker which can be used later to insert the target node in the right place, # and also remember the marker here in the mapping (so we can offer that service) ###doc better lp_id_rp = card.split()[1] assert lp_id_rp[0] + lp_id_rp[-1] == "()" ref_id = lp_id_rp[1:-1] marker = _MarkerNode(self.assy, ref_id) # note: we remove this if not used, so its node type might not matter much. self.addmember(marker) self.markers[ref_id] = marker def guess_sim_input(self, type): #bruce 050405 """ Caller finds (and will correct) weird structure which makes us guess this is a sim input file of the specified type; warn user if you have not already given the same warning (normally only one such warning should appear, so warn about that as well). """ # once we see how this is used, we'll revise it to be more like a "state machine" # knowing the expected behavior for the various types of files. bad_to_worse = ['no_shelf', 'one_part', 'missing_group_or_chunk'] # order is not yet used badness = bad_to_worse.index(type) if badness not in self.sim_input_badnesses_so_far: self.sim_input_badnesses_so_far[badness] = type if type == 'missing_group_or_chunk' or type == 'one_part': # (this message is a guess, since erroneous files could give rise to this too) # (#e To narrow down the cmd that wrote it, we'd need more info than type or # even file comment, from old files -- sorry; maybe we should add an mmp record for # the command that made the file! Will it be bad that file contents are nondet (eg for md5)? # Probably not, since they were until recently anyway, due to dict item arb order.) msg = "mmp file probably written by Adjust or Minimize or Simulate -- " \ "lacks original file's chunk/group structure and display modes; " \ "unreadable by pre-Alpha5 versions unless resaved." #e revise version name elif type == 'no_shelf': # (this might not happen at all for files written by Alpha5 and beyond) # comment from old code's fix_grouplist: #bruce 050217 upward-compatible reader extension (needs no mmpformat-record change): # permit missing 3rd group, so we can read mmp files written as input for the simulator # (and since there is no good reason not to!) msg = "this mmp file was written as input for the simulator, and contains no clipboard items" #e add required version else: msg = "bug in guess_sim_input: missing message for %r" % type self.warning( msg) # normally only one of these warnings will occur, so we also ought to warn if that is not what happens... if len(self.sim_input_badnesses_so_far) > 1: self.format_error("the prior warnings should not appear together for the same file") return pass # end of class _readmmp_state # helper for forward_ref class _MarkerNode(Node): def __init__(self, assy, ref_id): name = ref_id Node.__init__(self, assy, name) # will passing no assy be legal? I doubt it... so don't bother trying. return pass # helpers for _read_info method: class mmp_interp: #bruce 050217; revised docstrings 050422 """ helps translate object refs in mmp file to their objects, while reading the file [compare to class writemmp_mapping, which helps turn objs to their refs while writing the file] [but also compare to class _readmmp_state... maybe this should be the same object as that. ###k] [also has decode methods, and some external code makes one of these just to use those (which is a kluge).] """ # make these helper functions available as if they were methods, # to permit clients to avoid import cycles # which would occur if they imported them directly from this file decode_atom_coordinate = staticmethod( decode_atom_coordinate) decode_atom_coordinates = staticmethod( decode_atom_coordinates) def __init__(self, ndix, markers): self.ndix = ndix # maps atom numbers to atoms (??) self.markers = markers def atom(self, atnum): """ map atnum string to atom, while reading mmp file (raises KeyError if that atom-number isn't recognized, which is an mmp file format error) """ return self.ndix[int(atnum)] def move_forwarded_node( self, node, val): """ find marker based on val, put node after it, and then del the marker """ try: marker = self.markers.pop(val) # val is a string; should be ok since we also read it as string from forward_ref record except KeyError: assert 0, "mmp format error: no forward_ref was written for this forwarded node" ###@@@ improve errmsg marker.addsibling(node) marker.kill() def decode_int(self, val): #bruce 050701; should be used more widely """ helper method for parsing info records; returns an int or None; warns of unrecognized values only if ATOM_DEBUG is set """ try: assert val.isdigit() or (val[0] == '-' and val[1:].isdigit()) return int(val) except: # several kinds of exception are possible here, which are not errors if debug_flags.atom_debug: print "atom_debug: fyi: some info record wants an int val but got this non-int (not an error): " + repr(val) # btw, the reason it's not an error is that the mmp file format might be extended to permit it, in that info record. return None pass def decode_bool(self, val): #bruce 050701; should be used more widely """ helper method for parsing info records; returns True or False or None; warns of unrecognized values only if ATOM_DEBUG is set """ val = val.lower() if val in ['0', 'no', 'false']: return False if val in ['1', 'yes', 'true']: return True if debug_flags.atom_debug: print "atom_debug: fyi: some info record wants a boolean val but got this instead (not an error): " + repr(val) return None pass # end of class mmp_interp def mmp_interp_just_for_decode_methods(): #bruce 050704 """ Return an mmp_interp object usable only for its decode methods (kluge) """ return mmp_interp("not used", "not used") def readmmp_info( card, currents, interp ): #bruce 050217; revised 050421, 050511 """ Handle an info record 'card' being read from an mmp file; currents should be a dict from thingtypes to the current things of those types, for all thingtypes which info records can give info about (including 'chunk', 'opengroup', 'leaf', 'atom'); interp should be an mmp_interp object #doc. The side effect of this function, when given "info <type> <name> = <val>", is to tell the current thing of type <type> (that is, the last one read from this file) that its optional info <name> has value <val>, using a standard info-accepting method on that thing. <type> should be a "word"; <name> should be one or more "words" (it's supplied as a python list of strings to the info-accepting method); <val> can be (for now) any string with no newlines, and no whitespace at the ends; its permissible syntax might be further restricted later. """ #e interface will need expanding when info can be given about non-current things too what, val = card.split('=', 1) key = "info" what = what[len(key):] what = what.strip() # e.g. "chunk xxx" for info of type xxx about the current chunk val = val.strip() what = what.split() # e.g. ["chunk", "xxx"], always 2 or more words type = what[0] # as of 050511 this can be 'chunk' or 'opengroup' or 'leaf' or 'atom' name = what[1:] # list of words (typically contains exactly one word, an attribute-name) thing = currents.get(type) if thing: # can be false if type not recognized, or if current one was None # record info about the current thing of type <type> try: meth = getattr(thing, "readmmp_info_%s_setitem" % type) # should be safe regardless of the value of 'type' except AttributeError: if debug_flags.atom_debug: print "atom_debug: fyi: object %r doesn't accept \"info %s\" keys (like %r); ignoring it (not an error)" \ % (thing, type, name) else: try: meth( name, val, interp ) except: print_compact_traceback("internal error in %r interpreting %r, ignored: " % (thing, card) ) elif debug_flags.atom_debug: print "atom_debug: fyi: no object found for \"info %s\"; ignoring info record (not an error)" % (type,) return # == _readmmp_aborted = False _reference_to_readmmp_abort_function = None #bruce 080606 precaution def _readmmp(assy, filename, isInsert = False, showProgressDialog = False): """ Read an mmp file, print errors and warnings to history, modify assy in various ways (a bad design, see comment in insertmmp) (but don't actually add file contents to assy -- let caller do that if and where it prefers), and return (as part of a larger tuple described below) either None (after an error for which caller should store no file contents at all) or a list of 3 Groups, which caller should treat as having roles "viewdata", "tree", "shelf", regardless of how many toplevel items were in the file, or of whether they were groups. (We handle normal mmp files with exactly those 3 groups, old sim-input files with only the first two, and newer sim-input files for Parts (one group) or for minimize selection (maybe no groups at all). And most other weird kinds of mmp files someone might create.) @warning: the optional arguments are sometimes passed positionally. @param assy: the assembly the file contents are being added into @type assy: assembly.assembly @param filename: where the data will be read from @type filename: string @param isInsert: if True, the file contents are being added to an existing assembly, otherwise the file contents are being used to initialize a new assembly. @type isInsert: boolean @param showProgressDialog: if True, display a progress dialog while reading a file. Default is False. @type showProgressDialog: boolean @return: the tuple (ok, grouplist or None, listOfAtomsInFileOrder), where ok is one of the string constants named (in utilities.constants) SUCCESS, ABORTED, or READ_ERROR. (If ok is not SUCCESS, grouplist will be None and listOfAtomsInFileOrder will be [], but callers will be cleaner if they don't rely on this.) @rtype: (string, list, list) """ #bruce 050405 revised code & docstring #ericm 080409 revised return value to contain listOfAtomsInFileOrder #bruce 080502 documented return value; fixed it when file is empty state = _readmmp_state( assy, isInsert) # The following code is experimental. It reads an mmp file that is contained # within a ZIP file. To test, create a zipfile (i.e. "part.zip") which # contains an MMP file named "main.mmp", then rename "part.zip" to # "part.mmp". Set the constant READ_MAINMMP_FROM_ZIPFILE = True, # then run NE1 and open "part.mmp" using "File > Open...". # Mark 2008-02-03 READ_MAINMMP_FROM_ZIPFILE = False # Don't commit with True. if READ_MAINMMP_FROM_ZIPFILE: # Experimental. Read "main.mmp", a standard mmp file contained within # a zipfile opened via "File > Open...". from zipfile import ZipFile _zipfile = ZipFile(filename, 'r') _bytes = _zipfile.read("main.mmp") lines = _bytes.splitlines() else: # The normal way to read an MMP file. try: lines = open(filename,"rU").readlines() # 'U' in filemode is for universal newline support except: return READ_ERROR, None, [] # Commented this out since the assy.filename should be (and is) set by # another caller based on success. #if not isInsert: # assy.filename = filename ###e would it be better to do this at the end, and not at all if we fail? global _readmmp_aborted global _reference_to_readmmp_abort_function _readmmp_aborted = False #bruce 080606 bugfix or precaution # Create and display a Progress dialog while reading the MMP file. # One issue with this implem is that QProgressDialog always displays # a "Cancel" button, which is not hooked up. I think this is OK for now, # but later we should either hook it up or create our own progress # dialog that doesn't include a "Cancel" button. --mark 2007-12-06 if showProgressDialog: kluge_main_assy = env.mainwindow().assy # see comment about kluge_main_assy elsewhere in this file # [bruce 080319] assert not kluge_main_assy.assy_valid #bruce 080117 _progressValue = 0 _progressFinishValue = len(lines) win = env.mainwindow() win.progressDialog.setLabelText("Reading file...") win.progressDialog.setRange(0, _progressFinishValue) _progressDialogDisplayed = False _timerStart = time.time() def abort_readmmp(): """ This slot is called when the user aborts opening a large MMP file by pressing the "Cancel" button in the progress dialog. """ try: print "cancelled reading file" global _readmmp_aborted _readmmp_aborted = True win.disconnect(win.progressDialog, SIGNAL("canceled()"), abort_readmmp) # review: why no NameError for this abort_readmmp? # guess: it's a legal read-only reference into the # outer function's scope. But it's also possible that we have # an exception and don't see it, so I'm adding some prints to # find out, and try/except. These can remain since they are # harmless. [bruce 080606] print " (returning from abort_readmmp)" except: print_compact_traceback("exception in abort_readmmp ignored: ") return from PyQt4.Qt import SIGNAL win.connect(win.progressDialog, SIGNAL("canceled()"), abort_readmmp) _reference_to_readmmp_abort_function = abort_readmmp # make sure abort_readmmp doesn't get deallocated before use # [bruce 080606 precaution] pass for card in lines: if _readmmp_aborted: # User aborted while reading the MMP file. _readmmp_aborted = False # (precaution, not really needed, since not # sufficient to replace the reset earlier in this function) return ABORTED, None, [] try: errmsg = state.readmmp_line( card) # None or an error message except: # note: the following two error messages are similar but not identical errmsg = "bug while reading this mmp line: %s" % (card,) #e include line number; note, two lines might be identical print_compact_traceback("bug while reading this mmp line:\n %s\n" % (card,) ) #e assert errmsg is None or a string if errmsg: ###e general history msg for stopping early on error ###e special return value then?? break if showProgressDialog: # Update the progress dialog. _progressValue += 1 if _progressValue >= _progressFinishValue: win.progressDialog.setLabelText("Building model...") elif _progressDialogDisplayed: win.progressDialog.setValue(_progressValue) # WARNING: this can directly call glpane.paintGL! # So can the other 2 calls here of progressDialog.setValue. # To prevent bugs or slowdowns from drawing incomplete # models or from trying to run updaters (or take undo # checkpoints?) before drawing them, the GLPane now checks # kluge_main_assy.assy_valid to prevent redrawing when this happens. # (Does ThumbView also need this fix?? ### REVIEW) # [bruce 080117 comment / bugfix] else: _timerDuration = time.time() - _timerStart if _timerDuration > 0.25: # Display progress dialog after 0.25 seconds win.progressDialog.setValue(_progressValue) _progressDialogDisplayed = True grouplist = state.extract_toplevel_items() # for a normal mmp file this has 3 Groups, whose roles are viewdata, tree, shelf # now fix up sim input files and other nonstandardly-structured files; # use these extra groups if necessary, else discard them: viewdata = Group("Fake View Data", assy, None) # name is never used or stored shelf = Group("Clipboard", assy, None) # name might not matter since caller resets it for g in grouplist: if not g.is_group(): # might happen for files that ought to be 'one_part', too, I think, if clipboard item was not grouped state.guess_sim_input('missing_group_or_chunk') # normally same warning already went out for the missing chunk tree = Group("tree", assy, None, grouplist) grouplist = [ viewdata, tree, shelf ] break if len(grouplist) == 0: state.format_error("nothing in file") return SUCCESS, None, [] ### REVIEW: this is really a file format error; # what return code is best? need a new one? # guess: READ_ERROR would be best; needs analysis. # [bruce 080606 Q] elif len(grouplist) == 1: state.guess_sim_input('one_part') # note: 'one_part' gives same warning as 'missing_group_or_chunk' as of 050406 tree = Group("tree", assy, None, grouplist) #bruce 050406 removed [0] to fix bug in last night's new code grouplist = [ viewdata, tree, shelf ] elif len(grouplist) == 2: state.guess_sim_input('no_shelf') grouplist.append( shelf) elif len(grouplist) > 3: state.format_error("more than 3 toplevel groups -- treating them all as in the main part") #bruce 050405 change; old code discarded all the data tree = Group("tree", assy, None, grouplist) grouplist = [ viewdata, tree, shelf ] else: pass # nothing was wrong! assert len(grouplist) == 3 listOfAtomsInFileOrder = state.listOfAtomsInFileOrder state.destroy() # not before now, since it keeps track of which warnings we already emitted if showProgressDialog: # Make the progress dialog go away. win.progressDialog.setValue(_progressFinishValue) _reference_to_readmmp_abort_function = None return SUCCESS, grouplist, listOfAtomsInFileOrder # from _readmmp def readmmp(assy, filename, isInsert = False, showProgressDialog = False, returnListOfAtoms = False): """ Read an mmp file to create a new model (including a new Clipboard). Returns a tuple described below, which contains a grouplist tuple of (viewdata, tree, shelf). If isInsert is False (the default), assy will be modified to include the new items. (If caller wants assy to be marked as "not modified" afterwards, it's up to caller to handle this, e.g. using assy.reset_changed().) @note: mmp stands for Molecular Machine Part. @param assy: the assembly object which the file contents are being added to @type assy: instance of assembly.Assembly @param filename: where the data will be read from @type filename: string @param isInsert: if True, the file contents are being added to an existing assembly, otherwise the file contents are being used to initialize a new assembly. When this is true, some behavior is not done, e.g. calling assy.update_parts and all the updaters it normally calls. Doing that (or tolerating not doing it) is up to the caller. @type isInsert: boolean @param showProgressDialog: if True, display a progress dialog while reading a file. Default is False. @type showProgressDialog: boolean @param returnListOfAtoms: if True, return value contains a list of all atoms in the file, in the order they appeared. If False (the default), return value contains the group list. See return value doc for details. @type returnListOfAtoms: boolean @return: the tuple (ok, grouplist) or (ok, listOfAtoms) (depending on the returnListOfAtoms option) where ok is one of the following named string constants defined in utilities.constants: - SUCCESS - ABORTED - READ_ERROR @rtype: (string, atom list) or (string, grouplist or None) """ # todo: This interface needs revising and clarifying. Ideally, it should take only # a filename as parameter, and return a single data structure (of the same # class which we use for "the contents of a model file", more or less) # representing the contents of that file, and a success code. # (Whether it's practical for the data not to point to "its assy" is # questionable, but can be thought of as an independent issue, # except perhaps for performance considerations for Insert.) # Maybe the listOfAtoms should be accessible from the data structure # even if it's not identical to "all the atoms ultimately in that # structure"; if that's not wise, then returning it separately is ok. # [comment probably by EricM; revised/extended by bruce 080606] # TODO: clean up return value format to return a tuple of three values, # always in the same format (ok, grouplist, listOfAtoms) # (just like _readmmp does now). [bruce 080606 suggestion] kluge_main_assy = env.mainwindow().assy # use this instead of assy to fix logic bug in use of assy_valid flag # (explained where it's used in master_model_updater) # which would be a potential bug during partlib mmpread # [bruce 080319] assert kluge_main_assy.assy_valid kluge_main_assy.assy_valid = False # disable updaters during _readmmp # [bruce 080117/080124, revised 080319] try: ok, grouplist, listOfAtomsInFileOrder = _readmmp(assy, filename, isInsert, showProgressDialog) # warning: can show a dialog, which can cause paintGL calls. finally: kluge_main_assy.assy_valid = True if (not isInsert): # NOTE: we want to call this even if ok != SUCCESS, # since it detects grouplist is None in that case # and has side effects on assy which might be required # (needs review to see if they are really required). # [bruce 080606 comment] _reset_grouplist(assy, grouplist) # note: handles grouplist is None (though not very well) # note: runs all updaters when done, and sets per-part viewdata if (returnListOfAtoms): return ok, listOfAtomsInFileOrder return ok, grouplist def _reset_grouplist(assy, grouplist): """ [private] Stick a new just-read grouplist into assy, within readmmp. If grouplist is None, indicating file had bad format, do some but not all of the usual side effects. [appropriateness of behavior for grouplist is None is unreviewed] Otherwise grouplist must be a list of exactly 3 Groups (though this is not fully checked here), which we treat as viewdata, tree, shelf. Changed viewdata behavior 050418: We used to assume (if necessary) that viewdata contains Csys records which, when parsed during _readmmp, had side effects of storing themselves in assy (which was a bad design). Now we scan it and perform those side effects ourselves. """ #bruce 050302 split this out of readmmp; # it should be entirely rewritten and become an assy method #bruce 050418: revising this for assy/part split if grouplist is None: # do most of what old code did (most of which probably shouldn't be done, # but this needs more careful review (especially in case old code has # already messed things up by clearing assy), and merging with callers, # which don't even check for any kind of error return from readmmp), # except (as of 050418) don't do any side effects from viewdata. # Note: this is intentionally duplicated with code from the other case, # since the plan is to clean up each case independently. assy.shelf.name = "Clipboard" assy.shelf.open = False assy.root = Group("ROOT", assy, None, [assy.tree, assy.shelf]) assy.kluge_patch_toplevel_groups() assy.update_parts() return viewdata, tree, shelf = grouplist # don't yet store these in any Part, since those will all be replaced # with new ones by update_parts, below! assy.tree = tree assy.shelf = shelf # below, we'll scan viewdata for Csys records to store into mainpart assy.shelf.name = "Clipboard" if not assy.shelf.open_specified_by_mmp_file: #bruce 050421 added condition assy.shelf.open = False assy.root = Group("ROOT", assy, None, [assy.tree, assy.shelf]) assy.kluge_patch_toplevel_groups() assy.update_parts( do_special_updates_after_readmmp = True) #bruce 080319 added do_special_updates_after_readmmp = True # (note: we don't test will_special_updates_after_readmmp_do_anything() # since we have to call this even if they won't.) # # Note: by the time this is called, our callers as of 080319 # will have restored kluge_main_assy.assy_valid = True, # so updaters run by update_parts (such as dna updater) # will *not* be disabled. [bruce 080319 comment] # #bruce 050309 for assy/part split; # 080117 added do_post_event_updates = False; # 080124 removed that option (and revised when caller restores # kluge_main_assy.assy_valid) to fix recent bug in which all newly read # files are recorded as modified; at the time I thought that option was # needed for safety, like the disabling of updaters during paintGL is, # but a closer analysis of the following code shows that it's not. # NOTE: ideally the dna updater would mark the assy as modified even # during readmmp, if it had to do "irreversible changes" to fix a pre- # updater mmp file containing dna-related objects. To implement that # without restoring the just-fixed bug would require the dna updater # to know and record the difference in status of the different kinds # of updates it does; it would also require some new scheme in this # code for having that affect the ultimate value of assy._modified # (presently determined by code in our callers). Neither is trivial, # both are doable -- not yet clear if it's worth the trouble. # [bruce comment 080124] # Now the parts exist, so it's safe to store the viewdata into the mainpart; # this imitates what the pre-050418 code did when the csys records were parsed; # note that not all mmp files have anything at all in viewdata # (e.g. some sim-input files don't). mainpart = assy.tree.part for m in viewdata.members: if isinstance(m, NamedView): if m.name == "HomeView" or m.name == "OldVersion": # "OldVersion" will be changed to "HomeView" later... see comment elsewhere mainpart.homeView = m elif m.name == "LastView": mainpart.lastView = m elif m.name.startswith("HomeView"): _maybe_set_partview(assy, m, "HomeView", 'homeView') elif m.name.startswith("LastView"): _maybe_set_partview(assy, m, "LastView", 'lastView') return def _maybe_set_partview( assy, namedView, nameprefix, namedViewattr): #bruce 050421; docstring added 050602 """ [private helper function for _reset_grouplist] If namedView.name == nameprefix plus a decimal number, store namedView as the attr named namedViewattr of the .part of the clipboard item indexed by that number (starting from 1, using purely positional indices for clipboard items). """ partnodes = assy.shelf.members for i in range(len(partnodes)): #e inefficient if there are a huge number of shelf items... if namedView.name == nameprefix + "%d" % (i+1): part = partnodes[i].part setattr(part, namedViewattr, namedView) break return def insertmmp(assy, filename): """ Read an mmp file and insert its main part into the existing model. Discards other info from the file it reads, like the clipboard. @note: does not emit a history message about its result. The caller must do that if desired. @return: success_code, which is one of these named string constants defined in utilities.constants: - SUCCESS - ABORTED - READ_ERROR """ #bruce 050405 revised to fix one or more assembly/part bugs, I hope #bruce 080606 revised to return success code (but didn't yet fix # callers to make use of it) # Note: this is a normal user operation, so there is no need # to refrain from setting assy's modified flag. kluge_main_assy = env.mainwindow().assy # use this instead of assy to fix logic bug in use of assy_valid flag # (explained where it's used in master_model_updater) # which would be a potential bug during partlib mmpread # [bruce 080319] assert kluge_main_assy.assy_valid kluge_main_assy.assy_valid = False # disable updaters during insert [bruce 080117] ok = READ_ERROR try: ok, grouplist, listOfAtomsInFileOrder = _readmmp(assy, filename, isInsert = True, showProgressDialog = True) del listOfAtomsInFileOrder # isInsert = True prevents most side effects on assy; # a better design would be to let the caller do them (or not) if ok == SUCCESS and grouplist: #bruce 080606 added ok == SUCCESS condition (precaution or cleanup) ### TODO: NEEDS ERROR MESSAGE OTHERWISE viewdata, mainpart, shelf = grouplist del viewdata ## not yet (see below): del shelf assy.addnode( mainpart) #bruce 060604 ## assy.part.ensure_toplevel_group() ## assy.part.topnode.addchild( mainpart ) #bruce 050425 to fix bug 563: # Inserted mainpart might contain jigs whose atoms were in clipboard of inserted file. # Internally, right now, those atoms exist, in legitimate chunks in assy # (with a chain of dads going up to 'shelf' (the localvar above), which has no dad), # and have not been killed. Bug 563 concerns these jigs being inserted with no provision # for their noninserted atoms. It's not obvious what's best to do in this case, but a safe # simple solution seems to be to pretend to insert and then delete the shelf we just read, # thus officially killing those atoms, and removing them from those jigs, with whatever # effects that might have (e.g. removing those jigs if all their atoms go away). # (When we add history messages for jigs which die from losing all atoms, # those should probably differ in this case and in the usual case, # but those are NIM for now.) # I presume it's ok to kill these atoms without first inserting them into any Part... # at least, it seems unlikely to mess up any specific Part, since they're not now in one. #e in future -- set up special history-message behavior for jigs killed by this: shelf.kill() #e in future -- end of that special history-message behavior # run special updaters for readmmp, but (as optim for usual case) # only if necessary, since otherwise the normal updater run after # we return (which happens since this is a normal user op) # will be sufficient. For big files this might be a significant # optim (in spite of incremental nature of updater) (guess). # # note: for readmmp this is done in _reset_grouplist, in a call # of update_parts which is always required. # [bruce 080319] if will_special_updates_after_readmmp_do_anything(assy): assy.update_parts( do_special_updates_after_readmmp = True) pass pass finally: kluge_main_assy.assy_valid = True return ok def fix_assy_and_glpane_views_after_readmmp( assy, glpane): """ #doc; does gl_update but callers should not rely on that """ #bruce 050418 moved this code (written by Huaicai) out of MWsemantics.fileOpen # (my guess is it should mostly be done by readmmp itself); # here is Huaicai's comment about it: # Huaicai 12/14/04, set the initial orientation to the file's home view orientation # when open a file; set the home view scale = current fit-in-view scale #bruce 050418 change this for assembly/part split (per-part Csys attributes) mainpart = assy.tree.part assert assy.part is mainpart # necessary for glpane view funcs to refer to it (or was at one time) if mainpart.homeView.name == "OldVersion": ## old version of mmp file mainpart.homeView.name = "HomeView" glpane.set_part(mainpart) # also sets view, but maybe not fully correctly in this case ###k glpane.quat = Q( mainpart.homeView.quat) # might be redundant with above glpane.setViewFitToWindow() else: glpane.set_part(mainpart) ## done by that: glpane._setInitialViewFromPart( mainpart) return # end
NanoCAD-master
cad/src/files/mmp/files_mmp.py
""" printFunc.py: print method that can be called after populating DOM in order to see the XML objects in human readable format. Based on the original files from the pyXML 0.8.4 dom/ext module. @author: Urmi @version: $Id$ @copyright: 2004-2008 Nanorex, Inc. See LICENSE file for details. """ from xml.dom import XMLNS_NAMESPACE, XML_NAMESPACE, XHTML_NAMESPACE import string, re, sys from xml.dom import Node from Visitor import Visitor, WalkerInterface ILLEGAL_LOW_CHARS = '[\x01-\x08\x0B-\x0C\x0E-\x1F]' ILLEGAL_HIGH_CHARS = '\xEF\xBF[\xBE\xBF]' XML_ILLEGAL_CHAR_PATTERN = re.compile('%s|%s'%(ILLEGAL_LOW_CHARS, ILLEGAL_HIGH_CHARS)) def PrettyPrint(root, stream=sys.stdout, encoding='UTF-8', indent=' ', preserveElements=None): """ Prints the DOM object to stream """ if not hasattr(root, "nodeType"): return #from xml.dom.ext import Printer nss_hints = SeekNss(root) preserveElements = preserveElements or [] owner_doc = root.ownerDocument or root if hasattr(owner_doc, 'getElementsByName'): #We don't want to insert any whitespace into HTML inline elements #preserveElements = preserveElements + HTML_4_TRANSITIONAL_INLINE print "No provision for HTML Inline elements" visitor = PrintVisitor(stream, encoding, indent, preserveElements, nss_hints) PrintWalker(visitor, root).run() stream.write('\n') return def SeekNss(node, nss=None): """ traverses the tree to seek an approximate set of defined namespaces """ nss = nss or {} for child in node.childNodes: if child.nodeType == Node.ELEMENT_NODE: if child.namespaceURI: nss[child.prefix] = child.namespaceURI for attr in child.attributes.values(): if attr.namespaceURI == XMLNS_NAMESPACE: if attr.localName == 'xmlns': nss[None] = attr.value else: nss[attr.localName] = attr.value elif attr.namespaceURI: nss[attr.prefix] = attr.namespaceURI SeekNss(child, nss) return nss def utf8_to_code(text, encoding): # support for UTF-8 only encoding = string.upper(encoding) if encoding == 'UTF-8': return text def TranslateCdata(characters, encoding='UTF-8', prev_chars='', markupSafe=0, charsetHandler=utf8_to_code): """ charsetHandler is a function that takes a string or unicode object as the first argument, representing the string to be procesed, and an encoding specifier as the second argument. It must return a string or unicode object """ if not characters: return '' new_string = characters #Note: use decimal char entity rep because some browsers are broken #FIXME: This will bomb for high characters. Should, for instance, detect #The UTF-8 for 0xFFFE and put out &#xFFFE; if XML_ILLEGAL_CHAR_PATTERN.search(new_string): new_string = XML_ILLEGAL_CHAR_PATTERN.subn( lambda m: '&#%i;' % ord(m.group()), new_string)[0] new_string = charsetHandler(new_string, encoding) return new_string def TranslateCdataAttr(characters): """ Handles normalization and some intelligence about quoting """ if not characters: return '', "'" if "'" in characters: delimiter = '"' new_chars = re.sub('"', '&quot;', characters) else: delimiter = "'" new_chars = re.sub("'", '&apos;', characters) #FIXME: There's more to normalization #Convert attribute new-lines to character entity # characters is possibly shorter than new_chars (no entities) if "\n" in characters: new_chars = re.sub('\n', '&#10;', new_chars) return new_chars, delimiter class PrintVisitor(Visitor): def __init__(self, stream, encoding, indent='', plainElements=None, nsHints=None, isXhtml=0, force8bit=0): self.stream = stream self.encoding = encoding # Namespaces self._namespaces = [{}] self._nsHints = nsHints or {} # PrettyPrint self._indent = indent self._depth = 0 self._inText = 0 self._plainElements = plainElements or [] # HTML support self._html = None self._isXhtml = isXhtml self.force8bit = force8bit return def visit(self, node): if self._html is None: # Set HTMLDocument flag here for speed #print " leave html tag to be None" self._html = hasattr(node.ownerDocument, 'getElementsByName') nodeType = node.nodeType if node.nodeType == Node.ELEMENT_NODE: return self.visitElement(node) elif node.nodeType == Node.ATTRIBUTE_NODE: return self.visitAttr(node) elif node.nodeType == Node.TEXT_NODE: return self.visitText(node) elif node.nodeType == Node.DOCUMENT_NODE: return self.visitDocument(node) elif node.nodeType == Node.DOCUMENT_TYPE_NODE: return self.visitDocumentType(node) # It has a node type, but we don't know how to handle it raise Exception("Unknown node type: %s" % repr(node)) def _write(self, text): obj = utf8_to_code(text, self.encoding) self.stream.write(obj) return def _tryIndent(self): if not self._inText and self._indent: self._write('\n' + self._indent*self._depth) return def visitDocumentType(self, doctype): if not doctype.systemId and not doctype.publicId: return self._tryIndent() self._write('<!DOCTYPE %s' % doctype.name) if doctype.systemId and '"' in doctype.systemId: system = "'%s'" % doctype.systemId else: system = '"%s"' % doctype.systemId if doctype.publicId and '"' in doctype.publicId: # We should probably throw an error # Valid characters: <space> | <newline> | <linefeed> | # [a-zA-Z0-9] | [-'()+,./:=?;!*#@$_%] public = "'%s'" % doctype.publicId else: public = '"%s"' % doctype.publicId if doctype.publicId and doctype.systemId: self._write(' PUBLIC %s %s' % (public, system)) elif doctype.systemId: self._write(' SYSTEM %s' % system) if doctype.entities or doctype.notations: print "No support for entities" else: self._write('>') self._inText = 0 return def visitProlog(self): self._write("<?xml version='1.0' encoding='%s'?>" % ( self.encoding or 'utf-8' )) self._inText = 0 return def visitNodeList(self, node, exclude=None): for curr in node: curr is not exclude and self.visit(curr) return def visitDocument(self, node): not self._html and self.visitProlog() node.doctype and self.visitDocumentType(node.doctype) self.visitNodeList(node.childNodes, exclude=node.doctype) return def visitText(self, node): text = node.data if self._indent: text = string.strip(text) and text if text: text = TranslateCdata(text, self.encoding) self.stream.write(text) self._inText = 1 return def visitAttr(self, node): if node.namespaceURI == XMLNS_NAMESPACE: # Skip namespace declarations return self._write(' ' + node.name) value = node.value if value or not self._html: text = TranslateCdata(value, self.encoding) text, delimiter = TranslateCdataAttr(text) self.stream.write("=%s%s%s" % (delimiter, text, delimiter)) return def GetAllNs(self,node): #The xml namespace is implicit nss = {'xml': XML_NAMESPACE} if node.nodeType == Node.ATTRIBUTE_NODE and node.ownerElement: return self.GetAllNs(node.ownerElement) if node.nodeType == Node.ELEMENT_NODE: if node.namespaceURI: nss[node.prefix] = node.namespaceURI for attr in node.attributes.values(): if attr.namespaceURI == XMLNS_NAMESPACE: if attr.localName == 'xmlns': nss[None] = attr.value else: nss[attr.localName] = attr.value elif attr.namespaceURI: nss[attr.prefix] = attr.namespaceURI if node.parentNode: #Inner NS/Prefix mappings take precedence over outer ones parent_nss = self.GetAllNs(node.parentNode) parent_nss.update(nss) nss = parent_nss return nss def visitElement(self, node): self._namespaces.append(self._namespaces[-1].copy()) inline = node.tagName in self._plainElements not inline and self._tryIndent() self._write('<%s' % node.tagName) if self._isXhtml or not self._html: namespaces = '' if self._isXhtml: nss = {'xml': XML_NAMESPACE, None: XHTML_NAMESPACE} else: nss = self.GetAllNs(node) if self._nsHints: self._nsHints.update(nss) nss = self._nsHints self._nsHints = {} del nss['xml'] for prefix in nss.keys(): if not self._namespaces[-1].has_key(prefix) or self._namespaces[-1][prefix] != nss[prefix]: nsuri, delimiter = TranslateCdataAttr(nss[prefix]) if prefix: xmlns = " xmlns:%s=%s%s%s" % (prefix, delimiter,nsuri,delimiter) namespaces = namespaces + xmlns else: xmlns = " xmlns=%s%s%s" % (delimiter,nsuri,delimiter) self._namespaces[-1][prefix] = nss[prefix] self._write(namespaces) for attr in node.attributes.values(): self.visitAttr(attr) if len(node.childNodes): self._write('>') self._depth = self._depth + 1 self.visitNodeList(node.childNodes) self._depth = self._depth - 1 if not self._html or (node.tagName not in HTML_FORBIDDEN_END): not (self._inText and inline) and self._tryIndent() self._write('</%s>' % node.tagName) elif not self._html: self._write('/>') else: self._write('>') del self._namespaces[-1] self._inText = 0 return class PrintWalker(WalkerInterface): def __init__(self, visitor, startNode): WalkerInterface.__init__(self, visitor) self.start_node = startNode return def step(self): """ There is really no step to printing. It prints the whole thing """ self.visitor.visit(self.start_node) return def run(self): return self.step()
NanoCAD-master
cad/src/files/ios/printFunc.py
NanoCAD-master
cad/src/files/ios/__init__.py
# Copyright 2008 Nanorex, Inc. See LICENSE file for details. """ files_ios.py - provides functions to export a NE-1 model into IOS format as well as import optimized sequences into NE-1 @author: Urmi @version: $Id$ @copyright: 2008 Nanorex, Inc. See LICENSE file for details. Note: This is only applicable to DNA/ RNA models (so is IOS) """ from xml.dom.minidom import DOMImplementation from xml.dom import EMPTY_NAMESPACE, XML_NAMESPACE, XMLNS_NAMESPACE from dna.model.DnaLadderRailChunk import DnaStrandChunk from dna.model.DnaLadder import DnaLadder from printFunc import PrettyPrint import os, string, sys from xml.dom.minidom import parse from xml.parsers.expat import ExpatError from dna.model.DnaStrand import DnaStrand from PyQt4.Qt import QMessageBox def getAllDnaStrands(assy): """ get all the DNA strands from the NE-1 part to figure out strand info @param assy: the NE1 assy. @type assy: L{assembly} @return: a list of DNA strands """ dnaStrandList = [] def func(node): if isinstance(node, assy.DnaStrand): dnaStrandList.append(node) assy.part.topnode.apply2all(func) return dnaStrandList def createTokenLibrary(doc,elemDoc): """ create Token library in the IOS file @param: doc @type: DOM Document @param: elemDoc @type: root element """ elemTokenLibrary = doc.createElement('TokenLibrary') elemAtomicToken = doc.createElement('AtomicTokens') #create element name and child text from key value pair elemAtomicTokenA = doc.createElement('AtomicToken') elemAtomicTokenA.appendChild(doc.createTextNode('A')) elemAtomicToken.appendChild(elemAtomicTokenA) elemAtomicTokenC = doc.createElement('AtomicToken') elemAtomicTokenC.appendChild(doc.createTextNode('C')) elemAtomicToken.appendChild(elemAtomicTokenC) elemAtomicTokenG = doc.createElement('AtomicToken') elemAtomicTokenG.appendChild(doc.createTextNode('G')) elemAtomicToken.appendChild(elemAtomicTokenG) elemAtomicTokenT = doc.createElement('AtomicToken') elemAtomicTokenT.appendChild(doc.createTextNode('T')) elemAtomicToken.appendChild(elemAtomicTokenT) elemTokenLibrary.appendChild(elemAtomicToken) # create wild card token elemWildcardTokens = doc.createElement('WildcardTokens') elemWildcardToken = doc.createElement('WildcardToken') elemTokenT = doc.createElement('Token') elemTokenT.appendChild(doc.createTextNode('N')) elemWildcardToken.appendChild(elemTokenT) elemAtomicEquivalentA = doc.createElement('AtomicEquivalent') elemAtomicEquivalentA.appendChild(doc.createTextNode('A')) elemWildcardToken.appendChild(elemAtomicEquivalentA) elemAtomicEquivalentT = doc.createElement('AtomicEquivalent') elemAtomicEquivalentT.appendChild(doc.createTextNode('T')) elemWildcardToken.appendChild(elemAtomicEquivalentT) elemAtomicEquivalentG = doc.createElement('AtomicEquivalent') elemAtomicEquivalentG.appendChild(doc.createTextNode('G')) elemWildcardToken.appendChild(elemAtomicEquivalentG) elemAtomicEquivalentC = doc.createElement('AtomicEquivalent') elemAtomicEquivalentC.appendChild(doc.createTextNode('C')) elemWildcardToken.appendChild(elemAtomicEquivalentC) elemWildcardTokens.appendChild(elemWildcardToken) elemTokenLibrary.appendChild(elemWildcardTokens) #append token library to the iso file elemDoc.appendChild(elemTokenLibrary) return def createMappingLibrary(doc,elemDoc): """ create mapping library section for the NE-1 model file in the ios file @param: doc @type: DOM Document @param: elemDoc @type: root element """ elemMappingLibrary = doc.createElement('MappingLibrary') elemMapping = doc.createElement('Mapping') elemMapping.setAttribute('id', 'complement') # A to T elemTokenT = doc.createElement('Token') elemFrom = doc.createElement('From') elemFrom.appendChild(doc.createTextNode('A')) elemTokenT.appendChild(elemFrom) elemTo = doc.createElement('To') elemTo.appendChild(doc.createTextNode('T')) elemTokenT.appendChild(elemTo) elemMapping.appendChild(elemTokenT) # T to A elemTokenT = doc.createElement('Token') elemFrom = doc.createElement('From') elemFrom.appendChild(doc.createTextNode('T')) elemTokenT.appendChild(elemFrom) elemTo = doc.createElement('To') elemTo.appendChild(doc.createTextNode('A')) elemTokenT.appendChild(elemTo) elemMapping.appendChild(elemTokenT) # C to G elemTokenT = doc.createElement('Token') elemFrom = doc.createElement('From') elemFrom.appendChild(doc.createTextNode('C')) elemTokenT.appendChild(elemFrom) elemTo = doc.createElement('To') elemTo.appendChild(doc.createTextNode('G')) elemTokenT.appendChild(elemTo) elemMapping.appendChild(elemTokenT) # G to C elemTokenT = doc.createElement('Token') elemFrom = doc.createElement('From') elemFrom.appendChild(doc.createTextNode('G')) elemTokenT.appendChild(elemFrom) elemTo = doc.createElement('To') elemTo.appendChild(doc.createTextNode('C')) elemTokenT.appendChild(elemTo) elemMapping.appendChild(elemTokenT) elemMappingLibrary.appendChild(elemMapping) elemDoc.appendChild(elemMappingLibrary) return def createMapping(startIndex, endIndex): dictionary = dict() if startIndex < endIndex: j=0 i = startIndex while i <= endIndex : dictionary[i] = j j = j + 1 i = i + 1 else: j=0 i = startIndex while i >= endIndex : dictionary[i] = j j = j + 1 i = i - 1 return dictionary def createComplementaryChunkInformation(strandList, chunkNameListInOrder, indexTupleListInOrder): chunkAndComplementDict = dict() #visited array for all strands so that chunk info do not get written twice indexMappingList = [] visitedArray = [] for i in range(len(strandList)): strand = strandList[i] startIndex = indexTupleListInOrder[i][0][0] endIndex = indexTupleListInOrder[i][len(indexTupleListInOrder[i])-1][1] seqLen = len(strand.getStrandSequence()) indexMappingList.append(createMapping(startIndex, endIndex)) tempList = [] for j in range(seqLen): tempList.append(0) visitedArray.append(tempList) #create complementary info for strand in strandList: strand_wholechain = strand.get_strand_wholechain() for rail in strand_wholechain.rails(): atom = rail.baseatoms[0] atomMate = atom.get_strand_atom_mate() # do this only for double stranded DNA if atomMate is not None: #check visited array to see if complementary info has already been written baseIndices = strand_wholechain.wholechain_baseindex_range_for_rail(rail) index = strandList.index(strand) tempList = [] tempList = [x[0] for x in indexTupleListInOrder[index]] try: index1 = tempList.index(baseIndices[0]) startIndex = baseIndices[0] endIndex = baseIndices[1] except ValueError: index1 = tempList.index(baseIndices[1]) startIndex = baseIndices[1] endIndex = baseIndices[0] startIndexInVA = indexMappingList[index][startIndex] endIndexInVA = indexMappingList[index][endIndex] exist = 0 m = startIndexInVA while m <= endIndexInVA: if visitedArray[index][m] == 0: exist = 0 break else: exist = 1 m = m + 1 if exist == 1: #entry already exists continue else: #need to create chunk and complementary chunk info chunkName = chunkNameListInOrder[index][index1 + 1] #mark visited array to be 1 m = startIndexInVA while m <= endIndexInVA: visitedArray[index][m] = 1 m = m + 1 #find complementary chunk Name atomMateParent = atomMate.getDnaStrand() strandRails = atom.molecule.ladder.strand_rails assert len(strandRails) == 2 if rail == strandRails[0]: complementaryRail = strandRails[1] else: complementaryRail = strandRails[0] baseIndicesForComp = atomMateParent.get_strand_wholechain().wholechain_baseindex_range_for_rail(complementaryRail) tempList = [] indexComp = strandList.index(atomMateParent) tempList = [x[0] for x in indexTupleListInOrder[indexComp]] try: index1 = tempList.index(baseIndicesForComp[0]) startIndex = baseIndicesForComp[0] endIndex = baseIndicesForComp[1] except ValueError: index1 = tempList.index(baseIndicesForComp[1]) startIndex = baseIndicesForComp[1] endIndex = baseIndicesForComp[0] startIndexInVA = indexMappingList[indexComp][startIndex] endIndexInVA = indexMappingList[indexComp][endIndex] compChunkName = chunkNameListInOrder[indexComp][index1 + 1] m = startIndexInVA while m <= endIndexInVA: visitedArray[indexComp][m] = 1 m = m + 1 chunkAndComplementDict[chunkName] = compChunkName return chunkAndComplementDict def railImplementation(assy): strandList = getAllDnaStrands(assy) baseStringListInOrder = [] indexTupleListInOrder = [] chunkNameListInOrder = [] #initialization for i in range(len(strandList)): baseStringListInOrder.append([]) indexTupleListInOrder.append([]) chunkNameListInOrder.append([]) for strand in strandList: strandID = strand.name strandIndex = strandList.index(strand) #wholechain_baseindex_range_for_rail(rail) can return sequences either #in 3' or 5' sequences. Hence the final sequence should be compared with # that of atoms in the bond direction and their corresponding basenames # to figure out its directionality. strand_wholechain = strand.get_strand_wholechain() someList = [] if strand_wholechain: for rail in strand_wholechain.rails(): baseList = [] for a in rail.baseatoms: bases = a.getDnaBaseName() aComp = a.get_strand_atom_mate() parent = a.getDnaStrand() if bases == 'X': bases = 'N' baseList.append(bases) baseIndices = strand_wholechain.wholechain_baseindex_range_for_rail(rail) baseString = ''.join(baseList) if baseIndices[1] < baseIndices[0]: baseStringFinal = baseString[::-1] indexTuple = [baseIndices[1], baseIndices[0]] else: baseStringFinal = baseString indexTuple = [baseIndices[0], baseIndices[1]] someList.append( (indexTuple, baseStringFinal) ) someList.sort() indexTupleListInOrder[strandIndex] = [x[0] for x in someList] baseStringListInOrder[strandIndex] = [x[1] for x in someList] checkStrandSequence = ''.join(baseStringListInOrder[strandIndex]) strandSeq = strand.getStrandSequence() if strandSeq == checkStrandSequence[::-1]: baseStringListInOrder[strandIndex].reverse() indexTupleListInOrder[strandIndex].reverse() #we also need to flip the order of the individual element in the tuple for l in range(len(indexTupleListInOrder[strandIndex])): indexTupleListInOrder[strandIndex][l].reverse() #create names for each chunk within each strand someList = [] for l in range(len(baseStringListInOrder[strandIndex])): chunkName = strandID + '_chunk_' + str(l) someList.append(chunkName) chunkNameListInOrder[strandIndex] = someList chunkNameListInOrder[strandIndex].insert(0, strandID) chunkAndComplementDict = createComplementaryChunkInformation(strandList, chunkNameListInOrder, indexTupleListInOrder) return chunkNameListInOrder, baseStringListInOrder, chunkAndComplementDict def createStrands(doc,elemDoc, assy): """ create strand section for the NE-1 model file in the ios file @param: doc @type: DOM Document @param: elemDoc @type: root element @param assy: the NE1 assy. @type assy: L{assembly} """ chunkNameListInOrder, baseStringListInOrder, chunkAndComplementDict = railImplementation(assy) #write the strands to the IOS export file elemStrands = doc.createElement('Strands') i = 0 while i < len(chunkNameListInOrder): strandID = chunkNameListInOrder[i][0] elemStrand = doc.createElement('Strand') elemStrand.setAttribute('id',strandID) for j in range(0, len(chunkNameListInOrder[i])-1): chunkID = chunkNameListInOrder[i][j+1] baseString = baseStringListInOrder[i][j] baseString.replace('X','N') elemRegion = doc.createElement('Region') elemRegion.setAttribute('id', chunkID) elemRegion.appendChild(doc.createTextNode(baseString)) elemStrand.appendChild(elemRegion) i = i + 1 elemStrands.appendChild(elemStrand) elemDoc.appendChild(elemStrands) return chunkAndComplementDict def createConstraints(doc,elemDoc, assy, compInfoDict): """ create constraints section for the NE-1 model file in the ios file @param: doc @type: DOM Document @param: elemDoc @type: root element @param assy: the NE1 assy. @type assy: L{assembly} """ # write the constraints elemConstraints = doc.createElement('Constraints') elemConstraintGroup = doc.createElement('ios:ConstraintGroup') elemConstraintGroup.setAttribute('strict', '1') for key in compInfoDict: elemMatch = doc.createElement('ios:Match') elemMatch.setAttribute('mapping', 'complement') elemConstraintRegion = doc.createElement('Region') elemConstraintRegion.setAttribute('ref',key) elemMatch.appendChild(elemConstraintRegion) elemConstraintRegion = doc.createElement('Region') elemConstraintRegion.setAttribute('ref',compInfoDict[key]) elemConstraintRegion.setAttribute('reverse', '1') elemMatch.appendChild(elemConstraintRegion) elemConstraintGroup.appendChild(elemMatch) elemConstraints.appendChild(elemConstraintGroup) elemDoc.appendChild(elemConstraints) return #export to IOS format def exportToIOSFormat(assy, fileName): """ Writes the IOS file @param assy: the NE1 assy. @type assy: L{assembly} @param: IOS output file in XML @type: string """ if fileName == '': print "No file selected to export" return d = DOMImplementation() #create doctype doctype = DOMImplementation.createDocumentType(d,'ios', None, None) #create empty DOM Document and get root element doc = DOMImplementation.createDocument(d, EMPTY_NAMESPACE,'ios', doctype) elemDoc = doc.documentElement elemDoc.setAttributeNS(XMLNS_NAMESPACE, "xmlns:ios", "http://www.parabon.com/namespaces/inSeqioOptimizationSpecification") elemDoc.setAttributeNS(XMLNS_NAMESPACE, "xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance") createTokenLibrary(doc, elemDoc) createMappingLibrary(doc,elemDoc) compInfoDict = createStrands(doc, elemDoc, assy) createConstraints(doc, elemDoc, assy, compInfoDict) #print doc to file f = open(fileName,'w') PrettyPrint(doc,f) f.close() # don't know how to set the IOS prefix, so processing text to # include that f = open(fileName,'r') allLines=f.readlines() allLines[1] = "<ios:IOS xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:ios='http://www.parabon.com/namespaces/inSeqioOptimizationSpecification'>\n" allLines[len(allLines)-1] = "</ios:IOS>\n" f.close() #write the document all over to reflect the changes f = open(fileName,'w') f.writelines(allLines) f.close() return # UM 20080618: IOS IMPORT FUNCTIONS def importFromIOSFile(assy, fileName1): """ Imports optimized sequences to NE-1 from IOS file @param assy: the NE1 assy. @type assy: L{assembly} @param fileName1: IOS Import file @type fileName1: string @return: Returns True or False based on whether import was successful @note: Since DNA Strand Chunks do not get stored in the mmp file, there's no way, chunk by chunk info can be verified between the structure on the NE-1 window and that in the IOS file. The most that can be done is to verify the name of the strand Name info and their lengths. For instance if two NE-1 structures have the same name and number of strands,each of same length, but their pairing info is different, there's no way to check that and the sequences will get imported anyways. There IOS import happens at the user's risk. """ strandsOnScreen = checkStrandsOnNE_1Window(assy) if strandsOnScreen == False: msg = "Cannot import since currently IOS import is supported only for DNA strands and there are no DNA strands on the screen. There is also no support for importing into clipboard." QMessageBox.warning(assy.win, "Warning!", msg) return False fileName2 = doInitialProcessingOnXMLFile(fileName1) strandNameSeqDict = getHybridizationInfo(fileName2) if strandNameSeqDict is None: # Can remove the temp file if os.path.exists(fileName2): os.remove(fileName2) return False infoCorrect = verifyStructureInfo(assy, strandNameSeqDict) if infoCorrect: #import optimized bases from the IOS file importBases(assy, strandNameSeqDict) else: if os.path.exists(fileName2): os.remove(fileName2) return False if os.path.exists(fileName2): os.remove(fileName2) return True def checkStrandsOnNE_1Window(assy): """ Checks to see if at least one DNA strand exists on the NE-1 window @param part: the NE1 part. @type part: L{assembly} @return: True or False depending on whether there are DNA strands on the NE-1 window """ count = 0 part = assy.part if hasattr(part.topnode, 'members'): for node in part.topnode.members: if hasattr(node,'members'): if node.members is None: return False for nodeChild in node.members: if isinstance(nodeChild, assy.DnaStrand): count = count +1 else: if isinstance(node, assy.DnaStrand): count = count +1 if count >= 1: return True else: return False def importBases(assy, strandNameSeqDict): """ Imports optimized bases, currently stored in strandNameSeqDict dictionary @param assy: the NE1 assy. @type assy: L{assembly} @param strandNameSeqDict: the dictionary containing the strand names and sequences from the IOS import file @type strandNameSeqDict: dict """ def func(node): if isinstance(node, assy.DnaStrand): #retrive its name and see if it exists in the dictionary, if yes # then assign the base sequence try: seq = strandNameSeqDict[node.name] node.setStrandSequence(seq, False) for node in assy.part.topnode.members: for nodeChild in node.members: if isinstance(nodeChild, assy.DnaStrand): seq = nodeChild.getStrandSequence() except KeyError: msg = "Cannot import IOS file since strand %s does not exist in the IOS file" % node.name QMessageBox.warning(assy.win, "Warning!", msg) return assy.part.topnode.apply2all(func) #if we are in the Build DNA mode, update the LineEdit that displays the # sequences win = assy.win if win.commandSequencer.currentCommand.commandName == 'DNA_STRAND': win.commandSequencer.currentCommand.updateSequence() return def getStrandsBaseInfoFromNE_1(assy): """ Obtains the strand chunk names and their corresponding base string of the NE-1 part @param part: the NE1 part. @type part: L{assembly} @return: strand list and basestring list from NE-1 """ strandList = getAllDnaStrands(assy) strandListFromNE_1 = [] baseStringListFromNE_1 = [] for strand in strandList: strandID = strand.name #just get the name of the strand strandListFromNE_1.append(strandID) baseString = strand.getStrandSequence() baseStringListFromNE_1.append(baseString) return strandListFromNE_1, baseStringListFromNE_1 def verifyStructureInfo(assy, iosSeqNameDict): """ Verify that the structure info in the IOS file matches with that of the NE-1 part. @param part: the NE1 part. @type part: L{assembly} @param iosSeqNameDict: dictionary containing strand and basestring from the IOS file @type compInfoDict: dict @return: True or False based on if the structure in the IOS file matches up with the structure in the NE-1 window. """ strandListFromNE_1, baseStringListFromNE_1 = getStrandsBaseInfoFromNE_1(assy) #check their lengths first dictLength = len(iosSeqNameDict) strandListFromNE_1Length = len(strandListFromNE_1) if dictLength != strandListFromNE_1Length: msg = "IOS import aborted since the number of strands in the IOS file "\ "does not equal the number of strands in the current model." QMessageBox.warning(assy.win, "Warning!", msg) return False for strand in iosSeqNameDict: baseString = iosSeqNameDict[strand] try: index = strandListFromNE_1.index(strand) baseStringFromNE_1 = baseStringListFromNE_1[index] except ValueError: msg = "IOS import aborted since strand '%s' in the IOS file does"\ "not exist in the current model." % strand QMessageBox.warning(assy.win, "Warning!", msg) return False if len(baseStringFromNE_1) != len(baseString): msg = "IOS import aborted since the length of strand '%s' "\ "(%s bases) in the current model does not match the length "\ "of strand '%s' found in the IOS file (%d bases)." % \ (strandListFromNE_1[index], len(baseStringFromNE_1), strand, len(baseString)) QMessageBox.warning(assy.win, "Warning!", msg) return False return True def doInitialProcessingOnXMLFile(fileName1): """ do initial preprocessing on the file so that its acceptable by the parser from xml.dom.minidom @param fileName2: IOS import file @type fileName2: string @retun: Temporary file that is read by the xml.dom.minidom """ #its wierd, sometimes even with the prefix, the ExpatError exception does not #show up. Do n't know what's going on! Anyways the prefix ios is not needed #for any of the NE-1 processing and so it's better to be on the safe side! f1 = open(fileName1, 'r') allLines=f1.readlines() f1.close() #create a temporary file with the prefixes removed, make sure that you remove #this file at the end of processing fileName2 = "temp.xml" f2 = open(fileName2, 'w') for line in allLines: if line.find("<ios:")!= -1: line = line.replace("<ios:","<") if line.find("</ios:")!= -1: line = line.replace("</ios:","</") f2.writelines(line) f2.close() return fileName2 def getHybridizationInfo(fileName2): """ Process this temporary file for strand chunk info. At the same time, we check whether its a proper IOS file. @param fileName2: IOS import file @type fileName2: string @return: a dictionary containing (strand, sequence) """ try: doc = parse(fileName2) except ExpatError: msg = "Cannot import IOS file, since its not in correct XML format" QMessageBox.warning(assy.win, "Warning!", msg) return None #need to distinguish between regions for mapping and simple strand regions # hence get strand strandList = doc.getElementsByTagName("Strand") if len(strandList) == 0: msg = "Cannot import IOS file since no strands to import" QMessageBox.warning(assy.win, "Warning!", msg) return None strandNameList = [] strandSeqList = [] #Within each strand access all regions for i in range(len(strandList)): strandNameList.append(str(strandList.item(i).getAttribute("id"))) regionList = strandList.item(i).getElementsByTagName("Region") #each strand needs to have at least one region and so if one of them #does not have it, then it is not a correct IOS file and you should return # without bothering to process the rest of the file. # So far IOS file format is concerned, single strand chunks do not neeed # to be in a Region node. However, without the ID of the region, we have # no way to read it into NE-1 and hence this import is invalid. if len(regionList) == 0: msg = "Cannot import IOS file: strand does not have any region, not a correct IOS file format" QMessageBox.warning(assy.win, "Warning!", msg) return None tempStrandSeq = '' for j in range(len(regionList)): #get new base sequence after IOS optimization tempBaseString = '' if regionList.item(j).childNodes.item(0) is not None: tempBaseString = str(regionList.item(j).childNodes.item(0).toxml()) #if the base string is empty, there's no point of analyzing any #further either if tempBaseString== '': msg = "Cannot import IOS file: strand region does not have any bases, not a correct IOS file format" QMessageBox.warning(assy.win, "Warning!", msg) return None tempStrandSeq = tempStrandSeq + tempBaseString strandSeqList.append(tempStrandSeq) strandNameSeqDict = dict(zip(strandNameList, strandSeqList)) return strandNameSeqDict
NanoCAD-master
cad/src/files/ios/files_ios.py
""" Visitor.py - Supporting class for printing a DOM Document @version: Original file from the pyXML 0.8.4 dom/ext module. Copyright (c) 2000 Fourthought Inc, USA. All Rights Reserved. See http://4suite.com/COPYRIGHT for license and copyright information """ class Visitor: def visit(self, node): """Default behavior for the visitor is simply to print an informational message""" print "Visiting %s node %s\n"%(node.nodeType, node.nodeName) return None class WalkerInterface: def __init__(self, visitor): self.visitor = visitor pass def step(self): """Advance to the next item in order, visit, and then pause""" pass def run(self): """Continue advancing from the current position through the last leaf node without pausing.""" pass class PreOrderWalker(WalkerInterface): def __init__(self, visitor, startNode): WalkerInterface.__init__(self, visitor) self.node_stack = [] self.node_stack.append(startNode) def step(self): """ Visits the current node, and then advances to its first child, if any, else the next sibling. returns a tuple completed, ret_val completed -- flags whether or not we've traversed the entire tree ret_val -- return value from the visitor """ completed = 0 ret_val = self.visitor.visit(self.node_stack[-1]) if (self.node_stack[-1].hasChildNodes()): self.node_stack.append(self.node_stack[-1].firstChild) else: #Back-track until we can find a node with an unprocessed sibling next_sib = None while not next_sib and not completed: next_sib = self.node_stack[-1].nextSibling del self.node_stack[-1] if next_sib: self.node_stack.append(next_sib) else: if not len(self.node_stack): completed = 1 return completed, ret_val def run(self): completed = 0 while not completed: completed, ret_val = self.step() #Set the default Walker class to the PreOrderWalker. #User can change this according to preferences Walker = PreOrderWalker
NanoCAD-master
cad/src/files/ios/Visitor.py
# Copyright 2005-2007 Nanorex, Inc. See LICENSE file for details. """ moviefile.py -- classes and other code for interpreting movie files (of various formats, once we have them) @author: Bruce @version: $Id$ @copyright: 2005-2007 Nanorex, Inc. See LICENSE file for details. """ # note that in future there's more than one class, and a function to figure out the right one to use # for an existing file, or to be told this (being told the format) for a new file we'll cause to be made... # # so the external code should rarely know the actual classnames in this file! # these imports are anticipated, perhaps not all needed import os, sys from struct import unpack # fyi: used for old-format header, no longer for delta frames ## from VQT import A from Numeric import array, Int8 from utilities import debug_flags from utilities.debug import print_compact_stack, print_compact_traceback import foundation.env as env def MovieFile(filename): #bruce 050913 removed history arg, since all callers passed env.history """ Given the name of an existing old-format movie file, return an object which can read frames from it (perhaps only after receiving further advice from its client code, like the absolute atom positions for one specific frame). The returned object should also know whatever can be known from the moviefile itself about the movie... like number of frames and atoms... for the old format, that's all there is. In case of a fatal error, print an appropriate message to env.history and return None. We might also print warnings to history (I don't know #k). In future, when new format is available, we'll detect the format in the file and open it in the proper way, perhaps also taking optional arguments for a trace filename, perhaps handling files that have not yet been finished or perhaps not yet even started, etc.... See also the docstring of class OldFormatMovieFile. """ # for now, assume old format, and assume file exists and has reached its final size. reader = OldFormatMovieFile_startup( filename) if reader.open_and_read_header_errQ(): return None return OldFormatMovieFile( reader) class OldFormatMovieFile_startup: #e maybe make these same obj, so easier to recheck header later, and big one needs invalid state anyway def __init__(self, filename): #bruce 050913 removed history arg self.filename = filename self.fileobj = None self.errcode = None def open_and_read_header_errQ(self): # because we assume file is fully written, we can do all this stuff immediately for now: #e try/except too? self.open_file() self.read_header() return self.errcode def open_file(self): assert not self.fileobj #e if we relax this, then worry about whether we should seek to start of file self.fileobj = open(self.filename,'rb') ###@@@ missing file is possible when we reopen after closing; this is caught below def read_header(self): # assume we're at start of file # Read header (4 bytes) from file containing the number of frames in the moviefile. self.totalFramesActual = unpack('i',self.fileobj.read(4))[0] # Compute natoms filesize = os.path.getsize(self.filename) self.natoms = (filesize - 4) / (self.totalFramesActual * 3) if self.natoms * (self.totalFramesActual * 3) != (filesize - 4): msg = "Movie file [%s] has invalid length -- might be truncated or still being written." % self.filename # (Without knowing correct natoms (as we don't in this case), we can't reliably say whether it has # missing frames, partly written frames, etc.) # For new format files this would only be a warning; we could use the whole frames. # But for old-format files, it means our calc of natoms will be wrong for them! So it's fatal. self.error(msg) return # how far do we return, on error?? (I mean, should we raise an exception instead?) ###k return def error(self, msg): self.errcode = msg or "error" # public attr for callers to see... from utilities.Log import redmsg env.history.message( redmsg( msg)) return def delta_frame_bytes(self, n): """ return the bytes of the delta frame which has index n (assuming our file is open and n is within legal range) """ # note: the first one has index 1 (since it gives delta from time 0 to time 1). assert n > 0 nbytes = self.natoms * 3 # number of bytes in frame (if complete) -- no relation to frame index n filepos = ((n-1) * nbytes) + 4 try: # several things here can fail if file is changing on disk in various ways if not self.fileobj: # this might not yet ever happen, not sure. self.open_file() #e check for error? check length still the same, etc? self.fileobj.seek( filepos) ####@@@@ failure here might be possible if file got shorter after size measured -- not sure res = self.fileobj.read(nbytes) assert len(res) == nbytes # this can fail, if file got shorter after we measured its size... except: # might be good to detect, warn, set flag, return 0s.... ####@@@@ test this if debug_flags.atom_debug: # if this happens at all it might happen a lot... print_compact_traceback( "atom_debug: ignoring exception reading delta_frame %d, returning all 00s: " % n) res = "\x00" * nbytes assert len(res) == nbytes, "mistake in python zero-byte syntax" # but I checked it, should be ok return res def close(self): if self.fileobj: self.fileobj.close() self.fileobj = None close_file = close def destroy(self): self.close() return # no other large state in this object pass class OldFormatMovieFile: #bruce 050426 """ Know the filename and format of an existing moviefile, and enough about it to read requested frames from it and report absolute atom positions (even if those frames, or all frames in the file, are differential frames). Provide methods for renaming it (actually moving or copying the file), when this is safe. Sometimes keep it open with a known file pointer, for speed. Sometimes keep cached arrays of absolute positions (like key frames but perhaps computed rather than taken from the file), either for speed or since it's the only way to derive absolute positions from delta frames in the file. [#e Someday we'll work even on files that are still growing, but this probably won't be tried for Alpha5.] What we *don't* know includes: anything about the actual atoms (if any) being repositioned as this file is read; anything about associated files (like a tracefile) or sim run parameters (if any), except whatever might be needed to do our job of interpreting the one actual moviefile we know about. Possible generalizations: really we're one kind of "atom-set trajectory", and in future there might be other kinds which don't get their data from files. (E.g. an object to morph atom-set-positions smoothly between two endpoints.) """ ##e How to extend this class to the new movie file format: # split it into one superclass with the toplevel caching-logic, # and two subclasses (one per file format) with the lower-level skills # specific to how often those files contain key frames (never vs. regularly), # and their other differences. But note that this obj's job is not really to interpret # the general parts of the new-format file header, only the "trajectory part". # So probably some other object would parse the header and only then hand off the rest of the file # to one of these. def __init__(self, filereader): self.filereader = filereader # this has file pointer, knows filename & header, can read raw frames #e someday: # conceivably the file does not yet exist and this is not an error # (if we're being used on a still-growing file whose producer didn't quite start writing it yet), # so let's check these things as needed/requested rather than on init. # For now we'll just "know that we don't know them". # This might be best done using __getattr__... and perhaps some quantities # are different each time we look (like file length)... not yet decided. # # now: just assume the file is complete before we're called, and grab these things from filereader. # Q: But does the caller need to tell us the set of starting atom positions, # in case the file doesn't? What if it doesn't know (for new-format file being explored)? # A: the way it tells us is by calling donate_immutable_cached_frame if it needs to, # on any single frame it wants (often but not always frame 0). # Re bug 1297, it better give us sim-corrected positions rather than raw ones, for any open bonds! # (For more info on that see comment in get_sim_posns.) [bruce 060111] self.totalFramesActual = filereader.totalFramesActual self.natoms = filereader.natoms # maybe these should be the same object... not sure self.temp_mutable_frames = {} self.cached_immutable_frames = {} #e for some callers, store a cached frame 0 here def get_totalFramesActual(self): return self.totalFramesActual def matches_alist(self, alist): return self.natoms == len(alist) #e could someday check more... def recheck_matches_alist(self, alist): return self.matches_alist(alist) ###@@@ stub, fails to recheck the file! should verify same header and same or larger nframes. def destroy(self): self.cached_immutable_frames = self.temp_mutable_frames = None self.filereader.destroy() self.filereader = None def frame_index_in_range(self, n): assert type(n) == type(1) return 0 <= n <= self.totalFramesActual # I think inclusive at both ends is correct... def ref_to_transient_frame_n(self, n): """ [This is meant to be the main external method for retrieving our atom positions, when the caller cares about speed but doesn't need to keep this array (e.g. when it's playing us as a movie).] Return a Numeric array containing the absolute atom positions for frame n. Caller promises not to modify this array, and to never use it again after the next time anything calls any(??) method of this object. (Since we might keep modifying and returning the same mutable array, each time this method is called for the next n during a scan.) [#e Someday we might need to document some methods that are safe to call even while the caller still wants to use this array, and/or provide a scheme by which the caller can ask whether it's holding of that array remains valid or not -- note that several callers might have "different holdings of the same physical array" for which that answer differs. Note that a "copy on write" scheme (an alternative to much of this) might be better in the long run, but I'm not sure it's practical for Numeric arrays, or for advising self on which frames to keep and which to discard. """ res = self.copy_of_frame(n) # res is owned by this method-run... self.donate_mutable_known_frame(n, res) # ... but not anymore! # But since we're a private implem, we can depend on res still # being valid and constant right now, and until the next method # on self is called sometime after we return. return res def copy_of_frame(self, n): """ Return the array of absolute atom positions corresponding to the specified frame-number (0 = array of initial positions). If necessary, scan through the file as needed (from a key frame, in future format, or from the position of a frame whose abs posns we have cached, in old format) in order to figure this out. """ assert self.frame_index_in_range(n) n0 = self.nearest_knownposns_frame_index(n) frame0 = self.copy_of_known_frame_or_None(n0) # an array of absposns we're allowed to modify, valid for n0 assert frame0 is not None # don't test it as a boolean -- it might be all 0.0 which in Numeric means it's false! while n0 < n: # move forwards using a delta frame (which is never cached, tho this code doesn't need to know that) # (##e btw it might be faster to read several at once and combine them into one, or add all at once, using Numeric ops! # I'm not sure, since intermediate states would use 4x the memory, so we might do smaller pieces at a time...) n0 += 1 df = self.delta_frame(n0) # array of differences to add to frame n0-1 to get frame n0 try: frame0 += df # note: += modifies frame0 in place (if it's a Numeric array, as we hope); that's desired except ValueError: # frames are not aligned -- happens when slider reaches right end print "frames not aligned; shapes:",frame0.shape, df.shape raise while n0 > n: # (this never happens if we just moved forwards, but there's no need to "confirm" or "enforce" that fact) # move backwards using a delta frame # (btw it might be faster to read all dfs forwards to make one big one to subtract all at once... # or perhaps even to read them all at once into a single Numeric 2d array, and turn them into # one big one using Numeric ops! ###e) df = self.delta_frame(n0) n0 -= 1 # note: we did this after grabbing the frame, not beforehand as above frame0 -= df #e future: #e If we'd especially like to keep a cached copy for future speed, make one now... #e Or do this inside forward-going loop? #e Or in caller, having it stop for breath every so many frames, perhaps also to process user events? ## if 0: #bruce 060111 debug code (two places), safe but could be removed when not needed (tiny bit slow) [bruce 060111] ###@@@ ## # maybe print coords for one atom ## import runSim ## if runSim.debug_all_frames: ## ii = runSim.debug_all_frames_atom_index ## print "copy_of_frame %d[%d] is" % (n, ii), frame0[ii] return frame0 def donate_mutable_known_frame(self, n, frame): """ Caller has a frame of absolute atom positions it no longer needs -- add this to our cache of known frames, marked as able to be modified further as needed (i.e. as its data not needing to be retained in self after it's next returned by copy_of_known_frame_or_None). This optimizes serial scans of the file, since the donated frame tends to be one frame away from the next desired frame. """ self.temp_mutable_frames[n] = frame # it's probably ok if we already had one for the same n and this discards it -- # we don't really need more than one per n ###e do something to affect the retval of nearest_knownposns_frame_index?? it should optimize for the last one of these being near... return def donate_immutable_cached_frame(self, n, frame): # (this is how client code can tell us abs posns to start with) """ Caller gives us the frame of abs positions for frame-index n, which we can keep and will never modify (in case caller wants to keep using it too), and caller also promises to never modify it (so we can keep trusting and copying it). This is the only way for client code using us on an all-differential file can tell us a known absolute frame from which other absolute frames can be derived. Note that that known frame need not be frame 0, and perhaps will sometimes not be (I don't know, as of 050426 2pm). [As of shortly before 060111 it can indeed be any frame.] Note: these positions better be sim-corrected (as if X was H) rather than raw, for any open bonds! Otherwise we'll get bug 1297. In fact, they really need to be a copy of positions the sim had, not just newly corrected H positions (see get_sim_posns comment for more info). [bruce 060111] """ self.cached_immutable_frames[n] = frame # note: we only need one per n! so don't worry if this replaces an older one. ###e do something to affect the retval of nearest_knownposns_frame_index?? return def copy_of_known_frame_or_None(self, n): """ If we have a mutable known frame at index n, return it (and forget it internally since caller is allowed to modify it). If not, we should have an immutable one, or the file should have one (i.e. a key frame). Make a copy and return it. If we can't, return None (for some callers this will be an error; detecting it is up to them). """ try: return self.temp_mutable_frames.pop(n) except KeyError: try: #e we don't yet support files with key frames, so a cached one is our only chance. frame_notouch = self.cached_immutable_frames[n] except KeyError: return None else: return + frame_notouch # the unary "+" makes a copy (since it's a Numeric array) pass def nearest_knownposns_frame_index(self, n): """ Figure out and return n0, the nearest frame index to n for which we already know the absolute positions, either since it's a key frame in the file or since we've kept a cached copy of the positions (or been given those positions by our client code) -- either a mutable copy or an immutable one. (This index is suitable for passing to copy_of_known_frame_or_None, but that method might or might not have to actually copy anything in order to come up with a mutable frame to return.) By "nearest", we really mean "fastest to scan over the delta frames from n0 to n", so if scanning forwards is faster then we should be biased towards returning n0 < n, but this issue is ignored for now (and will become barely relevant once we use the new file format with frequent occurrence of key frames). It's not an error if n is out of range, but the returned n0 will always be in range. If we can't find *any* known frame, return None (but for most callers this will be an error). ###e better to asfail?? """ # It's common during sequential movie playing that the frame we want is 1 away from what we have... # so it's worth testing this quickly, at least for the mutable frames used during that process. # (In fact, this is probably more common than an exact match! So we test it first.) if n - 1 in self.temp_mutable_frames: return n - 1 if n + 1 in self.temp_mutable_frames: return n + 1 # It's also common than n is already known, so test that quickly too. if n in self.temp_mutable_frames or n in self.cached_immutable_frames: return n # No exact match. In present code, we won't have very many known frames, # so it's ok to just scan them all and find the one that's actually nearest. # (For future moviefile format with frequent key frames, we'll revise this quite a bit.) max_lower = too_low = -1 min_higher = too_high = 100000000000000000000000 # higher than any actual frame number (I hope!) for n0 in self.temp_mutable_frames.keys() + self.cached_immutable_frames.keys(): if n0 < n: max_lower = max( max_lower, n0) else: min_higher = min( min_higher, n0) if max_lower > too_low and min_higher != too_high: # which is best: scanning forwards by n - max_lower, or scanning backwards by min_higher - n ? if n - max_lower <= min_higher - n: return max_lower else: return min_higher elif max_lower > too_low: return max_lower elif min_higher != too_high: return min_higher else: assert 0, "no known frame!" # for now, since I think this should never happen (unless file of new format is very incomplete) return None pass def delta_frame(self, n): """ return the delta frame with index n, as an appropriately-typed Numeric array """ bytes = self.filereader.delta_frame_bytes(n) ## older code: delta = A(unpack('bbb',file.read(3)))*0.01 # (with luck, reading the whole frame at once will be a nice speedup for fast-forwarding...) res = array(bytes,Int8) res.shape = (-1,3) res = res * 0.01 #e it might be nice to move that multiply into caller (for speedup and error-reduction): #bruce 060110 comment: 0.01 is not represented exactly, so including it here might introduce cumulative # roundoff errors into callers who add up lots of delta frames! Let's estimate the size: assume 53 significant bits, # and typical values within 10^6 of 0, and need for 10^-3 precision, then we're using about 30 bits, # so an error in last bit, accumulating badly, still has say 1/4 * 2^23 = >> 10^6 steps to cause trouble... # and I think adding or subtracting this delta frame should reverse properly (same error gets added or removed), # except perhaps for special coord values that won't occur most times, so if true, what matters is movie length # rather than how often user plays it forwards and back. So I think we can tolerate this error for A7, at least, # and I think we can rule it out as a possible cause of bug 1297 (and an experiment also seems to rule that out). # [For the true cause, see 060111 comment in get_sim_posns.] # In the long run, we should fix this, though I never observed a problem. ####@@@@ ## if 0: #bruce 060111 debug code (two places), safe but could be removed when not needed (tiny bit slow) [bruce 060111] ###@@@ ## # maybe print deltas for one atom ## import runSim ## if runSim.debug_all_frames: ## ii = runSim.debug_all_frames_atom_index ## print "delta_frame %d[%d] is" % (n, ii), res[ii] return res def close_file(self): self.filereader.close_file() # but don't forget about it! pass # end of class MovieFile
NanoCAD-master
cad/src/files/dpb_trajectory/moviefile.py
NanoCAD-master
cad/src/files/dpb_trajectory/__init__.py
# Copyright 2008 Nanorex, Inc. See LICENSE file for details. """ files_in.py -- reading AMBER .in file fragments @author: EricM @version: $Id$ @copyright: 2008 Nanorex, Inc. See LICENSE file for details. """ # Various standard residues appear in AMBER data files with .in # extensions. These describe the residue with internal coordinates, # each atom placed with respect to other previously placed atoms. # Actual .in files in the AMBER source tree contain multiple residues, # each of which has data specified beyond just the z-matrix of # internal coordinates. This routine is designed to read a single # fragment from one of those files, where the fragment consists of # just the lines defining the z-matrix for a single residue. # Here is a sample of such a fragment, Glycene: # i igraph isymbl itree na nb nc r theta phi chrg # # 1 DUMM DU M 0 -1 -2 0.000 0.000 0.000 0.00000 # 2 DUMM DU M 1 0 -1 1.449 0.000 0.000 0.00000 # 3 DUMM DU M 2 1 0 1.522 111.100 0.000 0.00000 # 4 N N M 3 2 1 1.335 116.600 180.000 -0.374282 # 5 H H E 4 3 2 1.010 119.800 0.000 0.253981 # 6 CA CT M 4 3 2 1.449 121.900 180.000 -0.128844 # 7 HA2 H0 E 6 4 3 1.090 109.500 300.000 0.088859 # 8 HA3 H0 E 6 4 3 1.090 109.500 60.000 0.088859 # 9 C C M 6 4 3 1.522 110.400 180.000 0.580584 # 10 O O E 9 6 4 1.229 120.500 0.000 -0.509157 # The format is columns of data separated by whitespace. Different # AMBER .in files use different widths for the various columns. The # first column is the atom index number (i). The first three atoms # are dummy atoms, used to establish the coordinate system. # The second column is a unique atom name for each of the non-dummy # atoms (igraph). # The third column is the AMBER atom type (isymbl). # Column 4 is the topology for the atom (itree). It determines the # number of non-loop bonds. We're going to ignore this, and just # create a bond for each radius specification. # Columns 5, 6, and 7 are indices for three previous atoms (na, nb, # nc) # Columns 8, 9, and 10 are the radius (r), angle (theta), and torsion # angle (phi) parameters. # The last column is the fractional charge on the atom (chrg). We are # ignoring the charge here. # The radius parameter is in Angstroms, the angle and torsion # parameters are in degrees. # Taking line ten an an example, the Oxygen atom it represents is # 1.229 Angstroms away from Carbon atom number 9. The O-C-C angle # between atoms 10, 9, and 6 is 120.5 degrees. The O-C-C-N torsion # angle between atoms 10, 9, 6, and 4 is 0 degrees, indicating that # the O and N are on the same side of the C-C bond. # See: http://amber.scripps.edu/doc/prep.html import os from geometry.InternalCoordinatesToCartesian import InternalCoordinatesToCartesian from geometry.VQT import A from model.chunk import Chunk from model.chem import Atom from model.bonds import bond_atoms from model.elements import PeriodicTable AMBER_AtomTypes = {} _is_initialized = False def _init(): global _is_initialized if (_is_initialized): return AMBER_AtomTypes["C"] = PeriodicTable.getElement("C").find_atomtype("sp2") AMBER_AtomTypes["CA"] = PeriodicTable.getElement("C").find_atomtype("sp2") AMBER_AtomTypes["CB"] = PeriodicTable.getElement("C").find_atomtype("sp2") AMBER_AtomTypes["CC"] = PeriodicTable.getElement("C").find_atomtype("sp2") AMBER_AtomTypes["CD"] = PeriodicTable.getElement("C").find_atomtype("sp2") AMBER_AtomTypes["CK"] = PeriodicTable.getElement("C").find_atomtype("sp2") AMBER_AtomTypes["CM"] = PeriodicTable.getElement("C").find_atomtype("sp2") AMBER_AtomTypes["CN"] = PeriodicTable.getElement("C").find_atomtype("sp2") AMBER_AtomTypes["CQ"] = PeriodicTable.getElement("C").find_atomtype("sp2") AMBER_AtomTypes["CR"] = PeriodicTable.getElement("C").find_atomtype("sp2") AMBER_AtomTypes["CT"] = PeriodicTable.getElement("C").find_atomtype("sp3") AMBER_AtomTypes["CV"] = PeriodicTable.getElement("C").find_atomtype("sp2") AMBER_AtomTypes["CW"] = PeriodicTable.getElement("C").find_atomtype("sp2") AMBER_AtomTypes["C*"] = PeriodicTable.getElement("C").find_atomtype("sp2") AMBER_AtomTypes["CY"] = PeriodicTable.getElement("C").find_atomtype("sp") AMBER_AtomTypes["CZ"] = PeriodicTable.getElement("C").find_atomtype("sp") AMBER_AtomTypes["C0"] = PeriodicTable.getElement("Ca").find_atomtype("?") AMBER_AtomTypes["H"] = PeriodicTable.getElement("H").find_atomtype("?") AMBER_AtomTypes["H0"] = PeriodicTable.getElement("H").find_atomtype("?") AMBER_AtomTypes["HC"] = PeriodicTable.getElement("H").find_atomtype("?") AMBER_AtomTypes["H1"] = PeriodicTable.getElement("H").find_atomtype("?") AMBER_AtomTypes["H2"] = PeriodicTable.getElement("H").find_atomtype("?") AMBER_AtomTypes["H3"] = PeriodicTable.getElement("H").find_atomtype("?") AMBER_AtomTypes["HA"] = PeriodicTable.getElement("H").find_atomtype("?") AMBER_AtomTypes["H4"] = PeriodicTable.getElement("H").find_atomtype("?") AMBER_AtomTypes["H5"] = PeriodicTable.getElement("H").find_atomtype("?") AMBER_AtomTypes["HO"] = PeriodicTable.getElement("H").find_atomtype("?") AMBER_AtomTypes["HS"] = PeriodicTable.getElement("H").find_atomtype("?") AMBER_AtomTypes["HW"] = PeriodicTable.getElement("H").find_atomtype("?") AMBER_AtomTypes["HP"] = PeriodicTable.getElement("H").find_atomtype("?") AMBER_AtomTypes["HZ"] = PeriodicTable.getElement("H").find_atomtype("?") AMBER_AtomTypes["F"] = PeriodicTable.getElement("F").find_atomtype("?") AMBER_AtomTypes["Cl"] = PeriodicTable.getElement("Cl").find_atomtype("?") AMBER_AtomTypes["Br"] = PeriodicTable.getElement("Br").find_atomtype("?") AMBER_AtomTypes["I"] = PeriodicTable.getElement("I").find_atomtype("?") AMBER_AtomTypes["IM"] = PeriodicTable.getElement("Cl").find_atomtype("?") AMBER_AtomTypes["IB"] = PeriodicTable.getElement("Na").find_atomtype("?") AMBER_AtomTypes["MG"] = PeriodicTable.getElement("Mg").find_atomtype("?") AMBER_AtomTypes["N"] = PeriodicTable.getElement("N").find_atomtype("sp2") AMBER_AtomTypes["NA"] = PeriodicTable.getElement("N").find_atomtype("sp2") AMBER_AtomTypes["NB"] = PeriodicTable.getElement("N").find_atomtype("sp2") AMBER_AtomTypes["NC"] = PeriodicTable.getElement("N").find_atomtype("sp2") AMBER_AtomTypes["N2"] = PeriodicTable.getElement("N").find_atomtype("sp2") AMBER_AtomTypes["N3"] = PeriodicTable.getElement("N").find_atomtype("sp3") AMBER_AtomTypes["NT"] = PeriodicTable.getElement("N").find_atomtype("sp3") AMBER_AtomTypes["N*"] = PeriodicTable.getElement("N").find_atomtype("sp2") AMBER_AtomTypes["NY"] = PeriodicTable.getElement("N").find_atomtype("sp") AMBER_AtomTypes["O"] = PeriodicTable.getElement("O").find_atomtype("sp2") AMBER_AtomTypes["O2"] = PeriodicTable.getElement("O").find_atomtype("sp2") AMBER_AtomTypes["OW"] = PeriodicTable.getElement("O").find_atomtype("sp3") AMBER_AtomTypes["OH"] = PeriodicTable.getElement("O").find_atomtype("sp3") AMBER_AtomTypes["OS"] = PeriodicTable.getElement("O").find_atomtype("sp3") AMBER_AtomTypes["P"] = PeriodicTable.getElement("P").find_atomtype("sp3(p)") #sp3(p) is 'sp3(phosphate) AMBER_AtomTypes["S"] = PeriodicTable.getElement("S").find_atomtype("sp3") # ? AMBER_AtomTypes["SH"] = PeriodicTable.getElement("S").find_atomtype("sp3") # ? AMBER_AtomTypes["CU"] = PeriodicTable.getElement("Cu").find_atomtype("?") AMBER_AtomTypes["FE"] = PeriodicTable.getElement("Fe").find_atomtype("?") AMBER_AtomTypes["Li"] = PeriodicTable.getElement("Li").find_atomtype("?") AMBER_AtomTypes["IP"] = PeriodicTable.getElement("Na").find_atomtype("?") AMBER_AtomTypes["Na"] = PeriodicTable.getElement("Na").find_atomtype("?") AMBER_AtomTypes["K"] = PeriodicTable.getElement("K").find_atomtype("?") #AMBER_AtomTypes["Rb"] = PeriodicTable.getElement("Rb").find_atomtype("?") #AMBER_AtomTypes["Cs"] = PeriodicTable.getElement("Cs").find_atomtype("?") AMBER_AtomTypes["Zn"] = PeriodicTable.getElement("Zn").find_atomtype("?") _is_initialized = True def insertin(assy, filename): _init() dir, nodename = os.path.split(filename) mol = Chunk(assy, nodename) mol.showOverlayText = True file = open(filename) lines = file.readlines() atoms = {} transform = InternalCoordinatesToCartesian(len(lines), None) for line in lines: columns = line.strip().split() index = int(columns[0]) name = columns[1] type = columns[2] na = int(columns[4]) nb = int(columns[5]) nc = int(columns[6]) r = float(columns[7]) theta = float(columns[8]) phi = float(columns[9]) transform.addInternal(index, na, nb, nc, r, theta, phi) xyz = transform.getCartesian(index) if (index > 3): if (AMBER_AtomTypes.has_key(type)): sym = AMBER_AtomTypes[type] else: print "unknown AMBER atom type, substituting Carbon: %s" % type sym = "C" a = Atom(sym, A(xyz), mol) atoms[index] = a a.setOverlayText(type) if (na > 3): a2 = atoms[na] bond_atoms(a, a2) assy.addmol(mol)
NanoCAD-master
cad/src/files/amber_in/files_in.py
NanoCAD-master
cad/src/files/amber_in/__init__.py
NanoCAD-master
cad/src/files/pdb/__init__.py
# Copyright 2004-2008 Nanorex, Inc. See LICENSE file for details. """ files_pdb.py -- reading and writing PDB files @version: $Id$ @copyright: 2004-2008 Nanorex, Inc. See LICENSE file for details. History: This was part of fileIO.py, until bruce 050414 started splitting that into separate modules for each file format. bruce 070410 added some hacks to read more pdb files successfully -- but they need review by someone who knows whether they're correct or not. (I'll commit this to both branches, Qt3 & Qt4, since this file is presently identical in both, so doing that should not cause a problem.) """ import os, time from model.chunk import Chunk from model.chem import Atom from model.bonds import bond_atoms from operations.bonds_from_atoms import inferBonds from string import capitalize from model.elements import PeriodicTable, Singlet from platform_dependent.PlatformDependent import fix_plurals from utilities.Log import redmsg, orangemsg from geometry.VQT import A from utilities.version import Version from utilities.debug_prefs import debug_pref, Choice_boolean_False from datetime import datetime from model.Comment import Comment from foundation.Group import Group import foundation.env as env from utilities.constants import gensym from protein.model.Protein import Protein from protein.model.Residue import Residue def _readpdb(assy, filename, isInsert = False, showProgressDialog = False, chainId = None): """ Read a Protein DataBank-format file into a single new chunk, which is returned unless there are no atoms in the file, in which case a warning is printed and None is returned. (The new chunk (if returned) is in assy, but is not yet added into any Group or Part in assy -- caller must do that.) Unless isInsert = True, set assy.filename to match the file we read, even if we return None. @param assy: The assembly. @type assy: L{assembly} @param filename: The PDB filename to read. @type filename: string @param isInsert: If True, the PDB file will be inserted into the current assembly. If False (default), the PDB is opened as the assembly. @param isInsert: boolean @param showProgressDialog: if True, display a progress dialog while reading a file. @type showProgressDialog: boolean @return: A chunk containing the contents of the PDB file. @rtype: L{Chunk} @see: U{B{PDB File Format}<http://www.wwpdb.org/documentation/format23/v2.3.html>} """ fi = open(filename,"rU") lines = fi.readlines() fi.close() dir, nodename = os.path.split(filename) if not isInsert: assy.filename = filename ndix = {} mol = Chunk(assy, nodename) numconects = 0 atomname_exceptions = { "HB":"H", #k these are all guesses -- I can't find this documented # anywhere [bruce 070410] ## "HE":"H", ### REVIEW: I'm not sure about this one -- ### leaving it out means it's read as Helium, # but including it erroneously might prevent reading an actual Helium # if that was intended. # Guess for now: include it for ATOM but not HETATM. (So it's # specialcased below, rather than being included in this table.) # (Later: can't we use the case of the 'E' to distinguish it from He?) "HN":"H", } # Create and display a Progress dialog while reading the MMP file. # One issue with this implem is that QProgressDialog always displays # a "Cancel" button, which is not hooked up. I think this is OK for now, # but later we should either hook it up or create our own progress # dialog that doesn't include a "Cancel" button. --mark 2007-12-06 if showProgressDialog: _progressValue = 0 _progressFinishValue = len(lines) win = env.mainwindow() win.progressDialog.setLabelText("Reading file...") win.progressDialog.setRange(0, _progressFinishValue) _progressDialogDisplayed = False _timerStart = time.time() for card in lines: key = card[:6].lower().replace(" ", "") if key in ["atom", "hetatm"]: ## sym = capitalize(card[12:14].replace(" ", "").replace("_", "")) # bruce 080508 revision (guess at a bugfix for reading NE1-saved # pdb files): # get a list of atomnames to try; use the first one we recognize. # Note that full atom name is in columns 13-16 i.e. card[12:16]; # see http://www.wwpdb.org/documentation/format2.3-0108-us.pdf, # page 156. The old code only looked at two characters, # card[12:14] == columns 13-14, and discarded ' ' and '_', # and capitalized (the first character only). The code as I revised # it on 070410 also discarded digits, and handled HB, HE, HN # (guesses) using the atomname_exceptions dict. name4 = card[12:16].replace(" ", "").replace("_", "") name3 = card[12:15].replace(" ", "").replace("_", "") name2 = card[12:14].replace(" ", "").replace("_", "") def nodigits(name): for bad in "0123456789": name = name.replace(bad, "") return name atomnames_to_try = [ name4, # as seems best according to documentation name3, name2, # like old code nodigits(name4), nodigits(name3), nodigits(name2) # like code as revised on 070410 ] foundit = False for atomname in atomnames_to_try: atomname = atomname_exceptions.get(atomname, atomname) if atomname == "HE" and key == "atom": atomname = "H" # see comment in atomname_exceptions sym = capitalize(atomname) # turns either 'he' or 'HE' into 'He' try: PeriodicTable.getElement(sym) except: # note: this typically fails with AssertionError # (not e.g. KeyError) [bruce 050322] continue else: foundit = True break pass if not foundit: msg = "Warning: Pdb file: will use Carbon in place of unknown element %s in: %s" \ % (name4, card) print msg #bruce 070410 added this print env.history.message( redmsg( msg )) ##e It would probably be better to create a fake atom, so the # CONECT records would still work. #bruce 080508 let's do that: sym = "C" # Better still might be to create a fake element, # so we could write out the pdb file again # (albeit missing lots of info). [bruce 070410 comment] # Note: an advisor tells us: # PDB files sometimes encode atomtypes, # using C_R instead of C, for example, to represent sp2 # carbons. # That particular case won't trigger this exception, since we # only look at 2 characters [eventually, after trying more, as of 080508], # i.e. C_ in that case. It would be better to realize this means # sp2 and set the atomtype here (and perhaps then use it when # inferring bonds, which we do later if the file doesn't have # any bonds). [bruce 060614/070410 comment] # Now the element name is in sym. xyz = map(float, [card[30:38], card[38:46], card[46:54]] ) n = int(card[6:11]) a = Atom(sym, A(xyz), mol) ndix[n] = a elif key == "conect": try: a1 = ndix[int(card[6:11])] except: #bruce 050322 added this level of try/except and its message; # see code below for at least two kinds of errors this might # catch, but we don't try to distinguish these here. BTW this # also happens as a consequence of not finding the element # symbol, above, since atoms with unknown elements are not # created. env.history.message( redmsg( "Warning: Pdb file: can't find first atom in CONECT record: %s" % (card,) )) else: for i in range(11, 70, 5): try: a2 = ndix[int(card[i:i+5])] except ValueError: # bruce 050323 comment: # we assume this is from int('') or int(' ') etc; # this is the usual way of ending this loop. break except KeyError: #bruce 050322-23 added history warning for this, # assuming it comes from ndix[] lookup. env.history.message( redmsg( "Warning: Pdb file: can't find atom %s in: %s" % (card[i:i+5], card) )) continue bond_atoms(a1, a2) numconects += 1 if showProgressDialog: # Update the progress dialog. _progressValue += 1 if _progressValue >= _progressFinishValue: win.progressDialog.setLabelText("Building model...") elif _progressDialogDisplayed: win.progressDialog.setValue(_progressValue) else: _timerDuration = time.time() - _timerStart if _timerDuration > 0.25: # Display progress dialog after 0.25 seconds win.progressDialog.setValue(_progressValue) _progressDialogDisplayed = True if showProgressDialog: # Make the progress dialog go away. win.progressDialog.setValue(_progressFinishValue) #bruce 050322 part of fix for bug 433: don't return an empty chunk if not mol.atoms: env.history.message( redmsg( "Warning: Pdb file contained no atoms")) return None if numconects == 0: msg = orangemsg("PDB file has no bond info; inferring bonds") env.history.message(msg) # let user see message right away (bond inference can take significant # time) [bruce 060620] env.history.h_update() inferBonds(mol) return mol # PDB atom types for proteins. Assumes that the remaining atom types # have default hybridizations. PROTEIN_ATOM_TYPES = { "ANY" : { "N" : "sp2(graphitic)", # these atom types are common for all amino "C" : "sp2", # acids "O" : "sp2" }, "PHE" : { "CG" : "sp2aro", # "sp2a" is an sp2 atom connected to another sp2a atom "CD1" : "sp2aro", # with an aromatic bond "CE1" : "sp2aro", "CZ" : "sp2aro", "CE2" : "sp2aro", "CD2" : "sp2aro" }, "GLU" : { "CD" : "sp2", "OE1" : "sp2" }, "GLN" : { "CD" : "sp2", "OE1" : "sp2" }, "ASP" : { "CG" : "sp2", "OD1" : "sp2" }, "ASN" : { "CG" : "sp2", "OD1" : "sp2" }, "TRP" : { "CG" : "sp2", "CD1" : "sp2", "CE2" : "sp2aro", "CZ2" : "sp2aro", "CH2" : "sp2aro", "CZ3" : "sp2aro", "CE3" : "sp2aro", "CD2" : "sp2aro" }, "TYR" : { "CG" : "sp2aro", "CD1" : "sp2aro", "CE1" : "sp2aro", "CZ" : "sp2aro", "CE2" : "sp2aro", "CD2" : "sp2aro" }, "ARG" : { "CZ" : "sp2", "NH2" : "sp2" }, "HIS" : { "CG" : "sp2", "CE1" : "sp2a", "NE2" : "sp2a", # Two "sp2s" atoms are connected with a bond "CD2" : "sp2" } } # of order 1. I introduced this temporary marker # to describe conjugated double bond systems. # If the one of the "a", "b", or "c" markers # is specified, only the atoms sharing the # same marker will be double-bonded. # " DG", "DC", "DT", and " DA" names correspond to deoxynucleotides # as defined in PDB format >= 3.0 # Older versions didn't distinguish between RNA and DNA base names # so both compounds used " G", " C", " A", " T" (and " U" in case of # RNA) NUCLEIC_ATOM_TYPES = { " DC" : { "P" : "sp3(p)", # phosphate phosphorus "OP1" : "sp2(-.5)", # and two negatively charged oxygens "OP2" : "sp2(-.5)", "C2" : "sp2a", "O2" : "sp2a", "C4" : "sp2b", "N3" : "sp2b", "C5" : "sp2a", "C6" : "sp2a" }, " DG" : { "P" : "sp3(p)", "OP1" : "sp2(-.5)", "OP2" : "sp2(-.5)", "C4" : "sp2b", "C5" : "sp2b", "C8" : "sp2a", "N7" : "sp2a", "C2" : "sp2a", "N3" : "sp2a", "C6" : "sp2c", "O6" : "sp2c" }, " DA" : { "P" : "sp3(p)", "OP1" : "sp2(-.5)", "OP2" : "sp2(-.5)", "C2" : "sp2a", "N3" : "sp2a", "C6" : "sp2b", "N1" : "sp2b", "N4" : "sp2b", "C4" : "sp2c", "C5" : "sp2c", "N7" : "sp2a", "C8" : "sp2a" }, " DT" : { "P" : "sp3(p)", "OP1" : "sp2(-.5)", "OP2" : "sp2(-.5)", "C5" : "sp2a", "C6" : "sp2a", "C4" : "sp2b", "O4" : "sp2b", "C2" : "sp2a", "O2" : "sp2a" }, " C" : { "P" : "sp3(p)", "O1P" : "sp2(-.5)", "O2P" : "sp2(-.5)", "C2" : "sp2a", "O2" : "sp2a", "C4" : "sp2b", "N3" : "sp2b", "C5" : "sp2a", "C6" : "sp2a" }, " G" : { "P" : "sp3(p)", "O1P" : "sp2(-.5)", "O2P" : "sp2(-.5)", "C4" : "sp2b", "C5" : "sp2b", "C8" : "sp2a", "N7" : "sp2a", "C2" : "sp2a", "N3" : "sp2a", "C6" : "sp2c", "O6" : "sp2c" }, " A" : { "P" : "sp3(p)", "O1P" : "sp2(-.5)", "O2P" : "sp2(-.5)", "C2" : "sp2a", "N3" : "sp2a", "C6" : "sp2b", "N1" : "sp2b", "N4" : "sp2b", "C4" : "sp2c", "C5" : "sp2c", "N7" : "sp2a", "C8" : "sp2a" }, " T" : { "P" : "sp3(p)", "O1P" : "sp2(-.5)", "O2P" : "sp2(-.5)", "C5" : "sp2a", "C6" : "sp2a", "C4" : "sp2b", "O4" : "sp2b", "C2" : "sp2a", "O2" : "sp2a" }, } # Important notes: (piotr 080909) # # - the PDB reading code can read standard Protein Data Bank files and preserve # ATOM and HETATM record information, so the molecules can be exported as PDB # and recognized by other programs # # - not all information contained in PDB files is preserved, only per-atom fields # # - only first model is read from multi-model files, # # - "Heteroatoms" group is created in Model Tree even if there are no heteroatoms # # - inferBonds method is used to rebuild bonds for proteins and DNA. This should # be replaced by bond assignment using pattern matching. Currently, only # proper bond orders are assigned for standard residues, but connectivity # is computed using the inferBonds method. # # - PAM3 and PAM5 models can be written and read using the new code, # although - as it was before - the internal DNA representation is not preserved # # - the old PDB I/O code still remains there, and will be used if ENABLE_PROTEINS # debug pref is set to False (perhaps this behavior should be controlled by # another debug pref) def _readpdb_new(assy, filename, isInsert = False, showProgressDialog = False, chainId = None): """ Read a Protein DataBank-format file into a single new chunk, which is returned unless there are no atoms in the file, in which case a warning is printed and None is returned. (The new chunk (if returned) is in assy, but is not yet added into any Group or Part in assy -- caller must do that.) Unless isInsert = True, set assy.filename to match the file we read, even if we return None. @param assy: The assembly. @type assy: L{assembly} @param filename: The PDB filename to read. @type filename: string @param isInsert: If True, the PDB file will be inserted into the current assembly. If False (default), the PDB is opened as the assembly. @param isInsert: boolean @param showProgressDialog: if True, display a progress dialog while reading a file. @type showProgressDialog: boolean @return: A chunk containing the contents of the PDB file. @rtype: L{Chunk} @see: U{B{PDB File Format}<http://www.wwpdb.org/documentation/format23/v2.3.html>} """ # These methods should be probably moved to this file. from protein.model.Protein import is_water, is_amino_acid, is_nucleotide def _add_bondpoints(mol): """ Adds missing bondpoints to a molecule. @param mol: molecule @type mol: Chunk """ atlist = [atom for (key, atom) in mol.atoms.items()] for atom in atlist: atom.make_enough_bondpoints() def _set_atom_type(atom, atom_name, res_name): """ Assigns an atom type based on atom name and residue name by simple name pattern matching. @param atom_name: PDB name of the atom @type atom_name: string @param res_name: PDB residue name @type res_name: string """ atom.setOverlayText(atom_name) _assigned = False ### print (res_name, atom_name) # Look for the atom type and set the type if PROTEIN_ATOM_TYPES.has_key(res_name): # Found a protein residue. atom_type_dict = PROTEIN_ATOM_TYPES[res_name] if atom_type_dict.has_key(atom_name): # Found the atom. atom_type = atom_type_dict[atom_name] if atom_type == "sp2a": sp2a_atoms.append(atom) atom_type = "sp2" if atom_type == "sp2c": sp2c_atoms.append(atom) atom_type = "sp2" if atom_type == "sp2b": sp2b_atoms.append(atom) atom_type = "sp2" if atom_type == "sp2aro": aromatic_atoms.append(atom) atom_type = "sp2" atom.set_atomtype_but_dont_revise_singlets(atom_type) _assigned = True elif NUCLEIC_ATOM_TYPES.has_key(res_name): # Found a nucleic acid residue atom_type_dict = NUCLEIC_ATOM_TYPES[res_name] if atom_type_dict.has_key(atom_name): # Found the atom. atom_type = atom_type_dict[atom_name] if atom_type == "sp2a": sp2a_atoms.append(atom) atom_type = "sp2" if atom_type == "sp2b": sp2b_atoms.append(atom) atom_type = "sp2" if atom_type == "sp2c": sp2c_atoms.append(atom) atom_type = "sp2" atom.set_atomtype_but_dont_revise_singlets(atom_type) _assigned = True if not _assigned: # Look for common atom types (N, C, O) atom_type_dict = PROTEIN_ATOM_TYPES["ANY"] # For remaining residues, look at one of the standard atom types if atom_type_dict.has_key(atom_name): atom_type = atom_type_dict[atom_name] atom.set_atomtype_but_dont_revise_singlets(atom_type) def _finalize_molecule(): """ Performs some operations after reading the entire PDB chain: - rebuild (infer) bonds for protein and DNA chains - assigns proper bond orders for standard residues - renames molecule to reflect a chain ID - deletes the "protein" attribute if it is not a protein - appends the molecule to the molecule list """ if mol == water: # Skip water, to be added to the mollist explicitly at the end. return if mol.atoms: # Create a molecule name by concatenating PDB ID and chain ID mol.name = pdbid.lower() + chainId if mol.protein.count_c_alpha_atoms() == 0 and \ not dont_split: # If there are C-alpha atoms and dont_split flag is not set, # consider the chunk non-protein. # Create a heteromolecule name mol.name = resName + '[' + resId.replace(' ','') + ']' hetgroup.addchild(mol) else: # For protein - infer the bonds anyway. This should be replaced # by a proper atom / bond type assignment, for example using # the templates present in the Peptide Generator. piotr 081908 inferBonds(mol) aromatic_atom_list = [] single_bonded_atom_list = [] # This is a protein. # Assign proper atom types according to protein templates. # amino_acid_list = mol.protein.get_amino_acids() #for aa in amino_acid_list: # aromatic, single_bonded = set_protein_atom_type(atom, # Assign bond orders. piotr 081908 from model.bond_constants import V_DOUBLE, V_AROMATIC, V_GRAPHITE # Inferring bond types for atom in mol.atoms.itervalues(): if atom.bonds: for bond in atom.bonds: atom1_type = bond.atom1.getAtomTypeName() atom2_type = bond.atom2.getAtomTypeName() if (atom1_type == "sp2" and atom2_type == "sp2"): if (bond.atom1 in aromatic_atoms and bond.atom2 in aromatic_atoms): bond.set_v6(V_AROMATIC) elif ((bond.atom1 in sp2a_atoms and bond.atom2 in sp2a_atoms) or (bond.atom1 in sp2b_atoms and bond.atom2 in sp2b_atoms) or (bond.atom1 in sp2c_atoms and bond.atom2 in sp2c_atoms) or (bond.atom1 not in sp2a_atoms and bond.atom1 not in sp2b_atoms and bond.atom1 not in sp2c_atoms and bond.atom1 not in aromatic_atoms)): bond.set_v6(V_DOUBLE) # for phosphate P - charged oxygen bond: assign V_GRAPHITE if ((atom1_type == "sp3(p)" and atom2_type == "sp2(-.5)") or ((atom2_type == "sp3(p)" and atom1_type == "sp2(-.5)"))): bond.set_v6(V_GRAPHITE) if mol.protein.count_c_alpha_atoms() == 0: # It is not a protein molecule: remove the protein information. mol.protein = None else: # Set the PDB information (chain ID and PDB code) mol.protein.set_chain_id(chainId) mol.protein.set_pdb_id(pdbid) # Add the molecule to mollist mollist.append(mol) # Create bondpoints for easy hydrogenation _add_bondpoints(mol) else: env.history.message( redmsg( "Warning: PDB residue contained no atoms")) env.history.h_update() pass pass # _finalize_molecule # Read the file contents. fi = open(filename,"rU") lines = fi.readlines() fi.close() assy.part.ensure_toplevel_group() aromatic_atoms = [] sp2a_atoms = [] sp2b_atoms = [] sp2c_atoms = [] # List of molecules read from PDB file. mollist = [] # Lists of secondary structure tuples (res_id, chain_id) helix = [] sheet = [] turn = [] dir, nodename = os.path.split(filename) if not isInsert: assy.filename = filename # dictionary for HETATM connectivity reconstruction ndix = {} lastResId = None # Create a molecule chunk mol = Chunk(assy, nodename) mol.protein = Protein() dont_split = False hetgroup = Group("Heteroatoms", assy, assy.part.topnode) # Create a chunk to store water molecules. water = Chunk(assy, nodename) numconects = 0 comment_text = "" _read_rosetta_info = False comment_title = "PDB Header" # Create a temporary PDB ID - it should be later extracted from the # file header. pdbid = nodename.replace(".pdb","").lower() atomname_exceptions = { "HB":"H", #k these are all guesses -- I can't find this documented # anywhere [bruce 070410] "CA":"C", "NE":"N", "HG":"H", ## "HE":"H", ### REVIEW: I'm not sure about this one -- ### leaving it out means it's read as Helium, # but including it erroneously might prevent reading an actual Helium # if that was intended. # Guess for now: include it for ATOM but not HETATM. (So it's # specialcased below, rather than being included in this table.) # (Later: can't we use the case of the 'E' to distinguish it from He?) "HN":"H", } # Create and display a Progress dialog while reading the MMP file. # One issue with this implem is that QProgressDialog always displays # a "Cancel" button, which is not hooked up. I think this is OK for now, # but later we should either hook it up or create our own progress # dialog that doesn't include a "Cancel" button. --mark 2007-12-06 if showProgressDialog: _progressValue = 0 _progressFinishValue = len(lines) win = env.mainwindow() win.progressDialog.setLabelText("Reading file...") win.progressDialog.setRange(0, _progressFinishValue) _progressDialogDisplayed = False _timerStart = time.time() for card in lines: key = card[:6].lower().replace(" ", "") if key in ["atom", "hetatm"]: # Set _is_hetero flag for HETATM if key == "atom": _is_hetero = False else: _is_hetero = True ## sym = capitalize(card[12:14].replace(" ", "").replace("_", "")) # bruce 080508 revision (guess at a bugfix for reading NE1-saved # pdb files): # get a list of atomnames to try; use the first one we recognize. # Note that full atom name is in columns 13-16 i.e. card[12:16]; # see http://www.wwpdb.org/documentation/format2.3-0108-us.pdf, # page 156. The old code only looked at two characters, # card[12:14] == columns 13-14, and discarded ' ' and '_', # and capitalized (the first character only). The code as I revised # it on 070410 also discarded digits, and handled HB, HE, HN # (guesses) using the atomname_exceptions dict. name4 = card[12:16].replace(" ", "").replace("_", "") name3 = card[12:15].replace(" ", "").replace("_", "") name2 = card[12:14].replace(" ", "").replace("_", "") chainId = card[21] resId = card[22:26].replace(" ", "") + card[27] if lastResId == None: lastResId = resId resName = card[17:20] _is_water = is_water(resName) _is_amino_acid = is_amino_acid(resName) _is_nucleotide = is_nucleotide(resName) sym = card[77:79] # Element symbol alt = card[16] # Alternate location indicator if alt != ' ' and \ alt != 'A': # Skip non-standard alternate location # This is not very safe test, it should preserve # the remaining atoms. piotr 080715 continue ###ATOM 131 CB ARG A 18 104.359 32.924 58.573 1.00 36.93 C def nodigits(name): for bad in "0123456789": name = name.replace(bad, "") return name atomnames_to_try = [ name4, # as seems best according to documentation name3, name2, # like old code nodigits(name4), nodigits(name3), nodigits(name2) # like code as revised on 070410 ] # piotr 080819: first look at the 77-78 field - it should include # the element symbol. foundit = False try: PeriodicTable.getElement(sym) except: pass else: foundit = True # if not found, look at possible atom names if not foundit: for atomname in atomnames_to_try: atomname = atomname_exceptions.get(atomname, atomname) if atomname[0] == 'H' and key == "atom": atomname = "H" # see comment in atomname_exceptions sym = capitalize(atomname) # turns either 'he' or 'HE' into 'He' try: PeriodicTable.getElement(sym) except: # note: this typically fails with AssertionError # (not e.g. KeyError) [bruce 050322] continue else: foundit = True break pass if not foundit: msg = "Warning: Pdb file: will use Carbon in place of unknown element %s in: %s" \ % (name4, card) print msg #bruce 070410 added this print env.history.message( redmsg( msg )) ##e It would probably be better to create a fake atom, so the # CONECT records would still work. #bruce 080508 let's do that: sym = "C" # Better still might be to create a fake element, # so we could write out the pdb file again # (albeit missing lots of info). [bruce 070410 comment] # Note: an advisor tells us: # PDB files sometimes encode atomtypes, # using C_R instead of C, for example, to represent sp2 # carbons. # That particular case won't trigger this exception, since we # only look at 2 characters [eventually, after trying more, as of 080508], # i.e. C_ in that case. It would be better to realize this means # sp2 and set the atomtype here (and perhaps then use it when # inferring bonds, which we do later if the file doesn't have # any bonds). [bruce 060614/070410 comment] # Now the element name is in sym. xyz = map(float, [card[30:38], card[38:46], card[46:54]] ) n = int(card[6:11]) if resId != lastResId and \ not _is_amino_acid and \ not _is_nucleotide and \ not _is_water: # Finalize current molecule. _finalize_molecule() # Discard the original molecule and create a new one. mol = Chunk(assy, nodename) mol.protein = Protein() dont_split = False if _is_water: # If this is a water molecule, add the atom to the Water chunk a = Atom(sym, A(xyz), water) else: # Otherwise, add it to the current molecule. a = Atom(sym, A(xyz), mol) # Store PDB information in the Atom object pdb_info dict. if not a.pdb_info: # Create the pdb_info dictionary if it doesn't exist. a.pdb_info = {} # Store PDB atom properties in the pdb_info dict a.pdb_info['atom_name'] = name4 a.pdb_info['residue_id'] = resId a.pdb_info['residue_name'] = resName a.pdb_info['chain_id'] = chainId if not _is_hetero: # The 'standard_atom' key represents a bool value set to # true if this atom is "standard PDB atom", e.g. it was # read from ATOM record. a.pdb_info['standard_atom'] = True # Normally, the connectivity information is only available # for HETATM records. But other programs can write CONECT info # for ATOM records, as well. ndix[n] = a if _is_amino_acid or \ _is_nucleotide: # Don't split proteins or nucleotides into individual # residues. What about carbohydrates? piotr 081908 dont_split = True if not _is_water: # Adds the atom to the "protein" chunk. mol.protein.add_pdb_atom(a, name4, resId, resName, setType=True) if _is_amino_acid or \ _is_nucleotide: # Recognize atom type by pattern matching of the atom name. # Do this only for proteins and nucleic acids. _set_atom_type(a, name4, resName) # Assign one of three types of secondary structure. if (resId, chainId) in helix: # helix mol.protein.assign_helix(resId) if (resId, chainId) in sheet: # extended mol.protein.assign_strand(resId) if (resId, chainId) in turn: # turn mol.protein.assign_turn(resId) # Remember the most recent resId lastResId = resId elif key == "conect": try: a1 = ndix[int(card[6:11])] except: #bruce 050322 added this level of try/except and its message; # see code below for at least two kinds of errors this might # catch, but we don't try to distinguish these here. BTW this # also happens as a consequence of not finding the element # symbol, above, since atoms with unknown elements are not # created. env.history.message( redmsg( "Warning: Pdb file: can't find first atom in CONECT record: %s" % (card,) )) else: for i in range(11, 70, 5): try: a2 = ndix[int(card[i:i+5])] except ValueError: # bruce 050323 comment: # we assume this is from int('') or int(' ') etc; # this is the usual way of ending this loop. break except KeyError: #bruce 050322-23 added history warning for this, # assuming it comes from ndix[] lookup. env.history.message( redmsg( "Warning: Pdb file: can't find atom %s in: %s" % (card[i:i+5], card) )) continue bond_atoms(a1, a2) numconects += 1 elif key == "ter": # Finalize current molecule. _finalize_molecule() # Discard the original molecule and create a new one. mol = Chunk(assy, nodename) mol.protein = Protein() dont_split = False ### numconects = 0 # HEADER, COMPND and REMARK fields are added to the comment text elif key == "header": # Extract PDB ID from the header string. pdbid = card[62:66].lower() comment_text += card elif key == "compnd": comment_text += card elif key == "remark": comment_text += card elif key == "model": # Check out the MODEL record, ignore everything other than MODEL 1. # This behavior should be optional and set via User Preference. # piotr 080714 model_id = int(card[6:20]) if model_id > 1: env.history.message( redmsg( "Warning: multi-model file; skipping remaining models.")) env.history.h_update() # Skip remaining part of the file. break elif key in ["helix", "sheet", "turn"]: # Read secondary structure information. if key == "helix": begin = int(card[22:25]) end = int(card[34:37]) chainId = card[19] for s in range(begin, end+1): helix.append((s, chainId)) elif key == "sheet": begin = int(card[23:26]) end = int(card[34:37]) chainId = card[21] for s in range(begin, end+1): sheet.append((s, chainId)) elif key == "turn": begin = int(card[23:26]) end = int(card[34:37]) chainId = card[19] for s in range(begin, end+1): turn.append((s, chainId)) else: # Rosetta-written PDB files include scoring information. if card[7:15] == "ntrials:": _read_rosetta_info = True comment_text += "Rosetta Scoring Analysis\n" if card[9:15] == "score:": score = float(card[16:]) comment_title = "Rosetta Score: %g" % score if _read_rosetta_info: comment_text += card if showProgressDialog: # Update the progress dialog. _progressValue += 1 if _progressValue >= _progressFinishValue: win.progressDialog.setLabelText("Building model...") elif _progressDialogDisplayed: win.progressDialog.setValue(_progressValue) else: _timerDuration = time.time() - _timerStart if _timerDuration > 0.25: # Display progress dialog after 0.25 seconds win.progressDialog.setValue(_progressValue) _progressDialogDisplayed = True if showProgressDialog: # Make the progress dialog go away. win.progressDialog.setValue(_progressFinishValue) _finalize_molecule() mollist.append(hetgroup) if water.atoms: # Rebuild bonds in case there are hydrogens present. inferBonds(water) # Add bondpoints. _add_bondpoints(water) # Check if there are any water molecules water.name = "Solvent" # The water should be hidden by default. water.hide() mollist.append(water) return (mollist, comment_text, comment_title) # read oa Protein DataBank-format file or insert it into a single Chunk # piotr 080715 refactored "read" and "insert" code so they both call # this method instead having a redundant code (the only difference is # "isInsert" parameter. #bruce 050322 revised this for bug 433 def read_or_insert_pdb(assy, filename, showProgressDialog = False, chainId = None, isInsert = False): """ Reads (loads) a PDB file, or inserts it into an existing chunk. @param assy: The assembly. @type assy: L{assembly} @param filename: The PDB filename to read. @type filename: string @param showProgressDialog: if True, display a progress dialog while reading a file. Default is False. @type showProgressDialog: boolean """ from utilities.GlobalPreferences import ENABLE_PROTEINS if ENABLE_PROTEINS: molecules, comment_text, comment_title = _readpdb_new(assy, filename, isInsert = isInsert, showProgressDialog = showProgressDialog, chainId = chainId) if molecules: assy.part.ensure_toplevel_group() dir, name = os.path.split(filename) #name = gensym(nodename, assy) group = Group(name, assy, assy.part.topnode) for mol in molecules: if mol is not None: group.addchild(mol) comment = Comment(assy, comment_title, comment_text) group.addchild(comment) assy.addnode(group) else: mol = _readpdb(assy, filename, isInsert = isInsert, showProgressDialog = showProgressDialog, chainId = chainId) if mol is not None: assy.addmol(mol) return # read a Protein DataBank-format file into a single Chunk #bruce 050322 revised this for bug 433 def readpdb(assy, filename, showProgressDialog = False, chainId = None): """ Reads (loads) a PDB file. @param assy: The assembly. @type assy: L{assembly} @param filename: The PDB filename to read. @type filename: string @param showProgressDialog: if True, display a progress dialog while reading a file. Default is False. @type showProgressDialog: boolean """ read_or_insert_pdb(assy, filename, showProgressDialog = showProgressDialog, chainId = chainId, isInsert = False) # Insert a Protein DataBank-format file into a single Chunk #bruce 050322 revised this for bug 433 def insertpdb(assy, filename, chainId = None): """ Reads a pdb file and inserts it into the existing model. @param assy: The assembly. @type assy: L{assembly} @param filename: The PDB filename to read. @type filename: string """ read_or_insert_pdb(assy, filename, showProgressDialog = True, chainId = chainId, isInsert = True) # Write a PDB ATOM record record. # Copied and modified version of chem.py Atom.writepdb method. # Should be moved back to Atom class as soon as we decided that the # new implementation is satisfactory. # piotr 080710 def writepdb_atom(atom, file, atomSerialNumber, atomName, chainId, resId, \ resName, hetatm, occup, temp): """ Write a PDB ATOM record for the atom into I{file}. @param atom: The atom. @type atom: Atom @param file: The PDB file to write the ATOM record to. @type file: file @param atomSerialNumber: A unique number for this atom. @type atomSerialNumber: int @param chainId: The chain id. It is a single character. See the PDB documentation for the ATOM record more information. @type chainId: str @note: If you edit the ATOM record, be sure to to test QuteMolX. @see: U{B{ATOM Record Format}<http://www.wwpdb.org/documentation/format23/sect9.html#ATOM>} """ space = " " # Begin ATOM record ---------------------------------- # Column 1-6: "ATOM " (str) or "HETATM" depending on a type of atom if hetatm: atomRecord = "HETATM" else: atomRecord = "ATOM " # Column 7-11: Atom serial number (int) atomRecord += "%5d" % atomSerialNumber # Column 12: Whitespace (str) atomRecord += "%1s" % space # Column 13-16 Atom name (str) # piotr 080710: moved Atom name to column 13 if len(atomName) == 4: atomRecord += "%-4s" % atomName[:4] else: atomRecord += " %-3s" % atomName[:3] # Column 17: Alternate location indicator (str) *unused* atomRecord += "%1s" % space # Column 18-20: Residue name - unused (str) atomRecord += "%3s" % resName # Column 21: Whitespace (str) atomRecord += "%1s" % space # Column 22: Chain identifier - single letter (str) # This has been tested with 35 chunks and still works in QuteMolX. atomRecord += "%1s" % chainId.upper() # Column 23-27: Residue sequence number (int) + Code for insertion of residues (AChar) atomRecord += "%5s" % resId # Column 28-30: Whitespace (str) atomRecord += "%3s" % space # Get atom XYZ coordinate _xyz = atom.posn() # Column 31-38: X coord in Angstroms (float 8.3) atomRecord += "%8.3f" % float(_xyz[0]) # Column 39-46: Y coord in Angstroms (float 8.3) atomRecord += "%8.3f" % float(_xyz[1]) # Column 47-54: Z coord in Angstroms (float 8.3) atomRecord += "%8.3f" % float(_xyz[2]) # Column 55-60: Occupancy (float 6.2) - should be "1.0" atomRecord += "%6.2f" % occup # Column 61-66: Temperature factor. (float 6.2) *unused* atomRecord += "%6.2f" % temp # Column 67-76: Whitespace (str) atomRecord += "%10s" % space # Column 77-78: Element symbol, right-justified (str) atomRecord += "%2s" % atom.element.symbol[:2] # Column 79-80: Charge on the atom (str) *unused* atomRecord += "%2s\n" % space # End ATOM record ---------------------------------- file.write(atomRecord) return # Write all Chunks into a Protein DataBank-format file # [bruce 050318 revised comments, and made it not write singlets or their bonds, # and made it not write useless 1-atom CONECT records, and include each bond # in just one CONECT record instead of two.] # PDB exclude flags, used by writepdb() and its callers. # Ask Bruce what "constants" file these should be moved to (if any). # Mark 2007-06-11 WRITE_ALL_ATOMS = 0 EXCLUDE_BONDPOINTS = 1 EXCLUDE_HIDDEN_ATOMS = 2 # excludes both hidden and invisible atoms. EXCLUDE_DNA_ATOMS = 4 EXCLUDE_DNA_AXIS_ATOMS = 8 EXCLUDE_DNA_AXIS_BONDS = 16 def writepdb(part, filename, mode = 'w', excludeFlags = EXCLUDE_BONDPOINTS | EXCLUDE_HIDDEN_ATOMS, singleChunk = None): """ Write a PDB file of the I{part}. @param part: The part. @type part: assembly @param filename: The fullpath of the PDB file to write. We don't care if it has the .pdb extension or not. @type filename: string @param mode: 'w' for writing (the default) 'a' for appending @type mode: string @param excludeFlags: used to exclude certain atoms from being written, where: WRITE_ALL_ATOMS = 0 (even writes hidden and invisble atoms) EXCLUDE_BONDPOINTS = 1 (excludes bondpoints) EXCLUDE_HIDDEN_ATOMS = 2 (excludes invisible atoms) EXCLUDE_DNA_ATOMS = 4 (excludes PAM3 and PAM5 pseudo atoms) EXCLUDE_DNA_AXIS_ATOMS = 8 (excludes PAM3 axis atoms) EXCLUDE_DNA_AXIS_BONDS = 16 (suppresses PAM3 axis bonds) @type excludeFlags: integer @note: Atoms and bonds of hidden chunks are never written. @see: U{B{PDB File Format}<http://www.wwpdb.org/documentation/format23/v2.3.html>} """ if mode != 'a': # Precaution. Mark 2007-06-25 mode = 'w' f = open(filename, mode) # doesn't yet detect errors in opening file [bruce 050927 comment] # Atom object's key is the key, the atomSerialNumber is the value atomsTable = {} # Each element of connectLists is a list of atoms to be connected with the # 1st atom in the list, i.e. the atoms to write into a CONECT record connectLists = [] atomSerialNumber = 1 from utilities.GlobalPreferences import ENABLE_PROTEINS def exclude(atm): #bruce 050318 """ Exclude this atom (and bonds to it) from the file under the following conditions (as selected by excludeFlags): - if it is a singlet - if it is not visible - if it is a member of a hidden chunk - some dna-related conditions (see code for details) """ # Added not visible and hidden member of chunk. This effectively deletes # these atoms, which might be considered a bug. # Suggested solutions: # - if the current file is a PDB and has hidden atoms/chunks, warn user # before quitting NE1 (suggest saving as MMP). # - do not support native PDB. Open PDBs as MMPs; only allow export of # PDB. # Fixes bug 2329. Mark 070423 if excludeFlags & EXCLUDE_BONDPOINTS: if atm.element == Singlet: return True # Exclude if excludeFlags & EXCLUDE_HIDDEN_ATOMS: if not atm.visible(): return True # Exclude if excludeFlags & EXCLUDE_DNA_AXIS_ATOMS: ## if atm.element.symbol in ('Ax3', 'Ae3'): #bruce 080320 bugfix: revise to cover new elements and PAM5. if atm.element.role == 'axis': return True # Exclude if excludeFlags & EXCLUDE_DNA_ATOMS: # PAM5 atoms begin at 200. # # REVIEW: better to check atom.element.pam? # What about "carbon nanotube pseudoatoms"? # [bruce 080320 question] if atm.element.eltnum >= 200: return True # Exclude # Always exclude singlets connected to DNA p-atoms. if atm.element == Singlet: for a in atm.neighbors(): if a.element.eltnum >= 200: # REVIEW: see above comment about atom.element.pam vs >= 200 return True return False # Don't exclude. excluded = 0 molnum = 1 chainIdChar = 65 # ASCII "A" if mode == 'w': writePDB_Header(f) # get a list of chunks in model tree order mollist = part.nodes_in_mmpfile_order(nodeclass = Chunk) for mol in mollist: if singleChunk: mol = singleChunk if mol.hidden: # Atoms and bonds of hidden chunks are never written. continue # write atoms in proper order ordered_atoms = mol.atoms_in_mmp_file_order() for a in ordered_atoms: if exclude(a): excluded += 1 continue atomConnectList = [] atomsTable[a.key] = atomSerialNumber hetatm = True if ENABLE_PROTEINS: # piotr 080709 : Use more robust ATOM output code for Proteins. resId = " 1 " resName = " " atomName = a.element.symbol hetatm = True occup = 1.0 temp = 0.0 if a.pdb_info: if a.pdb_info.has_key('residue_id'): resId = a.pdb_info['residue_id'] if a.pdb_info.has_key('residue_name'): resName = a.pdb_info['residue_name'] if a.pdb_info.has_key('atom_name'): atomName = a.pdb_info['atom_name'] if a.pdb_info.has_key('standard_atom'): hetatm = False if a.pdb_info.has_key('chain_id'): chainIdChar = ord(a.pdb_info['chain_id'][0]) if a.pdb_info.has_key('occupancy'): occup = a.pdb_info['occupancy'] if a.pdb_info.has_key('temperature_factor'): temp = a.pdb_info['temperature_factor'] writepdb_atom(a, f, atomSerialNumber, atomName, chr(chainIdChar), resId, resName, hetatm, occup, temp) else: a.writepdb(f, atomSerialNumber, chr(chainIdChar)) if hetatm: atomConnectList.append(a) for b in a.bonds: a2 = b.other(a) # The following removes bonds b/w PAM3 axis atoms. if excludeFlags & EXCLUDE_DNA_AXIS_BONDS: ## if a.element.symbol in ('Ax3', 'Ae3'): ## if a2.element.symbol in ('Ax3', 'Ae3'): ## continue #bruce 080320 bugfix: revise to cover new elements and PAM5. if a.element.role == 'axis' and a2.element.role == 'axis': continue if a2.key in atomsTable: assert not exclude(a2) # see comment below atomConnectList.append(a2) #bruce 050318 comment: the old code wrote every bond twice # (once from each end). I doubt we want that, so now I only # write them from the 2nd-seen end. (This also serves to # not write bonds to excluded atoms, without needing to check # that directly. The assert verifies this claim.) if len(atomConnectList) > 1: connectLists.append(atomConnectList) # bruce 050318 comment: shouldn't we leave it out if # len(atomConnectList) == 1? # I think so, so I'm doing that (unlike the previous code). atomSerialNumber += 1 # Write the chain TER-minator record # # COLUMNS DATA TYPE FIELD DEFINITION # ------------------------------------------------------ # 1 - 6 Record name "TER " # 7 - 11 Integer serial Serial number. # 18 - 20 Residue name resName Residue name. # 22 Character chainID Chain identifier. # 23 - 26 Integer resSeq Residue sequence number. # 27 AChar iCode Insertion code. # piotr 080908 note: This is not exactly correct, the TER record # shouldn't be saved between consecutive non-standard residues # (HETATM records), e.g. water molecules shouldn't be separated # by TER records. f.write("TER %5d %1s\n" % (molnum, chr(chainIdChar))) molnum += 1 chainIdChar += 1 if chainIdChar > 126: # ASCII "~", end of PDB-acceptable chain chars chainIdChar = 32 # Rollover to ASCII " " if singleChunk: break for atomConnectList in connectLists: # Begin CONECT record ---------------------------------- f.write("CONECT") for a in atomConnectList: index = atomsTable[a.key] f.write("%5d" % index) f.write("\n") # End CONECT record ---------------------------------- connectLists = [] f.write("END\n") f.close() if excluded: msg = "Warning: excluded %d open bond(s) from saved PDB file; " \ % excluded msg += "consider Hydrogenating and resaving." msg = fix_plurals(msg) env.history.message( orangemsg(msg)) return # from writepdb def writePDB_Header(fileHandle): """ Writes an informative REMARK 5 header at the top of the PDB file with the given fileHandle. @param fileHandle: The file to write into. @type fileHandle: file """ version = Version() fileHandle.write("REMARK 5\n") fileHandle.write("REMARK 5 Created %s" % (datetime.utcnow().strftime("%Y/%m/%d %I:%M:%S %p UTC\n"))) fileHandle.write("REMARK 5 with NanoEngineer-1 version %s nanoengineer-1.com\n" % repr(version)) fileHandle.write("REMARK 5") fileHandle.write(""" REMARK 6 REMARK 6 This file generally complies with the PDB format version 2.3 REMARK 6 Notes: REMARK 6 REMARK 6 - Sets of atoms are treated as PDB chains terminated with TER REMARK 6 records. Since the number of atom sets can exceed the 95 possible REMARK 6 unique chains expressed in ATOM records by single non-control ASCII REMARK 6 characters, TER record serial numbers will be used to uniquely REMARK 6 identify atom sets/chains. Chain identifiers in ATOM records will REMARK 6 "roll-over" after every 95 chains. REMARK 6\n""")
NanoCAD-master
cad/src/files/pdb/files_pdb.py
# Copyright 2008 Nanorex, Inc. See LICENSE file for details. """ @author: Ninad @copyright: 2008 Nanorex, Inc. See LICENSE file for details. @version:$Id$ History: Created on 2008-07-15 . The main purpose of this class was a workaround to new Qt4.3.2 BUG 2916 in the QToolbar extension popup indicator. TODO: """ from PyQt4.Qt import QWidgetAction from PyQt4.Qt import QToolButton from PyQt4.Qt import Qt def truncateText(text, length = 12, truncateSymbol = '...'): """ Truncates the tooltip text with the given truncation symbol (three dots) in the case """ #ninad 070201 This is a temporary fix. Ideally it should show the whole #text in the toolbutton. But there are some layout / size policy #problems because of which the toolbar height increases after you print #tooltip text on two or more lines. (undesirable effect) if not text: print "no text to truncate. Returning" return truncatedLength = length - len(truncateSymbol) if len(text) > length: return text[:truncatedLength] + truncateSymbol else: return text def wrapToolButtonText(text): """ Add a newline character at the end of each word in the toolbutton text """ #ninad 070126 QToolButton lacks this method. This is not really a #'word wrap' but OK for now. #@@@ ninad 070126. Not calling this method as it is creating an annoying #resizing problem in the Command toolbar layout. Possible solution is #to add a spacer item in a vbox layout to the command toolbar layout stringlist = text.split(" ", QString.SkipEmptyParts) text2 = QString() if len(stringlist) > 1: for l in stringlist: text2.append(l) text2.append("\n") return text2 return None _superclass = QWidgetAction class NE1_QWidgetAction(_superclass): def __init__(self, parent, win = None): _superclass.__init__(self, parent) self.win = win self._toolButtonPalette = None def createWidget(self, parent): cmdToolbar = self.win.commandToolbar btn = None if cmdToolbar: flyoutToolBar = cmdToolbar.flyoutToolBar if flyoutToolBar: if 0: print "***self.text() =%s, parent = %s"%(self.text(), parent) if parent is flyoutToolBar: btn = self._createToolButtonWidget(parent) return btn def _createToolButtonWidget(self, parent): """ @see: self.createWidget() """ btn = QToolButton(parent) btn.setAutoFillBackground(True) btn.setToolButtonStyle(Qt.ToolButtonTextUnderIcon) btn.setMinimumWidth(75) btn.setMaximumWidth(75) btn.setMinimumHeight(62) btn.setAutoRaise(True) btn.setCheckable(True) btn.setDefaultAction(self) text = truncateText(self.text()) btn.setText(text) if self._toolButtonPalette: btn.setPalette(self._toolButtonPalette) #@@@ ninad070125 The following function #adds a newline character after each word in toolbutton text. #but the changes are reflected only on 'mode' toolbuttons #on the flyout toolbar (i.e.only Checkable buttons..don't know #why. Disabling its use for now. debug_wrapText = False if debug_wrapText: text = wrapToolButtonText(action.text()) if text: action.setText(text) return btn def setToolButtonPalette(self, palette): """ @see: CommandToolbar._createFlyoutToolbar() """ self._toolButtonPalette = palette
NanoCAD-master
cad/src/ne1_ui/NE1_QWidgetAction.py
""" FetchPDBDialog.py Qt Dialog for fetching pdb files from the interweb @author: Urmi @version: $Id$ @copyright:2008 Nanorex, Inc. See LICENSE file for details. """ from PyQt4.Qt import SIGNAL, SLOT from PyQt4.QtGui import QDialog, QLineEdit, QPushButton, QLabel from PyQt4.QtGui import QHBoxLayout, QVBoxLayout, QApplication class FetchPDBDialog(QDialog): def __init__(self, parent = None): self.parentWidget = parent super(FetchPDBDialog, self).__init__(parent) self.text = '' self.setWindowTitle("Fetch PDB") layout = QVBoxLayout() idLayout = QHBoxLayout() self.label = QLabel("Enter PDB ID:") self.lineEdit = QLineEdit() #self.lineEdit.setMaxLength(8) # Check with Piotr about this. idLayout.addWidget(self.label) idLayout.addWidget(self.lineEdit) self.okButton = QPushButton("&OK") self.cancelButton = QPushButton("Cancel") buttonLayout = QHBoxLayout() buttonLayout.addStretch() buttonLayout.addWidget(self.okButton) buttonLayout.addWidget(self.cancelButton) layout.addLayout(idLayout) layout.addLayout(buttonLayout) self.setLayout(layout) self.connect(self.lineEdit, SIGNAL("returnPressed()"), self.getProteinCode) self.connect(self.okButton, SIGNAL("clicked()"), self.getProteinCode) self.connect(self.cancelButton, SIGNAL("clicked()"), self, SLOT("reject()")) self.show() return def getProteinCode(self): self.parentWidget.setPDBCode(str(self.lineEdit.text())) self.close() self.emit(SIGNAL("editingFinished()")) return
NanoCAD-master
cad/src/ne1_ui/FetchPDBDialog.py
# Copyright 2007-2008 Nanorex, Inc. See LICENSE file for details. """ WhatsThisText_for_PropertyManagers.py This file provides functions for setting the "What's This" and tooltip text for widgets in all NE1 Property Managers only. Edit WhatsThisText_for_MainWindow.py to set "What's This" and tooltip text for widgets in the Main Window. @version: $Id$ @copyright: 2007-2008 Nanorex, Inc. See LICENSE file for details. """ def whatsThis_InsertDna_PropertyManager(propMgr): """ Whats This text for the DnaDuplex Property Manager @see: B{InsertDna_PropertyManager._addWhatsThisText} """ propMgr.conformationComboBox.setWhatsThis( """<b>Conformation</b> <p> DNA exists in several possible conformations, with A-DNA, B-DNA, and Z-DNA being the most common.</p> <p> Only B-DNA is currently supported in NanoEngineer-1. </p>""") propMgr.dnaModelComboBox.setWhatsThis( """<b>Model Choice</b> <p> Selects between the model types supported by NanoEngineer-1: PAM3, PAM5, and atomistic representations of DNA. </p>""") propMgr.numberOfBasePairsSpinBox.setWhatsThis( """<b>Base Pairs</b> <p> Allows the user to create a duplex by specifying the number of base pairs </p>""") propMgr.basesPerTurnDoubleSpinBox.setWhatsThis( """<b>Bases Per Turn</b> <p> Allows the user to specifying the number of base pairs between one full turn of the DNA helix </p>""") propMgr.duplexLengthLineEdit.setWhatsThis( """<b>Duplex Length</b> <p> Displays the length of the DNA duplex in angstroms </p>""") propMgr.dnaRubberBandLineDisplayComboBox.setWhatsThis( """<b>Display As</b> <p> Selects between Ribbon and Ladder display styles </p>""") propMgr.lineSnapCheckBox.setWhatsThis( """<b>Enable Line Snap</b> <p> When checked a duplex will be constrained to a grid </p>""") return # End of whatsThis_InsertDna_PropertyManager def whatsThis_MakeCrossoversPropertyManager(propMgr): """ Whats This text for the DnaDuplex Property Manager @see: B{MakeCrossovers_PropertyManager._addWhatsThisText} """ propMgr.segmentListWidget.setWhatsThis("""<b> List of Dna segments for crossover search</b> <p>Lists DnaSegments that will be searched for potential crossover sites. To add/remove Dna segments to/from this list, activate the appropriate tool in this property manager and select the whole axis of the Dna segment. To add/remove multiple segments to the list at once, hold down left mouse button and drag it to draw a selection rectangle around the segments. </p> """) propMgr.crossoversBetGivenSegmentsOnly_checkBox.setWhatsThis(""" <b> Between above segments only Checkbox </b> <p>*If checked, program will search for the crossover sites <b>only between</b> the DNA segments listed in the segment's list. <br><br> *Unchecking this checkbox will make the program search for the crossover sites between each DNA segment in the segment's list and <b>all</b> the DNA segments in the model, that are within a certain distance from that particular DNA segment. <br><br><b>Note</b>This operation could be time consuming so it is recommended that user keeps this checkbox checked.</p>""") return # End of whatsThis_whatsThis_MakeCrossoversPropertyManager def whatsThis_InsertPeptide_PropertyManager(propMgr): """ "Whats This" text for widgets in the Insert Peptide Property Manager. """ propMgr.aaTypeComboBox.setWhatsThis( """<b>Confirmation</b> <p> Sets the secondary structure confirmation that will be applied when inserting a new polypeptide chain. </p>""") propMgr.phiAngleField.setWhatsThis( """<b>Phi angle</b> <p> Shows the <b>Phi dihedral backbone angle</b> that will be applied when inserting a new polypeptide chain. It is determined by the current <b>Conformation</b> selected above. </p>""") propMgr.psiAngleField.setWhatsThis( """<b>Psi angle</b> <p> Shows the <b>Psi dihedral backbone angle</b> that will be applied when inserting a new polypeptide chain. It is determined by the current <b>Conformation</b> selected above. </p>""") # The "Remember.png" icon will be blank until we call # fix_whatsthis_text_and_links(propMgr) # The problem is that this function only processes What's This text # for QActions and not PM_ToolButtonGrid (really a QButtonGroup). # I will talk to Bruce about this later. Mark 2008-12-12. propMgr.aaTypesButtonGroup.setWhatsThis( """<b>Amino acids</b> <p> Determines which amino acid is used when inserting a new polypeptide chain. <b>Glycine</b> is the default.</p> <p> <img source=\"ui/whatsthis/Remember.png\"><br> <b>Remember:</b> You can change the amino acid sequence later after first inserting a polypeptide chain. </p>""") # Deprecated widgets below here. These are marked for removal. # Mark 2008-12-12 #propMgr.invertChiralityPushButton.setWhatsThis( #"""<b>Invert chirality</b> #<p> #Inverts a chirality of the polypeptide backbone #</p>""") #propMgr.sequenceEditor.setWhatsThis( #"""<b>Sequence Editor</b> #<p> #Displays the amino acid sequence for the currently selected #polypeptide chain. #</p>""") return # End of whatsThis_InsertPeptide_PropertyManager def whatsThis_NanotubeGeneratorPropertyManager(propMgr): """ "Whats This" text for widgets in the Nanotube Property Manager. """ propMgr.chiralityNSpinBox.setWhatsThis( """<b>Chirality (n)</b> <p> Specifies <i>n</i> of the chiral vector (n, m), where n and m are integers of the vector equation R = na1 + ma2 . </p>""") propMgr.chiralityMSpinBox.setWhatsThis( """<b>Chirality (m)</b> <p> Specifies <i>m</i> of the chiral vector (n, m), where n and m are integers of the vector equation R = na1 + ma2 . </p>""") propMgr.typeComboBox.setWhatsThis( """<b>Type</b> <p> Specifies the type of nanotube to generate.</p> <p> Selecting <b>Carbon</b> creates a carbon nanotube (CNT) made entirely of carbon atoms. <p> Selecting <b>Boron nitride</b> creates a boron nitride (BN) nanotube made of boron and nitrogen atoms. </p>""") propMgr.endingsComboBox.setWhatsThis( """<b>Endings</b> <p> Specify how to deal with bondpoints on the two ends of the nanotube.</p> <p> Selecting <b>None</b> does nothing, leaving bondpoints on the ends.</p> <p> Selecting <b>Hydrogen</b>terminates the bondpoints using hydrogen atoms.</p> <p> Selecting <b>Nitrogen </b>transmutes atoms with bondpoints into nitrogen atoms. </p>""") propMgr.lengthField.setWhatsThis( """<b>Length</b> <p> Specify the length of the nanotube in angstroms. </p>""") propMgr.bondLengthField.setWhatsThis( """<b>Bond Length</b> <p> Specify the bond length between atoms in angstroms.</p>""") propMgr.twistSpinBox.setWhatsThis( """<b>Twist</b> <p> Introduces a twist along the length of the nanotube specified in degrees/angstrom. </p>""") propMgr.zDistortionField.setWhatsThis( """<b>Z-distortion</b> <p> Distorts the bond length between atoms along the length of the nanotube by this amount in angstroms. </p>""") propMgr.bendSpinBox.setWhatsThis( """<b>Bend</b> <p> Bend the nanotube by the specified number of degrees. </p>""") propMgr.xyDistortionField.setWhatsThis( """<b>XY-distortion</b> <p> Distorts the tube's cross-section so that the width in the X direction is this many angstroms greater than the width in the Y direction. Some distortion of bond lengths results. </p>""") propMgr.mwntCountSpinBox.setWhatsThis( """<b>Number of Nanotubes</b> <p> Specifies the number or Multi-Walled Nanotubes. Multi-Walled nanotubes (MWNT) consist of many concentric tubes wrapped one inside another.</p> <p> The specified chirality applies only to the innermost nanotube. The others, being larger, will have larger chiralities. </p>""") propMgr.mwntSpacingField.setWhatsThis( """<b>Spacing</b> <p> Specify the spacing between nanotubes in angstroms. </p>""") return def whatsThis_InsertNanotube_PropertyManager(propMgr): """ "Whats This" text for widgets in the Nanotube Property Manager. """ propMgr.ntTypeComboBox.setWhatsThis( """<b>Type</b> <p> Specifies the type of nanotube to insert.</p> <p> Selecting <b>Carbon</b> creates a carbon nanotube (CNT) made entirely of carbon atoms. <p> Selecting <b>Boron Nitride</b> creates a boron nitride nanotube (BNNT) made of boron and nitrogen atoms. </p>""") propMgr.ntDiameterLineEdit.setWhatsThis( """<b>Diameter</b> <p> Displays the diameter of the nanotube in angstroms. </p>""") propMgr.chiralityNSpinBox.setWhatsThis( """<b>Chirality (n)</b> <p> Specifies <i>n</i> of the chiral vector (n, m), where n and m are integers of the vector equation R = na1 + ma2 . </p>""") propMgr.chiralityMSpinBox.setWhatsThis( """<b>Chirality (m)</b> <p> Specifies <i>m</i> of the chiral vector (n, m), where n and m are integers of the vector equation R = na1 + ma2 . </p>""") propMgr.endingsComboBox.setWhatsThis( """<b>Endings</b> <p> Specify how to deal with bondpoints on the two ends of the nanotube.</p> <p> Selecting <b>None</b> does nothing, leaving bondpoints on the ends.</p> <p> Selecting <b>Hydrogen</b> terminates the bondpoints using hydrogen atoms.</p> <p> Selecting <b>Nitrogen</b> transmutes atoms with bondpoints into nitrogen atoms. </p>""") propMgr.bondLengthDoubleSpinBox.setWhatsThis( """<b>Bond Length</b> <p> Specify the bond length between neighboring atoms in angstroms.</p>""") propMgr.twistSpinBox.setWhatsThis( """<b>Twist</b> <p> Introduces a twist along the length of the nanotube specified in degrees/angstrom. </p>""") propMgr.zDistortionDoubleSpinBox.setWhatsThis( """<b>Z-distortion</b> <p> Distorts the bond length between atoms along the length of the nanotube by this amount in angstroms. </p>""") propMgr.bendSpinBox.setWhatsThis( """<b>Bend</b> <p> Bend the nanotube by the specified number of degrees. </p>""") propMgr.xyDistortionDoubleSpinBox.setWhatsThis( """<b>XY-distortion</b> <p> Distorts the tube's cross-section so that the width in the X direction is this many angstroms greater than the width in the Y direction. Some distortion of bond lengths results. </p>""") propMgr.mwntCountSpinBox.setWhatsThis( """<b>Number of Nanotubes</b> <p> Specifies the number or Multi-Walled Nanotubes. Multi-Walled nanotubes (MWNT) consist of many concentric tubes wrapped one inside another.</p> <p> The specified chirality applies only to the innermost nanotube. The others, being larger, will have larger chiralities. </p>""") propMgr.mwntSpacingDoubleSpinBox.setWhatsThis( """<b>Wall Spacing</b> <p> Specify the spacing between nanotubes in angstroms. </p>""") return def whatsThis_GrapheneGeneratorPropertyManager(propMgr): """ "What's This" text for widgets in the Graphene Property Manager. """ propMgr.heightField.setWhatsThis( """<b>Height</b> <p> The height (up to 50 angstroms) of the graphite sheet in angstroms. </p>""") propMgr.widthField.setWhatsThis( """<b>Width</b> <p> The width (up to 50 angstroms) of the graphene sheet in angstroms. </p>""") propMgr.bondLengthField.setWhatsThis( """<b>Bond length</b> <p> You can change the bond lengths (1.0-3.0 angstroms) in the graphene sheet. We believe the default value is accurate for sp <sup>2</sup>-hybridized carbons. </p>""") propMgr.endingsComboBox.setWhatsThis( """<b>Endings</b> <p> Graphene sheets can be unterminated (dangling bonds), or terminated with hydrogen atoms or nitrogen atoms. </p>""") return def whatsThis_MovePropertyManager(propMgr): """ "What's This" text for widgets in the Move Property Manager. """ # Translate group box widgets ################################ propMgr.translateComboBox.setWhatsThis( """<b>Translation Options</b> <p> This menu provides different options for translating the current selection where:</p> <p> <b>Free Drag</b>: translates the selection by dragging the mouse while holding down the left mouse button (LMB).</p> <p> <b>By Delta XYZ</b>: tranlates the selection by a specified offset.</p> <p> <b>To XYZ Position</b>: moves the selection to an absolute XYZ coordinate. The <i>centroid</i> of the selection is used for this operation. </p>""") propMgr.transFreeButton.setWhatsThis( """<b>Unconstrained Translation</b> <p> Translates the selection freely within the plane of the screen. </p>""") propMgr.transXButton.setWhatsThis( """<b>X Translation</b> <p> Constrains translation of the selection to the X axis. </p>""") propMgr.transYButton.setWhatsThis( """<b>Y Translation</b> <p> Constrains translation of the selection to the Y axis. </p>""") propMgr.transZButton.setWhatsThis( """<b>Z Translation</b> <p>Constrains translation of the selection to the Z axis. </p>""") propMgr.transAlongAxisButton.setWhatsThis( """<b>Axial Translation/Rotation</b> <p> Constrains both translation and rotation of the selection along the central axis of the selected object(s). This is especially useful for translating and rotating DNA duplexes along their own axis. </p>""") propMgr.moveFromToButton.setWhatsThis( """ <img source=\"ui/actions/Properties Manager/Translate_Components.png\"> <b>Translate from/to</b> <p> Translates the current selection by an offset vector defined by two points (i.e. left mouse button clicks) :</p> 1st point - The 'from' point.<br> 2nd point - the 'to' point. </p>""") propMgr.startCoordLineEdit.setWhatsThis( """<b>Define from and to points</b> <p> Becomes active when the user selects <b>Translate from/to</b>. </p>""") # By Delta XYZ widgets propMgr.moveDeltaXSpinBox.setWhatsThis( """<b>Delta X</b> <p> The X offset distance the selection is moved when clicking the +/- Delta buttons. </p>""") propMgr.moveDeltaYSpinBox.setWhatsThis( """<b>Delta Y</b> <p> The Y offset distance the selection is moved when clicking the +/- Delta buttons. </p>""") propMgr.moveDeltaZSpinBox.setWhatsThis( """<b>Delta Z</b> <p> The Z offset distance the selection is moved when clicking the +/- Delta buttons. </p>""") propMgr.transDeltaPlusButton.setWhatsThis( """<b>Delta +</b> <p> Moves the current selection by an offset specified by the Delta X, Y and Z spinboxes. </p>""") propMgr.transDeltaMinusButton.setWhatsThis( """<b>Delta -</b> <p> Moves the current selection by an offset opposite of that specified by the Delta X, Y and Z spinboxes. </p>""") # To XYZ Position widgets propMgr.moveXSpinBox.setWhatsThis( """<b>X</b> <p> The X coordinate the selection is moved when clicking the +/- Delta buttons. </p>""") propMgr.moveYSpinBox.setWhatsThis( """<b>Y</b> <p> The Y coordinate the selection is moved when clicking the +/- Delta buttons. </p>""") propMgr.moveZSpinBox.setWhatsThis( """<b>Z</b> <p> The Z coordinate the selection is moved when clicking the <b>Move to Absolute Position</b> button. </p>""") propMgr.moveAbsoluteButton.setWhatsThis( """<b>Move to Absolute Position</b> <p> Moves the current selection to the position specified by the X, Y and Z spinboxes. The selection's centroid is used compute how the selection is moved. </p>""") # Rotate group box widgets ############################ propMgr.rotateComboBox.setWhatsThis( """<b>Rotate Options</b> <p> This menu provides different options for rotating the current selection where:</p> <p> <b>Free Drag</b>: rotates the selection by dragging the mouse while holding down the left mouse button (LMB).</p> <p> <b>By Specified Angle</b>: rotates the selection by a specified angle. </p>""") # Free Drag widgets. propMgr.rotateFreeButton.setWhatsThis( """<b>Unconstrained Rotation</b> <p> Rotates the selection freely about its centroid. </p>""") propMgr.rotateXButton.setWhatsThis( """<b>X Rotation</b> <p> Constrains rotation of the selection to the X axis. </p>""") propMgr.rotateYButton.setWhatsThis( """<b>Y Rotation</b> <p> Constrains rotation of the selection to the Y axis. </p>""") propMgr.rotateZButton.setWhatsThis( """<b>Z Rotation</b> <p> Constrains rotation of the selection to the Z axis. </p>""") propMgr.rotAlongAxisButton.setWhatsThis( """<b>Axial Translation/Rotation</b> <p> Constrains both translation and rotation of the selection along the central axis of the selected object(s). This is especially useful for translating and rotating DNA duplexes along their own axis. </p>""") propMgr.rotateAsUnitCB.setWhatsThis( """<b>Rotate as unit</b> <p> When <b>checked</b>, the selection is rotated as a unit about its collective centroid.<br> When <b>unchecked</b>, the selected objects are rotated about their own individual centroids. </p>""") # Rotate selection about a point propMgr.rotateAboutPointButton.setWhatsThis( """ <img source=\"ui/actions/Properties Manager/Rotate_Components.png\"> <b>Rotate selection about a point</b> <p> Rotates the current selection about an axis perpendicular to the current view. The user defines 3 points (i.e. left mouse button clicks): <p> 1st point - The rotation point (i.e. the perpendicular axis).<br> 2nd point - The starting angle.<br> 3rd point - The ending angle.<br> </p>""") propMgr.rotateStartCoordLineEdit.setWhatsThis( """<b>Define 3 points</b> <p> Becomes active when the user selects <b>Rotate selection about a point</b>. </p>""") # By Specified Angle widgets propMgr.rotateXButton.setWhatsThis( """<b>Rotate about X axis</b> <p> Constrains rotation about the X axis. </p>""") propMgr.rotateYButton.setWhatsThis( """<b>Rotate about Y axis</b> <p> Constrains rotation about the Y axis. </p>""") propMgr.rotateZButton.setWhatsThis( """<b>Rotate about Z axis</b> <p> Constrains rotation about the Z axis. </p>""") propMgr.rotateThetaSpinBox.setWhatsThis( """<b>Rotation angle</b> <p> Specifies the angle of rotation. </p>""") propMgr.rotateThetaPlusButton.setWhatsThis( """<b>Rotate</b> <p> Rotates the selection by the specified angle. </p>""") propMgr.rotateThetaMinusButton.setWhatsThis( """<b>Rotate (minus)</b> <p> Rotates the selection by the specified angle (in the opposite direction). </p>""") propMgr.rotXaxisButton.setWhatsThis( """<b>Rotate about X axis</b> <p> Constrains rotation about the X axis. </p>""") propMgr.rotYaxisButton.setWhatsThis( """<b>Rotate about Y axis</b> <p> Constrains rotation about the Y axis. </p>""") propMgr.rotZaxisButton.setWhatsThis( """<b>Rotate about Z axis</b> <p> Constrains rotation about the Z axis. </p>""") return # End of whatsThis_MovePropertyManager def whatsThis_MoviePropertyManager(propMgr): """ "What's This" text for widgets in the Movie Property Manager. """ propMgr.frameNumberSpinBox.setWhatsThis( """<b>Frame Number</b> <p> Advances the movie to a specified frame </p>""") propMgr.movieLoop_checkbox.setWhatsThis( """<b>Loop</b> <p> Displays the movie as a continuous loop. When enabled the movie player will automatically reset to the first frame after the last frame is shown and replay the movie. </p>""") propMgr.frameSkipSpinBox.setWhatsThis( """<b>Skip</b> <p> Allows you to skip the entered amount of frames during movie playback. </p>""") propMgr.fileOpenMovieAction.setWhatsThis( """<b>Open Movie File</b> <p> Loads an exsisting movie from file </p>""") propMgr.fileSaveMovieAction.setWhatsThis( """<b>Save Movie File</b> <p> Loads and exsisting movie file or saves the file as a POV-ray series to be used in an animation </p>""") propMgr.moviePlayRevAction.setWhatsThis( """<b>Play Reverse</b> <p> Plays the movie backward in time </p>""") propMgr.moviePlayAction.setWhatsThis( """<b>Play Forward</b> <p> Plays the movie forward in time </p>""") propMgr.moviePauseAction.setWhatsThis( """<b>Pause Movie</b> <p> Pauses movie on current frame </p>""") propMgr.movieMoveToEndAction.setWhatsThis( """<b>Advance to End</b> <p> Advances movie to last frame </p>""") propMgr.movieResetAction.setWhatsThis( """<b>Reset Movie</b> <p> Advances movie to first frame </p>""") propMgr.frameNumberSlider.setWhatsThis( """<b>Advance Frame</b> <p> Dragging the slider advances the movie </p>""") return def whatsThis_DnaSequenceEditor(propMgr): """ "What's This" text for widgets in the DNA Sequence Editor. """ propMgr.loadSequenceButton.setWhatsThis( """<b>Load Sequence File</b> <p> Loads an existing strand sequence from a text file </p>""") propMgr.sequenceTextEdit.setWhatsThis( """<b>Sequence field</b> <p> This field is used to view and edit the sequence of the current strand. The field background color turns pink whenever the sequence has been changed by the user, but hasn't yet been applied as the new sequence to the current strand. The new sequence is applied by pressing the <b>Enter</b> key or clicking <b>Done</b>. </p>""") propMgr.baseDirectionChoiceComboBox.setWhatsThis( """<b>Strand Directon </b> <p> Sets the direction in which the sequence is shown in the sequence field. </p>""") propMgr.saveSequenceButton.setWhatsThis( """<b>Save Sequence </b> <p> Write the current sequence to a text file. </p>""") propMgr.findLineEdit.setWhatsThis( """<b>Find field</b> <p> The <i>find string</i> to search for in the sequence field. </p>""") propMgr.findPreviousToolButton.setWhatsThis( """<b>Find Previous</b> <p> Find the previous occurrence of the <i>find string</i> in the sequence. </p>""") propMgr.findNextToolButton.setWhatsThis( """<b>Find Next</b> <p> Find the next occurrence of the <i>find string</i> in the sequence. </p>""") propMgr.replacePushButton.setWhatsThis( """<b>Replace</b> <p> Replaces the current <i>find string</i> in the sequence with the <i>replace string</i>. </p>""") propMgr.sequenceTextEdit_mate.setWhatsThis( """<b>Strand complement field</b> <p> This read-only field shows the complementary bases of the current strand sequence. </p>""") return def whatsThis_ProteinSequenceEditor(propMgr): """ "What's This" text for widgets in the Protein Sequence Editor. """ propMgr.loadSequenceButton.setWhatsThis( """<b>Load Sequence File</b> <p> Loads a peptide sequence from a text file. </p>""") propMgr.sequenceTextEdit.setWhatsThis( """<b>Sequence field</b> <p> This field (read-only) shows the amino acid sequence of the current protein. </p>""") propMgr.secStrucTextEdit.setWhatsThis( """<b>Secondary structure</b> <p> This field (read-only) shows the corresponding secondary structure of the current protein sequence. </p>""") propMgr.aaRulerTextEdit.setWhatsThis( """<b>Sequence ruler</b> <p> A basic ruler showing the position of each amino acid in the sequence. </p>""") propMgr.saveSequenceButton.setWhatsThis( """<b>Save Sequence </b> <p> Write the current sequence to a text file. </p>""") propMgr.findLineEdit.setWhatsThis( """<b>Find field</b> <p> The <i>find string</i> to search for in the sequence field. </p>""") propMgr.findPreviousToolButton.setWhatsThis( """<b>Find Previous</b> <p> Find the previous occurrence of the <i>find string</i> in the sequence. </p>""") propMgr.findNextToolButton.setWhatsThis( """<b>Find Next</b> <p> Find the next occurrence of the <i>find string</i> in the sequence. </p>""") propMgr.replacePushButton.setWhatsThis( """<b>Replace</b> <p> Replaces the current <i>find string</i> in the sequence with the <i>replace string</i>. </p>""") return def whatsThis_ExtrudePropertyManager(propMgr): """ "What's This" text for widgets in the Extrude Property Manager. """ propMgr.extrude_productTypeComboBox.setWhatsThis( """<b>Final product</b> <p> The type of product to create. Options are:</p> <p> <b>Rod</b>: a straight rod. <br> <b>Ring</b>: a closed ring. </p>""") propMgr.extrudeSpinBox_n.setWhatsThis( """<b>Number of copies</b> <p> The total number of copies, including the originally selected chunk(s). </p>""") propMgr.showEntireModelCheckBox.setWhatsThis( """<b>Show Entire Model</b> <p> Normally, only the selection and their copies are displayed during the Extrude command. Checking this option displays everything in the current model. </p>""") propMgr.makeBondsCheckBox.setWhatsThis( """<b>Make Bonds</b> <p> When checked, bonds will be made between pairs of bondpoints highlighted in blue and green after clicking <b>Done</b>. </p>""") propMgr.extrudeBondCriterionSlider.setWhatsThis( """<b>Tolerance slider</b> <p> Sets the bond criterion tolerance. The larger the tolerance value, the further bonds will be formed between pairs of bondpoints. </p>""") propMgr.extrudePrefMergeSelection.setWhatsThis( """<b>Merge Selection</b> <p> Merges the selected chunks into a single chunk after clicking <b>Done</b>. </p>""") propMgr.mergeCopiesCheckBox.setWhatsThis( """<b>Merge Copies</b> <p> When checked, copies are merged with the original chunk after clicking <b>Done</b>. </p>""") propMgr.extrudeSpinBox_length.setWhatsThis( """<b>Total Offset</b> <p> The total offset distance between copies. </p>""") propMgr.extrudeSpinBox_x.setWhatsThis( """<b>X Offset</b> <p> The X offset distance between copies. </p>""") propMgr.extrudeSpinBox_y.setWhatsThis( """<b>Y Offset</b> <p> The Y offset distance between copies. </p>""") propMgr.extrudeSpinBox_z.setWhatsThis( """<b>Z Offset</b> <p> The Z offset distance between copies. </p>""") return def whatsThis_CookiePropertyManager(propMgr): """ "What's This" text for widgets in the Build Crystal Property Manager. """ propMgr.surface100_btn.setWhatsThis(\ "<b>Surface 100</b>"\ "<p>"\ "Reorients the view to the nearest angle that would "\ "look straight into a (1,0,0) surface of a "\ "diamond lattice."\ "</p>") # Surface 110 propMgr.surface110_btn.setWhatsThis(\ "<b>Surface 110</b>"\ "<p>"\ "Reorients the view to the nearest angle that would "\ "look straight into a (1,1,0) surface of a "\ "diamond lattice."\ "</p>") # Surface 111 propMgr.surface111_btn.setWhatsThis(\ "<b>Surface 111</b>"\ "<p>"\ "Reorients the view to the nearest angle that would "\ "look straight into a (1,1,1) surface of a "\ "diamond lattice."\ "</p>") propMgr.addLayerButton.setWhatsThis(\ "<b>Add Layer</b>"\ "<p>"\ "Adds a new layer of diamond lattice to the existing "\ "layer."\ "</p>") propMgr.latticeCBox.setWhatsThis( "<b>Lattice Type</b>"\ "<p>"\ "Selects which lattice structure is displayed, either "\ "Diamond or Lonsdaleite"\ "</p>") propMgr.rotateGridByAngleSpinBox.setWhatsThis( "<b>Rotate By</b>"\ "<p>"\ "Allows you to select the degree of rotation"\ "</p>") propMgr.rotGridAntiClockwiseButton.setWhatsThis( "<b>Rotate Counter Clockwise</b>"\ "<p>"\ "Rotates the current view in a counter-clockwise direction"\ "</p>") propMgr.rotGridClockwiseButton.setWhatsThis( "<b>Rotate Clockwise</b>"\ "<p>"\ "Rotates the current view in a clockwise direction"\ "</p>") propMgr.layerCellsSpinBox.setWhatsThis( "<b>Lattice Cells</b>"\ "<p>"\ "Determines the thickness of the crystal layer"\ "</p>") propMgr.dispModeComboBox.setWhatsThis ( "<b>Display Style</b>"\ "<p>"\ "Lets you select the format in which your crystal selection " "is displayed"\ "</p>") propMgr.layerThicknessLineEdit.setWhatsThis( "<b>Thickness</b>"\ "<p>"\ "Thickness of layer in angstroms is displayed"\ "</p>") propMgr.gridLineCheckBox.setWhatsThis( "<b>Show Grid</b>"\ "<p>"\ "Allows you to turn on/off the orange lattice grid lines"\ "</p>") propMgr.fullModelCheckBox.setWhatsThis( "<b>Show Model</b>"\ "<p>"\ "Allows you to view your current model from the Graphics Area in "\ "overlay with the Crystal Cutter lattice view"\ "</p>") propMgr.snapGridCheckBox.setWhatsThis( "<b>Snap Grid</b>"\ "<p>"\ "Makes your lattice selection correspond with the grid lines "\ "</p>") propMgr.freeViewCheckBox.setWhatsThis( "<b>Free View</b>"\ "<p>"\ "Allows you to change the current view of the lattice structure so "\ "that it can be viewed from any angle. This can be done by using the "\ "middle mouse button."\ "</p>") return def whatsThis_RotaryMotorPropertyManager(propMgr): """ What's This text for some of the widgets in the Property Manager. """ # Removed name field from property manager. Mark 2007-05-28 #propMgr.nameLineEdit.setWhatsThis("""<b>Name</b><p>Name of Rotary Motor #that appears in the Model Tree</p>""") propMgr.torqueDblSpinBox.setWhatsThis( """<b>Torque </b> <p> Simulations will begin with the motor's torque set to this value. </p>""") propMgr.initialSpeedDblSpinBox.setWhatsThis( """<b>Initial Speed</b> <p> Simulations will begin with the motor's flywheel rotating at this velocity. </p>""") propMgr.finalSpeedDblSpinBox.setWhatsThis( """<b>Final Speed</b> <p> The final velocity of the motor's flywheel during simulations. </p>""") propMgr.dampersCheckBox.setWhatsThis( """<b>Dampers</b> <p> If checked, the dampers are enabled for this motor during a simulation. See the Rotary Motor web page on the NanoEngineer-1 Wiki for more information. </p>""") propMgr.enableMinimizeCheckBox.setWhatsThis( """<b>Enable in Minimize <i>(experimental)</i></b> <p> If checked, the torque specified above will be applied to the motor atoms during a structure minimization. While intended to allow simulations to begin with rotary motors running at speed, this feature requires more work to be useful. </p>""") propMgr.motorLengthDblSpinBox.setWhatsThis( """<b>Motor Length</b> <p> The motor jig is drawn as a cylinder. This is the dimensions of the solid's length, measured in angstroms. </p>""") propMgr.motorRadiusDblSpinBox.setWhatsThis( """<b>Motor Radius</b> <p> The motor jig is drawn as a cylinder. This is the radius of the cylinder, measured in angstroms. </p>""") propMgr.spokeRadiusDblSpinBox.setWhatsThis( """<b>Spoke Radius</b> <p> Atoms are connected to the motor body by spokes, and this is the radius of the spokes, measured in angstroms. </p>""") propMgr.motorColorComboBox.setWhatsThis( """<b>Color</b> <p> Changes the color of the motor. </p>""") propMgr.directionPushButton.setWhatsThis( """<b>Change Direction</b> <p> Changes direction of the motor </p>""") return def whatsThis_LinearMotorPropertyManager(propMgr): """ What's This text for widgets in the Linear Motor Property Manager. """ propMgr.forceDblSpinBox.setWhatsThis( """<b>Force </b> <p> Simulations will begin with the motor's force set to this value. </p>""") propMgr.enableMinimizeCheckBox.setWhatsThis( """<b>Enable in Minimize <i>(WARNING: EXPERIMENTAL FEATURE)</i></b> <p> If checked, the force specified above will be applied to the motor atoms during a structure minimization. While intended to allow simulations to begin with Linear motors running at speed, this feature requires more work to be useful. </p>""") propMgr.stiffnessDblSpinBox.setWhatsThis( """<b>Stiffness</b> <p> If non-zero, this parameter will modify the motor's force according to its position, as though the motor were a spring.</p> <p> When stiffness = 0, the motor's force is constant and will have the same direction and magnitude regardless of atom position. </p>""") propMgr.motorLengthDblSpinBox.setWhatsThis( """<b>Motor Length</b> <p> The body of the motor jig is drawn as a rectangular solid, with the long dimension in the direction of the motor's motion. This is the dimensions of the solid's length, measured in angstroms. </p>""") propMgr.motorWidthDblSpinBox.setWhatsThis( """<b>Motor Width</b> <p> The body of the motor jig is drawn as a rectangular solid, with the long dimension in the direction of the motor's motion. This is the dimensions of the solid's width, measured in angstroms. </p>""") propMgr.spokeRadiusDblSpinBox.setWhatsThis( """<b>Spoke Radius</b> <p> Atoms are connected to the motor body by spokes, and this is the radius of the spokes, measured in angstroms. </p>""") propMgr.motorColorComboBox.setWhatsThis( """<b>Color</b> <p> Changes the color of the motor. </p>""") propMgr.directionPushButton.setWhatsThis( """<b>Change Direction</b> <p> Changes direction of the linear motor </p>""") return def whatsThis_PlanePropertyManager(propMgr): """ Add "What's This" text for widgets in the Plane Property Manager. """ propMgr.heightDblSpinBox.setWhatsThis( """<b>Height</b> <p> The height of the Plane in angstroms. (up to 200 angstroms) </p>""") propMgr.widthDblSpinBox.setWhatsThis( """<b>Width</b> <p> The width of the Plane in angstroms. (up to 200 angstroms) </p>""") return def whatsThis_QuteMolPropertyManager(propMgr): """ Add "What's This" text for widgets in the QuteMolX Property Manager. """ propMgr.launchQuteMolButton.setWhatsThis( """ <b>Launch QuteMolX</b> <p> Pressing this button launches QuteMolX. </p>""") propMgr.axesCombobox.setWhatsThis( """ <b>Render Axes</b> <p> Allows the user to select between rendering and hiding the DNA axis pseudo atoms </p>""") propMgr.basesCombobox.setWhatsThis( """ <b>Render Bases</b> <p> Allows the user to select between rendering and hiding the DNA strand bases </p>""") return def whatsThis_BuildAtomsPropertyManager(propMgr): """ Add "What's This" text for widgets in the QuteMolX Property Manager. """ propMgr.selectionFilterCheckBox.setWhatsThis( """<b>Enable Atom Selection Filter</b> <p> When checked, the <i>atom selection filter</i> is enabled. Only atom types listed in the <b>Atom Selection Filter List</b> are included in selection operations (i.e. region selections in the <a href=Graphics_Area>graphics area</a>).</p> <p> While the <i>atom selection filter</i> is enabled, the <b>Atom Selection Filter List</b> is updated by selecting atom types in the <b>Atom Chooser</b>.</p> <p> <img source=\"ui/whatsthis/HotTip.png\"><br> <b>Hot Tip:</b> To specify multiple atom types in the <b>Atom Selection Filter Field</b>, hold down the <b>Shift Key</b> while selecting atom types in the <b>Atom Chooser</b>. </p>""") propMgr.filterlistLE.setWhatsThis( """<b>Atom Selection Filter List</b> <p> When the <b>Enable atom selection filter</b> is checked, this list shows the current atom type(s) to be included in the selection during selection operations. <i>Only atom types in this list are included in selection operations.</i></p> <p> This list is updated by selecting atom types in the <b>Atom Chooser</b>.</p> <p> <img source=\"ui/whatsthis/HotTip.png\"><br> <b>Hot Tip:</b> To specify multiple atom types, hold down the <b>Shift Key</b> while selecting atom types in the <b>Atom Chooser</b>. </p>""") propMgr.autoBondCheckBox.setWhatsThis( """<b>Auto bond</b> <p> When enabled, additional bonds are formed automatically with the deposited atom if possile. </p>""") propMgr.reshapeSelectionCheckBox.setWhatsThis( """<b>Dragging reshapes selection</b> <p> When enabled, selected atoms are "reshaped" when dragged by the mouse. </p> <p> When disabled (default), selected atoms follow the mouse as typical when dragged. </p>""") propMgr.waterCheckBox.setWhatsThis( """<b><u>Z depth filter</u></b> <b>(water surface)</b> <p> Enables/disables the Z depth filter for hover highlighting and single atom/bond selection. When enabled, a semi-transparent "water surface" is displayed that remains parallel to the screen. This gives the illusion that atoms below the surface are under water. Atoms and bonds under the water are not highlighted and cannot be selected by clicking on them. This is useful when working on local regions of large structures since only atoms and bonds above the surface are highlighted. This can speed up interactive response times significantly.</p> <p> <img source=\"ui/whatsthis/HotTip.png\"><br> The water surface can be made deeper/shallower by holding down the <b>Control + Shift</b> keys together and pushing/pulling the mouse while holding down the middle mouse button.</p> <p> <b>Note:</b> Region selections are immume to the Z depth filter. </p>""") propMgr.highlightingCheckBox.setWhatsThis( """<b>Hover highlighting</b> <p> Enables/disables <i>hover highlighting</i>. When enabled, atoms and bonds under the cursor are highlighted to indicate what would be selected if the user clicks the left mouse button. </p>""") propMgr.showSelectedAtomInfoCheckBox.setWhatsThis( """<b>Show Selected Atoms's Info</b> <p> When checked an atom's position is displayed as X Y Z coordinates. These coordinates can also be adjusted with provided spin boxes. </p>""") return def whatsThis_PartLibPropertyManager(propMgr): """ Add "What's This" text for widgets in the Part Library Property Manager. """ propMgr.previewGroupBox.setWhatsThis( """<b>Preview Window</b> <p> This window displays the selected part chosen from the library. The user may also rotate the part and set a hot spot while the part is displayed in the preview window""" ) propMgr.partLibGroupBox .setWhatsThis( """<b>Part Library</b> <p> This is a directory of available parts contained in the part library """ ) return def whatsThis_PasteItemsPropertyManager(propMgr): """ Add "What's This" text for widgets in the Part Library Property Manager. """ propMgr.previewGroupBox.setWhatsThis( """<b>Preview Window</b> <p> This window displays the selected part chosen from the clipboard. The user may also rotate the part and set a hot spot while the part is displayed in the preview window""" ) propMgr.clipboardGroupBox.setWhatsThis( """<b>Clipboard</b> <p> This is a list of items contained on the Clipboard """ ) return def WhatsThis_EditDnaDisplayStyle_PropertyManager(propMgr): """ Add "What's This" text for widgets in the Edit DNA Display Style Property Manager. """ propMgr.favoritesComboBox.setWhatsThis( """<b>DNA Display Style Favorites</b> <p> A list of DNA display style favorites added by the user that can be applied by pressing the <b>Apply Favorite</b> button. The settings are only in effect whenever the <i>Global Display Style</i> is set to DNA Cylinder or to DNA objects that have their display style set to DNA Cylinder.</p> <p> <img source=\"ui/actions/Properties Manager/ApplyFavorite.png\"><br> The <b>Apply Favorite</b> button must be clicked to apply the current favorite selected from this list. <b>Factory default settings</b> resets all color options to their default settings.</p> <p> <img source=\"ui/actions/Properties Manager/AddFavorite.png\"><br> The <b>Add Favorite</b> button allows new favorites to be added to the list. This saves the current settings to a user specified name.</p> <p> <img source=\"ui/actions/Properties Manager/DeleteFavorite.png\"><br> The <b>Delete Favorite</b> button allows an existing favorite to be deleted from the list. <b>Factory default settings</b> can never be deleted, however. """) propMgr.applyFavoriteButton.setWhatsThis( """<b>Apply Favorite </b> <p> <img source=\"ui/actions/Properties Manager/ApplyFavorite.png\"><br> Applies the settings stored in the selected Favorite to the current settings. """) propMgr.addFavoriteButton.setWhatsThis( """<b>Add Favorite </b> <p> <img source=\"ui/actions/Properties Manager/AddFavorite.png\"><br> Allows a new Favorite to be added to the list. This saves the current settings to a user specified Favorite name. """) propMgr.deleteFavoriteButton.setWhatsThis( """<b>Delete Favorite </b> <p> <img source=\"ui/actions/Properties Manager/DeleteFavorite.png\"><br> Allows an existing favorite to be deleted from the list. <b>Factory default settings</b> can never be deleted, however. """) propMgr.loadFavoriteButton.setWhatsThis( """<b>Load Favorite </b> <p> <img source=\"ui/actions/Properties Manager/LoadFavorite.png\"><br> Allows the user to load a <i>favorites file</i> from disk to be added to the favorites list. Favorites files must have a .txt extension. """) propMgr.saveFavoriteButton.setWhatsThis( """<b>Save Favorite </b> <p> <img source=\"ui/actions/Properties Manager/SaveFavorite.png\"><br> Writes the selected favorite (selected in the combobox) to a file that can be given to another NE1 user (i.e. as an email attachment). The file is saved with a .txt entension so that it can loaded back using the <b>Load Favorite</b> button. """) return def WhatsThis_ColorScheme_PropertyManager(propMgr): """ Add "What's This" text for widgets in the Color Scheme Property Manager. """ propMgr.favoritesComboBox.setWhatsThis( """<b>Color Scheme Favorites</b> <p> A list of color scheme favorites added by the user that can be applied to NanoEngineer-1 by pressing the <b>Apply Favorite</b> button.</p> <p> <img source=\"ui/actions/Properties Manager/ApplyColorSchemeFavorite.png\"><br> The <b>Apply Favorite</b> button must be clicked to apply the current favorite selected from this list. <b>Factory default settings</b> resets all color options to their default settings.</p> <p> <img source=\"ui/actions/Properties Manager/AddFavorite.png\"><br> The <b>Add Favorite</b> button allows new favorite color schemes to be added to the list. This saves the current color settings to a user specified name.</p> <p> <img source=\"ui/actions/Properties Manager/DeleteFavorite.png\"><br> The <b>Delete Favorite</b> button allows an existing favorite to be deleted from the list. <b>Factory default settings</b> can never be deleted, however. """) propMgr.applyFavoriteButton.setWhatsThis( """<b>Apply Favorite </b> <p> <img source=\"ui/actions/Properties Manager/ApplyColorSchemeFavorite.png\"><br> Applies the color settings stored in the selected Color Scheme Favorite to the current color scheme. """) propMgr.addFavoriteButton.setWhatsThis( """<b>Add Favorite </b> <p> <img source=\"ui/actions/Properties Manager/AddFavorite.png\"><br> Allows a new Color Scheme Favorite to be added to the list. This saves the current color settings to a user specified name. """) propMgr.deleteFavoriteButton.setWhatsThis( """<b>Delete Favorite </b> <p> <img source=\"ui/actions/Properties Manager/DeleteFavorite.png\"><br> Allows an existing favorite to be deleted from the list. <b>Factory default settings</b> can never be deleted, however. """) propMgr.loadFavoriteButton.setWhatsThis( """<b>Load Favorite </b> <p> <img source=\"ui/actions/Properties Manager/LoadFavorite.png\"><br> Allows the user to load a <i>favorites file</i> from disk to be added to the favorites list. Favorites files must have a .txt extension. """) propMgr.saveFavoriteButton.setWhatsThis( """<b>Save Favorite </b> <p> <img source=\"ui/actions/Properties Manager/SaveFavorite.png\"><br> Writes the selected favorite (selected in the combobox) to a file that can be given to another NE1 user (i.e. as an email attachment). The file is saved with a .txt entension so that it can loaded back using the <b>Load Favorite</b> button. """) propMgr.backgroundColorComboBox.setWhatsThis( """ <b>Background Color </b> <p> Allows user to change the color of the background. </p>""") propMgr.hoverHighlightingStyleComboBox.setWhatsThis( """ <b>Highlighting Style </b> <p> Allows user to change the type of pattern the indicates a highlighted object. </p>""") propMgr.hoverHighlightingColorComboBox.setWhatsThis( """ <b>Highlighting Color </b> <p> Allows user to change the color of the highlight. </p>""") propMgr.selectionStyleComboBox.setWhatsThis( """ <b>Selection Style </b> <p> Allows user to change the type of pattern the indicates a selected object. </p>""") propMgr.selectionColorComboBox.setWhatsThis( """ <b>Selction Color </b> <p> Allows user to change the color of a selected object. </p>""") propMgr.enableFogCheckBox.setWhatsThis( """ <b>Fog </b> <p> Enable/Disable a fog over the working area. </p>""") return def WhatsThis_LightingScheme_PropertyManager(propMgr): """ Add "What's This" text for widgets in the Lighting Scheme Property Manager. """ propMgr.favoritesComboBox.setWhatsThis( """<b>Lighting Scheme Favorites</b> <p> A list of lighting scheme favorites added by the user that can be applied to NanoEngineer-1 by pressing the <b>Apply Favorite</b> button.</p> <p> <img source=\"ui/actions/Properties Manager/ApplyLightingSchemeFavorite.png\"><br> The <b>Apply Favorite</b> button must be clicked to apply the current favorite selected from this list. <b>Factory default settings</b> resets all color options to their default settings.</p> <p> <img source=\"ui/actions/Properties Manager/AddFavorite.png\"><br> The <b>Add Favorite</b> button allows new favorite color schemes to be added to the list. This saves the current color settings to a user specified name.</p> <p> <img source=\"ui/actions/Properties Manager/DeleteFavorite.png\"><br> The <b>Delete Favorite</b> button allows an existing favorite to be deleted from the list. <b>Factory default settings</b> can never be deleted, however. """) propMgr.applyFavoriteButton.setWhatsThis( """<b>Apply Favorite </b> <p> <img source=\"ui/actions/Properties Manager/ApplyLightingSchemeFavorite.png\"><br> Applies the lighting settings stored in the selected Lighting Scheme Favorite to the current color scheme. """) propMgr.addFavoriteButton.setWhatsThis( """<b>Add Favorite </b> <p> <img source=\"ui/actions/Properties Manager/AddFavorite.png\"><br> Allows a new Lighting Scheme Favorite to be added to the list. This saves the current color settings to a user specified name. """) propMgr.deleteFavoriteButton.setWhatsThis( """<b>Delete Favorite </b> <p> <img source=\"ui/actions/Properties Manager/DeleteFavorite.png\"><br> Allows an existing favorite to be deleted from the list. <b>Factory default settings</b> can never be deleted, however. """) propMgr.loadFavoriteButton.setWhatsThis( """<b>Load Favorite </b> <p> <img source=\"ui/actions/Properties Manager/LoadFavorite.png\"><br> Allows the user to load a <i>favorites file</i> from disk to be added to the favorites list. Favorites files must have a .txt extension. """) propMgr.saveFavoriteButton.setWhatsThis( """<b>Save Favorite </b> <p> <img source=\"ui/actions/Properties Manager/SaveFavorite.png\"><br> Writes the selected favorite (selected in the combobox) to a file that can be given to another NE1 user (i.e. as an email attachment). The file is saved with a .txt entension so that it can loaded back using the <b>Load Favorite</b> button. """) propMgr.lightComboBox.setWhatsThis( """<b> Light </b> <p> The current light to modify. NanoEngineer-1 supports up to 3 light sources. </p>""") propMgr.enableLightCheckBox.setWhatsThis( """<b> On Check Box</b> <p> Enables/disables the current light. </p>""") propMgr.lightColorComboBox.setWhatsThis( """<b> Color </b> <p> Change color of the current light. </p>""") propMgr.ambientDoubleSpinBox.setWhatsThis( """<b> Ambient </b> <p> The ambient value (between 0-1) of the current light. </p>""") propMgr.diffuseDoubleSpinBox.setWhatsThis( """<b> Diffuse </b> <p> The diffuse value (between 0-1) of the current light. </p>""") propMgr.specularDoubleSpinBox.setWhatsThis( """<b> Specular </b> <p> The specularity value (between 0-1) of the current light. </p>""") propMgr.xDoubleSpinBox.setWhatsThis( """<b> X Position </b> <p> The X coordinite of the current light position. </p>""") propMgr.yDoubleSpinBox.setWhatsThis( """<b> Y Position </b> <p> The Y coordinite of the current light position. </p>""") propMgr.zDoubleSpinBox.setWhatsThis( """<b> Z Position </b> <p> The Z coordinite of the current light position. </p>""") propMgr.enableMaterialPropertiesCheckBox.setWhatsThis( """<b> Material Properties</b> <p> Enables/Disables the material properties. </p>""") propMgr.finishDoubleSpinBox.setWhatsThis( """<b> Finish </b> <p> Material finish value (between 0-1) </p>""") propMgr.shininessDoubleSpinBox.setWhatsThis( """<b> Shininess </b> <p> Material shininess value (between 0-60). </p>""") propMgr.brightnessDoubleSpinBox.setWhatsThis( """<b> Brightness </b> <p> Material brightness value (between 0-1). </p>""") return def WhatsThis_EditProteinDisplayStyle_PropertyManager(propMgr): """ Add "What's This" text for widgets in the Edit Protein Display Style Property Manager. """ propMgr.favoritesComboBox.setWhatsThis( """<b>Protein Display Style Favorites</b> <p> A list of Protein display style favorites added by the user that can be applied by pressing the <b>Apply Favorite</b> button. </p> <p> <img source=\"ui/actions/Properties Manager/ApplyFavorite.png\"><br> The <b>Apply Favorite</b> button must be clicked to apply the current favorite selected from this list. <b>Factory default settings</b> resets all options to their default settings.</p> <p> <img source=\"ui/actions/Properties Manager/AddFavorite.png\"><br> The <b>Add Favorite</b> button allows new favorites to be added to the list. This saves the current settings to a user specified name.</p> <p> <img source=\"ui/actions/Properties Manager/DeleteFavorite.png\"><br> The <b>Delete Favorite</b> button allows an existing favorite to be deleted from the list. <b>Factory default settings</b> can never be deleted, however. """) propMgr.applyFavoriteButton.setWhatsThis( """<b>Apply Favorite </b> <p> <img source=\"ui/actions/Properties Manager/ApplyFavorite.png\"><br> Applies the settings stored in the selected Favorite to the current settings. """) propMgr.addFavoriteButton.setWhatsThis( """<b>Add Favorite </b> <p> <img source=\"ui/actions/Properties Manager/AddFavorite.png\"><br> Allows a new Favorite to be added to the list. This saves the current settings to a user specified Favorite name. """) propMgr.deleteFavoriteButton.setWhatsThis( """<b>Delete Favorite </b> <p> <img source=\"ui/actions/Properties Manager/DeleteFavorite.png\"><br> Allows an existing favorite to be deleted from the list. <b>Factory default settings</b> can never be deleted, however. """) propMgr.loadFavoriteButton.setWhatsThis( """<b>Load Favorite </b> <p> <img source=\"ui/actions/Properties Manager/LoadFavorite.png\"><br> Allows the user to load a <i>favorites file</i> from disk to be added to the favorites list. Favorites files must have a .txt extension. """) propMgr.saveFavoriteButton.setWhatsThis( """<b>Save Favorite </b> <p> <img source=\"ui/actions/Properties Manager/SaveFavorite.png\"><br> Writes the selected favorite (selected in the combobox) to a file that can be given to another NE1 user (i.e. as an email attachment). The file is saved with a .txt entension so that it can loaded back using the <b>Load Favorite</b> button. """) return def whatsThis_OrderDna_PropertyManager(propMgr): """ Add "What's This" text for widgets in the Color Scheme Property Manager. """ propMgr.includeStrandsComboBox.setWhatsThis( """<b>Include strands</b> <p> Strands to include in the DNA order file. """) propMgr.numberOfBasesLineEdit.setWhatsThis( """<b>Total nucleotides</b> <p> The total number of nucleotides (bases) that will be written to the DNA order file. </p> """) propMgr.numberOfXBasesLineEdit.setWhatsThis( """<b>Unassigned</b> <p> The total number of unassigned "X" bases that will be written to the DNA order file. There should be 0 unassigned bases if the file will be used to place an order. </p> """) propMgr.viewDnaOrderFileButton.setWhatsThis( """<b>View DNA Order File</b> <p> View the DNA Order file in comma-separated values (CVS) format. The file is temporary and should be saved via the text editor to a permanant name/location. </p> """) return
NanoCAD-master
cad/src/ne1_ui/WhatsThisText_for_PropertyManagers.py
# Copyright 2004-2007 Nanorex, Inc. See LICENSE file for details. """ ToolTipText_for_MainWindow.py This file provides functions for setting the Tool tip text for widgets in the Property Managers. @version:$Id$ @copyright: 2004-2007 Nanorex, Inc. See LICENSE file for details. """ def ToolTip_CookiePropertyManager(propMgr): """ "Tool Tip" text for widgets in the BuildCrystal Property Manager. """ propMgr.addLayerButton.setToolTip("Add Layer") propMgr.latticeCBox.setToolTip("Select Lattice Type") propMgr.rotateGridByAngleSpinBox.setToolTip("Set Angle") propMgr.rotGridAntiClockwiseButton.setToolTip("Rotate Counter Clockwise") propMgr.rotGridClockwiseButton.setToolTip("Rotate Clockwise") propMgr.layerCellsSpinBox.setToolTip("Number of Lattice Cells") propMgr.dispModeComboBox.setToolTip("Display Style") propMgr.layerThicknessLineEdit.setToolTip(\ "Thickness of Layer in Angstroms is Displayed") propMgr.gridLineCheckBox.setToolTip("Show Grid") propMgr.fullModelCheckBox.setToolTip("Show Model") propMgr.snapGridCheckBox.setToolTip("Snap to Grid") propMgr.freeViewCheckBox.setToolTip("Free View") def ToolTip_RotaryMotorPropertyManager(propMgr): """ "Tool Tip" text for widgets in the Rotary Motor Property Manager. """ propMgr.torqueDblSpinBox.setToolTip("Motor torque") propMgr.initialSpeedDblSpinBox.setToolTip("Initial speed") propMgr.finalSpeedDblSpinBox.setToolTip("Final speed") propMgr.dampersCheckBox.setToolTip("Turn motor dampers on/off") propMgr.enableMinimizeCheckBox.setToolTip("Enable motor during" \ " minimizations") propMgr.motorLengthDblSpinBox.setToolTip("Set motor length") propMgr.motorRadiusDblSpinBox.setToolTip("Set motor radius") propMgr.spokeRadiusDblSpinBox.setToolTip("Set spoke radius") propMgr.motorColorComboBox.setToolTip("Change motor color") propMgr.directionPushButton.setToolTip("Set rotation direction") def ToolTip_LinearMotorPropertyManager(propMgr): """ Tool Tip text for widgets in the Linear Motor Property Manager. """ propMgr.forceDblSpinBox.setToolTip("Specify motor force") propMgr.enableMinimizeCheckBox.setToolTip("Enabled motor during" \ " minimizations") propMgr.stiffnessDblSpinBox.setToolTip("Specify stiffness") propMgr.motorLengthDblSpinBox.setToolTip("Set motor length") propMgr.motorWidthDblSpinBox.setToolTip("Set motor width") propMgr.spokeRadiusDblSpinBox.setToolTip("Set motor radius") propMgr.motorColorComboBox.setToolTip("Change motor color") propMgr.directionPushButton.setToolTip("Set motor direction") def ToolTip_GrapheneGeneratorPropertyManager(propMgr): """ "Tool Tip" text for widgets in the Graphene Property Manager. """ propMgr.heightField.setToolTip("The Height in Angstroms") propMgr.widthField.setToolTip("The Width in Angstroms") propMgr.bondLengthField.setToolTip("Adjust Bond Length") propMgr.endingsComboBox.setToolTip("Set Sheet Endings") def ToolTip_NanotubeGeneratorPropertyManager(propMgr): """ "ToolTip" text for widgets in the Nanotube Property Manager. """ propMgr.chiralityNSpinBox.setToolTip("Chirality (n)") propMgr.chiralityMSpinBox.setToolTip("Chirality (m)") propMgr.typeComboBox.setToolTip("Select Tube Type") propMgr.endingsComboBox.setToolTip("Select Tube Endings") propMgr.lengthField.setToolTip("Length of the Nanotube in Angstroms") propMgr.bondLengthField.setToolTip("Length Between Atoms in Angstroms") propMgr.twistSpinBox.setToolTip("Twist") propMgr.zDistortionField.setToolTip("Z-distortion") propMgr.bendSpinBox.setToolTip("Bend Tube") propMgr.xyDistortionField.setToolTip("XY-distortion") propMgr.mwntCountSpinBox.setToolTip("Number of Tubes") propMgr.mwntSpacingField.setToolTip("Spacing Between Multiple Tubes") def ToolTip_InsertDna_PropertyManager(propMgr): """ "ToolTip" text for the DnaDuplex Property Manager """ propMgr.conformationComboBox.setToolTip("Only B-DNA is currently "\ "supported in NanoEngineer-1") propMgr.dnaModelComboBox.setToolTip("Selects Between Model Types") propMgr.numberOfBasePairsSpinBox.setToolTip("Number of Base Pairs") propMgr.basesPerTurnDoubleSpinBox.setToolTip("Bases Per Turn") propMgr.duplexLengthLineEdit.setToolTip("Duplex Length") propMgr.dnaRubberBandLineDisplayComboBox.setToolTip("Display as Ribbon or "\ "Ladder") propMgr.lineSnapCheckBox.setToolTip("Enable Line Snap") def ToolTip_InsertPeptide_PropertyManager(propMgr): """ "ToolTip" text for the Peptide Generator Property Manager """ return def ToolTip_BuildAtomsPropertyManager(propMgr): """ "ToolTip" text for widgets in the QuteMolX Property Manager. """ propMgr.selectionFilterCheckBox.setToolTip("Atom Selection Filter") propMgr.filterlistLE.setToolTip("Atom Selection Filter List") propMgr.reshapeSelectionCheckBox.setToolTip("Enable/disable reshaping the selection while dragging selected atom") propMgr.autoBondCheckBox.setToolTip("Enable/disable atomic auto-bonding") propMgr.waterCheckBox.setToolTip("Enable/disable water surface") propMgr.highlightingCheckBox.setToolTip("Enable/disable hover highlighting") propMgr.showSelectedAtomInfoCheckBox.setToolTip("Show Atom Info") def ToolTip_MoviePropertyManager(propMgr): """ "ToolTip" text for widgets in the Movie Property Manager. """ propMgr.frameNumberSpinBox.setToolTip("Advance to Frame") propMgr.movieLoop_checkbox.setToolTip("Loop Movie") propMgr.frameSkipSpinBox.setToolTip("Skip Frames") propMgr.fileOpenMovieAction.setToolTip("Open Movie") propMgr.fileSaveMovieAction.setToolTip("Save Movie") propMgr.moviePlayRevAction.setToolTip("Reverse") propMgr.moviePlayAction.setToolTip("Forward") propMgr.moviePauseAction.setToolTip("Pause") propMgr.movieMoveToEndAction.setToolTip("Last Frame") propMgr.movieResetAction.setToolTip("Reset Movie") propMgr.frameNumberSlider.setToolTip("Advance Frame") def ToolTip_DnaSequenceEditor(propMgr): """ "ToolTip" text for widgets in the DNA Sequence Editor. """ propMgr.loadSequenceButton.setToolTip("Load Sequence") propMgr.sequenceTextEdit.setToolTip("Sequence edit field") propMgr.saveSequenceButton.setToolTip("Save Sequence") propMgr.baseDirectionChoiceComboBox.setToolTip("Strand Directon") propMgr.findLineEdit.setToolTip("Find Sequence") propMgr.findPreviousToolButton.setToolTip("Find Previous") propMgr.findNextToolButton.setToolTip("Find Next") propMgr.replacePushButton.setToolTip("Replace") propMgr.sequenceTextEdit_mate.setToolTip("Complement sequence (read-only)") return def ToolTip_ProteinSequenceEditor(propMgr): """ "ToolTip" text for widgets in the Protein Sequence Editor. """ propMgr.loadSequenceButton.setToolTip("Load amino acid sequence from FASTA file") propMgr.sequenceTextEdit.setToolTip("Sequence field (read-only)") propMgr.saveSequenceButton.setToolTip("Save sequence") propMgr.findLineEdit.setToolTip("Find Sequence") propMgr.findPreviousToolButton.setToolTip("Find Previous") propMgr.findNextToolButton.setToolTip("Find Next") propMgr.replacePushButton.setToolTip("Replace") propMgr.secStrucTextEdit.setToolTip("Secondary structure (read-only)") propMgr.aaRulerTextEdit.setToolTip("Sequence ruler") return def ToolTip_MovePropertyManager(propMgr): """ "ToolTip" text for widgets in the Move Property Manager. """ # Translate group box widgets propMgr.translateComboBox.setToolTip("Translation Options") propMgr.transFreeButton.setToolTip("Unconstrained Translation") propMgr.transXButton.setToolTip("X Translation (X)") propMgr.transYButton.setToolTip("Y Translation (Y)") propMgr.transZButton.setToolTip("Z Translation (Z)") propMgr.transAlongAxisButton.setToolTip("Axial Translation/Rotation (A)") propMgr.moveFromToButton.setToolTip("Translate between two defined points") # By Delta XYZ widgets propMgr.moveDeltaXSpinBox.setToolTip("Delta X") propMgr.moveDeltaYSpinBox.setToolTip("Delta Y") propMgr.moveDeltaZSpinBox.setToolTip("Delta Z") propMgr.transDeltaPlusButton.setToolTip( "Move selection by + (plus) delta XYZ") propMgr.transDeltaMinusButton.setToolTip( "Move selection by - (minus) delta XYZ") # To XYZ Position widgets propMgr.moveXSpinBox.setToolTip("X Coordinate") propMgr.moveYSpinBox.setToolTip("Y Coordinate") propMgr.moveZSpinBox.setToolTip("Z Coordinate") propMgr.moveAbsoluteButton.setToolTip( "Move selection to absolute XYZ position") # Rotate group box widgets propMgr.rotateComboBox.setToolTip("Rotate Options") # Free Drag widgets. propMgr.rotateFreeButton.setToolTip("Unconstrained Rotation") propMgr.rotateXButton.setToolTip("X Rotation (X)") propMgr.rotateYButton.setToolTip("Y Rotation (Y)") propMgr.rotateZButton.setToolTip("Z Rotation (Z)") propMgr.rotAlongAxisButton.setToolTip("Axial Translation/Rotation (A)") propMgr.rotateAsUnitCB.setToolTip("Rotate As Unit") # By Specified Angle widgets propMgr.rotateThetaSpinBox.setToolTip("Angle of rotation") propMgr.rotateThetaPlusButton.setToolTip("Rotate") propMgr.rotateThetaMinusButton.setToolTip("Rotate (minus)") def ToolTip_QuteMolPropertyManager(propMgr): """ Add "What's This" text for widgets in the QuteMolX Property Manager. """ propMgr.launchQuteMolButton.setToolTip("Launch QuteMolX") propMgr.axesCombobox.setToolTip("Render Axes") propMgr.basesCombobox.setToolTip("Render Bases") def ToolTip_PartLibPropertyManager(propMgr) : """ Add "What's This" text for widgets in the Part Library Property Manager. """ propMgr.previewGroupBox.setToolTip("Preview Window") propMgr.partLibGroupBox.setToolTip("Part Library") def ToolTip_PasteItemPropertyManager(propMgr) : """ Add "What's This" text for widgets in the Paste Items Property Manager. """ propMgr.previewGroupBox.setToolTip("Preview Window") propMgr.clipboardGroupBox.setToolTip("Clipboard") def ToolTip_EditProteinDisplayStyle_PropertyManager(propMgr): """ Add "What's This" text for widgets in the Edit DNA Display Style Property Manager. """ return def ToolTip_EditDnaDisplayStyle_PropertyManager(propMgr): """ Add "What's This" text for widgets in the Edit DNA Display Style Property Manager. """ propMgr.favoritesComboBox.setToolTip("List of Favorites") propMgr.dnaRenditionComboBox.setToolTip("Change DNA Rendition") propMgr.dnaComponentComboBox.setToolTip("Change Component Display Settings") propMgr.standLabelColorComboBox.setToolTip("Change Strand Label Color") propMgr.axisShapeComboBox.setToolTip("Change Axis Shape") propMgr.axisScaleDoubleSpinBox.setToolTip("Change Axis Scale") propMgr.axisColorComboBox.setToolTip("Change Axis Color") propMgr.axisEndingStyleComboBox.setToolTip("Change Axis Ending Style") propMgr.strandsShapeComboBox.setToolTip("Change Strands Shape") propMgr.strandsScaleDoubleSpinBox.setToolTip("Change Strands Scale") propMgr.strandsColorComboBox.setToolTip("Change Strands Color") propMgr.strandsArrowsComboBox.setToolTip("Change Strands Arrows") propMgr.strutsShapeComboBox.setToolTip("Change Struts Shape") propMgr.strutsScaleDoubleSpinBox.setToolTip("Change Struts Scale" ) propMgr.strutsColorComboBox.setToolTip("Change Struts Color") propMgr.nucleotidesShapeComboBox.setToolTip("Change Nucleotides Shape") propMgr.nucleotidesScaleDoubleSpinBox.setToolTip("Change Nucleotides Scale") propMgr.nucleotidesColorComboBox.setToolTip("Change Nucleotides Color") propMgr.dnaStyleBasesDisplayLettersCheckBox.setToolTip("Display DNA Bases") return def ToolTip_ColorScheme_PropertyManager(propMgr): """ Add tooltip text for widgets in the Color Scheme Property Manager. """ propMgr.favoritesComboBox.setToolTip("List of favorites") propMgr.backgroundColorComboBox.setToolTip("Change background color") propMgr.hoverHighlightingStyleComboBox.setToolTip("Change hover highlighting style") propMgr.hoverHighlightingColorComboBox.setToolTip("Change hover highlighting color") propMgr.selectionStyleComboBox.setToolTip("Change selection style") propMgr.selectionColorComboBox.setToolTip("Change selection color") return def ToolTip_LightingScheme_PropertyManager(propMgr): """ Add tooltip text for widgets in the Lighting Scheme Property Manager. """ return
NanoCAD-master
cad/src/ne1_ui/ToolTipText_for_PropertyManagers.py
# Copyright 2004-2007 Nanorex, Inc. See LICENSE file for details. """ $Id$ """ # -*- coding: utf-8 -*- from PyQt4 import QtCore, QtGui from PyQt4.Qt import Qt, QWidget, QVBoxLayout from utilities.icon_utilities import geticon import ne1_ui.Ui_MainWindowWidgets as Ui_MainWindowWidgets import ne1_ui.Ui_MainWindowWidgetConnections as Ui_MainWindowWidgetConnections import ne1_ui.menus.Ui_FileMenu as Ui_FileMenu import ne1_ui.menus.Ui_EditMenu as Ui_EditMenu import ne1_ui.menus.Ui_ViewMenu as Ui_ViewMenu import ne1_ui.menus.Ui_InsertMenu as Ui_InsertMenu import ne1_ui.menus.Ui_ToolsMenu as Ui_ToolsMenu import ne1_ui.menus.Ui_SimulationMenu as Ui_SimulationMenu import ne1_ui.menus.Ui_RenderingMenu as Ui_RenderingMenu import ne1_ui.help.Ui_HelpMenu as Ui_HelpMenu import ne1_ui.toolbars.Ui_StandardToolBar as Ui_StandardToolBar import ne1_ui.toolbars.Ui_ViewToolBar as Ui_ViewToolBar import ne1_ui.toolbars.Ui_StandardViewsToolBar as Ui_StandardViewsToolBar import ne1_ui.toolbars.Ui_DisplayStylesToolBar as Ui_DisplayStylesToolBar import ne1_ui.toolbars.Ui_SelectToolBar as Ui_SelectToolBar import ne1_ui.toolbars.Ui_SimulationToolBar as Ui_SimulationToolBar import ne1_ui.toolbars.Ui_BuildToolsToolBar as Ui_BuildToolsToolBar import ne1_ui.toolbars.Ui_BuildStructuresToolBar as Ui_BuildStructuresToolBar import ne1_ui.toolbars.Ui_RenderingToolBar as Ui_RenderingToolBar from widgets.StatusBar import StatusBar import foundation.env as env class Ui_MainWindow(object): """ The Ui_MainWindow class creates the main window and all its widgets. """ def setupUi(self): """ Sets up the main window UI in the following order: - Create all main window widgets used by menus and/or toolbars. - Create main menu bar and its menus - Create main toolbars - Create the statusbar """ self.setObjectName("MainWindow") self.setEnabled(True) self.setWindowIcon(geticon("ui/border/MainWindow.png")) self.setWindowTitle("NanoEngineer-1") # Set minimum width and height of the main window. # To do: Check that the current screen size is at least 800 x 600. MINIMUM_MAIN_WINDOW_SIZE = (800, 600) # Mark 2008-02-08 self.setMinimumWidth(MINIMUM_MAIN_WINDOW_SIZE[0]) self.setMinimumHeight(MINIMUM_MAIN_WINDOW_SIZE[1]) # Create all widgets for all main window menus and toolbars. Ui_MainWindowWidgets.setupUi(self) # Set up all main window widget connections to their slots. Ui_MainWindowWidgetConnections.setupUi(self) # Toolbars should come before menus. The only reason this is necessary # is that the "View > Toolbars" submenu needs the main window toolbars # to be created before it is created (in self._setupToolbars() self._setupMenus() # Now set all UI text for main window widgets. # Note: I intend to compile all retranslateUi() functions into a single # function/method soon. mark 2007-12-31. self._retranslateUi() # The central widget of the NE1 main window contains a VBoxLayout # containing the Command Toolbar at top. Below that will be either: # 1. a Part Window widget (the default), or # 2. a QWorkspace widget (for MDI support) which will contain only # a single Part Window (experimental) # The QWorkspace can be enabled by setting the following debug pref # to True: "Enable QWorkspace for MDI support? (next session)" # Mark 2007-12-31 _centralWidget = QWidget() self.setCentralWidget(_centralWidget) self.centralAreaVBoxLayout = QVBoxLayout(_centralWidget) self.centralAreaVBoxLayout.setMargin(0) self.centralAreaVBoxLayout.setSpacing(0) # Add the Command Toolbar to the top of the central widget. # Note: Main window widgets must have their text set # via retranslateUi() before instantiating CommandToolbar. from commandToolbar.CommandToolbar import CommandToolbar self.commandToolbar = CommandToolbar(self) self.centralAreaVBoxLayout.addWidget(self.commandToolbar) # Create the statusbar for the main window. self.setStatusBar(StatusBar(self)) # = # Create the "What's This?" text for all main window widgets. from ne1_ui.WhatsThisText_for_MainWindow import createWhatsThisTextForMainWindowWidgets createWhatsThisTextForMainWindowWidgets(self) # IMPORTANT: All main window widgets and their "What's This" text should # be created before this line. [If this is not possible, we'll need to # split out some functions within this one which can be called # later on individual QActions and/or QWidgets. bruce 060319] from foundation.whatsthis_utilities import fix_whatsthis_text_and_links fix_whatsthis_text_and_links(self) # (main call) Fixes bug 1136. Mark 051126. fix_whatsthis_text_and_links(self.toolsMoveRotateActionGroup) # This is needed to add links to the "Translate" and "Rotate" # QAction widgets on the standard toolbar, since those two # widgets are not direct children of the main window. # Fixes one of the many bugs listed in bug 2412. Mark 2007-12-19 def _setupToolbars(self): """ Populates all Main Window toolbars. Also restores the state of toolbars from the NE1 last session. """ # Add toolbars to the Top area of the main window (first row) toolbarArea = Qt.TopToolBarArea Ui_StandardToolBar.setupUi(self, toolbarArea) Ui_BuildToolsToolBar.setupUi(self, toolbarArea) self.addToolBarBreak (toolbarArea) # Starts second row. Ui_ViewToolBar.setupUi(self, toolbarArea) Ui_StandardViewsToolBar.setupUi(self, toolbarArea) Ui_SimulationToolBar.setupUi(self, toolbarArea) # Add toolbars to the Right area of the main window. toolbarArea = Qt.RightToolBarArea Ui_SelectToolBar.setupUi(self, toolbarArea) Ui_DisplayStylesToolBar.setupUi(self, toolbarArea) Ui_RenderingToolBar.setupUi(self, toolbarArea) # This is hidden the first time NE1 starts (below). # BTW, I don't think the "Build Structures" toolbar is necessary since # all its options are available prominentaly on the Command Toolbar. # I intend to completely remove it soon. Mark 2008-02-29. Ui_BuildStructuresToolBar.setupUi(self, toolbarArea) from utilities.prefs_constants import toolbar_state_prefs_key # This fixes bug 2482. if not env.prefs[toolbar_state_prefs_key] == 'defaultToolbarState': # Restore the state of the toolbars from the last session. toolBarState = QtCore.QByteArray(env.prefs[toolbar_state_prefs_key]) self.restoreState(toolBarState) else: # No previous session. Hide only these toolbars by default. self.buildStructuresToolBar.hide() return def _setupMenus(self): """ Populates all main window menus and adds them to the main menu bar. """ # Populate the menus that appear in the main window menu bar. Ui_FileMenu.setupUi(self) Ui_EditMenu.setupUi(self) Ui_ViewMenu.setupUi(self) Ui_InsertMenu.setupUi(self) Ui_ToolsMenu.setupUi(self) Ui_SimulationMenu.setupUi(self) Ui_RenderingMenu.setupUi(self) Ui_HelpMenu.setupUi(self) # Add menus to the main window menu bar. self.MenuBar.addAction(self.fileMenu.menuAction()) self.MenuBar.addAction(self.editMenu.menuAction()) self.MenuBar.addAction(self.viewMenu.menuAction()) self.MenuBar.addAction(self.insertMenu.menuAction()) self.MenuBar.addAction(self.toolsMenu.menuAction()) self.MenuBar.addAction(self.simulationMenu.menuAction()) self.MenuBar.addAction(self.renderingMenu.menuAction()) self.MenuBar.addAction(self.helpMenu.menuAction()) # Add the MenuBar to the main window. self.setMenuBar(self.MenuBar) return def _retranslateUi(self): """ This method centralizes all calls that set UI text for the purpose of making it easier for the programmer to translate the UI into other languages. @see: U{B{The Qt Linquist Manual}<http://doc.trolltech.com/4/linguist-manual.html>} """ self.setWindowTitle(QtGui.QApplication.translate( "MainWindow", "NanoEngineer-1", None, QtGui.QApplication.UnicodeUTF8)) # QActions Ui_MainWindowWidgets.retranslateUi(self) # Toolbars Ui_StandardToolBar.retranslateUi(self) Ui_ViewToolBar.retranslateUi(self) Ui_StandardViewsToolBar.retranslateUi(self) Ui_DisplayStylesToolBar.retranslateUi(self) Ui_BuildStructuresToolBar.retranslateUi(self) Ui_BuildToolsToolBar.retranslateUi(self) Ui_SelectToolBar.retranslateUi(self) Ui_SimulationToolBar.retranslateUi(self) Ui_RenderingToolBar.retranslateUi(self) # Menus and submenus Ui_FileMenu.retranslateUi(self) Ui_EditMenu.retranslateUi(self) Ui_ViewMenu.retranslateUi(self) Ui_InsertMenu.retranslateUi(self) Ui_ToolsMenu.retranslateUi(self) Ui_SimulationMenu.retranslateUi(self) Ui_RenderingMenu.retranslateUi(self) Ui_HelpMenu.retranslateUi(self)
NanoCAD-master
cad/src/ne1_ui/Ui_MainWindow.py
# Copyright 2007 Nanorex, Inc. See LICENSE file for details. """ Ui_ReportsDockWidget.py @author: Mark @version: $Id$ @copyright: 2007 Nanorex, Inc. See LICENSE file for details. To do: - Restore state (hidden/displayed) from last session. History: Mark 2008-01-05: Created. """ from history.HistoryWidget import HistoryWidget from PyQt4.Qt import Qt, QDockWidget, QWidget, QVBoxLayout, QTabWidget from PyQt4.Qt import QPalette, QSizePolicy from PM.PM_Colors import pmGrpBoxColor from PM.PM_Colors import getPalette from platform_dependent.PlatformDependent import make_history_filename from utilities.qt4transition import qt4todo from utilities.prefs_constants import displayReportsWidget_prefs_key import foundation.env as env class Ui_ReportsDockWidget(QDockWidget): """ The Ui_ReportsDockWidget class provides a DockWidget containing a tabbed widget providing convenient access to "reports". It is docked at the bottom of the NE1 main window. Currently, the history widget is the only report available. Future ideas for inclusion: - Python command line tab - NE1 command line tab - NE1 Job Manager tab """ _title = "Reports" def __init__(self, win): """ Constructor for Ui_ReportsDockWidget. @param win: The main window @type win: QMainWindow """ QDockWidget.__init__(self, win) self.win = win #Define layout self._containerWidget = QWidget() self.setWidget(self._containerWidget) # Create vertical box layout self.vBoxLayout = QVBoxLayout(self._containerWidget) vBoxLayout = self.vBoxLayout vBoxLayout.setMargin(0) vBoxLayout.setSpacing(0) self.setEnabled(True) self.setFloating(False) self.setVisible(True) self.setWindowTitle(self._title) self.setAutoFillBackground(True) self.setPalette(getPalette( None, QPalette.Window, pmGrpBoxColor)) # Create the reports tabwidget. It will contain the history tab # and possibly other tabs containing reports. self.reportsTabWidget = QTabWidget() self.reportsTabWidget.setObjectName("reportsTabWidget") self.reportsTabWidget.setCurrentIndex(0) self.reportsTabWidget.setAutoFillBackground(True) vBoxLayout.addWidget(self.reportsTabWidget) # Create the history tab. It will contain the history widget. self.historyTab = QWidget() self.historyTab.setObjectName("historyTab") self.reportsTabWidget.addTab(self.historyTab, "History") self.historyTabLayout = QVBoxLayout(self.historyTab) historyTabLayout = self.historyTabLayout historyTabLayout.setMargin(0) historyTabLayout.setSpacing(0) self._addHistoryWidget() self.setMinimumHeight(100) self.setSizePolicy( QSizePolicy(QSizePolicy.Policy(QSizePolicy.Expanding), QSizePolicy.Policy(QSizePolicy.Expanding))) win.addDockWidget(Qt.BottomDockWidgetArea, self) # Since the connection to the toggle() slot hasn't been made yet, # we must set the checkmark and hide/show self manually. if env.prefs[displayReportsWidget_prefs_key]: self.win.viewReportsAction.setChecked(True) # No slot connected yet, so show self manually. self.show() else: self.win.viewReportsAction.setChecked(False) # No slot connected yet, so hide self manually. self.hide() def _addHistoryWidget(self): """ Sets up and adds the history widget. """ histfile = make_history_filename() #@@@ ninad 061213 This is likely a new bug for multipane concept # as each file in a session will have its own history widget qt4todo('histfile = make_history_filename()') #bruce 050913 renamed self.history to self.history_object, and # deprecated direct access to self.history; code should use env.history # to emit messages, self.history_widget to see the history widget, # or self.history_object to see its owning object per se # rather than as a place to emit messages (this is rarely needed). self.history_object = HistoryWidget(self, filename = histfile, mkdirs = 1) # this is not a Qt widget, but its owner; # use self.history_widget for Qt calls that need the widget itself. self.history_widget = self.history_object.widget self.history_widget.setSizePolicy(QSizePolicy.Ignored,QSizePolicy.Ignored) # bruce 050913, in case future code splits history widget # (as main window subwidget) from history message recipient # (the global object env.history). env.history = self.history_object #bruce 050727, revised 050913 self.historyTabLayout.addWidget(self.history_widget) def show(self): """ Show this widget. Makes sure that this widget is shown only when the B{View > Reports} action is checked @see: B{self.closeEvent} """ if not env.prefs[displayReportsWidget_prefs_key]: return if not self.win.viewReportsAction.isChecked(): self.win.viewReportsAction.setChecked(True) return QDockWidget.show(self) def closeEvent(self, event): """ Makes sure that this widget is closed (hidden) only when the B{View > Reports} action is unchecked. Overrides QDockWidget.closeEvent() @parameter event: closeEvent for the QDockWidget """ if self.win.viewReportsAction.isChecked(): self.win.viewReportsAction.setChecked(False) # setChecked() generates signal and calls toggle() slot. return QDockWidget.closeEvent(self, event) def hide_DISABLED(self): """ Hide this widget. Makes sure that this widget is closed (hidden ) only when the B{View > Reports} action is unchecked @see: self.closeEvent @deprecated: Not needed and marked for removal. Mark 2008-01-18 """ if self.win.viewReportsAction.isChecked(): self.win.viewReportsAction.setChecked(False) # setChecked() generates signal and calls toggle() slot. return QDockWidget.hide(self) def toggle(self, isChecked): """ Hides or shows the Reports DockWidget. @param isChecked: Checked state of the B{View > Reports} menu item @type isChecked: boolean """ if isChecked: env.prefs[displayReportsWidget_prefs_key] = True self.show() else: env.prefs[displayReportsWidget_prefs_key] = False self.hide()
NanoCAD-master
cad/src/ne1_ui/Ui_ReportsDockWidget.py
# Copyright 2004-2008 Nanorex, Inc. See LICENSE file for details. """ WhatsThisText_for_CommandToolbars.py This file provides functions for setting the "What's This" text for widgets (typically QActions) in the Command Toolbar. @author: Mark @version:$Id$ @copyright: 2004-2008 Nanorex, Inc. See LICENSE file for details. """ from foundation.whatsthis_utilities import fix_whatsthis_text_and_links # Try to keep this list in order (by appearance in Command Toolbar). --Mark # Command Toolbar Menus (i.e. Build, Tools, Move and Simulation ###### def whatsThisTextForCommandToolbarBuildButton(button): """ "What's This" text for the Build button (menu). """ button.setWhatsThis( """<b>Build</b> <p> <img source=\"ui/actions/Command Toolbar/ControlArea/Build.png\"><br> The <b>Build Command Set</b> for modeling and editing structures interactively. </p>""") return def whatsThisTextForCommandToolbarInsertButton(button): """ "What's This" text for the Insert button (menu). """ button.setWhatsThis( """<b>Insert</b> <p> <img source=\"ui/actions/Command Toolbar/ControlArea/Insert.png\"><br> The <b>Insert Command Set</b> which includes commands for inserting various things into the current part. </p>""") return def whatsThisTextForCommandToolbarToolsButton(button): """ Menu of Build tools. """ button.setWhatsThis( """<b>Tools</b> <p> <img source=\"ui/actions/Command Toolbar/ControlArea/Tools.png\"><br> The <b>Tools Command Set</b> which includes specialized tools for model editing. </p>""") return def whatsThisTextForCommandToolbarMoveButton(button): """ "What's This" text for the Move button (menu). """ button.setWhatsThis( """<b>Move</b> <p> <img source=\"ui/actions/Command Toolbar/ControlArea/Move.png\"><br> The <b>Move Command Set</b> which includes specialized rotation and translation commands that operate on the current selection. </p>""") return def whatsThisTextForCommandToolbarSimulationButton(button): """ "What's This" text for the Simulation button (menu). """ button.setWhatsThis( """<b>Simulation</b> <p> <img source=\"ui/actions/Command Toolbar/ControlArea/Simulation.png\"><br> The <b>Simulation Command Set</b> which includes commands for setting up, launching and playing back movies of molecular dynamics simulations. </p>""") return # Build command toolbars #################### def whatsThisTextForAtomsCommandToolbar(commandToolbar): """ "What's This" text for widgets in the Build Atoms Command Toolbar. @note: This is a placeholder function. Currenly, all the tooltip text is defined in BuildAtoms_Command.py. """ commandToolbar.exitModeAction.setWhatsThis( """<b>Exit Atoms</b> <p> Exits the <b>Build Atoms</b> command set. </p>""") commandToolbar.atomsToolAction.setWhatsThis( """<b>Atoms Tool</b> <p> <img source=\"ui/actions/Command Toolbar/BuildAtoms/AtomsTool.png\"><br> Activates <i>Atoms Tool Mode</i> for depositing and/or selecting atoms. Double-click to insert a new atom into the model by itself. Single-click on <a href=Bondpoints>bondpoints</a> to insert and bond a new atom to an existing atom. </p>""") commandToolbar.transmuteAtomsAction.setWhatsThis( """<b>Transmute Atoms</b> <p> <img source=\"ui/actions/Command Toolbar/BuildAtoms/TransmuteAtoms.png\"><br> Transmutes the selected atoms to the active element type. The active element type in set using the <b>Atom Chooser</b> in the <a href=Property_Manager>property manager</a>.</p> <p> <img source=\"ui/whatsthis/HotTip.png\"><br> <b>Hot Tip:</b> Use the <b>Selection Filter</b> to limit selects to specific atom types in the <a href=Graphics_Area>raphics area</a> <a href=Command_Toolbar>command toolbar</a>. </p>""") commandToolbar.bondsToolAction.setWhatsThis( """<b>Bonds Tool</b> <p> <img source=\"ui/actions/Command Toolbar/BuildAtoms/BondsTool.png\"><br> Enters <i>Bonds Tool Mode</i> for changing bonds (i.e. the bond order) or deleting bonds. Singe-clicking bonds will transmute them into the active bond type. The active bond type in set by selecting one of the bond types (i.e. single, double, triple, etc.) in the flyout area of the <a href=Command_Toolbar>command toolbar</a>.</p> <p> <img source=\"ui/whatsthis/HotTip.png\"><br> <b>Hot Tip:</b> It is possible to transmute multiple bonds at the same time. To do this, select all the atoms with bonds you want to transmute, then click on the bond type in the <a href=Command_Toolbar>command toolbar</a>. </p>""") commandToolbar.bond1Action.setWhatsThis( """<b>Single Bond</b> <p> <img source=\"ui/actions/Command Toolbar/BuildAtoms/SingleBond.png\"><br> Sets the active bond type to <b>single</b>. Singe-clicking a highlighted bond transmutes it into a single bond.</p> <p> <img source=\"ui/whatsthis/HotTip.png\"><br> <b>Hot Tip:</b> It is possible to transmute multiple bonds into single bonds at the same time. To do this, select all the atoms with bonds you want to transmute, then click on this button. <b>Note:</b> <i>Only selected atoms with bonds between them will be transmuted.</i> </p>""") commandToolbar.bond2Action.setWhatsThis( """<b>Double Bond</b> <p> <img source=\"ui/actions/Command Toolbar/BuildAtoms/DoubleBond.png\"><br> Sets the active bond type to <b>double</b>. Singe-clicking a highlighted bond transmutes it into a double bond.</p> <p> <img source=\"ui/whatsthis/HotTip.png\"><br> <b>Hot Tip:</b> It is possible to transmute multiple bonds into double bonds at the same time. To do this, select all the atoms with bonds you want to transmute, then click on this button. <b>Note:</b> <i>Only selected atoms with bonds between them will be transmuted.</i> </p>""") commandToolbar.bond3Action.setWhatsThis( """<b>Triple Bond</b> <p> <img source=\"ui/actions/Command Toolbar/BuildAtoms/TripleBond.png\"><br> Sets the active bond type to <b>triple</b>. Singe-clicking a highlighted bond transmutes it into a triple bond.</p> <p> <img source=\"ui/whatsthis/HotTip.png\"><br> <b>Hot Tip:</b> It is possible to transmute multiple bonds into triple bonds at the same time. To do this, select all the atoms with bonds you want to transmute, then click on this button. <b>Note:</b> <i>Only selected atoms with bonds between them will be transmuted.</i> </p>""") commandToolbar.bondaAction.setWhatsThis( """<b>Aromatic Bond</b> <p> <img source=\"ui/actions/Command Toolbar/BuildAtoms/AromaticBond.png\"><br> Sets the active bond type to <b>aromatic</b>. Singe-clicking a highlighted bond transmutes it into an aromatic bond.</p> <p> <img source=\"ui/whatsthis/HotTip.png\"><br> <b>Hot Tip:</b> It is possible to transmute multiple bonds into aromatic bonds at the same time. To do this, select all the atoms with bonds you want to transmute, then click on this button. <b>Note:</b> <i>Only selected atoms with bonds between them will be transmuted.</i> </p>""") commandToolbar.bondgAction.setWhatsThis( """<b>Graphitic Bond</b> <p> <img source=\"ui/actions/Command Toolbar/BuildAtoms/GraphiticBond.png\"><br> Sets the active bond type to <b>graphitic</b>. Singe-clicking a highlighted bond transmutes it into a graphitic bond.</p> <p> <img source=\"ui/whatsthis/HotTip.png\"><br> <b>Hot Tip:</b> It is possible to transmute multiple bonds into graphitic bonds at the same time. To do this, select all the atoms with bonds you want to transmute, then click on this button. <b>Note:</b> <i>Only selected atoms with bonds between them will be transmuted.</i> </p>""") commandToolbar.cutBondsAction.setWhatsThis( """<b>Cut Bonds</b> <p> <img source=\"ui/actions/Command Toolbar/BuildAtoms/CutBonds.png\"><br> Activates cut bonds mode. Singe-clicking a highlighted bond deletes it. </p>""") # Convert all "img" tags in the button's "What's This" text # into abs paths (from their original rel paths). # Partially fixes bug 2943. --mark 2008-12-07 fix_whatsthis_text_and_links(commandToolbar.subControlActionGroup) fix_whatsthis_text_and_links(commandToolbar.bondToolsActionGroup) return def whatsThisTextForProteinCommandToolbar(commandToolbar): """ "What's This" text for the Build Protein Command Toolbar """ commandToolbar.exitModeAction.setWhatsThis( """<b>Exit Protein</b> <p> Exits the <b>Build Protein</b> command set. </p>""") commandToolbar.modelProteinAction.setWhatsThis( """<b>Model Protein</b> <p> <img source=\"ui/actions/Command Toolbar/BuildProtein/ModelProtein.png\"><br> Enter protein modeling mode. Protein modeling sub-commands are displayed to the right in the flyout area of the <a href=Command_Toolbar>command toolbar</a>. </p>""") commandToolbar.simulateProteinAction.setWhatsThis( """<b>Simulate Protein with Rosetta</b> <p> <img source=\"ui/actions/Command Toolbar/BuildProtein/Simulate.png\"><br> Enter protein simulation mode using Rosetta. Rosetta simulation sub-commands are displayed to the right in the flyout area of the <a href=Command_Toolbar>command toolbar</a>.</p> <p> Rosetta is a collection of computational tools for the prediction and design of protein structures and protein-protein interactions.</p> <p> <a href=Rosetta_for_NanoEngineer-1> Click here for more information about Rosetta for NanoEngineer-1</a> </p>""") commandToolbar.buildPeptideAction.setWhatsThis( """<b>Insert Peptide</b> <p> <img source=\"ui/actions/Command Toolbar/BuildProtein/InsertPeptide.png\"><br> Insert a peptide chain by clicking two endpoints in the <a href=Graphics_Area>graphics area</a>. The user can also specify different conformation options (i.e. Alpha helix, Beta sheet, etc.) in the <a href=Property_Manager>property manager</a>. </p>""") commandToolbar.compareProteinsAction.setWhatsThis( """<b>Compare Proteins</b> <p> <img source=\"ui/actions/Command Toolbar/BuildProtein/Compare.png\"><br> Select two protein structures and compare them visually. </p>""") commandToolbar.displayProteinStyleAction.setWhatsThis( """<b>Edit (Protein Display) Style</b> <p> <img source=\"ui/actions/Command Toolbar/BuildProtein/EditProteinDisplayStyle.png\"><br> Edit the Protein Display Style settings used whenever the <b>Global Display Style</b> is set to <b>Protein</b>. </p>""") commandToolbar.rosetta_fixedbb_design_Action.setWhatsThis( """<b>Fixed Backbone Protein Sequence Design</b> <p> <img source=\"ui/actions/Command Toolbar/BuildProtein/FixedBackbone.png\"><br> Design an optimized fixed backbone protein sequence using Rosetta. </p>""") commandToolbar.rosetta_backrub_Action.setWhatsThis( """<b>Backrub Motion</b> <p> <img source=\"ui/actions/Command Toolbar/BuildProtein/Backrub.png\"><br> Design an optimized backbone protein sequence using Rosetta with backrub motion allowed. </p>""") commandToolbar.editResiduesAction.setWhatsThis( """<b>Edit Residues</b> <p> <img source=\"ui/actions/Command Toolbar/BuildProtein/Residues.png\"><br> Provides an interface to edit residues so that Rosetta can predict the optimized sequence of an initial sequence (peptide chain). </p>""") commandToolbar.rosetta_score_Action.setWhatsThis( """<b>Compute Rosetta Score</b> <p> <img source=\"ui/actions/Command Toolbar/BuildProtein/Score.png\"><br> Produce the Rosetta score, which is useful for predicting errors in a peptide/protein structure. </p> <p> The Rosetta scoring function is an all-atom force field that focuses on short-range interactions (i.e., van der Waals packing, hydrogen bonding and desolvation) while neglecting long-range electrostatics. </p>""") # Convert all "img" tags in the button's "What's This" text # into abs paths (from their original rel paths). # Partially fixes bug 2943. --mark 2008-12-07 fix_whatsthis_text_and_links(commandToolbar.subControlActionGroup) fix_whatsthis_text_and_links(commandToolbar.subControlActionGroupForModelProtein) fix_whatsthis_text_and_links(commandToolbar.subControlActionGroupForSimulateProtein) return def whatsThisTextForDnaCommandToolbar(commandToolbar): """ "What's This" text for the Build DNA Command Toolbar """ commandToolbar.exitModeAction.setWhatsThis( """<b>Exit DNA</b> <p> Exits the <b>Build DNA</b> command set. </p>""") commandToolbar.dnaDuplexAction.setWhatsThis( """<b>Insert DNA</b> <p> <img source=\"ui/actions/Command Toolbar/BuildDna/InsertDna.png\"><br> Insert a DNA duplex by clicking two endpoints in the graphics area. </p>""") commandToolbar.breakStrandAction.setWhatsThis( """<b>Break Strands</b> <p> <img source=\"ui/actions/Command Toolbar/BuildDna/BreakStrand.png\"><br> This command provides an interactive mode where the user can break strands by clicking on a bond in a DNA strand. </p> <p> You can also join strands while in this command by dragging and dropping strand arrow heads onto their strand conjugate (i.e. 3' on to 5' and vice versa). </p> <p> <img source=\"ui/whatsthis/HotTip.png\"><br> <b>Hot Tip:</b> Changing the <b>Global display style</b> to <b>CPK</b> results in faster interactive graphics while in this command, especially for large models. </p>""") commandToolbar.joinStrandsAction.setWhatsThis( """<b>Join Strands</b> <p> <img source=\"ui/actions/Command Toolbar/BuildDna/JoinStrands.png\"><br> This command provides an interactive mode where the user can join strands by dragging and dropping strand arrow heads onto their strand conjugate (i.e. 3' on to 5' and vice versa). </p> <p> <img source=\"ui/whatsthis/HotTip.png\"><br> <b>Hot Tip:</b> Changing the <b>Global display style</b> to <b>CPK</b> results in faster interactive graphics while in this command, especially for large models. </p>""") commandToolbar.convertDnaAction.setWhatsThis( """<b>Convert DNA </b> <p> <img source=\"ui/actions/Command Toolbar/BuildDna/ConvertDna.png\"><br> Converts the selected DNA from PAM3 to PAM5 or PAM5 to PAM3. The only reason to convert to PAM5 is to get more accurate minimizations of DNA nanostructures.</p> <p> Here is the protocol for producing more accurate minimizations:<br> 1. Make sure the current model is saved. 2. Select <b>File > Save As...</b> to save the model under a new name (i.e. <i>model_name</i>_minimized).<br> 3. Select <b>Build > DNA > Convert</b> to convert the entire model from PAM3 to PAM5.<br> 4. Select <b>Tools > Minimize Energy</b>.<br> 5. In the Minimize Energy dialog, select <b>GROMACS with ND1 force field</b> as the Physics engine.<br> 6. Click the <b>Minimize Energy</b> button.<br> 7. After minimize completes, convert from PAM5 to PAM3.</p> <p> Next, visually inspect the model for structural distortions such as puckering, warping, or other unwanted strained areas that will require model changes to correct. Model changes should be made in a version of the model that hasn't been minimized. You can either click <b>Edit > Undo</b> or save this model and reopen the previous version.</p> <p> <img source=\"ui/whatsthis/HotTip.png\"><br> <b>Hot Tip:</b> Changing the <b>Global display style</b> to <b>CPK</b> or <b>DNA Cylinder</b> may make the model easier to visually inspect.</p> <p> <a href=PAM3_and_PAM5_Model_Descriptions>Click here for a technical overview of the NanoEngineer-1 PAM3 and PAM5 reduced models.</a> </p>""") commandToolbar.orderDnaAction.setWhatsThis( """<b>Order DNA</b> <p> <img source=\"ui/actions/Command Toolbar/BuildDna/OrderDna.png\"><br> Produces a comma-separated value (.CSV) text file containing all DNA strand sequences in the model.</p> <p> <img source=\"ui/whatsthis/HotTip.png\"><br> <b>Hot Tip:</b> This file can be used to order oligos from suppliers of custom oligonucleotides such as Integrated DNA Technologies and Gene Link. </p>""") commandToolbar.editDnaDisplayStyleAction.setWhatsThis( """<b>Edit (DNA Display) Style</b> <p> <img source=\"ui/actions/Command Toolbar/BuildDna/EditDnaDisplayStyle.png\"><br> Edit the DNA Display Style settings used whenever the <b>Global Display Style</b> is set to <b>DNA Cylinder</b>. These settings also apply to DNA strands and segments that have had their display style set to <b>DNA Cylinder</b>. </p>""") commandToolbar.makeCrossoversAction.setWhatsThis( """<b>Make Crossovers</b> <p> <img source=\"ui/actions/Command Toolbar/BuildDna/MakeCrossovers.png\"><br> Creates crossovers interactively between two or more selected DNA segments.</p> <p> To create crossovers, select the DNA segments to be searched for potential crossover sites. Transparent green spheres indicating potential crossover sites are displayed as you move (rotate or translate) a DNA segment. After you are finished moving a DNA segment, crossover sites are displayed as a pair of white cylinders that can be highlighted/selected. Clicking on a highlighted crossover site makes a crossover. </p>""") # Convert all "img" tags in the button's "What's This" text # into abs paths (from their original rel paths). # Partially fixes bug 2943. --mark 2008-12-07 fix_whatsthis_text_and_links(commandToolbar.subControlActionGroup) return def whatsThisTextForNanotubeCommandToolbar(commandToolbar): """ "What's This" text for widgets in the Build Nanotube Command Toolbar. """ commandToolbar.exitModeAction.setWhatsThis( """<b>Exit Nanotube</b> <p> Exits the <b>Build Nanotube</b> command set. </p>""") commandToolbar.insertNanotubeAction.setWhatsThis( """<b>Insert Nanotube</b> <p> <img source=\"ui/actions/Command Toolbar/BuildNanotube/InsertNanotube.png\"><br> Insert a carbon or boron-nitride nanotube by clicking two endpoints in the graphics area. </p>""") # Convert all "img" tags in the button's "What's This" text # into abs paths (from their original rel paths). # Partially fixes bug 2943. --mark 2008-12-07 fix_whatsthis_text_and_links(commandToolbar.subControlActionGroup) return def whatsThisTextForCrystalCommandToolbar(commandToolbar): """ "Tool Tip" text for widgets in the Build Crystal (crystal) Command Toolbar. """ commandToolbar.exitModeAction.setWhatsThis( """<b>Exit Crystal</b> <p> Exits the <b>Build Crystal</b> command set. </p>""") commandToolbar.polygonShapeAction.setWhatsThis( """<b>Polygon</b> <p> <img source=\"ui/actions/Command Toolbar/BuildCrystal/Polygon.png\"><br> Defines the selection shape as a polygon with the user specifying the vertices.</p> <p> <img source=\"ui/whatsthis/Remember.png\"><br> <b>Remember:</b> You must <b>double-click</b> to define the final vertex and close the polygon. </p>""") commandToolbar.circleShapeAction.setWhatsThis( """<b>Circle</b> <p> <img source=\"ui/actions/Command Toolbar/BuildCrystal/Circle.png\"><br> Defines the selection shape as a circle with the user specifying the center (first click) and radius (second click). </p>""") commandToolbar.squareShapeAction.setWhatsThis( """<b>Square</b> <p> <img source=\"ui/actions/Command Toolbar/BuildCrystal/Square.png\"><br> Defines the selection shape as a square with the user specifying the center (first click) and a corner (second click). </p>""") commandToolbar.rectCtrShapeAction.setWhatsThis( """<b>Rectangle</b> <p> <img source=\"ui/actions/Command Toolbar/BuildCrystal/RectCenter.png\"><br> Defines the selection shape as a rectangle with the user defining the center (first click) and corner (second click). </p>""") commandToolbar.rectCornersShapeAction.setWhatsThis( """<b>Rectangle Corners</b> <p> <img source=\"ui/actions/Command Toolbar/BuildCrystal/RectCorners.png\"><br> Defines the selection shape as a rectangle with the user specifying one corner (first click) and then the opposite corner (second click). </p>""") commandToolbar.hexagonShapeAction.setWhatsThis( """<b>Hexagon</b> <p> <img source=\"ui/actions/Command Toolbar/BuildCrystal/Hexagon.png\"><br> Defines the selection shape as a hexagon with the user specifying the center (first click) and corner (second click). </p>""") commandToolbar.triangleShapeAction.setWhatsThis( """<b>Triangle</b> <p> <img source=\"ui/actions/Command Toolbar/BuildCrystal/Triangle.png\"><br> Defines the selection shape as a triangle with the user specifying the center (first click) and corner (second click). </p>""") commandToolbar.diamondShapeAction.setWhatsThis( """<b>Diamond</b> <p> <img source=\"ui/actions/Command Toolbar/BuildCrystal/Diamond.png\"><br> Defines the selection shape as a diamond with the user specifying the center (first click) and corner (second click). </p>""") commandToolbar.lassoShapeAction.setWhatsThis( """<b>Lasso</b> <p> <img source=\"ui/actions/Command Toolbar/BuildCrystal/Lasso.png\"><br> Defines the selection shape as a freeform lasso. Draw the shape by dragging the mouse while holding down the <a href=LMB>LMB</a>. </p>""") # Convert all "img" tags in the button's "What's This" text # into abs paths (from their original rel paths). # Partially fixes bug 2943. --mark 2008-12-07 fix_whatsthis_text_and_links(commandToolbar.subControlActionGroup) return # Move command toolbar #################### def whatsThisTextForMoveCommandToolbar(commandToolbar): """ "What's This" text for widgets in the Move Command Toolbar. """ commandToolbar.exitModeAction.setWhatsThis( """<b>Exit Move</b> <p> Exits the <b>Move</b> command set. </p>""") # NOTE: "What's This" descriptions for Translate, Rotate and # Align to Common Axis can be found in WhatsThisText_for_MainWindow.py. # (and they should remain there until Ui_MoveFlyout is refactored ) # - Mark 2008-12-02 return def whatsThisTextForMovieCommandToolbar(commandToolbar): """ "What's This" text for widgets in the Movie Command Toolbar. """ return
NanoCAD-master
cad/src/ne1_ui/WhatsThisText_for_CommandToolbars.py
# Copyright 2004-2007 Nanorex, Inc. See LICENSE file for details. """ cursors.py - load all the custom cursors needed by NE1 @author: Mark @version: $Id$ @copyright: 2004-2007 Nanorex, Inc. See LICENSE file for details. mark 060427 - loadCursors() moved from MWsemantics.py. To do: (Mark) - Find and replace all uses of self.o.setCursor(QCursor(Qt.ArrowCursor)) with self.o.setCursor(win.ArrowCursor)). - Replace all bitmap cursors with color PNG cursors. """ from PyQt4.Qt import QCursor, QBitmap, Qt, QPainter, QApplication import os, sys from utilities.icon_utilities import getCursorPixmap def showWaitCursor(on_or_off): """ Show the wait cursor or revert to the prior cursor if the current cursor is the wait cursor. For on_or_off True, set the main window waitcursor. For on_or_off False, revert to the prior cursor. [It might be necessary to always call it in matched pairs, I don't know [bruce 050401].] """ if on_or_off: QApplication.setOverrideCursor( QCursor(Qt.WaitCursor) ) else: QApplication.restoreOverrideCursor() # Restore the cursor return def loadCursors(w): """ This routine is called once to load all the custom cursors needed by NE1. """ filePath = os.path.dirname(os.path.abspath(sys.argv[0])) # Pencil symbols. w.addSymbol = QCursor(getCursorPixmap("symbols/PlusSign.png"), 0, 0) w.subtractSymbol = QCursor(getCursorPixmap("symbols/MinusSign.png"), 0, 0) # Selection lock symbol w.selectionLockSymbol = \ QCursor(getCursorPixmap("symbols/SelectionLock.png"), 0, 0) # Pencil symbols. horizontalSymbol = \ QCursor(getCursorPixmap("symbols/HorizontalSnap.png"), 0, 0) verticalSymbol = \ QCursor(getCursorPixmap("symbols/VerticalSnap.png"), 0, 0) # Pencil cursors w.colorPencilCursor = QCursor(getCursorPixmap("Pencil.png"), 0, 0) w.pencilHorizontalSnapCursor = \ createCompositeCursor(w.colorPencilCursor, horizontalSymbol, offsetX = 22, offsetY = 22) w.pencilVerticalSnapCursor = \ createCompositeCursor(w.colorPencilCursor, verticalSymbol, offsetX = 22, offsetY = 22) # Select Chunks cursors w.SelectArrowCursor = \ QCursor(getCursorPixmap("SelectArrowCursor.png"), 0, 0) w.SelectArrowAddCursor = \ createCompositeCursor(w.SelectArrowCursor, w.addSymbol, offsetX = 12, offsetY = 0) w.SelectArrowSubtractCursor = \ createCompositeCursor(w.SelectArrowCursor, w.subtractSymbol, offsetX = 12, offsetY = 0) # Build Atoms - normal cursors w.SelectAtomsCursor = \ QCursor(getCursorPixmap("SelectAtomsCursor.png"), 0, 0) w.SelectAtomsAddCursor = \ createCompositeCursor(w.SelectAtomsCursor, w.addSymbol, offsetX = 12, offsetY = 0) w.SelectAtomsSubtractCursor = \ createCompositeCursor(w.SelectAtomsCursor, w.subtractSymbol, offsetX = 12, offsetY = 0) w.DeleteCursor = \ QCursor(getCursorPixmap("DeleteCursor.png"), 0, 0) # Build Atoms - Atom Selection Filter cursors w.SelectAtomsFilterCursor = \ QCursor(getCursorPixmap("SelectAtomsFilterCursor.png"), 0, 0) w.SelectAtomsAddFilterCursor = \ createCompositeCursor(w.SelectAtomsFilterCursor, w.addSymbol, offsetX = 12, offsetY = 0) w.SelectAtomsSubtractFilterCursor = \ createCompositeCursor(w.SelectAtomsFilterCursor, w.subtractSymbol, offsetX = 12, offsetY = 0) w.DeleteAtomsFilterCursor = \ QCursor(getCursorPixmap("DeleteAtomsFilterCursor.png"), 0, 0) # Build Atoms - Bond Tool cursors with no modkey pressed w.BondToolCursor = [] w.BondToolCursor.append(QCursor(getCursorPixmap("SelectAtomsCursor.png"), 0, 0)) w.BondToolCursor.append(QCursor(getCursorPixmap("Bond1ToolCursor.png"), 0, 0)) w.BondToolCursor.append(QCursor(getCursorPixmap("Bond2ToolCursor.png"), 0, 0)) w.BondToolCursor.append(QCursor(getCursorPixmap("Bond3ToolCursor.png"), 0, 0)) w.BondToolCursor.append(QCursor(getCursorPixmap("BondAToolCursor.png"), 0, 0)) w.BondToolCursor.append(QCursor(getCursorPixmap("BondGToolCursor.png"), 0, 0)) w.BondToolCursor.append(QCursor(getCursorPixmap("CutBondCursor.png"), 0, 0)) # Build Atoms - Bond Tool cursors with Shift modkey pressed w.BondToolAddCursor = [] for cursor in w.BondToolCursor: w.BondToolAddCursor.append( createCompositeCursor(cursor, w.addSymbol, offsetX = 12, offsetY = 0)) # Build Atoms - Bond Tool cursors with Control/Cmd modkey pressed w.BondToolSubtractCursor = [] for cursor in w.BondToolCursor: w.BondToolSubtractCursor.append( createCompositeCursor(cursor, w.subtractSymbol, offsetX = 12, offsetY = 0)) # Translate selection cursors w.TranslateSelectionCursor = \ QCursor(getCursorPixmap("TranslateSelectionCursor.png"), 0, 0) w.TranslateSelectionAddCursor = \ createCompositeCursor(w.TranslateSelectionCursor, w.addSymbol, offsetX = 12, offsetY = 0) w.TranslateSelectionSubtractCursor = \ createCompositeCursor(w.TranslateSelectionCursor, w.subtractSymbol, offsetX = 12, offsetY = 0) # Rotate selection cursors w.RotateSelectionCursor = \ QCursor(getCursorPixmap("RotateSelectionCursor.png"), 0, 0) w.RotateSelectionAddCursor = \ createCompositeCursor(w.RotateSelectionCursor, w.addSymbol, offsetX = 12, offsetY = 0) w.RotateSelectionSubtractCursor = \ createCompositeCursor(w.RotateSelectionCursor, w.subtractSymbol, offsetX = 12, offsetY = 0) # Axis translation/rotation cursor w.AxisTranslateRotateSelectionCursor = \ QCursor(getCursorPixmap("AxisTranslateRotateSelectionCursor.png"), 0, 0) # Build Crystal cursors w.CookieCursor = QCursor(getCursorPixmap("Pencil.png"), 0, 0) w.CookieAddCursor = \ createCompositeCursor(w.colorPencilCursor, w.addSymbol, \ offsetX = 12, offsetY = 0) w.CookieSubtractCursor = \ createCompositeCursor(w.colorPencilCursor, w.subtractSymbol, \ offsetX = 12, offsetY = 0) # View Zoom, Pan, Rotate cursors # The zoom cursor(s). One is for a dark background, the other for a light bg. # See GLPane.setCursor() for more details about this list. w.ZoomCursor = [] _cursor = QCursor(getCursorPixmap("darkbg/ZoomCursor.png"), 11, 11) w.ZoomCursor.append(_cursor) _cursor = QCursor(getCursorPixmap("litebg/ZoomCursor.png"), 11, 11) w.ZoomCursor.append(_cursor) w.ZoomInOutCursor = [] _cursor = QCursor(getCursorPixmap("darkbg/ZoomCursor.png"), 11, 11) w.ZoomInOutCursor.append(_cursor) _cursor = QCursor(getCursorPixmap("litebg/ZoomCursor.png"), 11, 11) w.ZoomInOutCursor.append(_cursor) w.PanViewCursor = QCursor(getCursorPixmap("PanViewCursor.png"), 0, 0) w.RotateViewCursor = QCursor(getCursorPixmap("RotateViewCursor.png"), 0, 0) # Miscellaneous cursors w.RotateZCursor = QCursor(getCursorPixmap("RotateZCursor.png"), 0, 0) w.ZoomPovCursor = QCursor(getCursorPixmap("ZoomPovCursor.png"), -1, -1) w.ArrowWaitCursor = QCursor(getCursorPixmap("ArrowWaitCursor.png"), 0, 0) w.ArrowCursor = QCursor(Qt.ArrowCursor) #bruce 070627 # Confirmation corner cursors [loaded by bruce 070626 from files committed by mark] w._confcorner_OKCursor = \ QCursor(getCursorPixmap("OKCursor.png"), 0, 0) w.confcorner_TransientDoneCursor = \ QCursor(getCursorPixmap("TransientDoneCursor.png"), 0, 0) w._confcorner_CancelCursor = \ QCursor(getCursorPixmap("CancelCursor.png"), 0, 0) # Some Build Dna mode cursors w.rotateAboutCentralAxisCursor = \ QCursor(getCursorPixmap("Rotate_About_Central_Axis.png"), 0, 0) w.translateAlongCentralAxisCursor = \ QCursor(getCursorPixmap("Translate_Along_Central_Axis.png"), 0, 0) #Rotate about a point cursors w.rotateAboutPointCursor = \ QCursor(getCursorPixmap("RotateAboutPointCursor.png"), 0, 0) w.rotateAboutPointHorizontalSnapCursor = \ createCompositeCursor(w.rotateAboutPointCursor, horizontalSymbol, offsetX = 22, offsetY = 22) w.rotateAboutPointVerticalSnapCursor = \ createCompositeCursor(w.rotateAboutPointCursor, verticalSymbol, offsetX = 22, offsetY = 22) #Add a segment to a list of segments to be resized (in Multiple_DnaSegments #command) w.addSegmentToResizeSegmentListCursor = \ QCursor(getCursorPixmap("AddSegment_To_ResizeSegmentListCursor.png"), 0, 0) w.removeSegmentFromResizeSegmentListCursor = \ QCursor(getCursorPixmap("RemoveSegment_From_ResizeSegmentList_Cursor.png"), 0, 0) w.specifyPlaneCursor = \ QCursor(getCursorPixmap("SpecifyPlaneCursor.png"), 0, 0) w.clickToJoinStrandsCursor = QCursor(getCursorPixmap( "ClickToJoinStrands_Cursor.png"), 0, 0) return # from loadCursors def createCompositeCursor(cursor, overlayCursor, hotX = None, hotY = None, offsetX = 0, offsetY = 0): """ Returns a composite 32x32 cursor using two other cursors. This is useful for creating composite cursor images from two (or more) cursors. For example, the pencil cursor includes a horizontal and vertical symbol when drawing a horizontal or vertical line. This function can be used to create these cursors without having to create each one by hand. The payoff is when the developer/artist wants to change the base cursor image (i.e. the pencil cursor) without having to redraw and save all the other versions of the cursor in the set. @param cursor: The main cursor. @type cursor: QCursor @param overlayCursor: The cursor to overlay on top of I{cursor}. @type overlayCursor: QCursor @param hotX: The X coordinate of the hotspot. If none is given, the hotspot of I{cursor} is used. @type hotX: int @param hotY: The Y coordinate of the hotspot. If none is given, the hotspot of I{cursor} is used. @type hotY: int @param offsetX: The X offset in which to draw the overlay cursor onto I{cursor}. The default is 0. @type offsetX: int @param offsetY: The Y offset in which to draw the overlay cursor onto I{cursor}. The default is 0. @type offsetY: int @return: The composite cursor. @rtype: QCursor @note: It would be easy and useful to allow overlayCursor to be a QPixmap. I'll add this when it becomes helpful. --Mark 2008-03-06. """ # Method: # 1. Get cursor's pixmap and create a painter from it. # 2. Get the pixmap from the overlay cursor and draw it onto the # cursor pixmap to create the composite pixmap. # 3. Create and return a new QCursor from the composite pixmap. # Mark 2008-03-05 assert isinstance(cursor, QCursor) assert isinstance(overlayCursor, QCursor) if hotX is None: hotX = cursor.hotSpot().x() if hotY is None: hotY = cursor.hotSpot().y() pixmap = cursor.pixmap() overlayPixmap = overlayCursor.pixmap() painter = QPainter(pixmap) painter.drawPixmap(offsetX, offsetY, overlayPixmap) painter.end() return QCursor(pixmap, hotX, hotY)
NanoCAD-master
cad/src/ne1_ui/cursors.py