python_code
stringlengths
0
992k
repo_name
stringlengths
8
46
file_path
stringlengths
5
162
# Copyright 2007-2008 Nanorex, Inc. See LICENSE file for details. """ dna_updater_commands.py - UI commands offered directly by the dna updater. @author: Bruce @version: $Id$ @copyright: 2007-2008 Nanorex, Inc. See LICENSE file for details. """ from utilities.debug import register_debug_menu_command from model.global_model_changedicts import _changed_structure_Atoms import foundation.env as env from platform_dependent.PlatformDependent import fix_plurals from utilities.Log import greenmsg from dna.model.pam3plus5_ops import add_basepair_handles_to_atoms #k import ok? # == def initialize_commands(): _register_our_debug_menu_commands() return # == def rescan_atoms_in_current_part(assy, only_selected = False): oldlen = len(_changed_structure_Atoms) for mol in assy.molecules: for atom in mol.atoms.itervalues(): if not only_selected or atom.picked or \ (atom.is_singlet() and atom.singlet_neighbor().picked): _changed_structure_Atoms[atom.key] = atom newlen = len(_changed_structure_Atoms) msg = "len(_changed_structure_Atoms) %d -> %d" % (oldlen, newlen) env.history.message(greenmsg( "DNA debug command:") + " " + msg) assy.w.win_update() #bruce 080312 bugfix return def rescan_all_atoms(glpane): rescan_atoms_in_current_part( glpane.assy) def rescan_selected_atoms(glpane): rescan_atoms_in_current_part( glpane.assy, only_selected = True) def add_basepair_handles_to_selected_atoms(glpane): #bruce 080515 assy = glpane.assy goodcount, badcount = add_basepair_handles_to_atoms(assy.selatoms.values()) msg = "adding handles to %d duplex Gv5 atom(s)" % (goodcount,) if badcount: msg += " (but not %d other selected atom(s))" % (badcount,) msg = fix_plurals(msg) env.history.message(greenmsg( "Add basepair handles:") + " " + msg) assy.w.win_update() return # == def _register_our_debug_menu_commands(): register_debug_menu_command( "DNA: rescan all atoms", rescan_all_atoms ) register_debug_menu_command( "DNA: rescan selected atoms", rescan_selected_atoms ) register_debug_menu_command( "DNA: add basepair handles", add_basepair_handles_to_selected_atoms ) # end
NanoCAD-master
cad/src/dna/updater/dna_updater_commands.py
# Copyright 2007-2008 Nanorex, Inc. See LICENSE file for details. """ dna_updater_utils.py -- miscellaneous utilities for dna_updater @author: Bruce @version: $Id$ @copyright: 2007-2008 Nanorex, Inc. See LICENSE file for details. """ from utilities import debug_flags from utilities.debug import print_compact_traceback # == def replace_atom_class( atom, newclass, *atomdicts): #e refile? """ Change atom's class to newclass. This might be done by directly replacing atom.__class__, or by making a new Atom instance (identical except for __class__) and replacing atom with newatom in the rest of the model (assy) in which atom resides, and in all transient state that might point to atom (accessible via atom's assy). If any atomdicts are passed, they are assumed to be atom.key -> atom dicts in which atom should be also replaced with newatom (at the same key, since it will be given the same .key). @param atom: a real atom or bondpoint of any subclass of Atom. @type atom: Atom. @param newclass: any subclass of Atom. @type newclass: class @param atomdicts: zero or more dicts which map atom.key to atom (for any atom, not just the one passed) and in which atom (the one passed) should be replaced with newatom if necessary. @type atomdicts: zero or more dictionaries. @return: None. (If newatom is needed, caller should get it from one of the atomdicts.) """ # The present implem works by directly resetting atom.__class__, # since this works in Python (though I'm not sure how officially # it's supported) and is much simpler and faster than the alternative. # # (This is not a kluge, except to the extent that it might not be # officially supported. It's a well-defined concept (assuming the # classes are written to be compatible), is officially supported # in some languages, and does exactly what we want.) # # If resetting __class__ ever stops working, we'll have to implement # this function in a much harder way: make a new Atom of the desired # class, and then replace atom with newatom everywhere it occurs, # both in the model and in all transient state -- in bonds, jigs, # chunks (including hotspot), part.selatoms, glpane.selobj/.selatom, # and any other state I'm forgetting or that gets added to the code. # (But I think we could get away without also replacing it in undo diffs # or the glname allocator, since the old atom won't have had a chance # to get into undo diffs by the time the dna_updater runs, or to get # drawn (so its glname won't matter yet).) # # See outtakes/Atom_replace_class.py for unfinished code which does # some of that work, and a more detailed comment about what would have # to be done, also covering analogous replacements for Bond and Chunk. if debug_flags.DEBUG_DNA_UPDATER: print "dna_updater: replacing %r class %r with %r" % (atom, atom.__class__, newclass) atom.__class__ = newclass return def replace_bond_class( bond, newclass, *bonddicts): #e refile? """ Like replace_atom_class, except for Bonds. The bonddicts map id(bond) -> bond. """ if debug_flags.DEBUG_DNA_UPDATER: print "dna_updater: replacing %r class %r with %r" % (bond, bond.__class__, newclass) bond.__class__ = newclass return # == def remove_killed_atoms( atomdict): """ Remove any killed atoms from atomdict. @warning: Closing a file does not presently [071126] kill its atoms (let alone destroy them and (ideally) remove all references to them); they can remain in global changedicts and later be seen by dna updater functions; this function will not remove them. There is presently no good way to detect a "closed-file atom". Correction: that's true in general, but for non-killed atoms it's not hard; see remove_closed_or_disabled_assy_atoms for this. @see: remove_closed_or_disabled_assy_atoms """ killed = [] for atom in atomdict.itervalues(): if atom.killed(): killed.append(atom) if debug_flags.DEBUG_DNA_UPDATER and killed: print "dna_updater: ignoring %d killed atoms" % len(killed) for atom in killed: del atomdict[atom.key] return def remove_error_atoms( atomdict): """ Remove from atomdict any atoms with _dna_updater__error set. """ error_atoms = [] for atom in atomdict.itervalues(): if atom._dna_updater__error: error_atoms.append(atom) if debug_flags.DEBUG_DNA_UPDATER and error_atoms: print "dna_updater: ignoring %d atoms with _dna_updater__error" % len(error_atoms) for atom in error_atoms: del atomdict[atom.key] return def remove_closed_or_disabled_assy_atoms( atomdict): #bruce 080314 """ Assuming atomdict contains only non-killed atoms (for which atom.killed() returns False), remove any atoms from it whose assy does not want updaters to modify its atoms (e.g. whose assy has been closed). """ atoms_to_remove = [] for atom in atomdict.itervalues(): try: disabled = atom.molecule.assy.permanently_disable_updaters except: print_compact_traceback("bug in atom.molecule.assy.permanently_disable_updaters: ") disabled = True if disabled: atoms_to_remove += [atom] if debug_flags.DEBUG_DNA_UPDATER and atoms_to_remove: print "dna_updater: ignoring %d atoms from closed files or updater-disabled assys" % len(atoms_to_remove) for atom in atoms_to_remove: del atomdict[atom.key] return # end
NanoCAD-master
cad/src/dna/updater/dna_updater_utils.py
# Copyright 2007-2008 Nanorex, Inc. See LICENSE file for details. """ dna_updater_chunks.py - enforce rules on chunks containing changed PAM atoms @author: Bruce @version: $Id$ @copyright: 2007-2008 Nanorex, Inc. See LICENSE file for details. """ from foundation.state_utils import transclose from dna.updater.dna_updater_globals import ignore_new_changes from dna.updater.dna_updater_globals import _f_ladders_with_up_to_date_baseframes_at_ends from dna.updater.dna_updater_globals import _f_atom_to_ladder_location_dict from dna.updater.dna_updater_globals import _f_baseatom_wants_pam from dna.updater.dna_updater_globals import _f_invalid_dna_ladders from dna.updater.dna_updater_globals import temporarily_set_dnaladder_inval_policy from dna.updater.dna_updater_globals import DNALADDER_INVAL_IS_OK from dna.updater.dna_updater_globals import DNALADDER_INVAL_IS_ERROR from dna.updater.dna_updater_globals import restore_dnaladder_inval_policy from dna.updater.dna_updater_globals import _f_clear_invalid_dna_ladders from utilities import debug_flags from dna.updater.dna_updater_debug import assert_unique_chain_baseatoms from dna.updater.dna_updater_debug import assert_unique_ladder_baseatoms from dna.updater.dna_updater_debug import assert_unique_wholechain_baseatoms from dna.model.WholeChain import Axis_WholeChain, Strand_WholeChain from dna.updater.dna_updater_find_chains import find_axis_and_strand_chains_or_rings from dna.updater.dna_updater_ladders import dissolve_or_fragment_invalid_ladders from dna.updater.dna_updater_ladders import make_new_ladders, merge_and_split_ladders from dna.updater.dna_updater_prefs import pref_dna_updater_convert_to_PAM3plus5 from utilities.constants import MODEL_PAM3, MODEL_PAM5 # == def update_PAM_chunks( changed_atoms, homeless_markers): """ Update chunks containing changed PAM atoms, ensuring that PAM atoms remain divided into AxisChunks and StrandChunks in the right way. Also update DnaMarkers as needed. @param changed_atoms: an atom.key -> atom dict of all changed atoms that this update function needs to consider, which includes no killed atoms. WE ASSUME OWNERSHIP OF THIS DICT and modify it in arbitrary ways. Note: in present calling code [071127] this dict might include atoms from closed files. @param homeless_markers: ###doc, ###rename @return: the 2-tuple (all_new_chunks, new_wholechains), containing a list of all newly made DnaLadderRailChunks (or modified ones, if that's ever possible), and a list of all newly made WholeChains (each of which covers either all new small chains, or some new and some old small chains, with each small chain also called one "DnaLadder rail" and having its own DnaLadderRailChunk). """ # see scratch file for comments to revise and bring back here... ignore_new_changes("as update_PAM_chunks starts", changes_ok = False ) # Move each DnaMarker in which either atom got killed or changed in # structure (e.g. rebonded) onto atoms on the same old wholechain # (if it has one) which remain alive. We don't yet know if they'll # be in the same new wholechain and adjacent in it -- that will be # checked when new wholechains are made, and we retain the moved # markers so we can assert that they all get covered that way # (which they ought to -- todo, doc why). # # Note that we might find markers which are not on old wholechains # (e.g. after mmp read), and we might even find markers like that # on killed atoms (e.g. after mmp insert, which kills clipboard). # Those markers can't be moved, but if valid without being moved, # can be found and used by a new wholechain. [revised 080311] # # The old wholechain objects still # exist within the markers, and can be used to scan their atoms even though # some are dead or their bonding has changed. The markers use them to help # decide where and how to move. Warning: this will only be true during the early # parts of the dna updater run, since the wholechains rely on rail.neighbor_baseatoms # to know how their rails are linked, and that will be rewritten later, around the time # when new wholechains are made. TODO: assert that we don't rely on that after # it's invalid. # # [code and comment rewritten 080311] ## homeless_markers = _f_get_homeless_dna_markers() #e rename # now an arg, 080317 # this includes markers whose atoms got killed (which calls marker.remove_atom) # or got changed in structure (which calls marker.changed_structure) # so it should not be necessary to also add to this all markers noticed # on changed_atoms, even though that might include more markers than # we have so far (especially after we add atoms from invalid ladders below). live_markers = [] for marker in homeless_markers: still_alive = marker._f_move_to_live_atompair_step1() #e @@@@ rename (no step1) (also fix @@@) # note: we don't yet know if they'll still be alive # when this updater run is done. if still_alive: live_markers.append(marker) # only used for asserts if (not not still_alive) != (not marker.killed()): print "\n***BUG: still_alive is %r but %r.killed() is %r" % \ (still_alive, marker, marker.killed()) if debug_flags.DEBUG_DNA_UPDATER: # SOON: _VERBOSE if still_alive: print "dna updater: moved marker %r, still alive after step1" % (marker,) else: print "dna updater: killed marker %r (couldn't move it)" % (marker,) del homeless_markers ignore_new_changes("from moving DnaMarkers") # ignore changes caused by adding/removing marker jigs # to their atoms, when the jigs die/move/areborn # make sure invalid DnaLadders are recognized as such in the next step, # and dissolved [possible optim: also recorded for later destroy??]. # also (#e future optim) break long ones at damage points so the undamaged # parts needn't be rescanned in the next step. # # Also make sure that atoms that are no longer in valid ladders # (due to dissolved or fragmented ladders) are scanned below, # or that the chains they are in are covered. This is necessary so that # the found chains below cover all atoms in every "base pair" (Ss-Ax-Ss) # they cover any atom in. Presently this is done by # adding some or all of their atoms into changed_atoms # in the following method. dissolve_or_fragment_invalid_ladders( changed_atoms) # note: this does more than its name implies: # - invalidate all ladders containing changed_atoms # (or touching changed Pl atoms, as of 080529 bugfix); # - add all live baseatoms from invalid ladders to changed_atoms # (whether they were invalidated by it or before it was called). # see its comments and the comment just before it (above) for details. # # NOTE: THIS SETS dnaladder_inval_policy to DNALADDER_INVAL_IS_ERROR # (at the right time during its side effects/tests on ladders) # TODO: make sure _f_baseatom_wants_pam is extended to cover whole basepairs # (unless all code which stores into it does that) # Find the current axis and strand chains (perceived from current bonding) # on which any changed atoms reside, but only scanning along atoms # not still part of valid DnaLadders. (I.e. leave existing undamaged # DnaLadders alone.) (The found chains or rings will be used below to # make new DnaChain and DnaLadder objects, and (perhaps combined with # preexisting untouched chains ###CHECK) to make new WholeChains and tell the # small chains about them.) ignore_new_changes("from dissolve_or_fragment_invalid_ladders", changes_ok = False) axis_chains, strand_chains = find_axis_and_strand_chains_or_rings( changed_atoms) ignore_new_changes("from find_axis_and_strand_chains_or_rings", changes_ok = False ) if debug_flags.DNA_UPDATER_SLOW_ASSERTS: assert_unique_chain_baseatoms(axis_chains + strand_chains) # make ladders # Now use the above-computed info to make new DnaLadders out of the chains # we just made (which contain all PAM atoms no longer in valid old ladders), # and to merge end-to-end-connected ladders (new/new or new/old) into larger # ones, when that doesn't make them too long. We'll reverse chains # as needed to make the ones in one ladder correspond in direction, and to # standardize their strand bond directions. (There is no longer any need to # keep track of index_direction -- it might be useful for new/new ladder # merging, but that probably doesn't help us since we also need to handle # new/old merging. For now, the lower-level code maintains it for individual # chains, and when fragmenting chains above, but discards it for merged # chains.) # Note: we don't need to rotate smallchains that are rings, to align them # properly in ladders, since make_new_ladders will break them up as # needed into smaller pieces which are aligned. new_axis_ladders, new_singlestrand_ladders = make_new_ladders( axis_chains, strand_chains) all_new_unmerged_ladders = new_axis_ladders + new_singlestrand_ladders ignore_new_changes("from make_new_ladders", changes_ok = False) if debug_flags.DNA_UPDATER_SLOW_ASSERTS: assert_unique_ladder_baseatoms( all_new_unmerged_ladders) # convert pam model of ladders that want to be converted # (assume all old ladders that want this were invalidated # and therefore got remade above; do this before merging # in case conversion errors are confined to smaller ladders # that way, maybe for other reasons) [bruce 080401 new feature] # note: several of the pam conversion methods might temporarily change # dnaladder_inval_policy, but only very locally in the code, # and they will change it back to its prior value before returning default_pam = pref_dna_updater_convert_to_PAM3plus5() and MODEL_PAM3 or None # None means "whatever you already are", i.e. do no conversion # except whatever is requested by manual conversion operations. # There is not yet a way to say "display everything in PAM5". # We will probably need either that, or "convert selection to PAM5", # or both. As of 080401 we only have "convert one ladder to PAM5" (unfinished). if default_pam or _f_baseatom_wants_pam: #bruce 080523 optim: don't always call this _do_pam_conversions( default_pam, all_new_unmerged_ladders ) if _f_invalid_dna_ladders: #bruce 080413 print "\n*** likely bug: _f_invalid_dna_ladders is nonempty " \ "just before merging new ladders: %r" % _f_invalid_dna_ladders # During the merging of ladders, we make ladder inval work normally; # at the end, we ignore any invalidated ladders due to the merge. # (The discarding is a new feature and possible bugfix, but needs more testing # and review since I'm surprised it didn't show up before, so I might be # missing something) [bruce 080413 1pm PT] _old_policy = temporarily_set_dnaladder_inval_policy( DNALADDER_INVAL_IS_OK) assert _old_policy == DNALADDER_INVAL_IS_ERROR # merge axis ladders (ladders with an axis, and 1 or 2 strands) merged_axis_ladders = merge_and_split_ladders( new_axis_ladders, debug_msg = "axis" ) # note: each returned ladder is either entirely new (perhaps merged), # or the result of merging new and old ladders. ignore_new_changes("from merging/splitting axis ladders", changes_ok = False) del new_axis_ladders # merge singlestrand ladders (with no axis) # (note: not possible for an axis and singlestrand ladder to merge) merged_singlestrand_ladders = merge_and_split_ladders( new_singlestrand_ladders, debug_msg = "single strand" ) # not sure if singlestrand merge is needed; split is useful though ignore_new_changes("from merging/splitting singlestrand ladders", changes_ok = False) del new_singlestrand_ladders restore_dnaladder_inval_policy( _old_policy) del _old_policy _f_clear_invalid_dna_ladders() merged_ladders = merged_axis_ladders + merged_singlestrand_ladders if debug_flags.DNA_UPDATER_SLOW_ASSERTS: assert_unique_ladder_baseatoms( merged_ladders) # Now make or remake chunks as needed, so that each ladder-rail is a chunk. # This must be done to all newly made or merged ladders (even if parts are old). all_new_chunks = [] for ladder in merged_ladders: new_chunks = ladder.remake_chunks() # note: this doesn't have an issue about wrongly invalidating the # ladders whose new chunks pull atoms into themselves, # since when that happens the chunks didn't yet set their .ladder. all_new_chunks.extend( new_chunks) ladder._f_reposition_baggage() #bruce 080404 # only for atoms with _f_dna_updater_should_reposition_baggage set # (and optimizes by knowing where those might be inside the ladder) # (see comments inside it about what might require us # to do it in a separate loop after all chunks are remade) ### REVIEW: will this invalidate any ladders?? If so, need to turn that off. ignore_new_changes("from remake_chunks and _f_reposition_baggage", changes_ok = True) # (changes are from parent chunk of atoms changing; # _f_reposition_baggage shouldn't cause any [#test, using separate loop]) # Now make new wholechains on all merged_ladders, # let them own their atoms and markers (validating any markers found, # moved or not, since they may no longer be on adjacent atoms on same wholechain), # and choose their controlling markers. # These may have existing DnaSegmentOrStrand objects, # or need new ones (made later), and in a later step (not in this function) # those objects take over their chunks. # Note that due to the prior step, any atom in a ladder (new or old) # can find its smallchain via its chunk. # We'll do axis chains first, in case we want them finalized # in figuring out anything about strand markers (not the case for now). # For any length-1 axis chains, we'll pick a direction arbitrarily (?), # so we can store, for all chains, a pointer to the ladder-index of the # chain it connects to (if any). # For each kind of chain, the algorithm is handled by this function: def algorithm( ladders, ladder_to_rails_function ): """ [local helper function] Given a list of ladders (DnaLadders and/or DnaSingleStrandDomains), and ladder_to_rails_function to return a list of certain rails of interest to the caller from each ladder, partition the resulting rails into connected sets (represented as dicts from id(rail) to rail) and return a list of these sets. "Connected" means the rails are bonded end-to-end so that they belong in the same WholeChain. To find some rail's connected rails, we just use atom.molecule.ladder and then look for atom in the rail ends of the same type of rail (i.e. the ones found by ladder_to_rails_function). """ # note: this is the 3rd or 4th "partitioner" I've written recently; # could there be a helper function for partitioning, like there is # for transitive closure (transclose)? [bruce 080119] toscan_all = {} # maps id(rail) -> rail, for initial set of rails to scan for ladder in ladders: for rail in ladder_to_rails_function(ladder): toscan_all[id(rail)] = rail def collector(rail, dict1): """ function for transclose on a single initial rail: remove each rail seen from toscan_all if present; store neighbor atom pointers in rail, and store neighbor rails themselves into dict1 """ toscan_all.pop(id(rail), None) # note: forgetting id() made this buggy in a hard-to-notice way; # it worked without error, but returned each set multiple times. rail._f_update_neighbor_baseatoms() # called exactly once per rail, # per dna updater run which encounters it (whether as a new # or preexisting rail); implem differs for axis or strand atoms. # Notes [080602]: # - the fact that we call it even on preexisting rails (not # modified during this dna updater run) might be important, # if any of their neighbor atoms differ. OTOH this might never # happen, since such changes would call changed_structure # on those baseatoms (even if there's an intervening Pl, # as of a recent bugfix). # - the order of rail.neighbor_baseatoms doesn't matter here, # but might matter in later code, so it's necessary to make sure # it's consistent for all rails in a length-1 ladder, but ok # to do that either in the above method which sets them, # or in later code which makes them consistent. (As of 080602 # it's now done in the above method which sets them.) for neighbor_baseatom in rail.neighbor_baseatoms: if neighbor_baseatom is not None: rail1 = _find_rail_of_atom( neighbor_baseatom, ladder_to_rails_function ) dict1[id(rail1)] = rail1 return # from collector res = [] # elements are data args for WholeChain constructors (or helpers) for rail in toscan_all.values(): # not itervalues (modified during loop) if id(rail) in toscan_all: # if still there (hasn't been popped) toscan = {id(rail) : rail} rails_for_wholechain = transclose(toscan, collector) res.append(rails_for_wholechain) return res # Make new wholechains. Note: The constructors call marker methods on all # markers found on those wholechains; those methods can kill some of the # markers. new_wholechains = ( map( Axis_WholeChain, algorithm( merged_axis_ladders, lambda ladder: ladder.axis_rails() ) ) + map( Strand_WholeChain, algorithm( merged_ladders, # must do both kinds at once! lambda ladder: ladder.strand_rails ) ) ) if debug_flags.DEBUG_DNA_UPDATER: print "dna updater: made %d new or changed wholechains..." % len(new_wholechains) if debug_flags.DNA_UPDATER_SLOW_ASSERTS: assert_unique_wholechain_baseatoms(new_wholechains) # The new WholeChains should have found and fully updated (or killed) # all markers we had to worry about. Assert this -- but only with a # debug print, since I might be wrong (e.g. for markers on oldchains # of length 1, now on longer ones??) and it ought to be harmless to # ignore any markers we missed so far. for marker in live_markers: marker._f_should_be_done_with_move() del live_markers # note: those Whatever_WholeChain constructors above also have side effects: # - own their atoms and chunks (chunk.set_wholechain) # - kill markers no longer on adjacent atoms on same wholechain # # (REVIEW: maybe use helper funcs so constructors are free of side effects?) # # but for more side effects we run another loop: for wholechain in new_wholechains: wholechain.own_markers() # - own markers # - and (in own_markers) # - choose or make controlling marker, # - and tell markers whether they're controlling (might kill some of them) if debug_flags.DEBUG_DNA_UPDATER: print "dna updater: owned markers of those %d new or changed wholechains" % len(new_wholechains) ignore_new_changes("from making wholechains and owning/validating/choosing/making markers", changes_ok = True) # ignore changes caused by adding/removing marker jigs # to their atoms, when the jigs die/move/areborn # (in this case, they don't move, but they can die or be born) # TODO: use wholechains and markers to revise base indices if needed # (if this info is cached outside of wholechains) return all_new_chunks, new_wholechains # from update_PAM_chunks # == def _do_pam_conversions( default_pam, all_new_unmerged_ladders): """ #doc [private helper] """ #bruce 080523 split this out of its sole caller # maybe: put it into its own module, or an existing one? number_converted = 0 # not counting failures number_failed = 0 ladders_dict = _f_ladders_with_up_to_date_baseframes_at_ends if ladders_dict: print "***BUG: _f_ladders_with_up_to_date_baseframes_at_ends was found with leftover garbage; clearing it now" ladders_dict.clear() locator = _f_atom_to_ladder_location_dict if locator: print "***BUG: _f_atom_to_ladder_location_dict was found with leftover garbage; clearing it now" locator.clear() if 1: # make errors more obvious, bugs less likely; # also make it easy & reliable to locate all atoms in new ladders # (this could surely be optimized, but simple & reliable is primary # concern for now) for ladder in all_new_unmerged_ladders: if not ladder.error: ladder.clear_baseframe_data() ladder._f_store_locator_data() for ladder1 in ladder.strand_neighbor_ladders(): ladder.clear_baseframe_data() # no need to store locator data for these pass for ladder in all_new_unmerged_ladders: assert ladder.valid, "bug: new ladder %r not valid!" % self wanted, succeeded = ladder._f_convert_pam_if_desired(default_pam) # - this checks for ladder.error and won't succeed if set # - this sets baseframe data if conversion succeeds, # and stores ladder in ladders_dict, with value False assert ladder.valid, "bug: _f_convert_pam_if_desired made %r invalid!" % ladder didit = wanted and succeeded failed = wanted and not succeeded number_converted += not not didit number_failed += not not failed if didit: assert ladders_dict.get(ladder, None) == False if debug_flags.DEBUG_DNA_UPDATER_VERBOSE: print "converted:", ladder.ladder_string() continue if number_converted: ## for ladder in all_new_unmerged_ladders: ## ladders_dict[ladder] = None # TODO: refactor this -- see above comment for ladder in all_new_unmerged_ladders: if not ladder.error: ladder._f_finish_converting_bridging_Pl_atoms() # this assert not ladder.error assert ladder.valid, "bug: _f_finish_converting_bridging_Pl_atoms made %r invalid!" % ladder ladder.fix_bondpoint_positions_at_ends_of_rails() # (don't pass ladders_dict, it's accessed as the global which # is assigned to it above [080409 revision]) # the ladders in ladders_dict are known to have valid baseframes # (as we start this loop) or valid baseframes at the ends # (as we continue this loop); # this method needs to look at neighboring ladders # (touching ladder at corners) and use end-baseframes from # them; if it sees one not in the dict, it computes its # baseframes (perhaps just at both ends as an optim) # and also stores that ladder in the dict so this won't # be done to it again. continue pass ladders_dict.clear() del ladders_dict locator.clear() del locator _f_baseatom_wants_pam.clear() # Note: if ladders were converted, their chains are still ok, # since those only store baseatoms (for strand and axis), # and those transmuted and moved but didn't change identity. # So the ladders also don't change identity, and remain valid # unless they had conversion errors. If not valid, they are ok # in those lists since this was already possible in other ways # (I think). (All this needs test and review.) # # But lots of atoms got changed in lots of ways (transmute, move, # rebond, create Pl, kill Pl). Ignore all that. # (review: any changes to ignore if conversion wanted and failed?) msg = "from converting %d ladders" % number_converted if number_failed: msg += " (%d desired conversions failed)" % number_failed # msg is just for debug, nevermind calling fix_plurals if number_converted: ignore_new_changes(msg, changes_ok = True) else: ignore_new_changes(msg, changes_ok = False) return # from _do_pam_conversions # == def _find_rail_of_atom( atom, ladder_to_rails_function): """ [private helper] (can assume atom is an end_baseatom of its rail) """ try: rails = ladder_to_rails_function( atom.molecule.ladder) for rail in rails: for end_atom in rail.end_baseatoms(): if end_atom is atom: return rail assert 0, "can't find any rail in ladder %r (rails %r) which has %r as an end_atom" % \ ( atom.molecule.ladder, rails, atom ) except: print "\n*** BUG: following exception is about _find_rail_of_atom( %r, .mol = %r, ._dna_updater__error = %r, %r): " % \ (atom, atom.molecule, atom._dna_updater__error, ladder_to_rails_function ) raise pass # end
NanoCAD-master
cad/src/dna/updater/dna_updater_chunks.py
NanoCAD-master
cad/src/dna/updater/__init__.py
# Copyright 2008 Nanorex, Inc. See LICENSE file for details. """ dna_updater_debug.py -- debug code for dna_updater @author: Bruce @version: $Id$ @copyright: 2008 Nanorex, Inc. See LICENSE file for details. """ from utilities import debug_flags from graphics.drawing.CS_draw_primitives import drawline from model.jigs import Jig import foundation.env as env from utilities.Log import quote_html from utilities.debug import register_debug_menu_command from platform_dependent.PlatformDependent import fix_plurals from utilities.constants import gensym from widgets.simple_dialogs import grab_text_using_dialog # == def assert_unique_chain_baseatoms(chains, when = ""): if when: when = " (%s)" % when baseatom_info = {} # maps atom.key to chain for chain in chains: for atom in chain.baseatoms: assert atom.key not in baseatom_info, \ "baseatom %r in two chains%s: %r and %r" % \ (atom, when, baseatom_info[atom.key], chain) baseatom_info[atom.key] = chain return def assert_unique_ladder_baseatoms(ladders, when = ""): if when: when = " (%s)" % when baseatom_info = {} # maps atom.key to (ladder, whichrail, rail, pos) for ladder in ladders: rails = ladder.all_rail_slots_from_top_to_bottom() # list of rail or None lastlength = None for whichrail in [0,1,2]: rail = rails[whichrail] if not rail: continue length = len(rail) if lastlength is not None: assert lastlength == length, "rail length mismatch in %r" % ladder lastlength = length baseatoms = rail.baseatoms for pos in range(length): atom = baseatoms[pos] loc_info = (ladder, whichrail, rail, pos) assert atom.key not in baseatom_info, \ "baseatom %r in two ladders%s; loc info: %r and %r" % \ (atom, when, baseatom_info[atom.key], loc_info) baseatom_info[atom.key] = loc_info return def assert_unique_wholechain_baseatoms(wholechains, when = ""): if when: when = " (%s)" % when baseatom_info = {} # maps atom.key to (wholechain, chain) for wholechain in wholechains: for chain in wholechain.rails(): for atom in chain.baseatoms: loc_info = (wholechain, chain) assert atom.key not in baseatom_info, \ "baseatom %r in two rails%s; loc info: %r and %r" % \ (atom, when, baseatom_info[atom.key], loc_info) baseatom_info[atom.key] = loc_info return # == # some of the following might be of more general use def find_atom_by_name(assy, name): # todo: refile to debug or assy """ Find atom in assy by its name (case sensitive) or number. @warning: current implementation only works in the current Part. """ name = str(name) # in case it's an int # bug: this version only works in the current Part for mol in assy.molecules: for atom in mol.atoms.itervalues(): foundname = str(atom) foundnumber = str(atom.key) if name in (foundname, foundnumber): # bugfix 080227: foundnumber return atom return None class VeryVisibleAtomMarker(Jig): mmp_record_name = "VeryVisibleAtomMarker" #k ok? note that it has no reading code... # todo: mmp reading code; icon def _draw_jig(self, glpane, color, highlighted = False): length = glpane.scale # approx. # print "%r got color = %r" % (self, color,) # it gets gray for atom in self.atoms: pos = atom.posn() drawline(color, pos, - glpane.pov, width = 2) # line from center of view, in case far off-screen # lines in diagonal directions (more likely to hit screen if off-screen) for direction in (glpane.up + glpane.right, glpane.right + glpane.down, glpane.down + glpane.left, glpane.left + glpane.up): endpoint = pos + direction * length drawline( color, pos, endpoint, width = 2) return # not needed if default __str__ contains atom name: ## def __str__(self): ## pass pass def mark_atom_by_name(assy, name): """ If you can find an atom of the given name, mark it visibly. """ atom = find_atom_by_name(assy, name) if atom: env.history.message(quote_html("found atom %r: %r, in part %r" % (name, atom, atom.molecule.part))) mark_one_atom(atom) else: env.history.message(quote_html("can't find atom %r (in part %r)" % (name, assy.part,))) return def mark_one_atom(atom): assy = atom.molecule.assy jig = VeryVisibleAtomMarker(assy, [atom]) jig.name = "Marked Atom %s" % (atom,) ##k assy.place_new_jig(jig) # redraw, etc assy.win.glpane.gl_update() # this works now to redraw if 0:##### assy.win.mt.mt_update() # guess this also might be needed, should fix in same way # AttributeError: mt_update, but didn't stop it from working to redraw, so only gl_update was needed for that # the above did not suffice to redraw. did our debug pref skip the redraw?? need assy.changed? or better checkpoints? # or was it assy.glpane attr error, now fixed (how come i didn;t see that vbefore?) assy.changed() # see if this helps; if so, should also debug need for this when i have time ###BUG - all the above is not enough to redraw it. Another deposit will do it though. @@@ return def mark_atoms(atoms): assert atoms # a list assy = atoms[0].molecule.assy for atom in atoms: assert atom.molecule.assy is assy # all in same assy jig = VeryVisibleAtomMarker(assy, atoms) jig.name = gensym("Marked Atoms ", assy) assy.place_new_jig(jig) # redraw, etc assy.win.glpane.gl_update() # this works now to redraw #e more updates? return def mark_atom_by_name_command(glpane): # review: is this really what the arg always is? i bet it's whatever widget this appeared in... ok, text = grab_text_using_dialog( default = "Ss3-564", title = "Mark atom by name", label = "atom name or number:" ) if ok: name = text assy = glpane.assy mark_atom_by_name(assy, name) return # todo: should do this in an initialize function! register_debug_menu_command( "Mark atom by name...", mark_atom_by_name_command ) #e could also: select multiple atoms by list of names def select_atoms_with_errors_command(glpane): """ current part only... """ count = 0 assy = glpane.win.assy for mol in assy.molecules: # current part only for atom in mol.atoms.itervalues(): if atom._dna_updater__error: count += 1 # whether or not already selected atom.pick() # should be safe inside itervalues ### REVIEW: selection filter effect not considered msg = "found %d pseudoatom(s) with dna updater errors in %r" % (count, assy.part) msg = fix_plurals(msg) env.history.message(quote_html(msg)) return register_debug_menu_command( "DNA updater: select atoms with errors", select_atoms_with_errors_command ) def mark_selected_atoms_command(glpane): # untested """ current part only... """ assy = glpane.win.assy atoms = assy.selatoms.values() mark_atoms(atoms) msg = "marked %d selected atom(s)" % len(atoms) #e could use part of this string in jig name too msg = fix_plurals(msg) env.history.message(quote_html(msg)) return register_debug_menu_command( "Mark selected atoms", mark_selected_atoms_command ) # == ##_found = None ##_found_molecule = -1 # impossible value of _found.molecule # convenience methods -- add code to these locally, to print things # at start and end of every dna updater run; runcount counts the runs of it # in one session; changed_atoms should not be modified, has not been filtered at all def debug_prints_as_dna_updater_starts( runcount, changed_atoms): # print "\ndebug_prints_as_dna_updater_starts: %d, len %d\n" % \ # (runcount, len(changed_atoms)) ## global _found, _found_molecule ## if _found is None: ## win = env.mainwindow() ## _found = find_atom_by_name(win.assy, 37) ## if _found is not None: ## print "\nfound atom", _found ## if _found is not None and _found_molecule is not _found.molecule: ## print "\nstart %d: %r.molecule = %r" % (runcount, _found, _found.molecule) ## _found_molecule = _found.molecule if debug_flags.DNA_UPDATER_SLOW_ASSERTS: win = env.mainwindow() win.assy.checkparts("start dna updater %d" % runcount) return def debug_prints_as_dna_updater_ends( runcount): # print "\ndebug_prints_as_dna_updater_ends: %d\n" % ( runcount, ) ## global _found, _found_molecule ## if _found is not None and _found_molecule is not _found.molecule: ## print "\nend %d: %r.molecule = %r" % (runcount, _found, _found.molecule) ## _found_molecule = _found.molecule if debug_flags.DNA_UPDATER_SLOW_ASSERTS: win = env.mainwindow() win.assy.checkparts("end dna updater %d" % runcount) return # end
NanoCAD-master
cad/src/dna/updater/dna_updater_debug.py
# Copyright 2007-2008 Nanorex, Inc. See LICENSE file for details. """ dna_updater_find_chains.py - helper for dna_updater_chunks @author: Bruce @version: $Id$ @copyright: 2007-2008 Nanorex, Inc. See LICENSE file for details. """ from utilities import debug_flags from operations.bond_chains import abstract_bond_chain_analyzer from dna.model.AtomChainOrRing import AtomChain, AtomRing from dna.model.DnaChain import AxisChain, StrandChain from dna.model.DnaChain import DnaChain_AtomChainWrapper # for isinstance from dna.model.PAM_atom_rules import PAM_atoms_allowed_in_same_ladder from utilities.debug import print_compact_stack from utilities.constants import MODEL_PAM3, MODEL_PAM5 # == # helper classes (will probably turn out to be private, or perhaps # even local to find_axis_and_strand_chains_or_rings) class dna_bond_chain_analyzer(abstract_bond_chain_analyzer): """ [private abstract helper class] For DNA, we like our found atom/bond chains or rings to be instances of one of AtomChainOrRing's subclasses, AtomChain or AtomRing. """ _wrapper = None # a per-subclass constant, to wrap an AtomChainOrRing def make_chain(self, listb, lista): # also used for lone atoms return self._wrap( AtomChain(listb, lista)) def make_ring(self, listb, lista): return self._wrap( AtomRing(listb, lista)) def _wrap(self, chain_or_ring): if chain_or_ring is None: return None res = self._wrapper(chain_or_ring) # check effect of wrapper: assert isinstance( res, DnaChain_AtomChainWrapper) #e remove when works? return res def found_object_iteratoms(self, chain_or_ring): if chain_or_ring is None: return () # check effect of wrapper: assert isinstance( chain_or_ring, DnaChain_AtomChainWrapper) #e remove when works? return chain_or_ring.iteratoms() # note: it's essential to include Pl atoms in this value, # for sake of find_chain_or_ring's dict.pop. def bond_ok(self, bond): """ [implements abstract_bond_chain_analyzer subclass API method] """ #bruce 080405; note that this function permits bondpoints # note: this is called (legitimately) on rung bonds even though only # non-rung bonds will end up in found chains. res = PAM_atoms_allowed_in_same_ladder( bond.atom1, bond.atom2 ) return res pass class axis_bond_chain_analyzer(dna_bond_chain_analyzer): _wrapper = AxisChain def atom_ok(self, atom): if not atom.molecule: # I've seen this after Undo, presumably since it's buggy [080122] # (To repeat: make a duplex, delete some atoms, Undo, Redo. # [bruce 080226 comment]) print_compact_stack( "bug: axis_bond_chain_analyzer skipping %r " \ "with no .molecule (killed = %r, _f_assy = %r): " \ % (atom, atom.killed(), atom._f_assy) ) return False if atom._dna_updater__error: return False return atom.element.role == 'axis' and not atom.molecule.in_a_valid_ladder() pass class strand_bond_chain_analyzer(dna_bond_chain_analyzer): _wrapper = StrandChain def atom_ok(self, atom): # note: this can include Pl atoms in PAM5, # but the wrapper class filters them out of # the atom list it stores. if not atom.molecule: print_compact_stack( "bug: strand_bond_chain_analyzer skipping %r with no .molecule: " % atom) return False if atom._dna_updater__error: return False return atom.element.role == 'strand' and not atom.molecule.in_a_valid_ladder() pass # end of class # singleton objects # (todo: could be local to the main using function, # if they returned instances so axis_analyzer.found_object_iteratoms etc # was not needed by other functions here; now they do, so REVIEW whether they can be local ###) axis_analyzer = axis_bond_chain_analyzer() strand_analyzer = strand_bond_chain_analyzer() # == def find_axis_and_strand_chains_or_rings( changed_atoms): """ Find and return the lists (axis_chains, strand_chains) of connected sets of axis and strand atoms respectively, in the representation described below. @param changed_atoms: an atom.key -> atom dict of all changed atoms that this function needs to consider, which includes no killed atoms. WE ASSUME OWNERSHIP OF THIS DICT and modify it in arbitrary ways. Note: in present calling code [071127] this dict might include atoms from closed files. @return: (axis_chains, strand_chains), which are sequences of objects representing changed chains or rings (or lone atoms) of the specified element roles (axis or strand respectively). (They should be both tuples or both lists, so the caller can concatenate them using +.) The chain or ring format is as returned by the make_* methods of the singleton objects axis_analyzer and strand_analyzer, which have methods for further use of those objects (in case they are just python data rather than class instances), e.g. for iterating over their atoms. Exception: None is never an element of the returned lists, since we remove it. """ # Sort changed atoms into types we consider differently. axis_atoms = {} strand_atoms = {} def classify(atom): """ [local helper function] put a live real atom into axis_atoms or strand_atoms, or discard it """ # REVIEW: should we use atom classes or per-class methods here? # REVIEW: need to worry about atoms with too few bonds? element = atom.element role = element.role # 'axis' or 'strand' or 'unpaired-base' or None pam = element.pam # MODEL_PAM3 or MODEL_PAM5 or None if role == 'axis': axis_atoms[atom.key] = atom assert pam in (MODEL_PAM3, MODEL_PAM5) # REVIEW: separate these too? elif role == 'strand': strand_atoms[atom.key] = atom assert pam in (MODEL_PAM3, MODEL_PAM5) # REVIEW: separate these too? else: pass # ignore all others, including role == 'unpaired-base' atoms return for atom in changed_atoms.itervalues(): if atom.killed(): print "bug: update_PAM_chunks: %r is killed (ignoring)" % atom elif atom.is_singlet(): # classify the real neighbor instead # (Note: I'm not sure if this is needed, but I'll do it to be safe. # A possible need-case to review is when an earlier update step # broke a bond.) classify(atom.singlet_neighbor()) else: classify(atom) continue if not axis_atoms and not strand_atoms: return (), () # optimization if debug_flags.DEBUG_DNA_UPDATER: print "dna updater: %d axis atoms, %d strand atoms" % (len(axis_atoms), len(strand_atoms)) axis_chains = axis_analyzer.find_chains_or_rings( axis_atoms ) # NOTE: this takes ownership of axis_atoms and trashes it. # NOTE: this only finds chains or rings which contain at least one # atom in axis_atoms, but they often contain other axis atoms too # (which were not in axis_atoms since they were not recently changed). # # Result is a list of objects returned by the make_ methods in # analyzer (for doc, see abstract_bond_chain_analyzer, unless we # override them in axis_bond_chain_analyzer). assert not axis_atoms # warning: this assert is correct now, but maybe it's not # formally guaranteed by find_chains_or_rings ## del axis_atoms ## SyntaxError: can not delete variable 'axis_atoms' referenced in nested scope axis_atoms = None # not a dict, bug if used if debug_flags.DEBUG_DNA_UPDATER: print "dna updater: found %d axis chains or rings" % len(axis_chains) # strand_chains = strand_analyzer.find_chains_or_rings( strand_atoms ) assert not strand_atoms # see warning on similar assert above if debug_flags.DEBUG_DNA_UPDATER: print "dna updater: found %d strand chains or rings" % len(strand_chains) return axis_chains, strand_chains # from find_axis_and_strand_chains_or_rings # == def find_newly_made_strand_chain( atom): #bruce 080523 strand_atoms = {atom.key: atom} #k strand_chains = strand_analyzer.find_chains_or_rings( strand_atoms ) assert not strand_atoms # see warning on similar assert above assert len(strand_chains) == 1, "should be len 1: %r" % (strand_chains,) return strand_chains[0] # end
NanoCAD-master
cad/src/dna/updater/dna_updater_find_chains.py
# Copyright 2007-2008 Nanorex, Inc. See LICENSE file for details. """ fix_atom_classes.py - fix classes of PAM atoms @author: Bruce @version: $Id$ @copyright: 2007-2008 Nanorex, Inc. See LICENSE file for details. """ from dna.updater.dna_updater_utils import replace_atom_class from model.chem import Atom StrandAtom = Atom # stub AxisAtom = Atom # stub UnpairedBaseAtom = Atom # stub ##issues: bondpoint classes. need a separate func to fix them later? ##which ones do we fix, all new bps and all bps on changed atoms? (yes) ##for all these, fix all bps on on base at once, so store base in a dict ##after all transmutes and breaks. ## ##other issues: ## Atom vs ChemAtom ## code on Atom or on Element? ## or Atomtype? ## ##guess: as we fix atoms colect bps and their base atoms into sep dict ##when it's full, incl of busted bonds, ##then fix all the bps of those base atoms. ##using a separate func, to fix bp classes and reposition them too. ## ##so this present code can ignore bps for now. # == # obs cmt? # Give bondpoints and real atoms the desired Atom subclasses. # (Note: this can affect bondpoints and real atoms created by earlier steps # of the same call of this function.) ## atom._f_actual_class_code != atom._f_desired_class_code: def real_atom_desired_class(atom): #e refile into an Atom method? return classname only? """ Which class do we wish a real atom was in, based on its element, and if it's a bondpoint, on its neighbor atom? """ assert not atom.killed() ## if atom.is_singlet(): ## # WRONG. true desire is for special atoms to have the right pattern of special bps... ## base = atom.singlet_neighbor() ## assert not base.killed() ## else: ## base = atom ## element = base.element assert not atom.is_singlet() element = atom.element pam = element.pam # MODEL_PAM3 or MODEL_PAM5 or None ### use this? role = element.role # 'strand' or 'axis' or 'unpaired-base' or None if role == 'strand': return StrandAtom # PAM3_StrandAtom? subclass of StrandAtom? What about Pl? elif role == 'axis': return AxisAtom elif role == 'unpaired-base': return UnpairedBaseAtom else: return Atom # ChemAtom? def fix_atom_classes( changed_atoms): #e rename, real_atom; call differently, see comment above ### @@@ """ Fix classes of PAM atoms in changed_atoms, ignoring bondpoints and/or killed atoms. (Also patch changed_atoms with replaced atoms if necessary.) """ for atom in changed_atoms.itervalues(): if not atom.killed() and not atom.is_singlet(): old_class = atom.__class__ ## new_class = atom._f_desired_class ### IMPLEM, maybe revise details new_class = real_atom_desired_class( atom) if old_class is not new_class: replace_atom_class( atom, new_class, changed_atoms) # note: present implem is atom.__class__ = new_class; # and any implem only changes changed_atoms # at atom.key (which is unchanged), # so is legal during itervalues. continue return
NanoCAD-master
cad/src/dna/updater/fix_atom_classes.py
# Copyright 2007-2008 Nanorex, Inc. See LICENSE file for details. """ dna_updater_ladders.py - ladder-related helpers for dna_updater_chunks @author: Bruce @version: $Id$ @copyright: 2007-2008 Nanorex, Inc. See LICENSE file for details. See also: DnaLadder """ from utilities import debug_flags from dna.updater.dna_updater_follow_strand import dna_updater_follow_strand from dna.model.DnaLadder import DnaLadder, DnaSingleStrandDomain from dna.updater.dna_updater_globals import _f_get_invalid_dna_ladders from dna.updater.dna_updater_globals import DNALADDER_INVAL_IS_OK from dna.updater.dna_updater_globals import temporarily_set_dnaladder_inval_policy from dna.updater.dna_updater_globals import DNALADDER_INVAL_IS_ERROR from dna.model.dna_model_constants import MAX_LADDER_LENGTH from model.elements import Pl5 # == def dissolve_or_fragment_invalid_ladders( changed_atoms): """ #doc... [some is in a caller comment] Also make sure that live atoms that are no longer in valid ladders (due to dissolved or fragmented ladders) are included in the caller's subsequent step of finding changed chains, or that the chains they are in are covered. This is necessary so that the found chains (by the caller, after this call) cover all atoms in every "base pair" (Ss-Ax-Ss) they cover any atom in. This might be done by adding some of their atoms into changed_atoms in this method (but only live atoms). """ # assume ladder rails are DnaLadderRailChunk instances, # or were such until atoms got removed (calling their delatom methods). changed_chunks = {} for atom in changed_atoms.itervalues(): chunk = atom.molecule ## print "DEBUG: changed atom %r -> chunk %r" % (atom, chunk) changed_chunks[id(chunk)] = chunk if atom.element is Pl5: #bruce 080529 fix bug 2887 (except for the lone Pl atom part, # really a separate bug) # Only needed for Pl5 whose structure actually changed # (so no need to do it recursively for the ones we add to # changed_atoms lower down). Needed because, without it, # breaking a Pl-Ss bond can leave a Pl whose only real bond # goes to a valid ladder, resulting in finding a strand chain # with only that Pl atom (thus no baseatoms), which assertfails, # and would probably cause other problems if it didn't. for Ss in atom.strand_neighbors(): chunk = Ss.molecule changed_chunks[id(chunk)] = chunk # no need to put Ss into changed_atoms, # that will happen lower down when chunk ladder becomes invalid # (and if somehow it doesn't, probably not needed anyway, # though that ought to be reviewed) continue pass continue for chunk in changed_chunks.itervalues(): if debug_flags.DEBUG_DNA_UPDATER_VERBOSE: # was useful for bug 080120 9pm print "dna updater: fyi: tell changed chunk %r -> inval its ladder %r" % \ (chunk, getattr(chunk, 'ladder', "<has none>")) pass # todo: assert not killed, not nullMol, is a Chunk ## chunk.invalidate_ladder() chunk.invalidate_ladder_and_assert_permitted() # fyi: noop except in DnaLadderRailChunk # this just invals chunk.ladder (and below code will dissolve it); # a future optim could fragment it instead, # if we also recorded which basepair positions # were invalid, and made sure their atoms were covered # below so their chains will get scanned by caller, # e.g. due to changed_atoms. # Changed atoms that got removed from their ladders invalidated them # at the time (in DnaLadderRailChunk.delatom). Those that didn't get # removed from them are still in them, and invalidated them just above. # So the following will now give us a complete list of invalid ladders, # all of whose atoms we want to scan here. invalid_ladders = _f_get_invalid_dna_ladders() # now that we grabbed invalid ladders, and callers will make new valid # ones soon, any uncontrolled/unexpected inval of ladders is a bug -- # so make it an error except for specific times when we temporarily # permit it and make it a noop (using DNALADDER_INVAL_IS_NOOP_BUT_OK). # [bruce 080413] _old = temporarily_set_dnaladder_inval_policy( DNALADDER_INVAL_IS_ERROR ) # note: the restore happens elsewhere, which is why we assert what the # old policy was, rather than bothering to later pass it to the # restore function (not called before we return), restore_dnaladder_inval_policy. assert _old == DNALADDER_INVAL_IS_OK for ladder in invalid_ladders: # WARNING: the following is only reviewed for the case of the above code # dissolving (invalidating, not fragmenting) chunk's ladder. #e Could optim if we know some rails were untouched, by # "including them whole" rather than rescanning them, in caller. # Note: what is meant by "dissolving the ladder" (done above) # vs "fragmenting it" (not implemented) is the difference between # what happens to the atoms no longer in a valid ladder -- # are they (until updater runs on them) in no valid ladder, # or in some newly made smaller one? The former, for now. # The comments and docstrings here are unclear about *when* # the dissolving or fragmenting is done. The dissolving can # be considered done right when the ladder is invalidated, # since we don't intend to make fragments from the untouched # parts of it. But this function name claims to do the dissolving # itself (even on already invalidated ladders). # todo: clarify. if debug_flags.DEBUG_DNA_UPDATER_VERBOSE: # was useful for bug 080120 9pm print "dna updater: fyi: adding all atoms from dissolved ladder %r" % ladder for rail in ladder.all_rails(): for atom in rail.baseatoms: # probably overkill, maybe just one atom is enough -- not sure # note: atom is in a ladder that was valid a moment ago, # but even so, it might be killed now, e.g. if you select # and delete one strand atom in a duplex. if not atom.killed(): changed_atoms[atom.key] = atom continue return # == helper for make_new_ladders class chains_to_break: """ Helper class for breaking chains all at once after incrementally recording all desired breakpoints. """ def __init__( self, chains): self.chains = chains # a list self._set_of_breakpoints_for_chain = d = {} for chain in chains: d[chain] = {} # avoid later setdefault return def break_chain_later( self, chain, index, whichside): """ Record info about where to later break chain -- on whichside of index. @param chain: a chain that must be in self.chains @type chain: DnaChain @param index: an atom index in chain; WARNING: would become invalid if we reversed the chain @param whichside: which side of the indexed atom the break should be on, represented as 1 or -1 -- the desired break is between index and index + whichsidetobreak """ ## key = (chain, index, whichside) # no, we don't need to record the distinction between break point and direction, # just enough to know where the break is; and we might as well collect # it up per chain: if whichside == -1: # break_indices = index - 1, index break_before = index else: assert whichside == 1 # break_indices = index, index + 1 break_before = index + 1 # not needed: assert chain in self.chains ## self._set_of_breakpoints_for_chain.setdefault(chain, {})[break_before] = None self._set_of_breakpoints_for_chain[chain][break_before] = None # arb value return def break_between_Q( self, chain, index1, index2): """ Is there a break between the given two adjacent indices in chain? @note: adjacent indices can be passed in either order. """ breaks = self._set_of_breakpoints_for_chain[chain] assert abs(index1 - index2) == 1 break_before = max(index1, index2) return breaks.has_key(break_before) def breakit(self, chain): """ Return a sequence of (start_index, length) pairs, suitable for passing to chain.virtual_fragment, which describes the fragments of chain into which our recorded breaks should break it. @param chain: a chain that must be in self.chains @type chain: DnaChain @return: sequence of (start_index, length) pairs """ breaks = self._set_of_breakpoints_for_chain[chain].keys() # might be empty breaks.sort() start_index = chain.start_baseindex() # modified during loop limit_index = chain.baselength() + start_index breaks.append(limit_index) res = [] num_bases = 0 # for asserts only for break_before in breaks: length = break_before - start_index num_bases += length # for asserts only # length can be 0 here, due to explicit breaks at the ends if length: res.append( (start_index, length) ) start_index = break_before continue if debug_flags.DEBUG_DNA_UPDATER_VERBOSE: # made verbose on 080201 print "will break %r -> %d pieces == %r" % (chain, len(res), res) assert num_bases == chain.baselength() return res pass # == def make_new_ladders(axis_chains, strand_chains): """ Make new DnaLadders and/or DnaSingleStrandDomains out of the given (partial) atom chains (which should contain only PAM atoms no longer in valid old ladders, and which are able to form complete new ladders, since they contain all or no PAM atoms from each "base pair" (Ss-Ax-Ss unit) or "single strand base" (either Ss-Ax- with no other Ss on that Ax, or Ss with no Ax (possibly with 'unpaired-base' atoms which we mostly ignore), fragmenting, reversing, and shifting the chains as needed. The newly made ladders might be more fragmented than required (i.e. new/new ladder merges might be possible), and they might be mergeable with old ladders. Their length can be as short as 1. They might be rings (or moebius rings), or some of their rails might be rings, but this is not detected or encoded explicitly. The new ladders will have rails in the same direction and with proper bond directions. (If necessary, we fix inconsistent bond directions.) [### partly nim; see ladder.error flag -- also it would be better to not change them but to break bonds. @@@] @return: tuple of two lists: newly made DnaLadders, newly made DnaSingleStrandDomains """ # Basic algorithm: scan each axis chain (or ring), and follow along its two # bound strands to see when one or both of them leave it or stop (i.e. when # the next atom along the strand is not bound to the next atom along the # axis). This should classify all strand atoms as well (since bare ones were # deleted earlier -- if they weren't, remaining strand fragments can also # be found). # possible simplification: should we just make lots of length==1 ladders # (one per axis atom), then merge them all? In theory, this should work, # and it might even be faster -- that depends on how often this step # manages to return ladders much longer than 1. It would eliminate # most code in this function. (Try it if this function is hard to debug? @@@) strand_axis_info = {} for axis in axis_chains: for atom, index in axis.baseatom_index_pairs(): # assume no termination atoms here new_strand_atoms = atom.strand_neighbors() # todo: make an AxisAtom method from this new Atom method # For efficiency, at this stage we just store info about these strand atoms' axis locations; # later we scan strands all at once and look at that info. This avoids trying both pairings # of prior and current strand atoms, and checking for bonding (perhaps thru Pl) or adjacency # (worrying about ring index wraparound). for s_atom in new_strand_atoms: strand_axis_info[s_atom.key] = (axis, index) # store axis object (not id) so it can help with ring indices # Make helper objects to record the strand and axis breaks we'll need to do # (in terms of putting their pieces into separate ladders/rails). # # Note: we don't actually do the breaks until we've scanned everything. # (We might even do some re-merging of unnecessary breaks before doing # any real breaks of axes.) # # Note that matched axis and strand indices might be in reversed relative # order. We won't reverse any chains until the scan is done and the # ladders are made (or being made, since merging ladders requires it). axis_breaker = chains_to_break(axis_chains) strand_breaker = chains_to_break(strand_chains) # helper functions; args are chain, index, whichside: break_axis = axis_breaker.break_chain_later break_strand = strand_breaker.break_chain_later for strand in strand_chains: # Loop over strand's base atoms, watching the strand join and leave # axis chains and move along them; virtually break both axis and strand # whenever it joins, leaves, or moves discontinuously # along axis (treating lack of Ax as moving continuously on an # imaginary Ax chain different from all real ones) # (for details, see the helper function). # (The break_ functions store the virtual breaks for later use # in fragmenting the chains.) dna_updater_follow_strand(1, strand, strand_axis_info, break_axis, break_strand) for strand in strand_chains: # Now copy any axis breaks that strand moves over # onto strand breaks, in case they originated from the # other strand at that point on the axis. dna_updater_follow_strand(2, strand, strand_axis_info, None, break_strand, axis_breaker.break_between_Q ) # Now use the recorded axis breaks to decide what new ladder fragments # to make, and the recorded strand breaks to make strand fragments to # assign to ladder fragments. (Note that matching index directions may # be reversed, and current indices are offset from those of the # fragments.) # # All fragments in the same ladder will now have the same length # (which can be as low as 1). Every ladder will have one or two # strands, assuming prior updater stage rules were not violated. # (The maximum of two strands comes from a maximum of two strand atoms # bonded to one axis atom. The minimum of 1 comes from deleting bare # axis atoms. The coverage of all strand atoms in this matching # process comes from the lack of bare strand atoms. All of this # is only true since a change to any old ladder atom makes us # process all its atoms in this updater cycle, or at least, # either all or no atoms from the 3 atoms in each of its rungs.) # # Maybe: do everything virtually at first, in case we can merge some # ladders before actually breaking chains. (I'm not sure if this is # likely if there were no non-physical situations, though, nor if it's # worth the trouble then, since we need code to merge real ladder # fragments too, in case new ones should merge with old unchanged ones.) ladder_locator = {} # atom.key -> ladder, for end axis atoms of each ladder we're making def end_baseatoms(rail): return rail.end_baseatoms() ladders = [] singlestrands = [] for axis in axis_chains: frags = axis_breaker.breakit(axis) for frag in frags: start_index, length = frag axis_rail = axis.virtual_fragment(start_index, length) ladder = DnaLadder(axis_rail) for atom in axis_rail.end_baseatoms(): ladder_locator[atom.key] = ladder ladders.append(ladder) for strand in strand_chains: frags = strand_breaker.breakit(strand) for frag in frags: start_index, length = frag strand_rail = strand.virtual_fragment(start_index, length) # find ladder to put it in (Ax attached to arbitrary strand atom) atom = strand_rail.end_baseatoms()[0].axis_neighbor() if atom is None: # single strand with no Ax (will be true of every Ss in chain) ## print "dna updater: fyi: found single strand domain %r" % (strand_rail,) for atom2 in strand_rail.baseatoms: assert atom2.axis_neighbor() is None, \ "%r.axis_neighbor() should be None, is %r; atom is %r, sr is %r" % \ (atom2, atom2.axis_neighbor(), atom, strand_rail) # remove when works?? has failed once, 080325 for tom... # and once for me, after exception in pam conversion, 080413 singlestrand = DnaSingleStrandDomain(strand_rail) singlestrands.append(singlestrand) else: # Ax is present ### REVIEW or BUG: why can we assume this works, for an arb (not just end) strand atom? @@@@ # but wait, it's not an arb atom, it's a strand_rail end atom. Should be ok -- FIX THE COMMENT ABOVE. # but there is a bug where dissolving a ladder failed to put axis atoms into changed_atoms... 080120 327p try: ladder = ladder_locator[atom.key] except KeyError: # this happens in a bug tom reported thismorning, so try to survive it and print debug info # [bruce 080219] print "\n***BUG: dna updater: ladder_locator lacks %r -- specialcase might cause bugs" % (atom,) # @@@@@ # specialcase is variant of single strand code above for atom2 in strand_rail.baseatoms: if not (atom2.axis_neighbor() is None): print " sub-bug: %r has %r with an axis_neighbor, %r" % \ (strand_rail, atom2, atom2.axis_neighbor()) singlestrand = DnaSingleStrandDomain(strand_rail) singlestrands.append(singlestrand) else: ladder.add_strand_rail(strand_rail) for ladder in ladders: ladder.finished() # this ensures ladder has one or two strands, antiparallel in standard bond directions, aligned with axis rungs # (it reverses chains as needed, for rung alignment and strand bond direction) # @@@ (does it rotate ring chains?) return ladders, singlestrands # from make_new_ladders # == def merge_ladders(new_ladders): """ Merge end-to-end-connected ladders (new/new or new/old) into larger ones, when that doesn't make the resulting ladders too long. @return: list of merged (or new and unable to be merged) ladders @note: each returned ladder is either entirely new (perhaps merged or perhaps one of the ones the caller passed in), or the result of merging (one or more) new and (presumably just one) old ladders. """ # Initial implem - might be too slow (quadratic in atomcount) if # repeated merges from small to large chain sizes occur. # Note, these ladders' rails might be real chunks (merge is slower) # or some sort of real or virtual atom chains (merge is faster). # (As of 080114 I think they are real atom chains, not yet associated # with chunks.) res = [] # collects ladders that can't be merged while new_ladders: # has ladders untested for can_merge # note about invalid ladders during these loops: # in the first iteration of this outer loop, the ladders in # new_ladders are newly made, all valid (though they might be invalid # by the time the inner loop reaches them, if they got merged into a # ladder encountered earlier in that loop over new_ladders). In all # other iterations they are newly merged ladders, but they might # *already* be invalid if they got merged again by a later ladder # in the inner loop that merged them. (Or they might become invalid # during the loop, just as in the first iteration.) # In all cases it means nothing if they are invalid now, # and they should just be skipped if they are invalid when encountered. # [comment and behavior revised to fix bug from incorrect assertion, # bruce 080222; earlier partial version of skip, bruce 080122] next = [] # new_ladders for next iteration for ladder in new_ladders: if not ladder.valid: # just skip it (not an error, as explained above) pass else: can_merge_info = ladder.can_merge() # (at either end) if can_merge_info: merged_ladder = ladder.do_merge(can_merge_info) # note: this invals the old ladders, one of which is # ladder; the other might be later in new_ladders, or # already appended to next earlier during this loop, # or not known to this function. # Q: what if the rails (also merged here) are already # contained in wholechains? # A: they're not yet contained in those -- we find those # later from the merged ladders. assert not ladder.valid assert merged_ladder.valid next.append(merged_ladder) else: res.append(ladder) new_ladders = next for ladder in res: assert ladder.valid # required by caller, trivially true here return res def split_ladders(ladders): # STUB but should cause no harm @@@@ res = [] for ladder in ladders: # REVIEW: higher threshhold for split than merge, for "hysteresis"?? maybe not needed... if len(ladder) > MAX_LADDER_LENGTH: print "NIM: split long ladder %r" % ladder res0 = [ladder] # the pieces # (real split function should inval original, then validate pieces) res.extend(res0) else: res.append(ladder) return res def merge_and_split_ladders(ladders, debug_msg = ""): """ See docstrings of merge_ladders and split_ladders (which this does in succession). @param ladders: list of 0 or more new DnaLadders @param debug_msg: string for debug prints """ len1 = len(ladders) # only for debug prints ladders = merge_ladders(ladders) len2 = len(ladders) ladders = split_ladders(ladders) len3 = len(ladders) assert len2 == len3 ### REMOVE WHEN WORKS (says split is a stub) @@@@ if debug_flags.DEBUG_DNA_UPDATER: if debug_flags.DEBUG_DNA_UPDATER_VERBOSE or len2 != len1 or len3 != len1: # note: _DEBUG_FINISH_AND_MERGE(sp?) is in another file if debug_msg: debug_msg = " (%s)" % debug_msg print "dna updater: merge_and_split_ladders%s: %d ladders, merged to %d, split to %d" % \ (debug_msg, len1, len2, len3) return ladders # end
NanoCAD-master
cad/src/dna/updater/dna_updater_ladders.py
# Copyright 2008 Nanorex, Inc. See LICENSE file for details. """ fix_after_readmmp.py - helpers to fix dna-related structure after readmmp @author: Bruce @version: $Id$ @copyright: 2008 Nanorex, Inc. See LICENSE file for details. """ from dna.updater.dna_updater_prefs import pref_fix_after_readmmp_before_updaters from dna.updater.dna_updater_prefs import pref_fix_after_readmmp_after_updaters def will_special_updates_after_readmmp_do_anything(assy): """ Permit callers to optimize for the likely usual case of these debug_prefs both being off. """ del assy if pref_fix_after_readmmp_before_updaters() or \ pref_fix_after_readmmp_after_updaters(): return True return False def fix_after_readmmp_before_updaters(assy): if pref_fix_after_readmmp_before_updaters(): ## print "\ndoing fix_after_readmmp_before_updaters" # note: this happens before updaters like dna updater and bond updater, # but not before update_parts has fixed the .part structure of assy. for part in assy.all_parts(): part.enforce_permitted_members_in_groups( pre_updaters = True ) pass return def fix_after_readmmp_after_updaters(assy): if pref_fix_after_readmmp_after_updaters(): ## print "\ndoing fix_after_readmmp_after_updaters" for part in assy.all_parts(): part.enforce_permitted_members_in_groups( pre_updaters = False ) # notice the different options than in before_updaters version pass return # end
NanoCAD-master
cad/src/dna/updater/fix_after_readmmp.py
# Copyright 2008 Nanorex, Inc. See LICENSE file for details. """ fix_bond_directions.py - dna updater helper functions @author: Bruce @version: $Id$ @copyright: 2008 Nanorex, Inc. See LICENSE file for details. """ from model.elements import Singlet import foundation.env as env from utilities.Log import orangemsg from platform_dependent.PlatformDependent import fix_plurals from dna.updater.dna_updater_prefs import pref_print_bond_direction_errors from model.elements import Pl5 # == _DEBUG_PRINT_BOND_DIRECTION_ERRORS = False # set later to match a debug_pref try: _global_direct_error_atoms except: _global_direct_error_atoms = {} # maps atom.key -> atom, for all atoms that have direct dna updater errors # (as opposed to error codes propogated from other atoms in their basepair) # at the end of a dna updater run. Coming into a run, we'll ignore this info # for any changed_atom but believe it for all other atoms. We'll then update it, # and use it to update all atom's error codes (direct or propogated). # # note: we optimize for this being empty, since that should be the usual case. try: _all_error_atoms_after_propogation except: _all_error_atoms_after_propogation = {} # == def fix_local_bond_directions( changed_atoms): """ Fix local directional bond issues, namely: - directional bond chain branches (illegal) - missing bond directions (when fixable locally -- most are not) - inconsistent bond directions But for most of these, "fix" just means "mark them as an error". We will only change bond direction on open bonds; we'll never break any bonds or change bond direction on any real bonds (unless it's illegal given the bonded atomtypes). """ global _DEBUG_PRINT_BOND_DIRECTION_ERRORS _DEBUG_PRINT_BOND_DIRECTION_ERRORS = pref_print_bond_direction_errors() new_error_atoms = {} # note: only used for its length in a warning message # Find new errors (or the lack of them) on changed_atoms, # updating _global_direct_error_atoms to be current for all atoms. # Then propogate errors within basepairs, and make sure all atoms # have correct error data, and call changeapp as needed when we # change this. This scheme is chosen mainly to optimize the case # when the number of atoms with errors is small or zero. for atom in changed_atoms.itervalues(): # look for new errors error_info = None # might be changed below if atom.element is Singlet: pass # handle these as part of their base atom elif not atom.element.bonds_can_be_directional: # note: we needn't worry here about nondirectional bonds # with a direction set. Those can't hurt us except on directional # elements, dealt with below. @@@DOIT pass # optimization elif atom.killed(): pass # not sure this ever happens else: # note: at this stage we might have Ss or Pl; # valence has not been checked (in code as of 080123) # catch specially labelled AssertionErrors from # _fix_atom_or_return_error_info; # turn them into errors, history summaries # (needed here? or done more generally for them all, elsewhere?), # and console prints try: error_info = _fix_atom_or_return_error_info(atom) except AssertionError, e: e_string = "%s" % (e,) if not e_string.startswith("__ERROR:"): raise # it's a specially labelled exception meant to become # an updater error string print "%s: %r (neighbors: %r)" % (e_string, atom, atom.neighbors()) # TODO: history summary needed? better error_data string? prefix = "" # STUB error_data = prefix + e_string[len("__ERROR:"):].strip() error_info = _ATOM_HAS_ERROR, error_data pass if error_info: error_type, error_data = error_info assert error_type == _ATOM_HAS_ERROR assert error_data and type(error_data) == type("") if _DEBUG_PRINT_BOND_DIRECTION_ERRORS: print "bond direction error for %r: %s" % (atom, error_data) print _atom_set_dna_updater_error( atom, error_data) atom.molecule.changeapp(0) #k probably not needed new_error_atoms[atom.key] = atom _global_direct_error_atoms[atom.key] = atom else: _atom_clear_dna_updater_error( atom) _global_direct_error_atoms.pop(atom.key, None) continue if new_error_atoms: #e if we print more below, this might be only interesting for debugging, not sure # maybe: move later since we will be expanding this set; or report number of base pairs msg = "Warning: dna updater noticed %d pseudoatom(s) with bond direction errors" % len(new_error_atoms) msg = fix_plurals(msg) env.history.orangemsg(msg) global _all_error_atoms_after_propogation old_all_error_atoms_after_propogation = _all_error_atoms_after_propogation new_all_error_atoms_after_propogation = {} for atom in _global_direct_error_atoms.itervalues(): for atom2 in _same_base_pair_atoms(atom): new_all_error_atoms_after_propogation[atom2.key] = atom2 _all_error_atoms_after_propogation = new_all_error_atoms_after_propogation for atom in old_all_error_atoms_after_propogation.itervalues(): if atom.key not in new_all_error_atoms_after_propogation: if atom._dna_updater__error: # should always be true del atom._dna_updater__error if not atom.killed(): atom.molecule.changeapp(0) #k needed? for atom in new_all_error_atoms_after_propogation.itervalues(): if atom.key not in _global_direct_error_atoms: _atom_set_dna_updater_error( atom, PROPOGATED_DNA_UPDATER_ERROR) # note: the propogated error is deterministic, # since only the fact of error is propogated, # not the error string itself, which could differ # on different sources of propogated error. atom.molecule.changeapp(0) return # from fix_local_bond_directions def _same_base_pair_atoms(atom): """ Defining a base pair as whatever portion of Ss-Ax-Ss exists, return a list of atoms in the same base pair as atom. At minimum this is atom itself. Pl atoms are not considered to be part of the base pair. (This is used only for propogating detected dna updater errors; for that use it's important to propogate across rung bonds, so that strand and axis chains cover the same set of base pairs.) @note: since we are used to report errors, we have to work even if there are arbitrary errors, including errors in how many atoms of what elements are bonded to a given atom. But, we don't want to consider too many atoms to be part of one base pair... or do we? For now, we will propogate errors across any number of "rung bonds", regardless of how many atoms this reaches. """ # POSSIBLE OPTIM: in current calling code, atom itself needs to be part of # our return value. This could be revised, permitting this to return # a constant value of () in some cases. # implem note: for speed, we don't use the utility function transclose, # and we use special case optimizations based on the kind of atoms and # bonds we are looking for. [implem rewritten, bruce 080304] look_at_these = {atom.key : atom} # atoms we still need to explore found = {} # atoms found in prior steps have_role = atom.element.role # role of all atoms in look_at_these # (where strand implies not Pl, in this loop but not in general; # we take no steps to exclude it explicitly, since it will not # be included in correct structures due to only crossing # strand-axis bonds) # look for neighbor atoms of alternating roles while look_at_these: found.update(look_at_these) next = {} next_role = (have_role == 'axis' and 'strand' or 'axis') for atom1 in look_at_these.itervalues(): assert have_role == atom1.element.role # remove when works for atom2 in atom1.neighbors(): # maybe add atom2 to next, if suitable and not in found if atom2.element.role == next_role and not found.has_key(atom2.key): next[atom2.key] = atom2 continue continue look_at_these = next have_role = next_role continue return found.values() ## if atom.element.role == 'strand': ## axis_atom = atom.axis_neighbor() # might be None (for Pl or single-stranded) ## if not axis_atom: ## return (atom,) ## elif atom.element.role == 'axis': ## axis_atom = atom ## else: ## return (atom,) ## return [axis_atom] + axis_atom.strand_neighbors() # == # error type codes (may be revised) _ATOM_HAS_ERROR = 1 def _fix_atom_or_return_error_info(atom): """ [private helper for fix_local_bond_directions] note: at this stage we might have Ss or Pl; valence has not been checked (in code as of 080123) If atom looks fine (re directional bonds), do nothing and return None. Otherwise try to fix it and/or return advice to caller about it, as a tuple of (error type code, error data). @param atom: a real atom which permits directional bonds. """ # note: the following code is related to these Atom methods # (but can't be fully handled by them): # - Atom.bond_directions_are_set_and_consistent # (not sufficient to say it's ok -- misses new real directional bonds # w/ no direction set) # - Atom.directional_bond_chain_status (only looks at bonds being # directional or not, not what directions are set) # TODO: once we're sure this is right, speed up the usual case # (no changes needed) by making a separate loop just to find # atoms that require any changes. Also consider coding that in C/Pyrex. @@@ # But don't optimize it that way right now, since the details of what # the fast initial check should do might change. # count kinds of directional bonds on atom num_plus_real = 0 num_minus_real = 0 num_unset_real = 0 num_plus_open = 0 num_minus_open = 0 num_unset_open = 0 neighbors = [] for bond in atom.bonds: direction = bond.bond_direction_from(atom) neighbor = bond.other(atom) # we'll use this to inline & optimize both # bond.is_directional and bond.is_open_bond, # since we know enough about atom that only neighbor # can affect their values. neighbors += [neighbor] is_directional = neighbor.element.bonds_can_be_directional is_open_bond = (neighbor.element is Singlet) if direction == 1: if not is_directional: assert not is_open_bond _clear_illegal_direction(bond) elif is_open_bond: num_plus_open += 1 else: num_plus_real += 1 elif direction == -1: if not is_directional: assert not is_open_bond _clear_illegal_direction(bond) elif is_open_bond: num_minus_open += 1 else: num_minus_real += 1 else: if is_open_bond: num_unset_open += 1 elif is_directional: num_unset_real += 1 pass continue # next bond of atom # first check for a legal set of neighbors [new feature, bruce 080304]; # for simpler code, we'll report errors as exceptions with unvarying text # and a standard prefix recognized by caller, and let caller convert those # to error strings (and also print them with name of specific atom). #### @@@@@ DOIT # # (note, someday this might be done more generally by an earlier # updater stage) # (note, this is not complete, just enough to catch some errors # noticed in test files on 080304) if atom.element is Pl5: # permit only strand atoms (not Pl) and bondpoints as neighbors, valence 2 assert len(atom.bonds) == 2, "__ERROR: Pl valence must be 2" for neighbor in neighbors: element = neighbor.element assert element is Singlet or \ (element.role == 'strand' and not element is Pl5), \ "__ERROR: Pl has non-permitted neighbor element %s" % element.symbol elif atom.element.role == 'strand': # other strand atoms (Ss or equivalent) must have 2 bonds to other strand atoms (Pl or not) or bondpoints, # and 1 bond to an axis atom or a bondpoint or (doesn't yet happen) 1 or 2 unpaired base atoms. num_bondpoint = 0 num_strand = 0 num_axis = 0 num_unpaired_base = 0 for neighbor in neighbors: element = neighbor.element role = element.role if element is Singlet: num_bondpoint += 1 elif role == 'strand': num_strand += 1 elif role == 'axis': num_axis += 1 elif role == 'unpaired-base': num_unpaired_base += 1 else: assert 0, \ "__ERROR: strand sugar has non-permitted " \ "neighbor element %s" % element.symbol continue assert num_strand <= 2, \ "__ERROR: strand sugar has more than 2 strand bonds" assert num_axis <= 1, \ "__ERROR: strand sugar has more than one axis bond" assert num_unpaired_base <= 2, \ "__ERROR: strand sugar has more than two unpaired base neighbors" assert num_bondpoint + num_strand + num_axis + \ (not not num_unpaired_base) == 3, \ "__ERROR: strand sugar has wrong number of bonds" else: # should never happen, so no valence or neighbor checks are # implemented here, but print a nim warning print "BUG: fix_bond_directions got %r of unexpected element %s" % (atom, element.symbol) msg = "BUG: fix_bond_directions got [N] atom(s) of unexpected element %s" % element.symbol summary_format = redmsg( msg ) env.history.deferred_summary_message(summary_format) pass # now look at actual bond directions. # # what to look for, for all to be already ok: ### REVIEW -- correct and complete? I think so, but re-check it... # (might optim the above to only check for that first -- usual case) # considering directional bonds (dirbonds) only: # - real directional bonds must number <= 2, # with 0 or 1 of each nonzero direction, none with direction unset # - open directional bonds must bring those totals to exactly one # of each nonzero direction. # those conds are equivalent to: # - exactly one dirbond of each nonzero direction; # - no real directional bonds are unset (in direction). num_plus = num_plus_real + num_plus_open num_minus = num_minus_real + num_minus_open # note: these variables might be modified below # but the just-assigned relations are kept correct. if not (num_unset_real or num_plus != 1 or num_minus != 1): # nothing wrong (note: doesn't check valence) return None # We need to fix something about this atom (assumed Ss or Pl), # or record an error. Detect the most serious errors first so they # will be the ones recorded. if _DEBUG_PRINT_BOND_DIRECTION_ERRORS: # (too bad we can't print the return value easily) # print info that tells me what cases need handling ASAP, @@@ # vs cases that can wait print "\n*** dna updater: fix_local_bond_directions ought to fix %r but is NIM" % (atom,) print " data about that atom:", \ num_plus_real, num_minus_real, num_unset_real, \ num_plus_open, num_minus_open, num_unset_open # that form is for sorting output text lines; # the next form is for readability (make it once only?): print " num_plus_real =", num_plus_real print " num_minus_real =", num_minus_real print " num_unset_real =", num_unset_real print " num_plus_open =", num_plus_open print " num_minus_open =", num_minus_open print " num_unset_open =", num_unset_open print if num_plus_real + num_minus_real + num_unset_real > 2: # Too many real directional bonds -- no way to fully fix # without breaking one, so let the user choose which one. return _ATOM_HAS_ERROR, "too many real directional bonds" if num_plus_real > 1 or num_minus_real > 1: # contradiction in real bond directions -- we would need to damage # something to fix it (break or unset (direction of) real bonds). return _ATOM_HAS_ERROR, "inconsistent bond directions" if num_unset_real: # Just report this error rather than spending development time # trying to fix it. Both ends of an unset real bond will get marked # as errors (no guarantee it's with *this* error, but that's ok), # so there's no danger of this bond making it into a chain later # (and thus causing trouble) from either end-atom. No need to mark # this error on the bond itself, since it's easy to detect directly # when drawing the bond. # @@@ DOIT return _ATOM_HAS_ERROR, "unset real bond direction" # Note: some of the following code is general enough to handle # num_unset_real > 0, so it is left in some expressions. def _dir(bond): # for assertions (could be done as a lambda) return bond.bond_direction_from(atom) assert num_plus == _number_of_bonds_with_direction(atom, +1), "%r" % (num_plus, atom, atom.bonds, map( _dir, atom.bonds)) assert num_minus == _number_of_bonds_with_direction(atom, -1), "%r" % (num_minus, atom, atom.bonds, map( _dir, atom.bonds)) if num_plus > 1 or num_minus > 1 or num_plus + num_minus + num_unset_real > 2: # too much is set, or *would be* if all real bonds were set # (as they should be) -- can we unset some open bonds to fix that? # (Note: due to earlier checks (ignoring the check on num_unset_real), # we know that num_plus_real and num_minus_real are 0 or 1, # and num_unset_real is 0 or 1 or 2.) # Any open bond that duplicates a real bond direction # (or another open bond direction) should be unset. # But if num_unset_real, we won't know which open bond direction # is bad until we set the real bond direction. We marked that # case as an error above, but if that ever changes, we would not # fix it here, but leave it for later code to fix when the real # bond directions were chosen. (As it is, only the user can choose # them, so the "later code" is the next dna updater pass after # they do that.) while num_plus_open and num_plus > 1: _unset_some_open_bond_direction(atom, +1) num_plus_open -= 1 num_plus -= 1 assert num_plus == _number_of_bonds_with_direction(atom, +1), "%r" % (num_plus, atom, atom.bonds, map( _dir, atom.bonds)) assert num_minus == _number_of_bonds_with_direction(atom, -1), "%r" % (num_minus, atom, atom.bonds, map( _dir, atom.bonds)) while num_minus_open and num_minus > 1: _unset_some_open_bond_direction(atom, -1) num_minus_open -= 1 num_minus -= 1 assert num_plus == _number_of_bonds_with_direction(atom, +1), "%r" % (num_plus, atom, atom.bonds, map( _dir, atom.bonds)) assert num_minus == _number_of_bonds_with_direction(atom, -1), "%r" % (num_minus, atom, atom.bonds, map( _dir, atom.bonds)) if not (num_unset_real or num_plus != 1 or num_minus != 1): # if not still bad, then declare atom as ok return None # (note: if we someday look for chains of unset real bonds to fix, # then we might want to do the above in an initial pass, # or in a subroutine called on any atom we hit then.) # at this point, real bonds are not excessive but might be deficient; # open bonds might make the total (of one nonzero direction value) # excessive but will be fixed at the end. # What remains is to add directions to open bonds if this would # fully fix things. assert num_plus <= 1 assert num_minus <= 1, \ "num_minus = %r, num_minus_open = %r, num_minus_real = %r, atom = %r, bonds = %r, dirs = %r" % \ (num_minus, num_minus_open, num_minus_real, atom, atom.bonds, map( _dir, atom.bonds) ) if (1 - num_plus) + (1 - num_minus) <= num_unset_open: # fully fixable case (given that we're willing to pick an open bond arbitrarily) while num_plus < 1: # note: runs at most once, but 'while' is logically most correct _set_some_open_bond_direction(atom, +1) num_plus += 1 num_plus_open += 1 num_unset_open -= 1 while num_minus < 1: # note: runs at most once _set_some_open_bond_direction(atom, -1) num_minus += 1 num_minus_open += 1 num_unset_open -= 1 assert not (num_unset_real or num_plus != 1 or num_minus != 1) # not still bad, so declare atom as ok return None # otherwise we can't fully fix things. assert (num_unset_real or num_plus != 1 or num_minus != 1) res = _ATOM_HAS_ERROR, "bond direction error" # not sure how best to describe it return res # from _fix_atom_or_return_error_info # == def _set_some_open_bond_direction(atom, direction): """ Find a directional open bond on atom with no bond direction set (error if you can't), and set its bond direction to the specified one. """ assert direction in (-1, 1) didit = False for bond in atom.bonds: if bond.is_open_bond() and \ bond.is_directional() and \ not bond.bond_direction_from(atom): bond.set_bond_direction_from(atom, direction) didit = True break continue assert didit summary_format = "Warning: dna updater set bond direction on [N] open bond(s)" env.history.deferred_summary_message( orangemsg(summary_format) ) # todo: refactor so orangemsg is replaced with a warning option # review: should we say in how many cases we picked one of several open bonds arbitrarily? return def _unset_some_open_bond_direction(atom, direction): """ Find an open bond on atom with the specified bond direction set (error if you can't), and unset its bond direction. """ assert direction in (-1, 1) didit = False for bond in atom.bonds: if bond.is_open_bond() and \ bond.bond_direction_from(atom) == direction: # bugfix 080201, care which direction is set, not just that some dir was set bond.clear_bond_direction() didit = True break continue assert didit summary_format = "Warning: dna updater unset bond direction on [N] open bond(s)" env.history.deferred_summary_message( orangemsg(summary_format) ) return def _number_of_bonds_with_direction(atom, direction): # for asserts count = 0 for bond in atom.bonds: if bond.bond_direction_from(atom) == direction: count += 1 return count def _clear_illegal_direction(bond): """ [private helper for _fix_atom_or_return_error_info] bond has a direction but is not directional (since one of its atoms does not permit directional bonds, e.g. it might be an Ss-Ax bond). Report and immediately fix this error. @type bond: Bond """ bond.clear_bond_direction() summary_format = "Warning: dna updater cleared [N] bond direction(s) on pseudoelements that don't permit one" env.history.deferred_summary_message( orangemsg(summary_format) ) return # == # the following will probably be moved into a separate file in dna_model, # both on general principles (it might become a file for an Atom subclass, # for a common superclass of StrandAtom and AxisAtom), # or if an import cycle exists from chem.py import of these. # [bruce 080204] PROPOGATED_DNA_UPDATER_ERROR = 'error elsewhere in basepair' def _atom_set_dna_updater_error(atom, error_string): # turn into method on an Atom subclass """ [private helper, will turn into friend method] Low-level setter for atom._dna_updater__error. Caller is responsible for atom.molecule.changeapp(0) if this is needed. (It is needed due to effect on atom color, unless caller knows it is done by other code.) """ atom._dna_updater__error = error_string if not error_string: del atom._dna_updater__error # optimization return def _atom_clear_dna_updater_error( atom): """ [private helper, will turn into friend method] Low-level clear for atom._dna_updater__error. Caller is responsible for atom.molecule.changeapp(0) if this is needed. (It is needed due to effect on atom color, unless caller knows it is done by other code.) """ if atom._dna_updater__error: del atom._dna_updater__error assert not atom._dna_updater__error # verify class default value is ok # otherwise it's ok to assume it's not set (doesn't matter much anyway) return def _f_detailed_dna_updater_error_string( atom): """ [friend function for use by Atom.dna_updater_error_string, which might be moved onto the same Atom subclass as _atom_set_dna_updater_error should be moved to] Assuming atom._dna_updater__error == PROPOGATED_DNA_UPDATER_ERROR, return a more complete error string for atom (perhaps containing internal newlines) which lists the errors directly assigned to other atoms in the same basepair. """ ### REVIEW: should we be documented to work even before propogation # actually occurs? assert atom._dna_updater__error == PROPOGATED_DNA_UPDATER_ERROR # find the sources of direct error direct_errors = {} # maps atom2 -> value of _dna_updater__error for atom2 in _same_base_pair_atoms(atom): error = atom2._dna_updater__error assert error # otherwise propogation did not finish or had a bug if error != PROPOGATED_DNA_UPDATER_ERROR: direct_errors[atom2] = error assert atom not in direct_errors assert direct_errors # otherwise where did the error come from? # (could happen if unsetting obs error strings has a bug) error_reports = [ "%s: %s" % (str(atom2), error) for atom2, error in direct_errors.items() ] if len(error_reports) <= 1: header = "error elsewhere in basepair:" else: error_reports.sort() # todo - should probably use atom key numbers as sort order header = "errors elsewhere in basepair:" error_reports.insert(0, header) res = "\n".join( error_reports) # todo: indicate visual direction? highlight error-source atoms? return res # end
NanoCAD-master
cad/src/dna/updater/fix_bond_directions.py
# Copyright 2007-2008 Nanorex, Inc. See LICENSE file for details. """ delete_bare_atoms.py - delete atoms lacking required neighbors @author: Bruce @version: $Id$ @copyright: 2007-2008 Nanorex, Inc. See LICENSE file for details. """ from dna.updater.dna_updater_prefs import pref_fix_bare_PAM3_atoms from dna.updater.dna_updater_prefs import pref_fix_bare_PAM5_atoms from dna.model.PAM_atom_rules import PAM_atoms_allowed_in_same_ladder from model.elements import Pl5 from utilities.constants import MODEL_PAM3, MODEL_PAM5 import foundation.env as env from utilities.Log import orangemsg # == def delete_bare_atoms( changed_atoms): # rename; also make not delete, just error (### need to review error propogation system) """ Delete excessively-bare atoms (defined as axis atoms without strand atoms, or any other PAM atoms that are not allowed to exist with as few neighbors as they have -- note that the rules for strand atoms are in flux as of 080117 since the representation of single-stranded DNA is as well). [must tolerate killed atoms; can kill more atoms and break bonds; can record more changes to neighbors of deleted atoms] """ # Q. Which changes recorded by our side effects are needed in subsequent # dna updater steps? # A. The changed neighbor atoms are needed, in case they're the only # indicator of a change to the chain they're on (especially if the killed # atom was in a different dna ladder). But their classes needn't be changed, # and their deletion can't cause any more atoms to become bare (due to # the current meaning of bare), so no earlier updater steps need to be # repeated. # Note: if these debug prefs are not both True, errors might occur in the # dna updater. The goal is for these errors to be harmless (just debug # prints). As of 071205 the defaults are True, False, respectively. # TODO: revise following code to debug-print when these prefs make it # refrain from killing a bare atom (giving a count, per PAM model). fix_PAM3 = pref_fix_bare_PAM3_atoms() fix_PAM5 = pref_fix_bare_PAM5_atoms() delete_these_atoms = [] # change to mark them as errors fix_these_bonds = {} # id(bond) -> bond for atom in changed_atoms.itervalues(): pam = atom.element.pam if pam: # optimization if (pam == MODEL_PAM3 and fix_PAM3) or \ (pam == MODEL_PAM5 and fix_PAM5): if not atom.killed(): if atom_is_bare(atom): delete_these_atoms.append(atom) else: # Do something about rung bonds between mismatched PAM atoms # (in pam model or pam3+5 properties) # [bruce 080405 new feature, for PAM3+5 safety] # Note: if this kills bonds, we'd need to do that first, # then recheck atom_is_bare (or always check it later). # But it doesn't. # #update 080407: maybe this is not necessary: # - we could permit these mismatches until DnaLadders # are formed, then fix them much more easily; # - or we could even permit them then # (each rail would be uniform within itself), # with a little extra complexity in PAM conversion, # but it might even be useful to display "one strand # in PAM5", for example. # So for now, I won't finish this code here, though I'll # leave it in for long enough to see if it prints # anything; then it should be removed, in case it's # slow. ##### @@@@@ for bond in atom.bonds: if bond.is_rung_bond(): if not PAM_atoms_allowed_in_same_ladder(bond.atom1, bond.atom2): fix_these_bonds[id(bond)] = bond for bond in fix_these_bonds.values(): # REVIEW: can one of its atoms be in delete_these_atoms? # (probably doesn't matter even if it is) print "*** need to fix this bad rung bond (nim, so bugs will ensue): %r" % bond ##### # pam model mismatch: mark them as errors, so not in any chains or ladders # pam option mismatch: reset options to default on all chunks connected by rung bonds (or could mark as errors) # other (if possible) (eg display styles, if that matters) -- # those differences would be ok here, only matters along axis # (we'll make the func distinguish this if it ever looks at those) # # no need to be fast, this only happens for rare errors a1, a2 = bond.atom1, bond.atom2 if a1.element.pam != a2.element.pam: # since it's a rung bond, we know the pams are both set print " nim: mark as errors", a1, a2 ## NIM here, look up how other code does it before propogation elif a1.molecule.display_as_pam != a2.molecule.display_as_pam or \ a1.molecule.save_as_pam != a2.molecule.save_as_pam: # transclose to find chunks connected by rung bonds, put in a dict, reset pam props below print " nim: reset pam props starting at", a1, a2 continue for atom in delete_these_atoms: #bruce 080515: always emit a deferred_summary_message, # since it can seem like a bug otherwise # (review this, if it happens routinely) summary_format = \ "Warning: dna updater deleted [N] \"bare\" %s pseudoatom(s)" % \ ( atom.element.symbol, ) env.history.deferred_summary_message( orangemsg(summary_format) ) atom.kill() return def atom_is_bare(atom): # fyi: only used in this file as of 080312; ### REVIEW [080320]: better to mark as errors, not delete? """ Is atom an axis atom with no axis-strand bonds, or (IF this is not allowed -- as of 080117 it *is* allowed) a strand base atom with no strand-axis bonds, or any other PAM atom with illegally-few neighbor atoms of the types it needs? (Note that a strand non-base atom, like Pl, can never be considered bare by this code.) """ if atom.element.role == 'axis': strand_neighbors = filter(lambda other: other.element.role == 'strand', atom.neighbors()) return not strand_neighbors elif atom.element.role == 'strand' and not atom.element is Pl5: return False # bruce 080117 revision, might be temporary -- # but more likely, we'll replace it with some "bigger fix" # like adding Ub (or we might just do that manually later # and allow this with no change in old files) ## axis_neighbors = filter(lambda other: other.element.role == 'axis', atom.neighbors()) ## return not axis_neighbors elif atom.element.role == 'unpaired-base': # guess, bruce 080117 strand_neighbors = filter(lambda other: other.element.role == 'strand', atom.neighbors()) return not strand_neighbors else: return False pass # end
NanoCAD-master
cad/src/dna/updater/delete_bare_atoms.py
# Copyright 2007-2008 Nanorex, Inc. See LICENSE file for details. """ dna_updater_init.py -- @author: Bruce @version: $Id$ @copyright: 2007-2008 Nanorex, Inc. See LICENSE file for details. """ from dna.updater.dna_updater_globals import initialize_globals from dna.updater.dna_updater_prefs import initialize_prefs from dna.updater.dna_updater_commands import initialize_commands # == def initialize(): """ Meant to be called only from master_model_updater.py. Do whatever one-time initialization is needed before our other public functions should be called. [Also called after this module is reloaded.] """ initialize_globals() initialize_prefs() initialize_commands() return # end
NanoCAD-master
cad/src/dna/updater/dna_updater_init.py
# Copyright 2008 Nanorex, Inc. See LICENSE file for details. """ convert_from_PAM5.py - detect PAM5 atoms and convert (some of) them to PAM3+5 WARNING: THIS MODULE IS PROBABLY OBSOLETE, and is no longer called as of 080408. Newer code does this in later stages of the dna updater after ladders are made. However, it might be partly revived (see comment near the commented-out call) and some code within it will be useful in those later stages, so don't remove it yet. @author: Bruce (but model and conversion function is by Eric D) @version: $Id$ @copyright: 2008 Nanorex, Inc. See LICENSE file for details. """ from model.elements import Pl5, Singlet from utilities import debug_flags from utilities.constants import MODEL_PAM5 from dna.updater.dna_updater_prefs import pref_dna_updater_convert_to_PAM3plus5 import foundation.env as env from utilities.Log import orangemsg, redmsg, graymsg from model.bond_constants import find_bond # == def convert_from_PAM5( changed_atoms): # might be misnamed, if it turns out it does only some of the conversion ### """ scan for PAM5 elements that should be converted, and convert them as well as can be done per-atom. @note: this replaces Pl5 with direct bonds, and may do more (undecided), but some conversion must be done later after ladders are constructed. """ convert = pref_dna_updater_convert_to_PAM3plus5() # note: in future this is likely to be a finer-grained setting if not convert: return pam5_atoms = [] #k needed? not yet used, might not be useful until we have ladders... ### for atom in changed_atoms.itervalues(): chunk = atom.molecule if chunk is None or atom.key not in chunk.atoms: continue # don't touch nonlive atoms if chunk.display_as_pam == MODEL_PAM5: continue # this atom doesn't want to be converted if atom.element is Pl5: _convert_Pl5(atom) # and save others to convert later?? see _save_Pl_info ... else: pam = atom.element.pam if pam == MODEL_PAM5: pam5_atoms += [atom] # note: slow and not yet used continue return # from convert_from_PAM5 # == def _convert_Pl5(atom): """ If atom's neighbors have the necessary structure (Ss-Pl-Ss or X-Pl-Ss, with fully set and consistent bond_directions), save atom's coordinates on its Ss neighbors, arrange for them to postprocess that info later, and then kill atom, replacing its bonds with a direct bond between its neighbors (same bond_direction). Summarize results (ok or error) to history. """ ### NOTE: the code starting from here has been copied and modified #### into a new function in pam3plus5_ops.py by bruce 080408. assert atom.element is Pl5 # remove when works # could also assert no dna updater error # Note: we optimize for the common case (nothing wrong, conversion happens) bonds = atom.bonds # change these during the loop bad = False saw_plus = saw_minus = False num_bondpoints = 0 neighbors = [] direction = None # KLUGE: set this during loop, but use it afterwards too for bond in bonds: other = bond.other(atom) neighbors += [other] element = other.element direction = bond.bond_direction_from(atom) if direction == 1: saw_plus = True elif direction == -1: saw_minus = True if element is Singlet: num_bondpoints += 1 elif element.symbol in ('Ss3', 'Ss5'): pass else: bad = True continue if not (len(bonds) == 2 and saw_minus and saw_plus and num_bondpoints < 2): bad = True if bad: summary_format = \ "Warning: dna updater left [N] Pl5 pseudoatom(s) unconverted" env.history.deferred_summary_message( orangemsg(summary_format) ) return del saw_plus, saw_minus, num_bondpoints, bad # Now we know it is either Ss-Pl-Ss or X-Pl-Ss, # with fully set and consistent bond_directions. # But we'd better make sure the neighbors are not already bonded! # # (This is weird enough to get its own summary message, which is red. # Mild bug: we're not also counting it in the above message.) # # (Note: there is potentially slow debug code in rebond which is # redundant with this. It does a few other things too that we don't # need, so if it shows up in a profile, just write a custom version # for this use. ### OPTIM) n0, n1 = neighbors del neighbors b0, b1 = bonds del bonds # it might be mutable and we're changing it below, # so be sure not to use it again if find_bond(n0, n1): summary_format = \ "Error: dna updater noticed [N] Pl5 pseudoatom(s) whose neighbors are directly bonded" env.history.deferred_summary_message( redmsg(summary_format) ) return # Pull out the Pl5 and directly bond its neighbors, # reusing one of the bonds for efficiency. # (This doesn't preserve its bond_direction, so set that again.) # Kluge: the following code only works for n1 not a bondpoint # (since bond.bust on an open bond kills the bondpoint), # and fixing that would require inlining and modifying a # few Atom methods, # so to avoid this case, reverse everything if needed. if n1.element is Singlet: direction = - direction n0, n1 = n1, n0 b0, b1 = b1, b0 # Note: bonds.reverse() might modify atom.bonds itself, # so we shouldn't do it even if we didn't del bonds above. # (Even though no known harm comes from changing an atom's # order of its bonds. It's not reviewed as a problematic # change for an undo snapshot, though. Which is moot here # since we're about to remove them all. But it still seems # safer not to do it.) pass # save atom_posn before modifying atom (not known to be needed), # and set atom.atomtype to avoid bugs in reguess_atomtype during atom.kill # (need to do that when it still has the right number of bonds, I think) atom_posn = atom.posn() atom.atomtype # side effect: set atomtype old_nbonds_neighbor1 = len(n1.bonds) # for assert old_nbonds_neighbor0 = len(n0.bonds) # for assert b1.bust(make_bondpoints = False) # n1 is now missing one bond; so is atom b0.rebond(atom, n1) # now n1 has enough bonds again; atom is missing both bonds assert len(atom.bonds) == 0, "Pl %r should have no bonds but has %r" % (atom, atom.bonds) assert not atom.killed() assert len(n1.bonds) == old_nbonds_neighbor1 assert len(n0.bonds) == old_nbonds_neighbor0 # KLUGE: we know direction is still set to the direction of b1 from atom # (since b1 was processed last by the for loop above), # which is the overall direction from n0 thru b0 to atom thru b1 to n1, # so use this to optimize recording the Pl info below. # (Of course we really ought to just rewrite this whole conversion in Pyrex.) ## assert direction == b1.bond_direction_from(atom) # too slow to enable by default # not needed, rebond preserves it: ## b0.set_bond_direction_from(n0, direction) ## assert b0.bond_direction_from(n0) == direction # too slow to enable by default # now save the info we'll need later (this uses direction left over from for-loop) if n0.element is not Singlet: _save_Pl_info( n0, direction, atom_posn) if n1.element is not Singlet: _save_Pl_info( n1, - direction, atom_posn) # note the sign on direction # get the Pl atom out of the way atom.kill() # (let's hope this happened before an Undo checkpoint ever saw it -- # sometime verify that, and optimize if it's not true) # summarize our success -- we'll remove this when it becomes the default, # or condition it on a DEBUG_DNA_UPDATER flag ### debug_flags.DEBUG_DNA_UPDATER # for use later summary_format = \ "Note: dna updater converted [N] Pl5 pseudoatom(s)" env.history.deferred_summary_message( graymsg(summary_format) ) return # == def _save_Pl_info( sugar, direction_to_Pl, Pl_posn ): print "_save_Pl_info is nim: %r" % ((sugar, direction_to_Pl, Pl_posn),) # end
NanoCAD-master
cad/src/dna/updater/convert_from_PAM5.py
# Copyright 2007-2008 Nanorex, Inc. See LICENSE file for details. """ dna_updater_main.py - enforce rules on newly changed DNA-related model objects, including DnaGroups, AxisChunks, PAM atoms, etc. @author: Bruce @version: $Id$ @copyright: 2007-2008 Nanorex, Inc. See LICENSE file for details. """ from dna.updater.dna_updater_globals import get_changes_and_clear from dna.updater.dna_updater_globals import ignore_new_changes from dna.updater.dna_updater_globals import clear_updater_run_globals from dna.updater.dna_updater_globals import _f_invalid_dna_ladders from dna.updater.dna_updater_globals import restore_dnaladder_inval_policy from dna.updater.dna_updater_globals import DNALADDER_INVAL_IS_OK from utilities import debug_flags from dna.updater.dna_updater_utils import remove_killed_atoms from dna.updater.dna_updater_utils import remove_closed_or_disabled_assy_atoms from dna.updater.dna_updater_atoms import update_PAM_atoms_and_bonds from dna.updater.dna_updater_chunks import update_PAM_chunks from dna.updater.dna_updater_groups import update_DNA_groups from dna.updater.dna_updater_debug import debug_prints_as_dna_updater_starts from dna.updater.dna_updater_debug import debug_prints_as_dna_updater_ends from dna.model.DnaMarker import _f_are_there_any_homeless_dna_markers from dna.model.DnaMarker import _f_get_homeless_dna_markers # == _runcount = 0 # for debugging [bruce 080227] def full_dna_update(): """ [meant to be called from _master_model_updater] Enforce rules on all newly changed DNA-related model objects, including DnaGroups, AxisChunks, PAM atoms, etc. @warning: external calls to any smaller parts of the dna updater would probably have bugs, due to the lack of beginning and ending calls to clear_updater_run_globals, and possibly for many other reasons. In fact, external calls to this function rather than to update_parts (which calls it) are risky, since it's not reviewed how much this function depends on things that update_parts has normally done by the time it calls this. @note: The newly changed objects are not necessarily all in the same assy (class assembly). E.g. there might be some from an open mmp file and some from a just-opened part library part. @return: None """ global _runcount _runcount += 1 clear_updater_run_globals() try: _full_dna_update_0( _runcount) # includes debug_prints_as_dna_updater_starts finally: debug_prints_as_dna_updater_ends( _runcount) clear_updater_run_globals() return def _full_dna_update_0( _runcount): """ [private helper for full_dna_update -- do all the work] """ # TODO: process _f_baseatom_wants_pam: (or maybe a bit later, after delete bare, and error finding?) # - extend to well-structured basepairs; drop structure error atoms (as whole basepairs) # - these and their baseatom neighbors in our changed atoms, maybe even real .changed_structure changed_atoms = get_changes_and_clear() debug_prints_as_dna_updater_starts( _runcount, changed_atoms) # note: this function should not modify changed_atoms. # note: the corresponding _ends call is in our caller. if not changed_atoms and not _f_are_there_any_homeless_dna_markers(): # maybe: also check _f_baseatom_wants_pam, invalid ladders, here and elsewhere # (or it might be more efficient to officially require _changed_structure on representative atoms, # which we're already doing now as a kluge workaround for the lack of testing those here) # [bruce 080413 comment] # # note: adding marker check (2 places) fixed bug 2673 [bruce 080317] return # optimization (might not be redundant with caller) # print debug info about the set of changed_atoms (and markers needing update) if debug_flags.DEBUG_DNA_UPDATER_MINIMAL: print "\ndna updater: %d changed atoms to scan%s" % \ ( len(changed_atoms), _f_are_there_any_homeless_dna_markers() and " (and some DnaMarkers)" or "" ) if debug_flags.DEBUG_DNA_UPDATER and changed_atoms: # someday: should be _VERBOSE, but has been useful enough to keep seeing for awhile items = changed_atoms.items() items.sort() atoms = [item[1] for item in items] NUMBER_TO_PRINT = 10 if debug_flags.DEBUG_DNA_UPDATER_VERBOSE or len(atoms) <= NUMBER_TO_PRINT: print " they are: %r" % atoms else: print " the first %d of them are: %r ..." % \ (NUMBER_TO_PRINT, atoms[:NUMBER_TO_PRINT]) if changed_atoms: remove_killed_atoms( changed_atoms) # only affects this dict, not the atoms if changed_atoms: remove_closed_or_disabled_assy_atoms( changed_atoms) # This should remove all remaining atoms from closed files. # Note: only allowed when no killed atoms are present in changed_atoms; # raises exceptions otherwise. if changed_atoms: update_PAM_atoms_and_bonds( changed_atoms) # this can invalidate DnaLadders as it changes various things # which call atom._changed_structure -- that's necessary to allow, # so we don't change dnaladder_inval_policy until below, # inside update_PAM_chunks [bruce 080413 comment] # (REVIEW: atom._changed_structure does not directly invalidate # dna ladders, so I'm not sure if this comment is just wrong, # or if it meant something not exactly what it said, like, # this can cause more ladders to be invalidated than otherwise # in an upcoming step -- though if it meant that, it seems # wrong too, since the existence of that upcoming step # might be enough reason to not be able to change the policy yet. # [bruce 080529 addendum/Q]) if not changed_atoms and not _f_are_there_any_homeless_dna_markers() and not _f_invalid_dna_ladders: return # optimization homeless_markers = _f_get_homeless_dna_markers() #e rename, homeless is an obs misleading term #### # this includes markers whose atoms got killed (which calls marker.remove_atom) # or got changed in structure (which calls marker.changed_structure) # so it should not be necessary to also add to this all markers noticed # on changed_atoms, even though that might include more markers than # we have so far (especially after we add atoms from invalid ladders below). # # NOTE: it can include fewer markers than are noticed by _f_are_there_any_homeless_dna_markers # since that does not check whether they are truly homeless. assert not _f_are_there_any_homeless_dna_markers() # since getting them cleared them new_chunks, new_wholechains = update_PAM_chunks( changed_atoms, homeless_markers) # note: at the right time during this or a subroutine, it sets # dnaladder_inval_policy to DNALADDER_INVAL_IS_ERROR # review: if not new_chunks, return? wait and see if there are also new_markers, etc... update_DNA_groups( new_chunks, new_wholechains) # review: # args? a list of nodes, old and new, whose parents should be ok? or just find them all, scanning MT? # the underlying nodes we need to place are just chunks and jigs. we can ignore old ones... # so we need a list of new or moved ones... chunks got made in update_PAM_chunks; jigs, in update_PAM_atoms_and_bonds... # maybe pass some dicts into these for them to add things to? ignore_new_changes("as full_dna_update returns", changes_ok = False ) if debug_flags.DEBUG_DNA_UPDATER_MINIMAL: if _f_are_there_any_homeless_dna_markers(): print "dna updater fyi: as updater returns, some DnaMarkers await processing by next run" # might be normal...don't know. find out, by printing it even # in minimal debug output. [bruce 080317] if _f_invalid_dna_ladders: #bruce 080413 print "\n*** likely bug: some invalid ladders are recorded, as dna updater returns:", _f_invalid_dna_ladders # but don't clear them, in case this was sometimes routine and we were # working around bugs (unknowingly) by invalidating them next time around restore_dnaladder_inval_policy( DNALADDER_INVAL_IS_OK) return # from _full_dna_update_0 # end
NanoCAD-master
cad/src/dna/updater/dna_updater_main.py
# Copyright 2007-2008 Nanorex, Inc. See LICENSE file for details. """ dna_updater_groups.py - enforce rules on chunks containing changed PAM atoms @author: Bruce @version: $Id$ @copyright: 2007-2008 Nanorex, Inc. See LICENSE file for details. """ from dna.updater.dna_updater_globals import ignore_new_changes _DEBUG_GROUPS = False # == def update_DNA_groups( new_chunks, new_wholechains ): """ @param new_chunks: list of all newly made DnaLadderRailChunks (or modified ones, if that's ever possible) @param new_wholechains: list of all newly made WholeChains (or modified ones, if that's ever possible) @@@ doc what we do to them @@@ use this arg Make sure that PAM chunks and jigs are inside the correct Groups of the correct structure and classes, according to the DNA Data Model. These Groups include Groups (which someday might be called Blocks in this context), DnaSegments, DnaStrands, and DnaGroups. Move nodes or create new groups of these kinds, as needed. Since the user can't directly modify the insides of a DnaGroup, and the maintaining code can be assumed to follow the rules, the main focus here is on newly created objects, made by old code or by reading old mmp files which don't already have them inside the right groups. For reading mmp files (old or new) to work smoothly, we may [###decide this! it may already sort of work for chunks...] also ask the lower-level code that runs before this point to add new chunks into the model next to some older chunk that contained one of its atoms (if there was one), so that if the old chunk was already in the right place, the new one will be too. We may also convert existing plain Groups into DnaGroups under some circumstances, but this is NIM to start with, and may never be worth doing, since some touchups of converted old files will always be required. But at least, if converted files contain useless singleton Groups around newly made DnaGroups, we might discard them except for copying their name down (which is essentially the same thing). @return: None (??) """ # Note: this is not (yet? ever?) enough to fully sanitize newly read # mmp files re Group structure. It might be enough for the results of # user operations, though. So it's probably better to process mmp files # in a separate step, after reading them and before (or after?) running # this updater. @@@ # Note: # - before we're called, markers have moved to the right place, died, been made, # so that every wholechain has one controlling marker. But nothing has moved # into new groups in the internal model tree. Markers that need new DnaSegments # or DnaStrands don't yet have them, and might be inside the wrong ones. # revise comment: # - for segments: [this] tells you which existing or new DnaSegment owns each marker and DnaSegmentChunk. Move nodes. # - for strands: ditto; move markers into DnaStrand, and chunks into that or DnaSegment (decide this soon). ignore_new_changes("as update_DNA_groups starts", changes_ok = False, debug_print_even_if_none = _DEBUG_GROUPS) old_groups = {} # find or make a DnaStrand or DnaSegment for each controlling marker # (via its wholechain), and move markers in the model tree as needed for wholechain in new_wholechains: strand_or_segment = wholechain.find_or_make_strand_or_segment() for marker in wholechain.all_markers(): ## print "dna updater: debug fyi: subloop on ", marker old_group = strand_or_segment.move_into_your_members(marker) if old_group: old_groups[id(old_group)] = old_group ignore_new_changes("from find_or_make_strand_or_segment", changes_ok = False, debug_print_even_if_none = _DEBUG_GROUPS ) # should not change atoms in the ways we track # move chunks if needed for chunk in new_chunks: wholechain = chunk.wholechain # defined for DnaLadderRailChunks assert wholechain # set by update_PAM_chunks # could assert wholechain is in new_wholechains strand_or_segment = wholechain.find_strand_or_segment() assert strand_or_segment old_group = strand_or_segment.move_into_your_members(chunk) # (For a StrandChunk will we place it into a DnaStrand (as in this code) # or based on the attached DnaSegment? # Not yet sure; the latter has some advantages and is compatible with current external code [080111]. # If we do it that way, then do that first for the new segment chunks, then another pass for the strand chunks. # Above code assumes it goes into its own DnaStrand object; needs review/revision.) # # MAYBE TODO: We might do part of this when creating the chunk # and only do it now if no home existed. if old_group: old_groups[id(old_group)] = old_group ignore_new_changes("from moving chunks and markers into proper Groups", changes_ok = False, debug_print_even_if_none = _DEBUG_GROUPS ) # Clean up old_groups: # # [update 080331: comment needs revision, since Block has been deprecated] # # For any group we moved anything out of (or are about to delete something # from now), we assume it is either a DnaSegment or DnaStrand that we moved # a chunk or marker out of, or a Block that we delete all the contents of, # or a DnaGroup that we deleted everything from (might happen if we mark it # all as having new per-atom errors), or an ordinary group that contained # ordinary chunks of PAM DNA, or an ordinary group that contained a DnaGroup # we'll delete here. # # In some of these cases, if the group has become # completely empty we should delete it. In theory we should ask the group # whether to do this. Right now I think it's correct for all the kinds listed # so I'll always do it. # # If the group now has exactly one member, should we dissolve it # (using ungroup)? Not for a 1-member DnaSomething, probably not # for a Block, probably not for an ordinary group, so for now, # never do this. (Before 080222 we might do this even for a # DnaSegment or DnaStrand, I think -- probably a bug.) # # Note, we need to do the innermost (deepest) ones first. # We also need to accumulate new groups that we delete things from, # or more simply, just transclose to include all dads from the start. # (Note: only correct since we avoid dissolving groups that are equal to # or outside the top of a selection group. Also assumes we never dissolve # singletons; otherwise we'd need to record which groups not in our # original list we delete things from below, and only consider those # (and groups originally in our list) for dissolution.) from foundation.state_utils import transclose # todo: make toplevel import def collector(group, dict1): # group can't be None, but an optim to earlier code might change that, # so permit it here if group and group.dad: dict1[id(group.dad)] = group.dad transclose( old_groups, collector) depth_group_pairs = [ (group.node_depth(), group) for group in old_groups.itervalues() ] depth_group_pairs.sort() depth_group_pairs.reverse() # deepest first for depth_junk, old_group in depth_group_pairs: if old_group.is_top_of_selection_group() or \ old_group.is_higher_than_selection_group(): # too high to dissolve continue if len(old_group.members) == 0: # todo: ask old_group whether to do this: old_group.kill() # note: affects number of members of less deep groups # no need for this code when that len is 1: ## old_group.ungroup() ## # dissolves the group; could use in length 0 case too continue ignore_new_changes("from trimming groups we removed things from", changes_ok = False, debug_print_even_if_none = _DEBUG_GROUPS ) ignore_new_changes("as update_DNA_groups returns", changes_ok = False ) return # from update_DNA_groups # end
NanoCAD-master
cad/src/dna/updater/dna_updater_groups.py
# find directional bond chains (or rings) covering our atoms def func( atom1, dir1): # wrong, see below if atom1.killed(): ###k return ### best place to do this? for b in atom1.bonds: if b.is_directional(): a1, a2 = b.atom1, b.atom2 dir1[a1.key] = a1 dir1[a2.key] = a2 return all_atoms = transclose( initial_atoms, func ) # wait, that only found all atoms, not their partition... ### # does transclose know when it has to go back to an initial atom to find more? probably not. # it does not even assume equiv relation, but on one-way relation this partition is not defined. # also when we do find these partitions, we probably want their chain lists, not just their sets. # so make new finding code to just grab the chains, then see which initial_atoms can be dropped (efficiently). # probably mark the atoms or store them in dicts, as well as making chains. # An easy way: grow_bond_chain, and a custom next function for it. It can remove from initial_atoms too, as it runs past. return # == # obs - see pop_arbitrary_item and its caller in bond_chains.py def _pop_arbitrary_atom_with_qualifying_bond(atoms_dict, bond_ok_func): """ Return (atom, bond) (and pop atom from atoms_dict) where atom has bond and bond_ok_func(bond) is true, or return (None, None) if no remaining atoms have qualifying bonds. Also pop all atoms returned, and all atoms skipped since they have no qualifying bonds. This means that atoms_dict will be empty when we return (None, None). It also means any atom is returned at most once, during repeated calls using the same atoms_dict, even if it has more than one qualifying bond. Warning: there is no atom_ok_func, and we consider all atoms or bondpoints with no checks at all, not even of atom.killed(). In typical usage, the caller might add atoms to or remove atoms from atoms_dict between repeated calls, terminating a loop when we return (None, None) and/or when atoms_dict becomes empty. """ while atoms_dict: key_unused, atom = pop_arbitrary_item(atoms_dict) # Assume any atom with a qualifying bond is ok # (i.e. caller must exclude non-ok atoms). # [Someday we might need to add an atom_ok_func, # or a func that looks at both atom and bond, # if of two atoms on an ok bond, only one might be ok. # But it's probably still easier to do it in a helper function # (like this one) than directly in a caller loop, due to our # desire to pop atom as soon as we return it with any bond, # even if it qualifies with other bonds too.] for bond in atom.bonds: if bond_ok_func(bond): return atom, bond # REVIEW: should we return (atom, None) here? return None, None # obs - see same-named method in class xxx in bond_chains.py def find_chains_or_rings(unprocessed_atoms, atom_ok_func): # needs rewrite as in TODO; REVIEW: discard lone atoms ok?? # TODO: also needs a function to find one bond or test one bond; # if that func just returns the special bonds from an atom, up to 2, open bonds ok??, # then maybe it's enough and we can use it to make the next_bond_in_chain function too. # (Or the special func could just be an atom test...) # ... def bond_ok_func(bond): return atom_ok_func(bond.atom1) and \ atom_ok_func(bond.atom2) def next_bond_in_chain(...): pass... while True: atom, bond = _pop_arbitrary_atom_with_qualifying_bond(unprocessed_atoms, bond_ok_func) if atom is None: assert not unprocessed_atoms break (ringQ, listb, lista) = res_element = grow_bond_chain(bond, atom, next_bond_in_chain) ### BUG: only grows in one direction! # see some caller # of grow_bond_chain # or grow_directional_bond_chain # which calls it twice... # ... hmm, make_pi_bond_obj calls twice grow_pi_sp_chain for atom in lista: unprocessed_atoms.pop(atom.key, None) res.append( res_element) continue return ksddskj # a lot of atom methods about directional bonds would also apply to axis bonds... almost unchanged, isomorphic # but i guess i'll dup/revise the code # also is it time to move these into subclasses of atom? i could introduce primitive updater that just keeps atom # classes right... it might help with open bonds marked as directional... have to review all code that creates them. # (and what about mmp reading? have to assume correct structure; for bare strand ends use geom or be arb if it is) === # Separate connected sets of axis atoms into AxisChunks, reusing existing # AxisChunks whereever possible; same with StrandChunks, but more complex... # # [REVIEW: also label the atoms with positional hints? Note that we need these # (e.g. base indices) in order to decide which old chunks correspond to # which new ones when they break or merge. For now we might just use atom.key, # since for generated structures it may have sort of the right order.] # REVIEW/obs/scratch comments: # divide atoms into chunks of the right classes, in the right way # some bond classes can't be internal bonds... some must be... # (If any improper branching is found, complain, and let it break up # the chunks so that each one is properly structured.) axis_chains, strand_chains = find_axis_and_strand_chains_or_rings( changed_atoms) # ... now we should recognize sections of axis on which both strands remain properly bonded... # assigning every atom an index ... probably the strand atoms look at their axis atom index... # PROBLEM: extent of axes and strands we have (the changed ones) does not correspond. # Ideally we'd like to ignore the unchanged parts. Even more ideally, not even scan them! # (tThough they have new indices and might be in different strands/segments, so in the end # we at least have to scan thru them to change some settings about that.) # # If we have these ids on atoms, can't we just trust them and not scan them, for sections # with no atom changes? those sections get broken up, but the pieces ought to have trustable indices... # to implement the breakage we might have to reindex (all but one of them) somehow... #### # goals: # - low runtime when few changes -- take advantage of unchanged sections, even if we have to reindex them # - simplicity, robustness # - know how to copy segment and strand info, incl unique id, as things change in extent (does it slide along the chains?) # - recognize base pairs and properly stacked basepairs, assign indices that fit, use those for geom/direction error checking, # direction assignment when unset # design Qs: # - how *do* we decide how to copy strand & segment info? note: pay more attention to basepair index than to strand direction. # e.g. compare basepair index (or atom key) of the connected axis atoms of the base pairs. # - user-settable jigs for base index origin/direction? # - user-settable jigs or tags for subsequences on strands or segments? # implem Qs: # - are the indices undoable? # (guess: no, they're always derived; # but if we make arb choices like ring-origin, create undoable/mmp state for them, either fields/tags or jigs. ###) # - do they affect display? (eg in rainbow coloring mode) # misc: # - if earlier stage assigns atom classes, it could also order the bonds in a definite way, # e.g. a strand atom's first bond could be to the axis for axis_set in axis_chains: axis_set.ringQ axis_set.lista # or atoms_list or atoms_dict? axis_set.listb for atom in axis_analyzer.found_object_iteratoms(axis_set): bla # class ChainAtomMarker(Jig): # .... # should AtomChain itself also be a Jig? (only if it can store its atoms in a set, not a list...) # ... or if its atom list never change. and killed atoms are not removed from it! but then should they point to it too?? # seems too weird, better to have a non-Jig object in that case. == # outtake: # but we might look up new strand atoms in new_chain_info for adjacency -- or test bonding if easier. # I think the lookup is easier and more general... # not used here [scanning axis and strand chains for chunking] after all: def adjacent(atom1, atom2): #e refile, use above too -- hmm, should new_chain_info be an object with this method?? ### Q "are two strand atoms adjacent (and in same chain) according to new_chain_info?" #e to work for ring indices, we need to ask the chain, but the chain_id does not know the ring object.... # can we just put the chain object instead of its id in that info thing? ### DECIDE chain1, index1 = new_chain_info[atom1.key] chain2, index2 = new_chain_info[atom2.key] if chain1 != chain2: return #k review, if these are objects assert index1 != index2 # hmm, would this fail for a length==1 ring?? yes!!! can that happen? ### REVIEW; special case return chain1.are_indices_adjacent( index1, index2) #IMPLEM # worry about "adjacent" for rings! ### LOGIC BUG: earlier code that moved markers forgot to use ringness in checking index adjacency # or in the lookup of an old index!!! Might need to ask the ring to canonicalize the index... that logic bug is a current bug in the code, refile it... strand1_atom = strand2_atom = None # from prior axis atom as we scan #e keep in a list or set? # if we're a ring, patch that up at the end by identifying strand_segment_ids if appropriate
NanoCAD-master
cad/src/dna/updater/dna_updater_scratch.py
# Copyright 2007-2008 Nanorex, Inc. See LICENSE file for details. """ fix_deprecated_elements.py - fix deprecated PAM elements in-place in models @author: Bruce @version: $Id$ @copyright: 2007-2008 Nanorex, Inc. See LICENSE file for details. """ from model.elements import PeriodicTable from utilities.constants import diDEFAULT from utilities import debug_flags from dna.updater.dna_updater_prefs import pref_fix_deprecated_PAM3_atoms from dna.updater.dna_updater_prefs import pref_fix_deprecated_PAM5_atoms from dna.updater.dna_updater_prefs import dna_updater_warn_when_transmuting_deprecated_elements import foundation.env as env from utilities.Log import orangemsg from utilities.constants import MODEL_PAM3, MODEL_PAM5 # == def fix_deprecated_elements( changed_atoms): """ scan for deprecated elements, and fix them """ fix_PAM3 = pref_fix_deprecated_PAM3_atoms() fix_PAM5 = pref_fix_deprecated_PAM5_atoms() deprecated_atoms = [] for atom in changed_atoms.itervalues(): deprecated_to = atom.element.deprecated_to # an element symbol, or None, or 'remove' if deprecated_to: pam = atom.element.pam assert pam in (MODEL_PAM3, MODEL_PAM5) if pam == MODEL_PAM3: fix = fix_PAM3 elif pam == MODEL_PAM5: fix = fix_PAM5 else: fix = False if fix: deprecated_atoms.append(atom) elif debug_flags.DEBUG_DNA_UPDATER: print "dna updater: debug_pref says don't alter deprecated atom %r" % (atom,) continue for atom in deprecated_atoms: deprecated_to = atom.element.deprecated_to # an element symbol, or 'remove' if atom.display != diDEFAULT: # Atoms of deprecated elements sometimes have funny display modes # set by the DNA Duplex Generator. Remove these here. # (This may be needed even after we fix the generator, # due to old mmp files. REVIEW: can it ever cause harm?) atom.setDisplayStyle(diDEFAULT) if deprecated_to == 'remove' or deprecated_to == 'X': # (Atom.kill might be unideal behavior for 'remove', # but that's only on Pl3 which never occurs AFAIK, so nevermind) # Kill the atom (and make sure that new bondpoints get into a good enough position). # REVIEW: does atom.kill make new bps immediately # (review whether ok if more than one needs making on one base atom) # or later # (review whether it's still going to happen in the current master_updater call)? #### if debug_flags.DEBUG_DNA_UPDATER_VERBOSE: print "dna updater: kill deprecated atom %r" % (atom,) summary_format = \ "Warning: dna updater killed [N] deprecated %s pseudoatom(s)" % \ (atom.element.symbol,) env.history.deferred_summary_message( orangemsg(summary_format) ) atom.kill() # TODO: worry about atom being a hotspot, or having a bondpoint which is a hotspot? else: # Transmute atom to a new element symbol -- assume its position, # bonds, and bondpoints are all ok and need no changes. # (Should be true of as 071119, since this is used only # to make Ax and Ss PAM atoms from variant atomtypes # used to mark them as being in special situations.) # # Use mvElement to avoid remaking existing bondpoints. elt = PeriodicTable.getElement(deprecated_to) if debug_flags.DEBUG_DNA_UPDATER_VERBOSE: print "dna updater: transmute deprecated atom %r to element %s" % \ (atom, elt.symbol) if dna_updater_warn_when_transmuting_deprecated_elements(): summary_format = \ "Warning: dna updater transmuted [N] %s to %s pseudoatom(s)" % \ (atom.element.symbol, elt.symbol ) env.history.deferred_summary_message( orangemsg(summary_format) ) # todo: refactor so orangemsg is replaced with a warning option atom.mvElement(elt) atom.make_enough_bondpoints() # REVIEW: do this later, if atom classes should be corrected first # to help this properly position bondpoints # (or perhaps, first set correct atom classes, then do this, # making sure it sets correct bondpoint classes, # or that we correct them separately afterwards) continue return # from fix_deprecated_elements # end
NanoCAD-master
cad/src/dna/updater/fix_deprecated_elements.py
# Copyright 2007-2008 Nanorex, Inc. See LICENSE file for details. """ dna_updater_globals.py -- global variables or mutables for dna_updater, and their lowest-level accessors. @author: Bruce @version: $Id$ @copyright: 2007-2008 Nanorex, Inc. See LICENSE file for details. """ from utilities import debug_flags from foundation.changedicts import refreshing_changedict_subscription from foundation.changedicts import _cdproc_for_dictid # but it's private! from model.global_model_changedicts import _changed_structure_Atoms # todo: rename to be non-private from model.global_model_changedicts import _changed_parent_Atoms from utilities.debug import print_compact_stack _DEBUG_ATOM_KEY = None # None, or a value of atom.key for which all ignored changes should be printed # == # _rcdp1 and _rcdp2 will be replaced in initialize_globals() # with refreshing_changedict_subscription instances: _rcdp1 = None _rcdp2 = None # REVIEW: when we reload this module during development, # do we need to preserve those global objects? # I would guess so, but I didn't yet see a bug from not doing so. # [bruce 071119] def initialize_globals(): """ Meant to be called only from master_model_updater.py (perhaps indirectly). Do whatever one-time initialization is needed before our other public functions should be called. [Also should be called if this module is reloaded.] """ # set up this module's private global changedict subscription handlers global _rcdp1, _rcdp2 _rcdp = _refreshing_changedict_subscription_for_dict _rcdp1 = _rcdp(_changed_structure_Atoms) _rcdp2 = _rcdp(_changed_parent_Atoms) return def _refreshing_changedict_subscription_for_dict(dict1): cdp = _cdproc_for_dictid[ id(dict1)] # error if not found; depends on import/initialize order rcdp = refreshing_changedict_subscription( cdp) return rcdp def get_changes_and_clear(): """ Grab copies of the global atom changedicts we care about, returning them in a single changed atom dict, and resubscribe so we don't grab the same changes next time. """ dict1 = _rcdp1.get_changes_and_clear() dict2 = _rcdp2.get_changes_and_clear() # combine them into one dict to return (which caller will own) # optim: use the likely-bigger one, dict2 (from _changed_parent_Atoms), # to hold them all dict2.update(dict1) return dict2 def ignore_new_changes( from_what, changes_ok = True, debug_print_even_if_none = False): """ Discard whatever changes occurred since the last time we called get_changes_and_clear, of the changes we normally monitor and respond to. @param from_what: a string for debug prints, saying what the changes are from, e.g. "from fixing classes". @type from_what: string @param changes_ok: whether it's ok (not an error) if we see changes. @type changes_ok: boolean @param debug_print_even_if_none: do our debug prints even if there were no changes @type debug_print_even_if_none: boolean """ ignore_these = get_changes_and_clear() if ignore_these or debug_print_even_if_none: if (not ignore_these) or changes_ok: if debug_flags.DEBUG_DNA_UPDATER: print "dna updater: ignoring %d new changes %s" % (len(ignore_these), from_what) else: msg = "\nBUG: dna updater: ignoring %d new changes %s -- any such changes are a bug: " % \ (len(ignore_these), from_what) print_compact_stack(msg) print if ignore_these.has_key(_DEBUG_ATOM_KEY): msg = "*** _DEBUG_ATOM_KEY %r: %r seen in those changes" % (_DEBUG_ATOM_KEY, ignore_these[_DEBUG_ATOM_KEY]) if changes_ok: print_compact_stack(msg + ": ") # since we didn't print stack just above else: print msg del ignore_these return # == # globals and accessors # (some can be set outside of dna updater runs, noticed during them) # (not yet here: _f_are_there_any_homeless_dna_markers, etc) _f_invalid_dna_ladders = {} # moved here from DnaLadder.py, bruce 080413 [rename with _f_?] def _f_get_invalid_dna_ladders(): # moved here from DnaLadder.py, bruce 080413 """ Return the invalid dna ladders, and clear the list so they won't be returned again (unless they are newly made invalid). Friend function for dna updater. Other calls would cause it to miss newly invalid ladders, causing serious bugs. """ res = _f_invalid_dna_ladders.values() _f_invalid_dna_ladders.clear() res = filter( lambda ladder: not ladder.valid, res ) # probably not needed return res def _f_clear_invalid_dna_ladders(): #bruce 080413; see comment in caller about need for review/testing if _f_invalid_dna_ladders: print "fyi: dna updater: ignoring %d newly invalid dnaladders" % \ len( _f_invalid_dna_ladders) _f_invalid_dna_ladders.clear() return _f_baseatom_wants_pam = {} # maps baseatom.key to a PAM_MODEL it wants updater to convert it to #bruce 080411, for use instead of chunk attrs like .display_as_pam # by commands for manual conversion of PAM model # note: Pl atoms are not baseatoms! To use _f_baseatom_wants_pam on them, # you need this function: def _f_anyatom_wants_pam(atom): #bruce 080411 # not counting its chunk attrs, just looking at _f_baseatom_wants_pam properly if atom.element.symbol == 'Pl5': atom = atom.Pl_preferred_Ss_neighbor() if atom is None: # that method printed a bug note already return None return _f_baseatom_wants_pam.get(atom.key) # == # These should be cleared at the start and end of any dna updater run. _f_DnaGroup_for_homeless_objects_in_Part = {} _f_ladders_with_up_to_date_baseframes_at_ends = {} #bruce 080409, replacing ladders_dict params (whose passing into enough # methods/functions was unfinished) _f_atom_to_ladder_location_dict = {} #bruce 080411, to permit finding ladder/rail/index of atoms in freshly # made ladders which didn't yet remake their chunks # (needn't store all end atoms, since those can be found using # rail_end_atom_to_ladder -- important for bridging Pls # between fresh and old-untouched ladders) DNALADDER_INVAL_IS_OK = 0 DNALADDER_INVAL_IS_ERROR = 1 DNALADDER_INVAL_IS_NOOP_BUT_OK = 2 dnaladder_inval_policy = DNALADDER_INVAL_IS_OK ### todo: make private; only used directly in this file # and this rule should be maintained # [bruce 080413] def get_dnaladder_inval_policy(): # (use this to prevent bugs from importing a mutable value # and having only the initial value defined globally in a # client module) return dnaladder_inval_policy def clear_updater_run_globals(): #bruce 080218 """ Clear globals which are only used during individual runs of the dna updater. """ # Note: perhaps not all such globals are here yet, which should be. # And there are some in fix_bond_directions (IIRC) which can't be here. _f_DnaGroup_for_homeless_objects_in_Part.clear() _f_ladders_with_up_to_date_baseframes_at_ends.clear() _f_atom_to_ladder_location_dict.clear() global dnaladder_inval_policy dnaladder_inval_policy = DNALADDER_INVAL_IS_OK # important in case of exceptions during updater return def temporarily_set_dnaladder_inval_policy(new): # bruce 080413 """ Must be used in matching pairs with restore_dnaladder_inval_policy, and only within the dna updater. """ global dnaladder_inval_policy old = dnaladder_inval_policy dnaladder_inval_policy = new return old def restore_dnaladder_inval_policy(old): # bruce 080413 global dnaladder_inval_policy dnaladder_inval_policy = old return # == def rail_end_atom_to_ladder(atom): """ Atom is believed to be the end-atom of a rail in a valid DnaLadder. Return that ladder. If anything looks wrong, either console print an error message and return None (which is likely to cause exceptions in the caller), or raise some kind of exception (which is what we do now, since easiest). """ #bruce 080510 moved this from DnaLadder.py to avoid import cycles # various exceptions are possible from the following; all are errors try: ladder = atom._DnaLadder__ladder # note: this attribute name is hardcoded in several files ## assert isinstance(ladder, DnaLadder) # (not worth the trouble, since we don't want the DnaLadder import) assert ladder is not None assert ladder.valid, "%r not valid" % ladder # note: changes in _ladder_set_valid mean this will become common for bugs, attrerror will be rare [080413] # or: if not, print "likely bug: invalid ladder %r found on %r during merging" % (ladder, atom) #k # REVIEW: it might be better to return an invalid ladder than no ladder or raise an exception, # so we might change this to return one, provided the atom is in the end_baseatoms. #### assert atom in ladder.rail_end_baseatoms() return ladder except: error = atom._dna_updater__error and ("[%s]" % atom._dna_updater__error) or "" print "\nfollowing exception is an error in rail_end_atom_to_ladder(%r%s): " % \ (atom, error) raise pass # end
NanoCAD-master
cad/src/dna/updater/dna_updater_globals.py
# Copyright 2007-2008 Nanorex, Inc. See LICENSE file for details. """ crossovers.py -- support for DNA crossovers, modelled at various levels @author: Bruce @version: $Id$ @copyright: 2007-2008 Nanorex, Inc. See LICENSE file for details. Includes Make Crossover and Remove Crossover Pl-atom-pair context menu commands. TODO: make it work for PAM3 as well as PAM5. """ ###BUGS: # - Remove Crossover needs to be offered when correct to do so, not otherwise # - Pl position is wrong after either op, esp. Remove # - Undo and Feature Help cmdnames are wrong (not working) from utilities.constants import noop, average_value from model.bond_constants import V_SINGLE from model.bond_constants import atoms_are_bonded, find_bond from model.bonds import bond_atoms_faster, bond_direction ##, bond_atoms from utilities.Log import redmsg, greenmsg, quote_html ##, orangemsg ##from debug_prefs import debug_pref, Choice import foundation.env as env from utilities.GlobalPreferences import dna_updater_is_enabled from model.elements import PeriodicTable Element_Sj5 = PeriodicTable.getElement('Sj5') Element_Ss5 = PeriodicTable.getElement('Ss5') def crossover_menu_spec(atom, selatoms): """ Make a crossover-related menu_spec list for the two atoms in the selatoms dict (atom.key -> atom), both Pl, for use in atom's context menu (which must be one of the atoms in selatoms). If no menu commands are needed, return [] (a valid empty menu_spec) or None. Should be reasonably fast, but needn't be super-fast -- called once whenever we construct a context menu for exactly two selected Pl atoms. """ assert len(selatoms) == 2 atoms = selatoms.values() assert atom in atoms for a1 in atoms: assert a1.element.symbol == 'Pl5' # Are these Pl atoms either: # - legitimate candidates for making a crossover, # - or already in a crossover? # They are candidates for making a crossover if: # - each one is in a double helix of pseudo-DNA (or locally appears to be) (ignoring Ss/Sj errors, though we'll fix them) # - this means, you can find the 5-ring of Pl5-Ss5-Ax5-Ax5-Ss5-samePl5... probably no more requirements are strictly needed # - the sets of involved atoms for each one don't overlap # - we *could* also require they're not nearby in the same helix, but we won't bother # - we *could* require geometric constraints, but we probably don't want to (and surely won't bother for now). # We'll create an object to figure this out, and we may keep it around to do the crossover-making if that's desired. # They're already in a crossover if: # - each one bridges two double helices of pseudo-DNA (or locally appears to); # - they bridge the same double helices, in neighboring locations. # Ideally we'd use a general framework for pattern recognizer objects to look for and remember these patterns, # where the patterns would include the basic structure of pseudo-dna bases and helices. # For now, we'll probably be simpler here to get started, but then we'll get generalized # when the pseudo-dna spelling checker is added, and/or take advantage of the persistent recognizers # which that will make use of (rather than creating new recognizer objects for each cmenu request, like we'll do now). res = [] ##e need to protect against exceptions while considering adding each item twoPls = map( Pl5_recognizer, atoms) Pl1, Pl2 = twoPls # Both Make and Remove Crossover need the strand directions to be well-defined, # so if they're not, just insert a warning and not the specific commands. # (This also simplifies the code for deciding whether to offer Remove Crossover.) if not Pl1.strand_direction_well_defined or not Pl2.strand_direction_well_defined: ###IMPLEM text = "(strand directions not well-defined)" #e shorten? mention which atom? do it for single selected atom? say how not? item = (text, noop, 'disabled') res.append(item) else: # maybe add a "Make Crossover" command if make_crossover_ok(twoPls): text = "Make Crossover (%s - %s)" % (Pl1.atom, Pl2.atom) #e or print the Pl5_recognizer objects in the menu text?? cmdname = "Make Crossover" ###k for undo -- maybe it figures this out itself due to those parens?? evidently not. command = (lambda twoPls = twoPls: make_crossover(twoPls)) res.append((text, command)) ###e how to include cmdname?? or kluge this by having text include a prefix-separator? #e maybe package up those two related functions (make_crossover and make_crossover_ok) # into a class for the potential command -- sort of a twoPl-recognizer, i guess # maybe add a "Remove Crossover" command # should we call this Break or Unmake or Delete? It leaves the atoms, patches things up... reverses effect of Make... # so Unmake seems best of those, but Remove seems better than any of them. if remove_crossover_ok(twoPls): text = "Remove Crossover (%s - %s)" % (Pl1.atom, Pl2.atom) cmdname = "Remove Crossover" command = (lambda twoPls = twoPls: remove_crossover(twoPls)) res.append((text, command)) # it should never happen that both are ok at once! if len(res) > 1: print "bug: both Make Crossover and %s are being offered" % text #kluge to ref text to include atom names pass return res def make_crossover_ok(twoPls): ##### NEED TO MAKE THIS A RECOGNIZER so it can easily be told to print why it's not saying it's ok. """ figure out whether to offer Make Crossover, assuming bond directions are well-defined """ Pl1, Pl2 = twoPls ## if Pl1.in_only_one_helix and Pl2.in_only_one_helix: not enough -- need to make sure the other 4 pairings are not stacked. a,b = Pl1.ordered_bases d,c = Pl2.ordered_bases # note: we use d,c rather than c,d so that the atom arrangement is as shown in the diagram far below. if bases_are_stacked((a, b)) and bases_are_stacked((c, d)) \ and not bases_are_stacked((a, d)) and not bases_are_stacked((b, c)) \ and not bases_are_stacked((a, c)) and not bases_are_stacked((b, d)): involved1, involved2 = map( lambda pl: pl.involved_atoms_for_make_crossover, twoPls) if not sets_overlap(involved1, involved2): return True return False # from make_crossover_ok def remove_crossover_ok(twoPls): """ Figure out whether to offer Remove Crossover, assuming bond directions are well-defined. """ ## when = debug_pref("Offer Remove Crossover...", ## Choice(["never", "always (even when incorrect)"]), ## non_debug = True, prefs_key = '_debug_pref_key:Offer Unmake Crossover...' ) ## offer = ( when != 'never' ) ## if not offer: ## return False Pl1, Pl2 = twoPls a,b = Pl1.ordered_bases d,c = Pl2.ordered_bases # WARNING: this is different than the similar-looking condition in make_crossover_ok. if bases_are_stacked((a, c)) and bases_are_stacked((b, d)) \ and not bases_are_stacked((a, d)) and not bases_are_stacked((b, c)) \ and not bases_are_stacked((a, b)) and not bases_are_stacked((d, c)): involved1, involved2 = map( lambda pl: pl.involved_atoms_for_remove_crossover, twoPls) if not sets_overlap(involved1, involved2): return True return False # from remove_crossover_ok # == # set functions; sets must be dicts whose keys and values are the same ###e get some of these from the Set or set module?? def union(set1, set2): res = dict(set1) res.update(set2) return res def sets_overlap(set1, set2): #e could be varargs, report whether there's any overlap (same alg) """ Say whether set1 and set2 overlap. (Return a boolean.) """ return len(set1) + len(set2) > len(union(set1, set2)) # == class RecognizerError(Exception): #k superclass? pass # for now DEBUG_RecognizerError = True # for now; maybe turn off before release -- might be verbose when no errors (not sure) class StaticRecognizer: """ Superclass for pattern and local-structure recognizer classes which don't need to invalidate/update their computed attrs as the local structure changes. Features include: - Support _C_attr compute methods, but optionally catch exceptions and "tame" them as error reports, and in some cases (declared?) as default values (e.g. False for booleans). Missing features include: - We don't track changes in inputs, and behavior of computed attrs after such changes depends on history of prior attr accesses (of them or any intermediate attrs they depend on, including internal accesses by other compute methods) -- in practice that means it's undefined whether we get old or new answers then (or a mixture of the two), and *that* means our derived (aka computed) attrs should no longer be used after input changes. (This limitation is why we are called StaticRecognizer rather than Recognizer.) """ _r_safe = False # subclass should redefine this if they want all their compute methods to stop propogating *all* exceptions # (I think that should be rare, but I don't know yet for sure. It does not affect RecognizerError.) def __getattr__(self, attr): # in class StaticRecognizer if attr.startswith('__') or attr.startswith('_C_'): raise AttributeError, attr # must be fast methodname = '_C_' + attr method = getattr(self, methodname) # compute method try: answer = method() # WARNING: Answer must be returned, not setattr'd by this method! Error in this is detected below. except RecognizerError, e: # An exception for use by compute methods, locally reporting errors. # When our own methods raise this, we [nim, but needed soon] add basic info like "self" and the attr; # when its gets passed on from other methods (does that ever happen?? maybe if they are not _r_safe???), # we might someday add some self-related info so it contains its own sort of traceback # of the objects and attrs involved in it. # FOR NOW, we just treat it as normal, and record the default value; # someday we'll record the exception message but for now there is no way of asking for it anyway. if DEBUG_RecognizerError: print e answer = None except: # any other exception ##e not sure if we should suppress, reraise now only, reraise every time; # maybe let this be declared per attr or per class? "safe" attrs or classes would never propogate exceptions in themselves # (but what about exceptions coming from other things they try to use? maybe those should be wrapped into a safe form? # no, if they say "the buck stops here" that better include errors from things they use, too.) if self._r_safe: print "should record error somewhere"### answer = None else: print "fyi, error: reraising an exception from %s.%s" % (self.__class__.__name__, methodname)### raise # we have the answer answer # (make sure we actually have it) assert not self.__dict__.has_key(attr), \ "Bug: %s.%s set %r itself -- should only return it" % (self.__class__.__name__, methodname, attr) setattr(self, attr, answer) return answer pass # end of class StaticRecognizer def element_matcher(sym): def func(atom, sym = sym): return atom.element.symbol == sym return func class Base5_recognizer(StaticRecognizer): """ StaticRecognizer for a base of PAM-DNA (represented by its Ss or Sj atom). @warning: it's an error to call this on any other kind of atom, and the constructor raises an exception if you do. @note: it's *not* an error to call it on a legal kind of atom, regardless of that atom's surroundings. Any structural errors detected around that atom (or on it, e.g. its valence) should not cause exceptions from the constructor or from any attr accesses, but only the use of fallback values for computed attrs, and/or the setting of an error flag, and (in the future) the tracking of errors and warnings into the dynenv. """ def __init__(self, atom): self.atom = atom assert atom.element.symbol in ('Ss5', 'Sj5') #e other possibilities for init args might be added later #e (we might become a polymorphic constructor). return def _C_axis_atom(self): """[compute method for self.axis_atom] Return our sole Ax5 neighbor; on error or if our valence is wrong, raise RecognizerError (which means the computed value will be None). """ nn = self.atom.neighbors() if not len(nn) == 3: raise RecognizerError("%s should have exactly three neighbor atoms" % self.atom) axes = filter( element_matcher('Ax5'), nn) if not len(axes) == 1: raise RecognizerError("%s should have exactly one Ax5 neighbor" % self.atom) return axes[0] def _C_in_helix(self): """[compute method for self.in_helix] Are we resident in a helix? (Interpreted as: do we have an Ax atom -- the other base on the same Ax5 (presumably on the other backbone strand) is not looked for and might be missing.) """ return self.axis_atom is not None pass def bases_are_stacked(bases): """ Say whether two Base5_recognizers' bases are in helices, and stacked (one to the other). For now, this means they have Ax (axis) pseudoatoms which are directly bonded (but not the same atom). @warning: This is not a sufficient condition, since it doesn't say whether they're on the same "side" of the helix! Unfortunately that is not easy to tell (or even define, in the present model) since it does not necessarily mean the same strand (in the case of a crossover at that point). I [bruce 070604] think there is no local definition of this property which handles that case. I'm not sure whether this leads to any problems with when to offer Make or Remove Crossover -- maybe the overall conditions end up being sufficient; this needs review. Also, I'm not yet sure how big a deficiency it is in our model. """ try: len(bases) except: print "following exception concerns bases == %r" % (bases,) assert len(bases) == 2, "bases == %r should be a sequence of length 2" % (bases,) for b in bases: assert isinstance(b, Base5_recognizer) for b in bases: if not b.in_helix: # i.e. b.axis_atom is not None return False b1, b2 = bases return b1.axis_atom is not b2.axis_atom and atoms_are_bonded(b1.axis_atom, b2.axis_atom) class Pl5_recognizer(StaticRecognizer): """ StaticRecognizer for surroundings of a Pl5 atom in pseudo-DNA. """ def __init__(self, atom): self.atom = atom assert atom.element.symbol == 'Pl5' def _C_unordered_bases(self): """ [compute method for self.unordered_bases] Require self.atom to have exactly two neighbors, and for them to be Ss5 or Sj5. Then return those atoms, wrapped in Base5_recognizer objects (which may or may not be .in_helix). @note: the bases are arbitrarily ordered; see also _C_ordered_bases. @warning: value will be None (not a sequence) if a RecognizerError was raised. [###REVIEW: should we pass through that exception, instead, for this attr? Or assign a different error value?] """ nn = self.atom.neighbors() if not len(nn) == 2: raise RecognizerError("Pl5 should have exactly two neighbor atoms") for n1 in nn: if not n1.element.symbol in ('Ss5','Sj5'): raise RecognizerError("Pl5 neighbor %s should be Ss5 or Sj5" % n1) bases = map(Base5_recognizer, nn) # should always succeed return bases def _C_ordered_bases(self): """ [compute method for self.ordered_bases] Return our two bases (as Base5_recognizer objects, which may or may not be .in_helix), in an order consistent with backbone bond direction, which we require to be locally defined in a consistent way. @warning: value will be None (not a sequence) if a RecognizerError was raised. """ if self.unordered_bases is None: raise RecognizerError("doesn't have two bases") bases = list(self.unordered_bases) # we might destructively reverse this later, before returning it nn = bases[0].atom, bases[1].atom # reverse bases if bond directions go backwards, or complain if not defined or not consistent # (Note: the following code is mostly generic for pairs of directional bonds, # so we might package it up into a utility function someday.) # BTW, in the future we should improve this as follows: # - find directional-bond strands in both directions, including at least one bond not altered # when making/unmaking a crossover, and ending on the first bond with direction defined, # or when you have to end due to error (too far away to stop us) or end of strand. # - require that this gave you a direction and was not inconsistent. # - when making the crossover later, actually set all those directions you passed over # (not just those of your new bonds). dir1 = bond_direction(nn[0], self.atom) # -1 or 0 or 1 dir2 = bond_direction(self.atom, nn[1]) dirprod = dir1 * dir2 if dirprod < 0: # both directions are set, and they're inconsistent raise RecognizerError("inconsistent bond directions") # including self.atom in the message would be redundant -- compute method glue will annotate with self ###DOIT elif dirprod > 0: # both directions are set, consistently if dir1 < 0: bases.reverse() else: # dirprod == 0 # at most one direction is set (need a warning if one is set and one not? assume not, for now) dir = dir1 + dir2 if dir < 0: bases.reverse() elif dir == 0: # both directions are unset raise RecognizerError("backbone bond direction is locally undefined") ###REVIEW: this should not prevent offering "Make Crossover", only doing it successfully. return bases def _C_strand_direction_well_defined(self): """ [compute method for self.strand_direction_well_defined] ###doc """ return self.ordered_bases is not None ## def _C_in_crossover(self): ## "Say whether we bridge bases in different double helices" ## # hmm, that's not enough to "be in a crossover"! but it's necessary. rename? just let caller use not thing.in_only_one_helix? ## nim def _C_in_only_one_helix(self): """ [compute method for self.in_only_one_helix] Say whether we're in one helix. (And return that helix? No -- we don't yet have anything to represent it with. Maybe return the involved atoms? For that, see _C_involved_atoms_for_create_crossover.) """ ###REVIEW: is it good for self.unordered_bases to be None (not a sequence) on certain kinds of error? # And, when that happens, is it right for this to return False (not True, not an exception)? return self.unordered_bases is not None and bases_are_stacked(self.unordered_bases) def _C_involved_atoms_for_make_crossover(self): """ [compute method for self.involved_atoms_for_make_crossover] Compute a set of atoms directly involved in using self to make a new crossover. Two Pl atoms will only be allowed to be in a newly made crossover if (among other things) their sets of involved atoms don't overlap. Require that these atoms are each in one helix. """ if not self.in_only_one_helix: raise RecognizerError("Pl5 atom must be in_only_one_helix") res = self._involved_atoms_for_make_or_remove_crossover if not len(res) == 5: # can this ever fail due to a structural error?? actually it can -- Ax atoms can be the same raise RecognizerError("structural error (two bases on one Pl and one Ax??)") return res def _C_involved_atoms_for_remove_crossover(self): #bruce 070604 """ #doc """ # seems like we need to check some of what the other method checks, like len 5 -- not sure -- guess yes for now res = self._involved_atoms_for_make_or_remove_crossover if not len(res) == 5: raise RecognizerError("structural error (two bases on one Pl and one Ax? missing Ax?)") return res def _C__involved_atoms_for_make_or_remove_crossover(self): """ [private: compute method for private attr, self._involved_atoms_for_make_or_remove_crossover] """ # KLUGE: the answer happens to be the same for both ops. This might change in the future if they check more # of the nearby bases (not sure). res = {} def include(atom): res[atom] = atom include(self.atom) for b in self.unordered_bases: include(b.atom) if b.axis_atom is not None: # otherwise not self.in_only_one_helix, but for _remove_ case we don't know that include(b.axis_atom) return res pass # Pl5_recognizer # == def remove_crossover(twoPls): assert len(twoPls) == 2 for pl in twoPls: assert isinstance(pl, Pl5_recognizer) assert remove_crossover_ok(twoPls) make_or_remove_crossover(twoPls, make = False, cmdname = "Remove Crossover") return def make_crossover(twoPls): assert len(twoPls) == 2 for pl in twoPls: assert isinstance(pl, Pl5_recognizer) assert make_crossover_ok(twoPls) make_or_remove_crossover(twoPls, make = True, cmdname = "Make Crossover") return def make_or_remove_crossover(twoPls, make = True, cmdname = None): """ Make or Remove (according to make option) a crossover, given Pl5_recognizers for its two Pl atoms. """ # What we are doing is recognizing one local structure and replacing it with another # made from the same atoms. It'd sure be easier if I could do the manipulation in an mmp file, # save that somewhere, and read those to generate the operation! I'd have two sets of atoms, before and after, # and see how bonds and atomtypes got changed. # In this case it's not too hard to hand-code... I guess only the Pl atoms and their bonds are affected. # We probably do have to look at strand directions -- hmm, probably we should require them to exist before saying it's ok! # Or maybe better to give history error message when the command is chosen, saying you need to set them (or repair them) first... # Then we have to move the new/moved Pl atoms into a good position... # Note: Pl.ordered_bases are ordered by bond direction, to make this easier... # but if we want to patch up the directions in the end, do we need to care exactly which ones were defined? # or only "per-Pl"? hmm... it's per-Pl for now assert cmdname for pl in twoPls: if pl.ordered_bases is None: # should no longer be possible -- now checked before menu commands are offered [bruce 070604] ###BUG: this could have various causes, not only the one reported below! Somehow we need access to the # message supplied to the RecognizerError, for use here. ###REVIEW: Does that mean it should pass through compute methods (probably in a controlled way) # rather than making computed values None? # Or, should the value not be None, but a "frozen" examinable and reraisable version of the error exception?? msg = "%s: Error: bond direction is locally undefined or inconsistent around %s" % (cmdname, pl.atom) ###UNTESTED print "should no longer be possible:", msg #bruce 070604 env.history.message( redmsg( quote_html( msg))) return Pl1, Pl2 = twoPls a,b = Pl1.ordered_bases d,c = Pl2.ordered_bases # note: we use d,c rather than c,d so that the atom arrangement is as shown in the diagram below. # Note: for either the Make or Remove operation, the geometric arrangement is initially: # # c <-- Pl2 <-- d # # a --> Pl1 --> b # # and it ends up being (where dots indicate arrowheads, to show bond direction): # # c d # . / # \ . # Pl1 Pl2 # . \ # / . # a b # # Note: Pl1 stays attached to a, and Pl2 to d. Which two opposite bonds to preserve like that # is an arbitrary choice -- as long as Make and Remove make the same choice about that, # they'll reverse each other's effects precisely (assuming the sugars were initially correct as Ss or Sj). # break the bonds we no longer want for obj1, obj2 in [(Pl1, b), (Pl2, c)]: bond = find_bond(obj1.atom, obj2.atom) bond.bust(make_bondpoints = False) # make the bonds we want and didn't already have for obj1, obj2 in [(Pl1, c), (Pl2, b)]: assert not atoms_are_bonded(obj1.atom, obj2.atom) ###e we should make bond_atoms do this assert itself, or maybe tolerate it (or does it already??) bond_atoms_faster(obj1.atom, obj2.atom, V_SINGLE) # set directions of all 4 bonds (even the preserved ones -- it's possible they were not set before, # if some but not all bonds had directions set in the part of a strand whose directions we look at.) for obj1, obj2 in [(a, Pl1), (Pl1, c), (d, Pl2), (Pl2, b)]: bond = find_bond(obj1.atom, obj2.atom) bond.set_bond_direction_from(obj1.atom, 1) # WARNING: after that bond rearrangement, don't use our Pl5_recognizers in ways that depend on Pl bonding, # since it's not well defined whether they think about the old or new bonding to give their answers. Pl_atoms = Pl1.atom, Pl2.atom del Pl1, Pl2, twoPls # transmute base sugars to Sj or Ss as appropriate if dna_updater_is_enabled(): want = Element_Ss5 #bruce 080320 bugfix else: want = make and Element_Sj5 or Element_Ss5 for obj in (a,b,c,d): obj.atom.Transmute(want) # Note: we do this after the bond making/breaking so it doesn't add singlets which mess us up. # move Pl atoms into better positions # (someday, consider using local minimize; for now, just place them directly between their new neighbor atoms, # hopefully we leave them selected so user can easily do their own local minimize.) for pl in Pl_atoms: pl.setposn( average_value( map( lambda neighbor: neighbor.posn() , pl.neighbors() ))) env.history.message( greenmsg( cmdname + ": ") + quote_html("(%s - %s)" % tuple(Pl_atoms))) #e need assy.changed()? evidently not. return # from make_or_remove_crossover # == ### TODO, someday: # - rename Recognizer? it's really more like Situational Perceiver... # # - btw we do want one for "any two Pl" to perceive whether to offer make or break of the crossover... # # - rename RecognizerError -- but to what? it's not even an error, more like "this attr is not well defined" or so... # WARNING: in this code, the recognizers don't notice changes in mutable input structures, # such as transmutes or even bonding changes. But they compute derived attributes lazily # using current (not cached on __init__) values of their input attrs. # # That means that the values of their derived attributes, after a mutable # change in an input structure, depends on whether those attrs (or intermediate attrs # used to compute them) were also computed before the input change. # old design comments: # think in terms of 3 base relations: paired base, stacked base, backbone-bonded base. two directions for some, one for other. # so, find bases, then look at them for patterns. # for phosphate find two bases (ie sugars), know they're backbone-bound, see if stacked or not (in right direction?) # end
NanoCAD-master
cad/src/dna/operations/crossovers.py
# Copyright 2008 Nanorex, Inc. See LICENSE file for details. """ ops_pam.py - PAM3+5 <-> PAM5 conversion operations @author: Bruce @version: $Id$ @copyright: 2008 Nanorex, Inc. See LICENSE file for details. """ from utilities.Log import greenmsg, redmsg, orangemsg from platform_dependent.PlatformDependent import fix_plurals import foundation.env as env from utilities.GlobalPreferences import debug_pref_enable_pam_convert_sticky_ends from utilities.GlobalPreferences import debug_pref_remove_ghost_bases_from_pam3 from dna.updater.dna_updater_globals import _f_baseatom_wants_pam from utilities.constants import MODEL_PAM3, MODEL_PAM5 from model.elements import Singlet, Pl5 # == class ops_pam_Mixin: """ Mixin class for providing these methods to class Part """ # these commands have toolbuttons: def convertPAM3to5Command(self): commandname = "Convert PAM3 to PAM5" which_pam = MODEL_PAM5 self._convert_selection_to_pam_model( which_pam, commandname) return def convertPAM5to3Command(self): commandname = "Convert PAM5 to PAM3" which_pam = MODEL_PAM3 self._convert_selection_to_pam_model( which_pam, commandname) return # these commands have no toolbuttons, for now, # and probably never should. For debugging (or in case they # are occasionally useful to users), they'll probably be given # debug menu commands. def convertPAM3to5_noghosts_Command(self): commandname = "Convert PAM3 to PAM5 no ghosts" which_pam = MODEL_PAM5 self._convert_selection_to_pam_model( which_pam, commandname, make_ghost_bases = False) return ## def convertPAM5to3_leaveghosts_Command(self): ## commandname = "Convert PAM5 to PAM3 leave ghosts" ## which_pam = MODEL_PAM3 ## self._convert_selection_to_pam_model( which_pam, commandname, remove_ghost_bases_from_PAM3 = False) ## return ## def makePlaceholderBasesCommand(self): ... # this command (to make ghost bases but do nothing else) # could be factored out from _convert_selection_to_pam_model below, # but not trivially, since all the history messages and # some of the return-since-no-work conditions need changes def _convert_selection_to_pam_model(self, which_pam, commandname = "", make_ghost_bases = True, # only implemented for PAM3, so far ## remove_ghost_bases_from_PAM3 = True ): #bruce 080413 """ Convert the selected atoms (including atoms into selected chunks), which don't have errors (in the atoms or their dnaladders), into the specified pam model (some, none, or all might already be in that pam model), along with all atoms in the same basepairs, but only for kinds of ladders for which conversion is yet implemented. Print summaries to history. This is a user operation, so the dna updater has run and knows which atoms are errors, knows ladders of atoms, etc. We take advantage of that to simplify the implementation. """ if not commandname: commandname = "Convert to %s" % which_pam # kluge, doesn't matter yet # find all selected atoms (including those in selected chunks) atoms = dict(self.selatoms) for chunk in self.selmols: atoms.update(chunk.atoms) if not atoms: env.history.message( greenmsg(commandname + ": ") + redmsg("Nothing selected.") ) return # expand them to cover whole basepairs -- use ladders to help? # (the atoms with errors are not in valid ladders, so that # is also an easy way to exclude those) num_atoms_with_good_ladders = 0 ladders = {} ghost_bases = {} # initially only holds PAM5 ghost bases for atom in atoms.itervalues(): try: ladder = atom.molecule.ladder except AttributeError: # for .ladder continue # not the right kind of atom, etc if not ladder or not ladder.valid: continue if ladder.error: continue if not ladder.strand_rails: # bare axis continue num_atoms_with_good_ladders += 1 ladders[ladder] = ladder # note: if atom is Pl, its Ss neighbors are treated specially # lower down in this method if atom.ghost and atom.element.pam == MODEL_PAM5: ghost_bases[atom.key] = atom continue orig_len_atoms = len(atoms) # for history messages, in case we add some # now iterate on the ladders, scanning their atoms to find the ones # in atoms, noting every touched baseindex # BUG: this does not notice Pls which are in atoms without either neighbor Ss being in atoms. # Future: fix by noticing them above in atom loop; see comment there. atoms_to_convert = {} ladders_to_inval = {} number_of_basepairs_to_convert = 0 number_of_unpaired_bases_to_convert = 0 ladders_needing_ghost_bases = {} # maps ladder to (ladder, list of indices) #bruce 080528 for ladder in ladders: # TODO: if ladder can't convert (nim for that kind of ladder), # say so as a summary message, and skip it. (But do we know how # many atoms in our dict it had? if possible, say that too.) # TODO: if ladder doesn't need to convert (already in desired model), # skip it. length = len(ladder) index_set = {} # base indexes in ladder of basepairs which touch our dict of atoms rails = ladder.all_rails() if len(ladder.strand_rails) not in (1, 2): continue for rail in rails: for ind in range(length): atom = rail.baseatoms[ind] if atom.key in atoms: # convert this base pair index_set[ind] = ind pass continue continue # conceivable that for some ladders we never hit them; # for now, warn but skip them in that case if not index_set: print "unexpected: scanned %r but found nothing to convert (only Pls selected??)" % ladder # env.history? else: if len(ladder.strand_rails) == 2: number_of_basepairs_to_convert += len(index_set) else: number_of_unpaired_bases_to_convert += len(index_set) # note: we do this even if the conversion will fail # (as it does initially for single strand domains), # since the summary error message from that is useful. if make_ghost_bases and ladder.can_make_ghost_bases(): # initially, this test rules out free floating single strands; # later we might be able to do this for them, which is why # we do the test using that method rather than directly. ladders_needing_ghost_bases[ladder] = (ladder, index_set.values()) # see related code in _cmd_convert_to_pam method # in DnaLadder_pam_conversion.py ladders_to_inval[ladder] = ladder if 0 in index_set or (length - 1) in index_set: for ladder2 in ladder.strand_neighbor_ladders(): # might contain Nones or duplicate entries if ladder2 is not None: ladders_to_inval[ladder2] = ladder2 # overkill if only one ind above was found for rail in rails: baseatoms = rail.baseatoms for ind in index_set: atom = baseatoms[ind] atoms_to_convert[atom.key] = atom # note: we also add ghost base atoms, below pass continue # next ladder if not atoms_to_convert: assert not number_of_basepairs_to_convert assert not number_of_unpaired_bases_to_convert assert not ladders_needing_ghost_bases if num_atoms_with_good_ladders < orig_len_atoms: # warn if we're skipping some atoms [similar code occurs twice in this method] msg = "%d atom(s) skipped, since not in valid, error-free DnaLadders" env.history.message( greenmsg(commandname + ": ") + orangemsg("Warning: " + fix_plurals(msg))) env.history.message( greenmsg(commandname + ": ") + redmsg("Nothing found to convert.") ) return # print a message about what we found to convert what1 = what2 = "" if number_of_basepairs_to_convert: what1 = fix_plurals( "%d basepair(s)" % number_of_basepairs_to_convert ) if number_of_unpaired_bases_to_convert: # doesn't distinguish sticky ends from free-floating single strands (fix?) what2 = fix_plurals( "%d unpaired base(s)" % number_of_unpaired_bases_to_convert ) if what1 and what2: what = what1 + " and " + what2 else: what = what1 + what2 env.history.message( greenmsg(commandname + ": ") + "Will convert %s ..." % what ) # warn if we're skipping some atoms [similar code occurs twice in this method] if num_atoms_with_good_ladders < orig_len_atoms: msg = "%d atom(s) skipped, since not in valid, error-free DnaLadders" env.history.message( orangemsg("Warning: " + fix_plurals(msg))) print "%s will convert %d atoms, touching %d ladders" % \ ( commandname, len(atoms_to_convert), len(ladders_to_inval) ) # make ghost bases as needed for this conversion (if enabled -- not by default since not yet working ####) # (this must not delete any baseatoms in atoms, or run the dna updater # or otherwise put atoms into different ladders, but it can make new # atoms in new chunks, as it does) if debug_pref_enable_pam_convert_sticky_ends(): for ladder, index_list in ladders_needing_ghost_bases.itervalues(): baseatoms = ladder.make_ghost_bases(index_list) # note: index_list is not sorted; that's ok # note: this makes them in a separate chunk, and returns them # as an atom list, but doesn't add the new chunk to the ladder. # the next dna updater run will fix that (making a new ladder # that includes all atoms in baseatoms and the old ladder). for ind in index_list: atom = baseatoms[ind] atoms_to_convert[atom.key] = atom # cause the dna updater (which would normally run after we return, # but is also explicitly run below) to do the rest of the conversion # (and report errors for whatever it can't convert) for ladder in ladders_to_inval: ladder._dna_updater_rescan_all_atoms() for atom in atoms_to_convert: _f_baseatom_wants_pam[atom] = which_pam # run the dna updater explicitly print "about to run dna updater for", commandname self.assy.update_parts() # not a part method # (note: this catches dna updater exceptions and turns them into redmsgs.) print "done with dna updater for", commandname if debug_pref_remove_ghost_bases_from_pam3(): # note: in commented out calling code above, this was a flag # option, remove_ghost_bases_from_PAM3; # that will be revived if we have a separate command for this. # # actually we only remove the ones we noticed as PAM5 above, # and succeeded in converting to PAM3. good = bad = 0 for atom in ghost_bases.values(): # must not be itervalues if atom.element.pam == MODEL_PAM3: good += 1 for n in atom.neighbors(): if n.is_ghost(): ghost_bases[n.key] = n else: bad += 1 del ghost_bases[atom.key] continue if good: print "removing %d ghost base(s) we converted to PAM3" % good if bad: print "leaving %d ghost base(s) we didn't convert to PAM3" % bad if not bool(good) == bool(ghost_bases): # should never happen print "bug: bool(good) != bool(ghost_bases), for", good, ghost_bases del good, bad if ghost_bases: for atom in ghost_bases.itervalues(): atom.kill() # todo: probably should use prekill code to avoid # intermediate bondpoint creation, even though there # are not usually a lot of atoms involved at once continue print "about to run dna updater 2nd time for", commandname self.assy.update_parts() print "done with dna updater 2nd time for", commandname pass env.history.message( greenmsg( commandname + ": " + "Done." )) self.assy.w.win_update() return pass # end of class ops_pam_Mixin # end
NanoCAD-master
cad/src/dna/operations/ops_pam.py
NanoCAD-master
cad/src/dna/operations/__init__.py
# Copyright 2008-2009 Nanorex, Inc. See LICENSE file for details. """ @author: Ninad @version: $Id$ @copyright: 2008-2009 Nanorex, Inc. See LICENSE file for details. History: 2008-08-07: Created. TODO: """ from PyQt4.Qt import QFont, QString import foundation.env as env from graphics.drawing.drawDnaLabels import draw_dnaBaseNumberLabels from commands.BuildAtoms.BuildAtoms_GraphicsMode import BuildAtoms_GraphicsMode _superclass = BuildAtoms_GraphicsMode class BreakOrJoinstrands_GraphicsMode(BuildAtoms_GraphicsMode): """ Common superclass for GraphicsMode classes of Break and Join Strands commands. @see: BreakStrand_GraphicsMode() @see: JoinStrands_GraphicsMode() """ def _drawLabels(self): """ Overrides superclass method """ _superclass._drawLabels(self) draw_dnaBaseNumberLabels(self.glpane) pass
NanoCAD-master
cad/src/dna/command_support/BreakOrJoinStrands_GraphicsMode.py
# Copyright 2008 Nanorex, Inc. See LICENSE file for details. """ @author: Urmi, Ninad @copyright: 2008 Nanorex, Inc. See LICENSE file for details. @version:$Id$ History: Ninad 2008-06-05: Revised and refactored code in JoinStrands_PropertyManager, and moved it to this class. """ from PyQt4.Qt import Qt from PyQt4.Qt import SIGNAL import foundation.env as env from command_support.Command_PropertyManager import Command_PropertyManager from PM.PM_GroupBox import PM_GroupBox from PM.PM_CheckBox import PM_CheckBox from PM.PM_ColorComboBox import PM_ColorComboBox from PM.PM_Constants import PM_DONE_BUTTON from PM.PM_Constants import PM_WHATS_THIS_BUTTON from utilities.prefs_constants import arrowsOnBackBones_prefs_key from utilities.prefs_constants import arrowsOnThreePrimeEnds_prefs_key from utilities.prefs_constants import arrowsOnFivePrimeEnds_prefs_key from utilities.prefs_constants import useCustomColorForThreePrimeArrowheads_prefs_key from utilities.prefs_constants import useCustomColorForFivePrimeArrowheads_prefs_key from utilities.prefs_constants import dnaStrandThreePrimeArrowheadsCustomColor_prefs_key from utilities.prefs_constants import dnaStrandFivePrimeArrowheadsCustomColor_prefs_key from widgets.prefs_widgets import connect_checkbox_with_boolean_pref from PM.PM_DnaBaseNumberLabelsGroupBox import PM_DnaBaseNumberLabelsGroupBox _superclass = Command_PropertyManager class BreakOrJoinStrands_PropertyManager(Command_PropertyManager): _baseNumberLabelGroupBox = None def __init__( self, command ): """ Constructor for the property manager. """ _superclass.__init__(self, command) self.showTopRowButtons( PM_DONE_BUTTON | \ PM_WHATS_THIS_BUTTON) return 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 # DNA Strand arrowhead display options signal-slot connections. self._connect_checkboxes_to_global_prefs_keys(isConnect) change_connect(self.fivePrimeEndColorChooser, SIGNAL("editingFinished()"), self.chooseCustomColorOnFivePrimeEnds) change_connect(self.threePrimeEndColorChooser, SIGNAL("editingFinished()"), self.chooseCustomColorOnThreePrimeEnds) change_connect(self.strandFivePrimeArrowheadsCustomColorCheckBox, SIGNAL("toggled(bool)"), self.allowChoosingColorsOnFivePrimeEnd) change_connect(self.strandThreePrimeArrowheadsCustomColorCheckBox, SIGNAL("toggled(bool)"), self.allowChoosingColorsOnThreePrimeEnd) self._baseNumberLabelGroupBox.connect_or_disconnect_signals(isConnect) return def show(self): """ Shows the Property Manager. Extends superclass method. @see: Command_PropertyManager.show() """ _superclass.show(self) #Required to update the color combobox for Dna base number labels. self._baseNumberLabelGroupBox.updateWidgets() def _connect_checkboxes_to_global_prefs_keys(self, isConnect = True): """ #doc """ if not isConnect: return #ORDER of items in tuples checkboxes and prefs_keys is IMPORTANT! checkboxes = ( self.arrowsOnThreePrimeEnds_checkBox, self.arrowsOnFivePrimeEnds_checkBox, self.strandThreePrimeArrowheadsCustomColorCheckBox, self.strandFivePrimeArrowheadsCustomColorCheckBox, self.arrowsOnBackBones_checkBox) prefs_keys = ( self._prefs_key_arrowsOnThreePrimeEnds(), self._prefs_key_arrowsOnFivePrimeEnds(), self._prefs_key_useCustomColorForThreePrimeArrowheads(), self._prefs_key_useCustomColorForFivePrimeArrowheads(), arrowsOnBackBones_prefs_key) for checkbox, prefs_key in zip(checkboxes, prefs_keys): connect_checkbox_with_boolean_pref(checkbox, prefs_key) return #Load various widgets ==================== def _loadBaseNumberLabelGroupBox(self, pmGroupBox): self._baseNumberLabelGroupBox = PM_DnaBaseNumberLabelsGroupBox(pmGroupBox, self.command) def _loadDisplayOptionsGroupBox(self, pmGroupBox): """ Load widgets in the display options groupbox """ title = "Arrowhead prefs in %s:"%self.command.featurename self._arrowheadPrefsGroupBox = PM_GroupBox( pmGroupBox, title = title) #load all the options self._load3PrimeEndArrowAndCustomColor(self._arrowheadPrefsGroupBox) self._load5PrimeEndArrowAndCustomColor(self._arrowheadPrefsGroupBox) self._loadArrowOnBackBone(pmGroupBox) return def _load3PrimeEndArrowAndCustomColor(self, pmGroupBox): """ Loads 3' end arrow head and custom color checkbox and color chooser dialog """ self.pmGroupBox3 = PM_GroupBox(pmGroupBox, title = "3' end:") self.arrowsOnThreePrimeEnds_checkBox = PM_CheckBox( self.pmGroupBox3, text = "Show arrowhead", widgetColumn = 0, setAsDefault = True, spanWidth = True ) self.strandThreePrimeArrowheadsCustomColorCheckBox = PM_CheckBox( self.pmGroupBox3, text = "Display custom color", widgetColumn = 0, setAsDefault = True, spanWidth = True) prefs_key = self._prefs_key_dnaStrandThreePrimeArrowheadsCustomColor() self.threePrimeEndColorChooser = \ PM_ColorComboBox(self.pmGroupBox3, color = env.prefs[prefs_key]) prefs_key = self._prefs_key_useCustomColorForThreePrimeArrowheads() if env.prefs[prefs_key]: self.strandThreePrimeArrowheadsCustomColorCheckBox.setCheckState(Qt.Checked) self.threePrimeEndColorChooser.show() else: self.strandThreePrimeArrowheadsCustomColorCheckBox.setCheckState(Qt.Unchecked) self.threePrimeEndColorChooser.hide() return def _load5PrimeEndArrowAndCustomColor(self, pmGroupBox): """ Loads 5' end custom color checkbox and color chooser dialog """ self.pmGroupBox2 = PM_GroupBox(pmGroupBox, title = "5' end:") self.arrowsOnFivePrimeEnds_checkBox = PM_CheckBox( self.pmGroupBox2, text = "Show arrowhead", widgetColumn = 0, setAsDefault = True, spanWidth = True ) self.strandFivePrimeArrowheadsCustomColorCheckBox = PM_CheckBox( self.pmGroupBox2, text = "Display custom color", widgetColumn = 0, setAsDefault = True, spanWidth = True ) prefs_key = self._prefs_key_dnaStrandFivePrimeArrowheadsCustomColor() self.fivePrimeEndColorChooser = \ PM_ColorComboBox(self.pmGroupBox2, color = env.prefs[prefs_key] ) prefs_key = self._prefs_key_useCustomColorForFivePrimeArrowheads() if env.prefs[prefs_key]: self.strandFivePrimeArrowheadsCustomColorCheckBox.setCheckState(Qt.Checked) self.fivePrimeEndColorChooser.show() else: self.strandFivePrimeArrowheadsCustomColorCheckBox.setCheckState(Qt.Unchecked) self.fivePrimeEndColorChooser.hide() return def _loadArrowOnBackBone(self, pmGroupBox): """ Loads Arrow on the backbone checkbox """ self.pmGroupBox4 = PM_GroupBox(pmGroupBox, title = "Global preference:") self.arrowsOnBackBones_checkBox = PM_CheckBox( self.pmGroupBox4, text = "Show arrows on back bones", widgetColumn = 0, setAsDefault = True, spanWidth = True ) return def allowChoosingColorsOnFivePrimeEnd(self, state): """ Show or hide color chooser based on the strandFivePrimeArrowheadsCustomColorCheckBox's state """ if self.strandFivePrimeArrowheadsCustomColorCheckBox.isChecked(): self.fivePrimeEndColorChooser.show() else: self.fivePrimeEndColorChooser.hide() return def allowChoosingColorsOnThreePrimeEnd(self, state): """ Show or hide color chooser based on the strandThreePrimeArrowheadsCustomColorCheckBox's state """ if self.strandThreePrimeArrowheadsCustomColorCheckBox.isChecked(): self.threePrimeEndColorChooser.show() else: self.threePrimeEndColorChooser.hide() return def chooseCustomColorOnThreePrimeEnds(self): """ Choose custom color for 3' ends """ color = self.threePrimeEndColorChooser.getColor() prefs_key = self._prefs_key_dnaStrandThreePrimeArrowheadsCustomColor() env.prefs[prefs_key] = color self.win.glpane.gl_update() return def chooseCustomColorOnFivePrimeEnds(self): """ Choose custom color for 5' ends """ color = self.fivePrimeEndColorChooser.getColor() prefs_key = self._prefs_key_dnaStrandFivePrimeArrowheadsCustomColor() env.prefs[prefs_key] = color self.win.glpane.gl_update() return #Return varius prefs_keys for arrowhead display options ui elements ======= def _prefs_key_arrowsOnThreePrimeEnds(self): """ Return the appropriate KEY of the preference for whether to draw arrows on 3' strand ends of PAM DNA. """ return arrowsOnThreePrimeEnds_prefs_key def _prefs_key_arrowsOnFivePrimeEnds(self): """ Return the appropriate KEY of the preference for whether to draw arrows on 5' strand ends of PAM DNA. """ return arrowsOnFivePrimeEnds_prefs_key def _prefs_key_useCustomColorForThreePrimeArrowheads(self): """ Return the appropriate KEY of the preference for whether to use a custom color for 3' arrowheads (if they are drawn) or for 3' strand end atoms (if arrowheads are not drawn) """ return useCustomColorForThreePrimeArrowheads_prefs_key def _prefs_key_useCustomColorForFivePrimeArrowheads(self): """ Return the appropriate KEY of the preference for whether to use a custom color for 5' arrowheads (if they are drawn) or for 5' strand end atoms (if arrowheads are not drawn). """ return useCustomColorForFivePrimeArrowheads_prefs_key def _prefs_key_dnaStrandThreePrimeArrowheadsCustomColor(self): """ Return the appropriate KEY of the preference for what custom color to use when drawing 3' arrowheads (if they are drawn) or 3' strand end atoms (if arrowheads are not drawn). """ return dnaStrandThreePrimeArrowheadsCustomColor_prefs_key def _prefs_key_dnaStrandFivePrimeArrowheadsCustomColor(self): """ Return the appropriate KEY of the preference for what custom color to use when drawing 5' arrowheads (if they are drawn) or 5' strand end atoms (if arrowheads are not drawn). """ return dnaStrandFivePrimeArrowheadsCustomColor_prefs_key
NanoCAD-master
cad/src/dna/command_support/BreakOrJoinStrands_PropertyManager.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-08-06: refactored Break and Join Strands commands to create this new class TODO: """ import foundation.env as env from commands.BuildAtoms.BuildAtoms_Command import BuildAtoms_Command from utilities.exception_classes import AbstractMethod from utilities.constants import CL_SUBCOMMAND _superclass = BuildAtoms_Command class BreakOrJoinStrands_Command(BuildAtoms_Command): """ A superclass for Break Strands and Join Strands commands """ #Property Manager class (overridden in subclasses) PM_class = None #Flyout toolbar class FlyoutToolbar_class = None command_level = CL_SUBCOMMAND command_parent = 'BUILD_DNA' __abstract_command_class = True #bruce 080905 command_should_resume_prevMode = True command_has_its_own_PM = True flyoutToolbar = None def _getFlyoutToolBarActionAndParentCommand(self): """ See superclass for documentation. @see: self.command_update_flyout() """ flyoutActionToCheck = self._get_init_gui_flyout_action_string() parentCommandName = None return flyoutActionToCheck, parentCommandName def _get_init_gui_flyout_action_string(self): raise AbstractMethod def command_enter_misc_actions(self): """ Overrides superclass method. See superclass for documentation. """ pass def command_exit_misc_action(self): """ Overrides superclass method. See superclass for documentation. """ pass def keep_empty_group(self, group): """ Returns True if the empty group should not be automatically deleted. otherwise returns False. The default implementation always returns False. Subclasses should override this method if it needs to keep the empty group for some reasons. Note that this method will only get called when a group has a class constant autdelete_when_empty set to True. (and as of 2008-03-06, it is proposed that dna_updater calls this method when needed. @see: Command.keep_empty_group() which is overridden here. """ bool_keep = _superclass.keep_empty_group(self, group) if not bool_keep: #Lets just not delete *ANY* DnaGroup while in BreakStrands_Command #Although BreakStrands command can only be accessed through #BuildDna_EditCommand, it could happen (due to a bug) that the #previous command is not BuildDna_Editcommand. So bool_keep #in that case will return False propmting dna updater to even delete #the empty DnaGroup (if it becomes empty for some reasons) of the #BuildDna command. To avoid this ,this method will instruct # to keep all instances of DnaGroup even when they might be empty. if isinstance(group, self.assy.DnaGroup): bool_keep = True return bool_keep
NanoCAD-master
cad/src/dna/command_support/BreakOrJoinStrands_Command.py
NanoCAD-master
cad/src/dna/command_support/__init__.py
# Copyright 2008 Nanorex, Inc. See LICENSE file for details. """ @author: Ninad @copyright: 2008 Nanorex, Inc. See LICENSE file for details. @version:$Id$ History: TODO: - See items in EditCommand_StructureList """ from utilities.Comparison import same_vals from command_support.EditCommand_StructureList import EditCommand_StructureList _superclass = EditCommand_StructureList class DnaSegmentList(EditCommand_StructureList): """ DnaSegmentList class provides an object that acts as a self.struct object for MultipleDnaSegmentResize_EditCommand. It maintains an internal list of structures (self._structList) which it loops through while resizing multiple segments at once. """ def getBasesPerTurn(self): """ Returns the bases per turn for the currentStucture of self's editcommand. """ assert self.editCommand.currentStruct return self.editCommand.currentStruct.getBasesPerTurn() def getDuplexRise(self): """ Returns the duplex rise for the currentStucture of self's editcommand. """ if self.editCommand.currentStruct: return self.editCommand.currentStruct.getDuplexRise() if not self._structList: return 3.18 firstSegment = self._structList[0] return firstSegment.getDuplexRise() def getNumberOfBasePairs(self): """ Returns the number of bae pairs (basepairs) per turn for the currentStucture of self's editcommand. """ if self.editCommand.currentStruct: return self.editCommand.currentStruct.getNumberOfBasePairs() if not self._structList: return 0 firstSegment = self._structList[0] return firstSegment.getNumberOfBasePairs() def getAxisEndAtomAtPosition(self, position): """ Returns the axis end atom of the 'currentStruct' of self's editCommand, at the given position. Example: If there are 4 Dnasegments being resized at the same time, the two resize handles will be at the average end positions. When you resize these segments using , for example , the right handle, it loops through the individual segments to resize those. While doing these, it needs to know the resize end axis atom. How to get that information? In self.updateAverageEndPoints() (which is called earlier), we create two lists for each end. Example: all end1 points are in self.endPoint_1_list (including their average end point which is self.end1) . So in this routine, we determine which of the list to use based on <position> (which is either of the average end points i.e. self.end1 or self.end2) and then check which of the endPoints of the editCommand's currentStruct lies in this list. @TODO: This method will be SLOW if there are large number of structures being edited at once (i.e. large self._structList) . Needs revision. Needs revision. We can't use a dictionary because dict.key cant be a Vector object (example dict[key] != ([1.0, 2.0, 3.0])) see the disabled code that tried to use has_key of dict. Need to come up with a better search algorithm. """ new_position = None for end in (self.end1, self.end2): if same_vals(position, end): if same_vals(end, self.end1): lst = self.endPoints_1 else: lst = self.endPoints_2 for e in self.editCommand.currentStruct.getAxisEndPoints(): for pos in lst: if same_vals(pos, e): new_position = e break if new_position is not None: break ##if e in lst: ##new_position = e ##break ##if self.endPointsDict.has_key(position): ##for end in self.editCommand.currentStruct.getAxisEndPoints(): ##if end in self.endPointsDict[position]: ##new_position = end ##break if new_position is not None: return self.editCommand.currentStruct.getAxisEndAtomAtPosition( new_position) return None def is_PAM3_DnaSegment(self): """ Returns True if all segments in self._structList are PAM3 dna segments @see: DnaSegment.is_PAM3_DnaSegment() """ if not self._structList: return False for segment in self._structList: if not segment.is_PAM3_DnaSegment(): return False return True def getOtherAxisEndAtom(self, atom_at_one_end): """ Returns the axis atom at the other end of the DnaSegment The DnaSegment object being 'currentStruct' of self's editCommand. """ return self.editCommand.currentStruct.getOtherAxisEndAtom( atom_at_one_end) def getAxisEndAtoms(self): """ Returns the axis end atoms of the DnaSegment. The DnaSegment object being 'currentStruct' of self's editCommand. """ if self.editCommand.currentStruct: return self.editCommand.currentStruct.getAxisEndAtoms() if not self._structList: return None, None #If there is no 'currentStruct' of self's editcommand, just return #the axis end atoms of the first segment in the list as a fall back. #(Caller should be careful in specifying currentStruct attr ) firstSegment = self._structList[0] return firstSegment.getAxisEndAtoms()
NanoCAD-master
cad/src/dna/command_support/DnaSegmentList.py
# Copyright 2007-2008 Nanorex, Inc. See LICENSE file for details. """ DnaGroup.py - ... @author: Bruce @version: $Id$ @copyright: 2007-2008 Nanorex, Inc. See LICENSE file for details. """ from foundation.Group import Group from utilities.constants import gensym from utilities.icon_utilities import imagename_to_pixmap from dna.updater.dna_updater_globals import _f_DnaGroup_for_homeless_objects_in_Part from utilities import debug_flags from utilities.debug import print_compact_stack class DnaGroup(Group): """ Model object which packages together some Dna Segments, Dna Strands, and other objects needed to represent all their PAM atoms and markers. Specific kinds of Group member contents include: - DnaStrands (optionally inside Groups) - DnaSegments (ditto) - Groups (someday might be called Blocks when they occur in this context; note that class Block is deprecated and should not be used for these) - DnaMarkers (a kind of Jig, always inside an owning DnaStrand or DnaSegment) - specialized chunks for holding PAM atoms: - DnaAxisChunk (these live inside the DnaSegments they belong to) - DnaStrandChunk (these live inside their DnaStrands) As other attributes: - whatever other properties the user needs to assign, which are not covered by the member nodes or superclass attributes. [nim?] """ # The iconPath specifies path(string) of an icon that represents the # objects of this class iconPath = "modeltree/DNA.png" hide_iconPath = "modeltree/DNA-hide.png" # This should be a tuple of classifications that appear in # files_mmp._GROUP_CLASSIFICATIONS, most general first. # See comment in class Group for more info. [bruce 080115] _mmp_group_classifications = ('DnaGroup',) # Open/closed state of the Dna Group in the Model Tree -- # default closed. open = False autodelete_when_empty = True # (but only if current command permits that for this class -- # see comment near Group.autodelete_when_empty for more info, # and implems of Command.keep_empty_group) def node_icon(self, display_prefs): """ Model Tree node icon for the dna group node @see: Group.all_content_is_hidden() """ del display_prefs # unused if self.all_content_is_hidden(): return imagename_to_pixmap( self.hide_iconPath) else: return imagename_to_pixmap( self.iconPath) def make_DnaStrandOrSegment_for_marker(self, controlling_marker): # review: wholechain arg needed? @@@ """ The given DnaMarker is either newly made to control a wholechain, or old but newly controlling it; but it has no DnaStrandOrSegment. Make and return a new DnaStrand or DnaSegment (ask marker what class to use) inside self (review: inside some Group inside self?), perhaps making use of info in controlling_marker to help decide how to initialize some of its attributes. (Assume calling code will later move all chunks and markers from marker's wholechain into the new DnaStrandOrSegment, and will store references to it as needed into controlling_marker and/or its wholechain, so don't do those things here.) """ assert not self.killed(), \ "self must not be killed in %r.make_DnaStrandOrSegment_for_marker" % self class1 = controlling_marker.DnaStrandOrSegment_class() name = gensym(class1.__name__.split('.')[-1], self.assy) ###STUB -- should use class constant prefix # todo: sensible name? (if we split a seg, is name related to old seg; if so how?) assy = controlling_marker.assy # it's a Jig so it has one obj = class1(name, assy, None) # note: these args are for Group.__init__ self.addchild(obj) # note: this asserts self.assy is not None # (but it can't assert not self.killed(), see its comment for why) return obj # Note: some methods below this point are examples or experiments or stubs, # and are likely to be revised significantly or replaced. # [bruce 080115 comment] # example method: def get_segments(self): """ Return a list of all our DnaSegment objects. """ return self.get_topmost_subnodes_of_class(self.assy.DnaSegment) def addSegment(self, segment): """ Adds a new segment object for this dnaGroup. @param segment: The DnaSegment to be added to this DnaGroup object @type: B{DnaSegment} """ self.addchild(segment) def getProps(self): """ Method to support Dna duplex editing. see Group.__init__ for a comment THIS IS THE DEFAULT IMPLEMENTATION. TO BE MODIFIED """ #Should it supply the Dna Segment list (children) and then add #individual segments when setProps is called?? # [probably not; see B&N email discussion from when this comment was added] if self.editCommand: props = () return props def setProps(self, props): """ Method to support Dna duplex editing. see Group.__init__ for a comment THIS IS THE DEFAULT IMPLEMENTATION. TO BE MODIFIED """ #Should it accept the Dna Segment list and then add individual segments? pass def edit(self): """ @see: Group.edit() """ commandSequencer = self.assy.w.commandSequencer commandSequencer.userEnterCommand('BUILD_DNA', always_update = True) currentCommand = commandSequencer.currentCommand assert currentCommand.commandName == 'BUILD_DNA' currentCommand.editStructure(self) def getDnaSequence(self, format = 'CSV'): """ Return the complete Dna sequence information string (i.e. all strand sequences) in the specified format. @return: The Dna sequence string @rtype: string """ if format == 'CSV':#comma separated values. separator = ',' dnaSequenceString = '' strandList = self.getStrands() for strand in strandList: dnaSequenceString = dnaSequenceString + strand.name + separator strandSequenceString = str(strand.getStrandSequence()) if strandSequenceString: strandSequenceString = strandSequenceString.upper() dnaSequenceString = dnaSequenceString + strandSequenceString dnaSequenceString = dnaSequenceString + "\n" return dnaSequenceString def getStrands(self): """ Returns a list of strands inside a DnaGroup object @return: A list containing all the strand objects within self. @rtype: list @see: B{BuildDna_PropertyManager.updateStrandListWidget()} @see: B{BuildDna_PropertyManager._currentSelectionParams} """ #TO BE REVISED. As of 2008-01-17, it uses isinstance check for #Chunk and some additional things to find out a list of strands inside # a DnaGroup -- Ninad 2008-01-17 if self.assy is None: #This is to avoid possible bugs if group gets deleted. But print #traceback so that we know about this bug. This could happen due to #insufficient command sequencer stack. Temporary fix for bug 2699 print_compact_stack("bug: self.assy is None for DnaGroup %s."%self) return () strandList = [] def filterStrands(node): if isinstance(node, self.assy.DnaStrand) and not node.isEmpty(): strandList.append(node) elif isinstance(node, self.assy.Chunk) and node.isStrandChunk(): if node.parent_node_of_class(self.assy.DnaStrand) is None: strandList.append(node) self.apply2all(filterStrands) return strandList def getAxisChunks(self): """ Returns a list of Axis chunks inside a DnaGroup object @return: A list containing all the axis chunks within self. @rtype: list """ if self.assy is None: #This is to avoid possible bugs if group gets deleted. But print #traceback so that we know about this bug. This could happen due to #insufficient command sequencer stack. Temporary fix for bug 2699 print_compact_stack("bug: self.assy is None for DnaGroup %s."%self) return () #TO BE REVISED. It uses isinstance check for #Chunk and some additional things to find out a list of strands inside # a DnaGroup -- Ninad 2008-02-02 axisChunkList = [] def filterAxisChunks(node): if isinstance(node, self.assy.Chunk) and node.isAxisChunk(): axisChunkList.append(node) self.apply2all(filterAxisChunks) return axisChunkList def isEmpty(self): """ Returns True if there are no axis or strand chunks as its members (Returns True even when there are empty DnaSegment objects inside) TODO: It doesn't consider other possibilitis such as hairpins . In general it relies on what getAxisChunks and getStrands returns (which in turn use 'Chunk' object to determine these things.) This method must be revised in the near future in a fully functional dna data model @see: BuildDna_EditCommand._finalizeStructure where this test is used. """ #May be for the short term, we can use self.getAtomList()? But that #doesn't ensure if the DnaGroup always has atom of type either #'strand' or 'axis' . if len(self.getStrands()) == 0 and len(self.getAxisChunks()) == 0: return True else: return False def getSelectedStrands(self): """ Returns a list of selected strands of the DnaGroup @return: A list containing the selected strand objects within self. @rtype: list """ selectedStrandList = [] for strand in self.getStrands(): if strand.picked: selectedStrandList.append(strand) return selectedStrandList def getSelectedSegments(self): """ Returns a list of segments whose all members are selected. @return: A list containing the selected strand objects within self. @rtype: list """ #TODO: This is a TEMPORARY KLUDGE until Dna model is fully functional. #Must be revised. Basically it returns a list of DnaSegments whose #all members are selected. #See BuildDna_PropertyManager._currentSelectionParams() where it is used #-- Ninad 2008-01-18 segmentList = self.get_segments() selectedSegmentList = [] for segment in segmentList: pickedNodes = [] unpickedNodes = [] def func(node): if isinstance(node, self.assy.Chunk): if not node.picked: unpickedNodes.append(node) else: pickedNodes.append(node) segment.apply2all(func) if len(unpickedNodes) == 0 and pickedNodes: selectedSegmentList.append(segment) return selectedSegmentList def getAtomList(self): """ Return a list of all atoms cotained within this DnaGroup """ atomList = [] def func(node): if isinstance(node, self.assy.Chunk): atomList.extend(node.atoms.itervalues()) self.apply2all(func) return atomList def draw_highlighted(self, glpane, color): """ Draw the strand and axis chunks as highlighted. (Calls the related methods in the chunk class) @param: GLPane object @param color: The highlight color @see: Chunk.draw_highlighted() @see: SelectChunks_GraphicsMode.draw_highlightedChunk() @see: SelectChunks_GraphicsMode._get_objects_to_highlight() """ for c in self.getStrands(): c.draw_highlighted(glpane, color) for c in self.getAxisChunks(): c.draw_highlighted(glpane, color) pass # end of class DnaGroup # == def find_or_make_DnaGroup_for_homeless_object(node): """ All DNA objects found outside of a DnaGroup during one run of the dna updater in one Part should be put into one new DnaGroup at the end of that Part. This is a fallback, since it only happens if we didn't sanitize DnaGroups when reading a file, or due to bugs in Dna-related user ops, or a user running an ordinary op on DNA that our UI is supposed to disallow. So don't worry much about prettiness, just correctness, though don't gratuitously discard info. The hard part is "during one run of the dna updater". We'll let it make a global dict from Part to this DnaGroup, and discard it after every run (so no need for this dict to be weak-keyed). If we have to guess the Part, we'll use the node's assy's current Part (but complain, since this probably indicates a bug). """ part = node.part or node.assy.part assert part if not node.part: print "likely bug: %r in %r has no .part" % \ (node, node.assy) try: res = _f_DnaGroup_for_homeless_objects_in_Part[part] except KeyError: res = None if res: # found one -- make sure it's still ok # maybe: also make sure it's still in the same part, assy, etc. # (not urgent, now that this only lasts for one run of the updater) if res.killed(): # discard it, after complaining [bruce 080218 bugfix for when this # got killed by user; works, but now should never happen due to the # better fix of calling clear_updater_run_globals() at start and end # of every updater run] print "\nBUG: _f_DnaGroup_for_homeless_objects_in_Part[%r] " \ "found %r which is killed -- discarding it" % \ (part, res) res = None if not res: res = _make_DnaGroup_for_homeless_objects_in_Part(part) _f_DnaGroup_for_homeless_objects_in_Part[part] = res return res def _make_DnaGroup_for_homeless_objects_in_Part(part): # not needed, done in addnode: part.ensure_toplevel_group() assy = part.assy #k name = gensym("DnaGroup", assy) #bruce 080407 remove "fallback", pass assy dad = None dnaGroup = DnaGroup(name, assy, dad) # same args as for Group.__init__ part.addnode(dnaGroup) if debug_flags.DEBUG_DNA_UPDATER: print "dna_updater: made new dnaGroup %r" % dnaGroup, \ "(bug or unfixed mmp file)" return dnaGroup # end
NanoCAD-master
cad/src/dna/model/DnaGroup.py
# Copyright 2008 Nanorex, Inc. See LICENSE file for details. """ WholeChain.py - a complete chain or ring of PAM atoms, made of one or more smaller chains (or 1 smaller ring) often known as rails (short for ladder rails, referring to DnaLadder), with refs to markers and a strand or segment @author: Bruce @version: $Id$ @copyright: 2008 Nanorex, Inc. See LICENSE file for details. """ from dna.model.dna_model_constants import LADDER_END0 from dna.model.dna_model_constants import LADDER_END1 from dna.model.DnaMarker import DnaMarker # for isinstance from dna.model.DnaMarker import DnaSegmentMarker # constructor from dna.model.DnaMarker import DnaStrandMarker # constructor from utilities.debug import print_compact_traceback from utilities.debug import print_compact_stack class WholeChain(object): """ A WholeChain knows a sequence of 1 or more rails, i.e. smaller chains (of DNA PAM atoms) which are linked into a single longer chain or ring (or which were so linked when it was constructed). (If it's not a ring, then it is required to be a maximal chain, i.e. to not be able to be extended with more atoms at the ends, at the time it's constructed.) It is immutable once constructed, as are its rails. Modifications to the underlying chaining from which it and its rails are derived result in its becoming invalid (in various ways needed by different users of it) and (for some of those users) replaced by one or more newly constructed wholechains. Its jobs and role in the DNA Data Model include: - Understand base indexing for any whole segment or strand. - Be able to find (and/or keep track of) all the DnaMarkers along its atoms. - Help a DnaMarker scan its atoms to decide where to move to, and help it actually move. - Decide which marker should determine strand or segment identity and base indexing scheme for the atoms in this wholechain (if it's valid). Markers might contain user-settable attributes (or inherit those from their owning strand or segment) to know how to do this, e.g. a higher or lower priority in controlling base indexing, policies for which direction to move in and how to adjust base index when moving, how to move when new bases are inserted (detectable if these go between the two marker atoms), etc. [### todo: say some of that on DnaMarker docstring] Specialized kinds of markers might serve as, for example, startpoints or endpoints of sequence constraints, or good places for a base index discontinuity in a ring (if the index origin should not be used). Invariants, and how it maintains them: - At any given time, just after any dna updater run, the valid WholeChains are in 1-1 correspondence with the set of DnaSegment and DnaStrand objects, via their controlling markers. - Just after any dna updater run, each WholeChain knows about the DnaMarkers on its atoms, of which there are one or more, with exactly one being a "controlling marker", which determines the identity of the DnaSegment and DnaStrand object which own the wholechain's atoms, and determines the base indexing scheme they use (origin and direction). - When things change (i.e. when user operations make wholechains invalid), and the dna updater runs again (always before the next undo checkpoint takes its snapshot of the model state), the dna updater (and methods in the markers and wholechains) decide how to maintain this association (wholechain -> controlling marker -> owning strand or segment) based on how the controlling marker moves and whether it stays / stops being / becomes controlling. (The wholechain chooses or makes a new controlling marker as needed for this.) - To do this, the wholechain uses the now-invalid wholechains to help it figure out when and how to modify existing DnaSegment or DnaStrand objects, and/or delete them or make new ones. (It does this mainly by moving DnaMarkers whose atoms got deleted to new locations (of non-deleted atoms) along their old wholechains, and then having new wholechains decide which markers should determine their strand's or segment's identity, by being the wholechain's one "controlling marker".) State: - A WholeChain contains no state for undo/copy/save; that's in the associated DnaSegment and DnaStrand objects and their DnaMarkers. (The set of DnaMarkers belonging to a DnaSegment and DnaStrand object is the same as the set of all the valid markers along its wholechain's atoms.) """ # default values of subclass-specific constants _DnaMarker_class = None # class of DnaMarker to make # default values of instance variables _strand_or_segment = None _controlling_marker = None _num_bases = -1 # unknown, to start with (used in __repr__ and __len__) _all_markers = () # in instances, will be a mutable dict # (len is used in __repr__; could be needed before __init__ done) def __init__(self, dict_of_rails): # fyi: called by update_PAM_chunks """ Construct self, own our chunks (and therefore our atoms). @note: this does not choose or make a marker or own our markers. For that see own_markers. @param dict_of_rails: maps id(rail) -> rail for all rails in wholechain @note: we can assume that rail._f_update_neighbor_baseatoms() has already been called (during this run of the dna updater) for every rail (preexisting or new) in dict_of_rails. Therefore it is ok for us to rely on rail.neighbor_baseatoms being set and correct for those rails, but conversely it is too late to use that info in any old wholechains of markers. """ assert dict_of_rails, "a WholeChain can't be empty" self._dict_of_rails = dict_of_rails self.ringQ = (len(self.end_baseatoms()) == 0) # 080311 # Scan all our atoms, for several reasons. # One is to find all the DnaMarkers on them. # These markers may have moved along their old wholechain, # and even if they didn't, they may no longer be on a pair of # adjacent atoms on the same wholechain, so don't assume they are. # (E.g. we might find one with one atom on self and the other on some # other wholechain.) For each marker we find, figure out whether it's # still valid, record its position if so, kill it if not. markers_1 = {} # collects markers from all our atoms during loop, maps them to (rail, baseindex) for their marked_atom markers_2 = {} # same, but for their next_atom (helps check whether they're still valid, and compute new position) num_bases = 0 end0_baseatoms = self._end0_baseatoms = {} # end0 atom key -> rail (aka chain) end1_baseatoms = self._end1_baseatoms = {} for rail in dict_of_rails.itervalues(): baseatoms = rail.baseatoms assert baseatoms num_bases += len(baseatoms) end0_baseatoms[baseatoms[0].key] = rail end1_baseatoms[baseatoms[-1].key] = rail chunk = baseatoms[0].molecule chunk.set_wholechain(self) for baseindex in range(len(baseatoms)): atom = baseatoms[baseindex] for jig in atom.jigs: # note: this is only correct because marker move step1 has # found new atoms for them (or reconfirmed old ones), and # has called marker.setAtoms to ensure they are recorded # on those atoms. if isinstance(jig, DnaMarker): marker = jig assert not marker.killed(), "marker %r is killed" % ( marker, ) # might fail if they're not yet all in the model @@@ # someday: possible optim: cache the set of markers on each rail # (and maintain it as markers move)? # might matter when lots of old rails. if marker.marked_atom is atom: markers_1[marker] = (rail, baseindex) if marker.next_atom is atom: # not elif, both can be true markers_2[marker] = (rail, baseindex) continue self._num_bases = num_bases # kill markers we only found on one of their atoms # or that are not on adjacent atoms in self, # and determine and record position for the others # [revised 080311] markers = {} # maps markers found on both atoms to (atom1info, atom2info), # but values are later replaced with PositionInWholeChains or discarded for marker in markers_1.iterkeys(): if not marker in markers_2: marker._f_kill_during_move(self, "different wholechains") else: markers[marker] = (markers_1[marker], markers_2.pop(marker)) continue for marker in markers_2.iterkeys(): # note the markers_2.pop above marker._f_kill_during_move(self, "different wholechains") continue del markers_1, markers_2 for marker in markers.keys(): # figure out new position and direction, # store it in same dict (or remove marker if invalid) # LOGIC BUG - des this need _all_markers stored, to use self.yield_... @@@@@ pos0 = marker._f_new_position_for(self, markers[marker]) if pos0 is not None: rail, baseindex, direction = pos0 pos = PositionInWholeChain(self, rail, baseindex, direction) assert isinstance(pos, PositionInWholeChain) # sanity check, for now markers[marker] = pos marker._f_new_pos_ok_during_move(self) # for debug else: marker._f_kill_during_move(self, "not on adjacent atoms on wholechain") del markers[marker] self._all_markers = markers return # from __init__ def __len__(self): if self._num_bases == -1: # We're being called too early during init to know the value. # If we just return -1, Python raises ValueError: __len__() should return >= 0. # That is not understandable, so raise a better exception. # Don't just work: it might hide bugs, and returning 0 might make # us seem "boolean false"! (We define __nonzero__ to try to avoid that, # but still it makes me nervous to return 0 here.) # Note that we need __repr__ to work now (e.g. in the following line), # so don't make it use len() unless it checks _num_bases first. # (As of now it uses _num_bases directly.) assert 0, "too early for len(%r)" % self assert self._num_bases > 0 # if this fails, we're being called too early (during __init__), or had some bug during __init__ return self._num_bases def __nonzero__(self): return True # needed for safety & efficiency, now that we have __len__! @@@@ TODO: same in other things with __len__; __eq__ too? destroyed = False #bruce 080403 def destroy(self): # 080120 7pm untested # note: this can be called from chunk._undo_update from one # of our chunks; it needs to be ok to call it multiple times. # I fixed a bug in that in two ways (either one is enough, # each is a precaution if the other is present): # a destroyed flag, and reset _all_markers to {} not (). # [bruce 080403] if self.destroyed: return self.destroyed = True # do this now, in case of exception or recursion for marker in self.all_markers(): marker.forget_wholechain(self) self._all_markers = {} self._controlling_marker = None self._strand_or_segment = None # review: need to tell it to forget us, too? @@@ for rail in self.rails(): chunk = rail.baseatoms[0].molecule ## rail.destroy() # IMPLEM @@@@ [also, goodness is partly a guess] if hasattr(chunk, 'forget_wholechain'): # KLUGE chunk.forget_wholechain(self) continue self._dict_of_rails = {} return def rails(self): """ Return all our rails, IN ARBITRARY ORDER (that might be revised) """ return self._dict_of_rails.values() def end_rails(self): # bruce 080212; rename? """ Return a list of those of our rails which have end_atoms of self as a whole (which they determine by which neighbor_baseatoms they have). @note: if we are a ring, this list will have length 0. if we are a length-1 wholechain, it will have length 1. if we are a longer wholechain, it will have length 1 or 2, depending on whether we're made of one rail or more. (We assert that the length is 0 or 1 or 2.) """ # note: if this shows up in any profiles, it can be easily # optimized by caching its value. res = [rail for rail in self.rails() if rail.at_wholechain_end()] assert len(res) <= 2 return res def end_baseatoms(self): """ Return a list of our end_baseatoms, based on rail.neighbor_baseatoms (used via rail.wholechain_end_baseatoms()) for each of our rails (set by dna updater, not always valid during it). @note: result is asserted length 0 or 2; will be 0 if we are a ring or 2 if we are a chain. @note: Intended for use by user ops between dna updater runs, but legal to call during self.__init__ as soon as self._dict_of_rails has been stored. """ res = [] for rail in self.end_rails(): res.extend(rail.wholechain_end_baseatoms()) assert len(res) in (0, 2), "impossible set of %r.end_baseatoms(): %r" % \ (self, res) return res def get_all_baseatoms(self): """ @return: a list of all baseatoms within self, IN ARBITRARY ORDER @rtype: list @see: self.get_all_baseatoms_in_order() which returns the base atoms in a fixed order """ baseAtomList = [] for rail in self.rails(): baseAtomList.extend(rail.baseatoms) return baseAtomList def get_all_baseatoms_in_order(self): #Ninad 2008-08-06 """ @return: a list of all baseatoms within self, in a fixed order -- from first baseatom of first rail to last base atom of last rail, in same order as wholechain_baseindex indices. @rtype: list @see: self.get_rails_in_order() """ rails = self.get_rails_in_order() atomList = [] for rail in rails: baseatoms = list(rail.baseatoms) first_index = self.wholechain_baseindex(rail, 0) last_index = self.wholechain_baseindex(rail, len(baseatoms) - 1) if first_index > last_index: baseatoms.reverse() atomList.extend(baseatoms) return atomList def __repr__(self): classname = self.__class__.__name__.split('.')[-1] res = "<%s (%d bases, %d markers) at %#x>" % \ (classname, self._num_bases, len(self._all_markers), id(self)) return res def all_markers(self): """ Assuming we still own all our atoms (not checked), return all the DnaMarkers on them. """ return self._all_markers.keys() def own_markers(self): """ Choose or make one of your markers to be controlling, then tell them all that you own them and whether they're controlling (which might kill some of them). (But don't move them in the model tree, not even the newly made ones.) Also cache whatever base-indexing info is needed (in self, our rails/chunks, and/or their atoms). [As of 080116 this part is not yet needed or done.] """ self._controlling_marker = self._choose_or_make_controlling_marker() for (marker, position_holder) in self._all_markers.items(): # can't be iteritems! ## print "debug loop: %r.own_marker %r" % (self, marker) controllingQ = (marker is self._controlling_marker) ## assert not marker.killed(), \ # [precaution 080222 - change assert to debug print & bug mitigation:] if marker.killed(): print "\n***BUG: " \ "marker %r (our controlling = %r) is killed" % \ ( marker, controllingQ ) # this might fail if they're not yet all in the model, # but we put them there when we make them, and we don't kill them when they # lose atoms, so they ought to be there @@@ # (it should not fail from them being killed between __init__ and now # and unable to tell us, since nothing happens in caller to kill them) self._f_marker_killed(marker) #k guess 080222 continue marker.set_wholechain(self, position_holder, controlling = controllingQ) # own it; tell it whether controlling (some might die then, # and if so they'll call self._f_marker_killed # which removes them from self._all_markers) continue for marker in self.all_markers(): # [precaution 080222 - change assert to debug print & bug mitigation:] ## assert not marker.killed(), \ if marker.killed(): print "\n***BUG: " \ "marker %r died without telling %r" % (marker, self) self._f_marker_killed(marker) continue # todo: use controlling marker to work out base indexing per rail... return def _f_marker_killed(self, marker): """ [friend method for DnaMarker] One of our markers is being killed (and calls this to advise us of that). [Also called by self if we realize that failed to happen.] """ try: self._all_markers.pop(marker) except: msg = "bug: can't pop %r from %r._all_markers: " % (marker, self) print_compact_traceback( msg) pass return # == def find_strand_or_segment(self): """ Return our associated DnaStrandOrSegment, which is required to be already defined in self. """ assert self._strand_or_segment return self._strand_or_segment def find_or_make_strand_or_segment(self): """ Return our associated DnaStrandOrSegment. If we don't yet know it or don't have one, ask our controlling marker (which we must have before now) to find or make it. """ if self._strand_or_segment: return self._strand_or_segment assert self._controlling_marker, "%r should have called _choose_or_make_controlling_marker before now" % self strand_or_segment = self._controlling_marker._f_get_owning_strand_or_segment(make = True) assert strand_or_segment, "%r._controlling_marker == %r has no " \ "owning_strand_or_segment and can't make one" % \ (self, self._controlling_marker) self._strand_or_segment = strand_or_segment return strand_or_segment # == ### review below def _choose_or_make_controlling_marker(self): """ [private] Choose one of our markers to control this wholechain, or make a new one (at a good position on one of our atoms) to do that. Return it, but don't save it anywhere (caller must do that). """ marker = self._choose_controlling_marker() if not marker: marker = self._make_new_controlling_marker() assert marker return marker def _choose_controlling_marker(self): """ [private] Look at the existing markers on our atoms which are able to be controlling markers. If there are none, return None. Otherwise choose one of them to be our controlling marker, and return it (don't save it anywhere, or tell any markers whether they are controlling now; caller must do those things if/when desired; fyi, as of 080116 own_markers does this). If one or more are already controlling, it will be one of them. [### REVIEW -- not sure this point is right] If more than one are controlling, we have rules to let them compete. If none is, ditto. """ all_markers = self.all_markers() # valid anytime after __init__ candidates = [marker for marker in all_markers if marker.wants_to_be_controlling()] if not candidates: return None # choose one of the candidates list_of_preferred_markers_this_time = [] ### stub - in real life let external code add markers to this list, pop them all here items = [] for marker in candidates: order_info = (marker in list_of_preferred_markers_this_time, # note: False < True in Python marker.control_priority, marker.get_oldness(), # assume oldness is unique -- inverse of something allocated by a counter ) items.append( (order_info, marker) ) items.sort() return items[-1][1] def _make_new_controlling_marker(self): """ [private] self has no marker which wants_to_be_controlling(). Make one (on some good choice of atom on self) (and in the same group in the model tree as that atom) and return it. (Don't store it as our controlling marker, or tell it it's controlling -- caller must do that if desired. But *do* add it to our list of all markers on our atoms.) @note: we always make one, even if this is a 1-atom wholechain (which means (for now) that it's not possible to make a good or fully correct one). We do that because the callers really need every wholechain to have one. """ # improvements, 080222: should pick end atom with lowest .key, but to be easier and work for rings, # might pick end atom of any rail with lowest key (over all rails). Also this is best for segments # and also ok for strands but maybe not best for strands (who should look at Ax atoms in same basepairs, # but note, these can be same for different strand atoms!). end_atoms = self.end_baseatoms() # should find 2 atoms unless we're a ring # review: if we're a chain of length 1, does it find our lone atom once, or twice? # I don't think it matters re following code, but review that too. # [bruce 080422 comment] if not end_atoms: # we're a ring - just consider all end atoms of all our rails # (don't bother not including some twice for length-1 rails, # no need in following code) end_atoms = [] for rail in self.rails(): end_atoms.append( rail.baseatoms[0] ) end_atoms.append( rail.baseatoms[-1] ) pass assert end_atoms candidates = [(atom.key, atom) for atom in end_atoms] # todo: for strands, first sort by attached Ax key? # todo: include info to help find next_atom? candidates.sort() # lowest key means first-made basepair by Dna Generator atom = candidates[0][1] # now pick the best next_atom rail, index, direction_into_chain = self._find_end_atom_chain_and_index( atom) # Q. is index for end1 positive or -1? # A. positive (or 0 for length-1 rail), but following code doesn't care. # Q. does best next_atom come from same rail if possible? # A. (guess yes, doing that for now) # WARNING: if len(rail) == 1, then direction_into_chain is arbitrary. # the following code doesn't use it in that case. # [bruce 080422 comment] if len(rail.baseatoms) > 1: next_atom = rail.baseatoms[index + direction_into_chain] position = (rail, index, direction_into_chain) elif rail.neighbor_baseatoms[LADDER_END1]: # ignore index and direction_into_chain next_atom = rail.neighbor_baseatoms[LADDER_END1] # direction within rail is 1, not necessarily same as direction within next_atom's rail position = (rail, index, 1) elif rail.neighbor_baseatoms[LADDER_END0]: next_atom = rail.neighbor_baseatoms[LADDER_END0] # reverse direction! atom, next_atom = next_atom, atom # direction within rail is -1, but we need the direction within the next rail! rail2, index2, dir2junk = self._find_end_atom_chain_and_index(next_atom) # if rail2 is len 1, dir2 and index2 are useless for finding # direction2 (direction in next rail), so always do this: if atom is rail2.neighbor_baseatoms[LADDER_END1]: direction2 = 1 else: assert atom is rail2.neighbor_baseatoms[LADDER_END0] direction2 = -1 position = rail2, index2, direction2 else: # a 1-atom wholechain, hmm ... # DnaMarker support for this added 080216, not fully tested # (note that a 1-atom wholechain *ring* is not possible, # but if it was it'd be handled by the above if/else cases) next_atom = atom direction = 1 # arbitrary, but needs to be in (-1, 1) position = (rail, index, direction) # now make the marker on those atoms # (todo: in future, we might give it some user settings too) assert atom.molecule, "%r has no .molecule" % atom assy = atom.molecule.assy assert assy assert atom.molecule.part, "%r has no .part; .molecule is %r" % (atom, atom.molecule) assert next_atom.molecule, "%r has no .molecule" % next_atom assert next_atom.molecule.part, "%r has no .part; .molecule is %r" % (next_atom, next_atom.molecule) assert atom.molecule.part is next_atom.molecule.part, \ "%r in part %r, %r in part %r, should be same" % \ (atom, atom.molecule.part, next_atom, next_atom.molecule.part) marker_class = self._DnaMarker_class # subclass-specific constant marker = marker_class(assy, [atom, next_atom]) # doesn't give it a wholechain yet # give it a temporary home in the model (so it doesn't seem killed) -- # in fact, it matters where we put it, since later code assumes it # *might* already be inside the right DnaStrandOrSegment (and checks # this). So we put it in the same group as the marked atom. part = atom.molecule.part part.place_new_jig(marker) # (overkill in runtime, but should be correct, since both marker's # atoms should be in the same group) # and remember it's on our atoms, and where on them it is self._append_marker(marker, *position) return marker def _append_marker(self, marker, rail, baseindex, direction): # 080306 assert not marker in self._all_markers self._all_markers[marker] = PositionInWholeChain(self, rail, baseindex, direction) return def _find_end_atom_chain_and_index(self, atom, next_atom = None): # REVIEW: rename chain -> rail, in this method name? (and all local vars in file) """ Assume atom is an end_baseatom of one of our rails (aka chains). (If not true, raise KeyError.) Find that rail and atom's index in it, and return them as the tuple (rail, index_in_rail, direction_into_rail). The index is nonnegative, meaning that we use 0 for either end of a length-1 rail (there is no distinction between the ends in that case). But in case the direction_into_rail return value component matters then, use the optional next_atom argument to disambiguate it -- if given, it must be next to end_atom, and we'll return the direction pointing away from it. """ key = atom.key try: rail = self._end0_baseatoms[key] index_in_rail = 0 direction_into_rail = 1 except KeyError: rail = self._end1_baseatoms[key] # raise KeyError if atom is not an end_atom of any of our rails index_in_rail = len(rail) - 1 direction_into_rail = -1 if next_atom is not None: #bruce 080422 bugfix and new assertions assert next_atom in rail.neighbor_baseatoms if next_atom is rail.neighbor_baseatoms[LADDER_END0]: direction_to_next_atom = -1 else: assert next_atom is rail.neighbor_baseatoms[LADDER_END1] direction_to_next_atom = 1 necessary_direction_into_rail = - direction_to_next_atom if len(rail) == 1: if necessary_direction_into_rail != direction_into_rail: print "fyi: fixing direction_into_rail to ", necessary_direction_into_rail ### remove when works direction_into_rail = necessary_direction_into_rail else: ## assert necessary_direction_into_rail == direction_into_rail if necessary_direction_into_rail != direction_into_rail: print "BUG: necessary_direction_into_rail %d != direction_into_rail %d, rail %r" % \ (necessary_direction_into_rail, direction_into_rail, rail) pass pass return rail, index_in_rail, direction_into_rail # todo: methods related to base indexing def yield_rail_index_direction_counter(self, # in class WholeChain pos, counter = 0, countby = 1, relative_direction = 1): """ #doc @note: the first position we yield is always the one passed, with counter at its initial value """ # possible optim: option to skip (most) killed atoms, and optimize that # to notice entire dead rails (noticeable when their chunks get killed) # and pass them in a single step. We might still need to yield the # final repeat of starting pos. rail, index, direction = pos pos = rail, index, direction # make sure pos is a tuple (required by comparison code below) # assert one of our rails, valid index in it assert direction in (-1, 1) while 1: # yield, move, adjust, check, continue yield rail, index, direction, counter # move counter += countby index += direction * relative_direction # adjust def jump_off(rail, end): neighbor_atom = rail.neighbor_baseatoms[end] # neighbor_atom might be None, atom, or -1 if not yet set assert neighbor_atom != -1 if neighbor_atom is None: new_rail = None # outer code will return due to this, ending the generated sequence index, direction = None, None # illegal values (to detect bugs in outer code) else: this_atom = rail.end_baseatoms()[end] #bruce 080422 bugfix new_rail, index, direction = self._find_end_atom_chain_and_index(neighbor_atom, this_atom) direction *= relative_direction assert new_rail # can't assert new_rail is not rail -- might be a ring of one rail return new_rail, index, direction if index < 0: # jump off END0 of this rail rail, index, direction = jump_off(rail, LADDER_END0) elif index >= len(rail): # jump off END1 of this rail rail, index, direction = jump_off(rail, LADDER_END1) else: pass # check if not rail: return assert 0 <= index < len(rail) assert direction in (-1, 1) if (rail, index, direction) == pos: # we wrapped around a ring to our starting position. # (or, someday, to another limit pos passed by caller?) # yield it one more time, as a signal that we're a ring, and # to help with algorithms looking at every pair of successive # positions; then return. yield rail, index, direction, counter return elif (rail, index) == pos[0:2]: ## assert 0, \ # this is failing, but might be harmless, so mitigate it by # just printing rather than assertfailing, and otherwise # treating this the same way as above. [bruce 080422 bug mitigation] # note: the underlying bug was probably then fixed by a change above, # in the same commit, passing this_atom to _find_end_atom_chain_and_index. print \ "bug: direction got flipped somehow in " \ "%r.yield_rail_index_direction_counter%r at %r" % \ ( self, (pos, counter, countby, relative_direction), (rail, index, direction, counter) ) yield rail, index, direction, counter return continue assert 0 # not reached pass _rail_to_wholechain_baseindex_data = None _wholechain_baseindex_range = None def wholechain_baseindex(self, rail, baseindex): #bruce 080421 (not in rc2) """ @param rail: one of our rails. @param baseindex: a baseindex within rail @type baseindex: int, from 0 to len(rail) - 1 @return: the corresponding baseindex within self as a whole @rtype: int @note: this function is expensive on the first call for self, and cheap thereafter. @note: if self is a ring, the baseindex origin and direction is determined by self's controlling marker. (WARNING: in initial implem this origin might be arbitrary, instead) @see: len(self) gives the total number of bases in self, but their indices don't necessarily start at 0 @see: self.wholechain_baseindex_range() """ if not self._rail_to_wholechain_baseindex_data: self._compute_wholechain_baseindices() baseindex_0, increment = self._rail_to_wholechain_baseindex_data[rail] return baseindex_0 + increment * baseindex def wholechain_baseindex_range(self): #bruce 080421 (not in rc2) """ Return the minimum and maximum wholechain_baseindex of all bases in all rails in self. @return: (min_baseindex, max_baseindex), where min_baseindex <= max_baseindex @rtype: a tuple of two ints @note: this function might be expensive on the first call for self, but is cheap thereafter. @see: self.wholechain_baseindex(rail, baseindex) """ if not self._wholechain_baseindex_range: self._compute_wholechain_baseindices() min_baseindex, max_baseindex = self._wholechain_baseindex_range return min_baseindex, max_baseindex def wholechain_baseindex_range_for_rail(self, rail): #bruce 080421 (not in rc2) """ @param rail: one of our rails. @return: the first and last wholechain_baseindex within rail @rtype: a tuple of two ints @see: self.wholechain_baseindex_range() """ first = self.wholechain_baseindex(rail, 0) last = self.wholechain_baseindex(rail, len(rail) - 1) return first, last def get_rails_in_order(self): #Ninad 2008-08-06 """ @return: a list containing self's rails, in increasing order of the index of each rail's baseatoms, according to wholechain_baseindex_range_for_rail. @rtype: list @see: self.get_all_baseatoms_in_order() @see: self.rails() (much faster when order doesn't matter) """ rails = self.rails() lst = [] for rail in rails: first_baseindex, last_baseindex = self.wholechain_baseindex_range_for_rail(rail) lst.append( (first_baseindex, rail) ) # Sort the list so that the rails are arranged in increasing order # of the baseindex of the first (or any) baseatom of each rail. # (Which baseatom is used in each rail doesn't matter, since within # any single rail the indices are contiguous.) lst.sort() return [rail for (baseindex, rail) in lst] def _compute_wholechain_baseindices(self): #bruce 080421 (not in rc2) """ Compute and assign the correct values to self._rail_to_wholechain_baseindex_data and self._wholechain_baseindex_range. """ self._rail_to_wholechain_baseindex_data = {} # modified herein marker = self._controlling_marker # for now, its marked_atom and next_atom will be treated as having # wholechain_baseindices of 0 and 1 respectively. In the future, # marker properties would specify this. min_so_far = 2 * len(self) # bigger than any possible wholechain_baseindex in self max_so_far = -2 * len(self) # smaller than any ... for direction_of_slide in (1, -1): if self.ringQ and direction_of_slide == -1: break pos_holder = marker._position_holder ### kluge assert pos_holder.wholechain is self pos_generator = pos_holder.yield_rail_index_direction_counter( relative_direction = direction_of_slide, counter = 0, countby = direction_of_slide, ) # TODO: optimization: pass a new option to skip from each # position returned to a position in the next rail. # (implem note: be sure to still return the precise initial # pos at the end, for a ring.) old_atom1, old_atom2 = marker.marked_atom, marker.next_atom if direction_of_slide == 1: _check_atoms = [old_atom1, old_atom2] # for assertions only -- make sure we hit these atoms first, # in this order else: _check_atoms = [old_atom1] # if we knew pos of atom2 we could # start there, and we could save it from when we go to the # right, but there's no need. last_rail = None for pos in pos_generator: rail, index, direction, counter = pos atom = rail.baseatoms[index] if _check_atoms: popped = _check_atoms.pop(0) if not (atom is popped): # FIX: remove this code once it works, and certainly # before implementing the optim in pos_generator # to return each rail only once. print "\n*** BUG: not (atom %r is _check_atoms.pop(0) %r), remaining _check_atoms %r, other data %r" % \ (atom, popped, _check_atoms, (marker, pos_holder)) # define the wholechain_baseindex of pos to be counter; # from this and direction, infer the index range for rail # and record it, also tracking min and max wholechain indices. if rail is not last_rail: # optim, until pos_generator can return each rail only once last_rail = rail def rail_index_to_whole_index(baseindex): return (baseindex - index) * direction + counter self._rail_to_wholechain_baseindex_data[rail] = ( rail_index_to_whole_index(0), direction ) for index in (rail_index_to_whole_index(0), rail_index_to_whole_index(len(rail) - 1) ): if index < min_so_far: min_so_far = index if index > max_so_far: max_so_far = index continue pass # if rail was not yet seen continue # next pos from pos_generator continue # next direction_of_slide self._wholechain_baseindex_range = ( min_so_far, max_so_far ) return # from _compute_wholechain_baseindices pass # end of class WholeChain # == class PositionInWholeChain(object): """ A mutable position (and direction) along a WholeChain. """ def __init__(self, wholechain, rail, index, direction): self.wholechain = wholechain self.set_position(rail, index, direction) def set_position(self, rail, index, direction): self.rail = rail self.index = index # base index in current rail self.direction = direction # in current rail only # note: our direction in each rail is unrelated self.pos = (rail, index, direction) return def yield_rail_index_direction_counter(self, **options): # in class PositionInWholeChain return self.wholechain.yield_rail_index_direction_counter( self.pos, **options ) # maybe: method to scan in both directions # (for now, our main caller does that itself) pass # == class Axis_WholeChain(WholeChain): _DnaMarker_class = DnaSegmentMarker """ A WholeChain for axis atoms. """ pass class Strand_WholeChain(WholeChain): _DnaMarker_class = DnaStrandMarker """ A WholeChain for strand atoms. """ pass # == def new_Group_around_Node(node, group_class): #e refile, might use in other ways too [not used now, but might be correct] node.part.ensure_toplevel_group() # might not be needed name = "(internal Group)" # stub assy = node.assy dad = None #k legal?? arg needed? group = group_class(name, assy, dad) # same args as for Group.__init__(self, name, assy, dad) [review: reorder those anytime soon??] node.addsibling(group) group.addchild(node) return group # end
NanoCAD-master
cad/src/dna/model/WholeChain.py
# Copyright 2005-2008 Nanorex, Inc. See LICENSE file for details. """ Dna_Constants.py -- constants for Dna. Note: these are used both by the newer DnaDuplex.py, and the older DnaGenHelper.py which it supersedes (and their associated files). @author: Mark Sims @version: $Id$ @copyright: 2005-2008 Nanorex, Inc. See LICENSE file for details. @see: References: - U{The Standard IUB codes used in NanoEngineer-1 <http://www.idtdna.com/InstantKB/article.aspx?id=13763>} - U{http://en.wikipedia.org/wiki/DNA} - U{http://en.wikipedia.org/wiki/Image:Dna_pairing_aa.gif} History: 2007-08-19 - Started out as part of DnaGenHelper.py """ import foundation.env as env from utilities.constants import purple, brass, steelblue, lightgreen, darkgray, lightblue from utilities.constants import darkorange, violet, copper, olive, gray from utilities.prefs_constants import adnaBasesPerTurn_prefs_key, adnaRise_prefs_key from utilities.prefs_constants import bdnaBasesPerTurn_prefs_key, bdnaRise_prefs_key from utilities.prefs_constants import zdnaBasesPerTurn_prefs_key, zdnaRise_prefs_key from PyQt4.Qt import QString basesDict = \ { 'A':{'Name':'Adenine', 'Complement':'T', 'Color':'darkorange' }, 'C':{'Name':'Cytosine', 'Complement':'G', 'Color':'cyan' }, 'G':{'Name':'Guanine', 'Complement':'C', 'Color':'green' }, 'T':{'Name':'Thymine', 'Complement':'A', 'Color':'teal' }, 'U':{'Name':'Uracil', 'Complement':'A', 'Color':'darkblue' }, 'X':{'Name':'Undefined', 'Complement':'X', 'Color':'darkred' }, 'N':{'Name':'aNy base', 'Complement':'N', 'Color':'orchid' }, 'B':{'Name':'C,G or T', 'Complement':'V', 'Color':'dimgrey' }, 'V':{'Name':'A,C or G', 'Complement':'B', 'Color':'dimgrey' }, 'D':{'Name':'A,G or T', 'Complement':'H', 'Color':'dimgrey' }, 'H':{'Name':'A,C or T', 'Complement':'D', 'Color':'dimgrey' }, 'R':{'Name':'A or G (puRine)', 'Complement':'Y', 'Color':'dimgrey'}, 'Y':{'Name':'C or T (pYrimidine)', 'Complement':'R', 'Color':'dimgrey'}, 'K':{'Name':'G or T (Keto)', 'Complement':'M', 'Color':'dimgrey'}, 'M':{'Name':'A or C (aMino)', 'Complement':'K', 'Color':'dimgrey'}, 'S':{'Name':'G or C (Strong - 3H bonds)', 'Complement':'W', 'Color':'dimgrey'}, 'W':{'Name':'A or T (Weak - 2H bonds)', 'Complement':'S', 'Color':'dimgrey'} } # I'd like to suggest that we change the name of key 'DuplexRise' to 'Rise'. # Need to run this by Bruce and Ninad first. Mark 2008-01-31. dnaDict = \ { 'A-DNA':{'BasesPerTurn': env.prefs[adnaBasesPerTurn_prefs_key], 'DuplexRise': env.prefs[adnaRise_prefs_key]}, 'B-DNA':{'BasesPerTurn': env.prefs[bdnaBasesPerTurn_prefs_key], 'DuplexRise': env.prefs[bdnaRise_prefs_key]}, 'Z-DNA':{'BasesPerTurn': env.prefs[zdnaBasesPerTurn_prefs_key], 'DuplexRise': env.prefs[zdnaRise_prefs_key]} } #If the qiven strand atom doesn't have a compelmentary strand base atom, #the sequence editor will show a specific character in the 'complement sequence #text field (i.e. in self.sequenceTextEdit_mate) indicating that the #complement is missing. #@see: DnaSequenceEditor._determine_complementSequence() #@see: DnaStrand.getStrandSequenceAndItsComplement() MISSING_COMPLEMENTARY_STRAND_ATOM_SYMBOL = '*' # Common DNA helper functions. ###################################### # for getNextStrandColor: # _strandColorList is used for assigning a color to a new strand created # by breaking an existing strand. # Do not use the following colors in _strandColorList: # - white/lightgray (reserved for axis) # - black (reserved as a default color for scaffold strand; # also used for dna updater duplex errors (subject to change) # [bruce 080206]) # - yellow (used for hover highlighting) # - red (used as delete highlight color) # - green (reserved for selection color) # - orange (reserved for dna updater errors on atoms and bonds [bruce 080206] # (subject to change)) # (update [bruce 080406]: orange is no longer used that way, but might # still be, or in future be, used for other warnings, so is still # left out of this list) _strandColorList = [ purple, brass, steelblue, lightgreen, darkgray, lightblue, darkorange, violet, copper, olive, gray] _strand_color_counter = 0 def getNextStrandColor(currentColor = None): """ Return a color to assign to a strand which is guaranteed to be different than currentColor (which is typically that strand's current color). @param currentColor: The color to avoid returning, or None if the next color is ok. @type currentColor: RGB tuple @return: New color. @rtype: RGB tuple """ global _strand_color_counter _new_color = _strandColorList[_strand_color_counter % len(_strandColorList)] _strand_color_counter += 1 if _new_color == currentColor: return getNextStrandColor() # Note: this won't equal currentColor, since successive colors # in _strandColorList are always different. return _new_color def getDuplexBasesPerTurn(conformation): """ Returns the number of U{bases per turn} specified in the user preferences. @param conformation: "A-DNA", "B-DNA", or "Z-DNA" @type conformation: str @return: The number of bases per turn. @rtype: float """ assert conformation in ("A-DNA", "B-DNA", "Z-DNA") return dnaDict[str(conformation)]['BasesPerTurn'] def getDuplexRise(conformation): """ Returns the duplex U{rise} specified in the user preferences. @param conformation: "A-DNA", "B-DNA", or "Z-DNA" @type conformation: str @return: The rise in Angstroms. @rtype: float """ assert conformation in ("A-DNA", "B-DNA", "Z-DNA") return dnaDict[str(conformation)]['DuplexRise'] def getDuplexLength(conformation, numberOfBases, duplexRise = 0): """ Returns the duplex length (in Angstroms) given the conformation and number of bases. @param conformation: "A-DNA", "B-DNA", or "Z-DNA" @type conformation: str @param numberOfBases: The number of base-pairs in the duplex. @type numberOfBases: int @param duplexRise: The duplex rise (in Angstroms). If not provided, the user preference for DNA rise is used. @return: The length of the duplex in Angstroms. @rtype: float """ assert conformation in ("A-DNA", "B-DNA", "Z-DNA") assert numberOfBases >= 0 assert duplexRise >= 0 if duplexRise: duplexLength = duplexRise * (numberOfBases - 1) else: duplexLength = getDuplexRise(conformation) * (numberOfBases - 1) return duplexLength def getNumberOfBasePairsFromDuplexLength(conformation, duplexLength, duplexRise = 0): """ Returns the number of base-pairs in the duplex given the conformation, duplex length and duplex rise (optional). The number of base-pairs returned is NOT rounded to the nearest integer. The rounding is intentionally not done. Example: While drawing a dna line, when user clicks on the screen to complete the second endpoint, the actual dna axis endpoint might be trailing the clicked point because the total dna length is not sufficient to complete the 'next step'. Thus, by not rounding the number of bases, we make sure that the dna consists of exactly same number of bases as displayed by the rubberband line ( The dna rubberband line gives enough visual indication about this. see draweRibbons.drawDnaRibbons() for more details on the visual indication ) @param conformation: "A-DNA", "B-DNA", or "Z-DNA" @type conformation: str @param duplexLength: The duplex length (in Angstroms). @type duplexLength: float @param duplexRise: The duplex rise (in Angstroms). If not provided, the user preference for DNA rise is used. @type duplexRise: float @return: The number of base-pairs in the duplex. @rtype: int """ assert conformation in ("A-DNA", "B-DNA", "Z-DNA") assert duplexLength >= 0 assert duplexRise >= 0 if duplexRise: numberOfBasePairs = 1.0005 + (duplexLength / duplexRise) else: numberOfBasePairs = 1.0005 + (duplexLength / getDuplexRise(conformation)) #Explanation on adding '1.0005': #The number of base-pairs returned is NOT rounded to the nearest integer. #See why its not done in this method's docstring. But why do we add 1.005 #instead of '1' while computing the number of basepairs? As of 2008-03-05 #there a bug observed in the number this method returns if we just add '1' #Suppose a print statement shows the the numberOfBasePairs computed #above as 5.0. But int(numberOfBasePairs) returns 4 and not 5! This happens #sometime. I am not sure if in those cases the number of basepairs are #something like 4.99999......N which python rounds off to 5.0, but int of #that number actually returns 4. This is just a guess. But some print #statements do show this happening! So a workaround is to add some tolerance #of 0.0005 to 1. This addition is unlikely to have any user visible effect. return int(numberOfBasePairs) def getDuplexRiseFromNumberOfBasePairs(numberOfBasePairs, duplexLength): """ Returns the duplex rise from the number of base pairs and the duplex length @param numberOfBasePairs: number of base pairs in the duplx @type numberOfBasePairs: int @param duplexLength: The length of duplex. @type duplexLength: double @return: The duplex rise. @rtype: double """ duplexRise = duplexLength/ (numberOfBasePairs - 1) return duplexRise def getComplementSequence(inSequence): """ Returns the complement of the DNA sequence I{inSequence}. @param inSequence: The original DNA sequence. @type inSequence: str (possible error: the code looks more like it requires a QString [bruce 080101 comment]) @return: The complement DNA sequence. @rtype: str (possible error: the code looks more like it might return a QString [bruce 080101 comment]) """ #If user enters an empty 'space' or 'tab key', treat it as an empty space #in the complement sequence. (don't convert it to 'N' base) #This is needed in B{DnaSequenceEditor} where , if user enters an empty space #in the 'Strand' Sequence, its 'Mate' also enters an empty space. validSpaceSymbol = QString(' ') validTabSymbol = QString('\t') assert isinstance(inSequence, str) outSequence = "" for baseLetter in inSequence: if baseLetter not in basesDict.keys(): if baseLetter in validSpaceSymbol: pass elif baseLetter in validTabSymbol: baseLetter = '\t' else: baseLetter = "N" else: baseLetter = basesDict[baseLetter]['Complement'] outSequence += baseLetter return outSequence def getReverseSequence(inSequence): """ Returns the reverse order of the DNA sequence I{inSequence}. @param inSequence: The original DNA sequence. @type inSequence: str @return: The reversed sequence. @rtype: str """ assert isinstance(inSequence, str) outSequence = list(inSequence) outSequence.reverse() outSequence = ''.join(outSequence) return outSequence def replaceUnrecognized(inSequence, replaceBase = "N"): """ Replaces any unrecognized/invalid characters (alphanumeric or symbolic) from the DNA sequence and replaces them with I{replaceBase}. This can also be used to remove all unrecognized bases by setting I{replaceBase} to an empty string. @param inSequence: The original DNA sequence. @type inSequence: str @param replaceBase: The base letter to put in place of an unrecognized base. The default is "N". @type replaceBase: str @return: The sequence. @rtype: str """ assert isinstance(inSequence, str) assert isinstance(replaceBase, str) outSequence = "" for baseLetter in inSequence: if baseLetter not in basesDict.keys(): baseLetter = replaceBase outSequence += baseLetter if 0: print " inSequence:", inSequence print "outSequence:", outSequence return outSequence
NanoCAD-master
cad/src/dna/model/Dna_Constants.py
# Copyright 2007-2008 Nanorex, Inc. See LICENSE file for details. """ ChainAtomMarker.py - a marked atom and direction in a chain of atoms, with help for moving it to a new atom if its old atom is killed; has state for undo/copy/save @author: Bruce @version: $Id$ @copyright: 2007-2008 Nanorex, Inc. See LICENSE file for details. ### REVIEW -- is the following true? Note: in principle, this is not specific to DNA, so it probably doesn't need to be inside the dna_model package, though it was written to support that. This module has no dna-specific knowledge (except in a few comments about intended uses), and that should remain true. See also: class DnaMarker, which inherits this. """ from model.jigs import Jig from utilities.debug import print_compact_traceback from utilities import debug_flags _NUMBER_OF_MARKER_ATOMS = 2 # == class ChainAtomMarker(Jig): """ Abstract class. Marks a single atom in some kind of chain of live atoms (which kind and how to move along it is known only to more concrete subclasses), and a direction along that chain, represented as a reference to the next atom along it (and/or by other subclass-specific attrs). As a jig, has pointers to both the marked and next atom, so it can be invalidated when either one is killed. Responding to that occurrence is up to subclasses, though this class has some support for the subclass "moving self to a new atom along the same chain". Contains state for undo/copy/save (namely the two atoms, individually distinguished), and perhaps more subclass- specific state). Note that there are several distinct ways this object can be "invalid" and become "valid" (making use of subclass-specific code in both, and for that matter with "validity" only meaningful in a subclass- specific way): - moving to a new atom, since the old marker_atom was killed (perhaps moving along an old chain that is no longer valid except for that purpose) - resetting its next_atom to a new one which records the same direction from its marker_atom, if next_atom died or got disconnected - becoming owned by the chain its atoms are on, after undo/copy/read. For all of these cases, the subclass needs to extend appropriate Jig API methods to be notified of and respond to these events, and it may record more info when updating self in response to them, which may be more definitive as a direction or position indicator than next_atom or perhaps even marker_atom. It is up to the subclass to keep those atoms up to date (i.e. change them if necessary to fit the more definitive info, which is not seen by copy/undo/save). """ # default values of instance variables: # Jig API variables sym = "ChainAtomMarker" # probably never visible, since this is an abstract class # other variables marked_atom = None next_atom = None _length_1_chain = False #bruce 080216 # declare attributes involved in copy, undo, mmp save copyable_attrs = Jig.copyable_attrs + ('marked_atom', 'next_atom', '_length_1_chain') # that sets them up for copy and undo; # no need for mmp write/read code for these, since they're written as part of self.atoms # and reinitialized from that when we're constructed, # but do REVIEW and assert that they're in the right order when written. # note: more copyable_attrs might be needed in subclasses ## _old_atom = None # (not undoable or copyable) (but see comment on "make _old_atom undoable" below) # == Jig API methods def __init__(self, assy, atomlist): """ """ if len(atomlist) == 2 and atomlist[0] is atomlist[1]: # let caller pass two atoms the same, but reduce it to one copy # (compensating in setAtoms) # (this is to make length-1 wholechains easier) [bruce 080216] atomlist = atomlist[:1] self._length_1_chain = True elif len(atomlist) == 1: # [bruce 080227 to support mmp read of 1-atom case] # TODO: print warning unless this is called from mmp read # (which is the only time it's not an error, AFAIK) # and mark self invalid unless we verify that marked_atom # is indeed on a length-1 chain (this might need to be # done later by dna updater). self._length_1_chain = True Jig.__init__(self, assy, atomlist) # calls self.setAtoms return def setAtoms(self, atomlist): #bruce 080208 split this out of __init__ so copy is simpler Jig.setAtoms(self, atomlist) if len(atomlist) == _NUMBER_OF_MARKER_ATOMS: marked_atom, next_atom = atomlist self.marked_atom = marked_atom self.next_atom = next_atom assert not self._length_1_chain elif len(atomlist) == 1 and self._length_1_chain: #bruce 080216, for 1-atom wholechains # (the flag test is to make sure it's only used then) self.marked_atom = self.next_atom = atomlist[0] else: # We are probably being called by _copy_fixup_at_end # with fewer or no atoms, or by __init__ in first stage of copy # (Jig.copy_full_in_mapping) with no atoms. # todo: would be better to make those callers tell us for sure. # for now: print bug warning if fewer atoms but not none # (i don't know if that can happen), and assert not too many atoms. assert len(atomlist) <= _NUMBER_OF_MARKER_ATOMS if atomlist: print "bug? %r.setAtoms(%r), len != _NUMBER_OF_MARKER_ATOMS or 0" % \ (self, atomlist) self.marked_atom = self.next_atom = None #bruce 080216 self._check_atom_order() #bruce 080216 do in all cases, was just main one return def needs_atoms_to_survive(self): # False, so that if both our atoms are removed, we don't die. # Problem: if we're selected and copied, but our atoms aren't, this would copy us. # But this can't happen if we're at toplevel in a DNA Group, and hidden from user, # and thus only selected if entire DNA Group is. REVIEW if this code is ever used # in a non-DnaGroup context. [Also REVIEW now that we have two atoms.] return False def confers_properties_on(self, atom): ### REVIEW now that we have two atoms, for copy code """ [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 def writemmp(self, mapping): """ [extends superclass method] """ # check a few things, then call superclass method try: assert not self.is_homeless() # redundant as of 080111, that's ok assert len(self.atoms) in (1, _NUMBER_OF_MARKER_ATOMS) self._check_atom_order() except: #bruce 080317, for debugging the save file traceback in # "assert not self.is_homeless()" (above) in bug 2673, # happens when saving after region select + delete of any # duplex; fixed now msg = "\n*** BUG: exception in checks before DnaMarker.writemmp; " \ "continuing, but beware of errors when reopening the file" print_compact_traceback( msg + ": ") pass return Jig.writemmp(self, mapping) def __repr__(self): # 080118 # find out if this harms Jig.writemmp; if not, i can try fixing __repr__ on all jigs classname = self.__class__.__name__.split('.')[-1] ## try: ## name = self.name ## except: ## name = "?" res = "<%s[%r -> %r] at %#x>" % \ (classname, self.marked_atom, self.next_atom, id(self)) return res # == other methods def _check_atom_order(self): """ Check assertions about the order of the special atoms we know about in the list self.atoms. """ # todo: extend/rename this to fix atom order (not just check it), # if it turns out the order can ever get messed up # (update 080208: maybe it can by copy or remove_atom, not sure @@@@) assert len(self.atoms) <= _NUMBER_OF_MARKER_ATOMS if len(self.atoms) == _NUMBER_OF_MARKER_ATOMS: assert [self.marked_atom, self.next_atom] == self.atoms elif len(self.atoms) == 1 and self._length_1_chain: assert self.marked_atom is self.next_atom is self.atoms[0] # nothing is asserted when len(self.atoms) == 1 and not self._length_1_chain return def _expected_number_of_atoms(self): #bruce 080216 if self._length_1_chain: return 1 return _NUMBER_OF_MARKER_ATOMS def is_homeless(self): # REVIEW: Maybe rename to needs_update? """ Has either of our atoms been killed? [misnamed, since if only next_atom is killed, we're not really homeless -- we just need an update.] """ res = ( len(self.atoms) < self._expected_number_of_atoms() ) if debug_flags.DEBUG_DNA_UPDATER_VERBOSE: print "is_homeless(%r) returning %r" % (self, res) return res # old code: ## res = (not self.atoms) and (self._old_atom is not None) ## if res: ## assert self._old_atom.killed() ## # BUG: can fail in Undo, e.g. if you select and delete all atoms, ## # then Undo that. (At least it did once after some other atom ## # deletes in a duplex, just after delete_bare_atoms was implemented.) ## # REVIEW: make _old_atom undoable, to fix this? Not sure it would help... ## # [071205] ## return res # REVIEW following - needed? correct for two atoms?? (i doubt it) [bruce 080111 comment] ## def _set_marker_atom(self, atom): # OBSOLETE, REMOVE SOON, use setAtoms instead [bruce comment 080311] ## ## assert not self.atoms #k needed? true for current callers, but not required in principle ## assert self.is_homeless() ## # this assumes we initially have an atom when we're made ## assert not atom.killed() ## self._old_atom = None ## self.setAtoms([atom]) ## #e other updates? ## return ## ## def _get_marker_atom(self): # OBSOLETE, REMOVE SOON [bruce comment 080311] ## if self.atoms: ## return self.atoms[0] ## else: ## assert self.is_homeless() ## return self._old_atom ## pass pass # end of class ChainAtomMarker
NanoCAD-master
cad/src/dna/model/ChainAtomMarker.py
# Copyright 2007-2008 Nanorex, Inc. See LICENSE file for details. """ dna_model_constants.py -- constants for dna_model internals (not the same as Dna_Constants.py, which is about DNA itself) @author: Bruce @version: $Id$ @copyright: 2007-2008 Nanorex, Inc. See LICENSE file for details. """ # Codes for ladder ends (used privately or passed to other-ladder friend methods) # or chain ends. # # WARNING: they don't correspond in these uses! That is, strand2 of a ladder # has chain-ends in the order 1,0, but has ladder-ends in the order 0,1. # So I'll introduce different names for these uses. But there might be # helper methods which accept either kind -- not sure. For now, # assume that it's required for the two sets to have identical values. # [bruce 080116] LADDER_ENDS = (0, 1) LADDER_END0 = LADDER_ENDS[0] # "left" for ladder LADDER_END1 = LADDER_ENDS[1] # "right" for ladder LADDER_OTHER_END = [1, 0] # 1 - end LADDER_BOND_DIRECTION_TO_OTHER_AT_END_OF_STRAND1 = [-1, 1] # not correct for strand2 of a ladder LADDER_STRAND1_BOND_DIRECTION = LADDER_BOND_DIRECTION_TO_OTHER_AT_END_OF_STRAND1[LADDER_END1] CHAIN_ENDS = LADDER_ENDS CHAIN_END0 = CHAIN_ENDS[0] # "5' end" for strand CHAIN_END1 = CHAIN_ENDS[1] # "3' end" for strand CHAIN_OTHER_END = [1, 0] # 1 - end CHAIN_BOND_DIRECTION_TO_OTHER_AT_END_OF_STRAND = [-1, 1] MAX_LADDER_LENGTH = 500 # @@@@ TODO: also use this to split long ladders # MAX_LADDER_LENGTH limits the length of a DnaLadder that we will create # by merging (this is implemented, and ran at 20 for a long time), # and (not yet implemented) causes us to split DnaLadders that are longer # than this (when encountered by the dna updater). # # When it's fully implemented, the best value should be determined based # on performance (eg of graphics), and might be 20 or lower (splitting # would be fairly common for 20). # # Right now, since it's only partly implemented, and since # some display or UI ops may not yet handle split ladders ideally, # make it a large enough value that failure to split # (resulting in history-dependence of final state) will be rare. # # [bruce 080314] # end
NanoCAD-master
cad/src/dna/model/dna_model_constants.py
# Copyright 2008 Nanorex, Inc. See LICENSE file for details. """ pam_conversion_mmp.py -- help dna model objects convert between PAM models during writemmp @author: Bruce @version: $Id$ @copyright: 2008 Nanorex, Inc. See LICENSE file for details. """ # Note: this file is indirectly imported by chem.py via PAM_Atom_methods, # so its imports need to be kept fairly clean to avoid import cycles. # [bruce 080510 comment] from utilities.GlobalPreferences import dna_updater_is_enabled from utilities.constants import PAM_MODELS from utilities.constants import MODEL_PAM3, MODEL_PAM5 from utilities.constants import Pl_STICKY_BOND_DIRECTION from utilities.constants import diDEFAULT from utilities.constants import average_value from utilities.constants import atKey import foundation.env as env from utilities.Log import orangemsg, redmsg from model.elements import Pl5 from geometry.VQT import V # == # TODO: refile this with class writemmp_mapping: class writemmp_mapping_memo(object): mapping = None def __init__(self, mapping): self.mapping = mapping def destroy(self): # todo: call, to avoid ref cycles self.mapping = None pass # == # helpers for DnaLadderRailChunk and subclasses class DnaLadderRailChunk_writemmp_mapping_memo(writemmp_mapping_memo): """ """ convert_pam_enabled = False _ladder_memo = None _save_as_pam = None def __init__(self, mapping, chunk): # immediately memoize some settings which need to be constant # during use, as a bug precaution. Also do whatever precomputes # are convenient. writemmp_mapping_memo.__init__(self, mapping) self.chunk = chunk self.ladder = chunk.ladder if not dna_updater_is_enabled(): msg = "Warning: can't convert PAM model when dna updater is disabled; affects [N] chunk(s)" env.history.deferred_summary_message( orangemsg( msg)) elif not self.ladder: # (might happen if dna updater is turned off at runtime -- not sure; # note, doing that might have worse effects, like self.ladder existing # but being out of date, causing traceback errors. #### FIX those sometime (elsewhere).) print "error: ladder not set during writemmp, can't convert pam model, in %r" % chunk msg = "Error: [N] chunk(s) don't have ladders set" env.history.deferred_summary_message( redmsg( msg)) else: self.convert_pam_enabled = True if self.convert_pam_enabled: # Note: this only means conversion is possible -- we don't yet know # if it's requested by options on this mapping and chunk. # The ladder memo will decide that. self._ladder_memo = mapping.get_memo_for(self.ladder) self._save_as_pam = self._ladder_memo._f_save_as_what_PAM_model() return def _f_save_as_what_PAM_model(self): return self._save_as_pam pass class DnaStrandChunk_writemmp_mapping_memo(DnaLadderRailChunk_writemmp_mapping_memo): """ """ number_of_conversion_atoms = None def __init__(self, mapping, chunk): DnaLadderRailChunk_writemmp_mapping_memo.__init__(self, mapping, chunk) self.Pl_atoms = self._compute_Pl_atoms() self.number_of_conversion_atoms = self._compute_number_of_conversion_atoms() return def _f_number_of_conversion_atoms(self): return self.number_of_conversion_atoms def _compute_number_of_conversion_atoms(self): # Our conversion atoms are whatever Pl atoms we are going to write # which are not in self.chunk.atoms if self._save_as_pam == MODEL_PAM3: return 0 chunk = self.chunk res = 0 for Pl in self.Pl_atoms: # in order, possible Nones at end (or in middle when not converting to PAM5) if Pl is not None: # not sure this is correct: if Pl.molecule is not self.chunk: if Pl.key not in chunk.atoms: # method for that? _Pl_alive? res += 1 return res def _compute_Pl_atoms(self): if self._save_as_pam == MODEL_PAM3: return None # or if this fails, [None] * (length+1) # find out idealized strand direction, based on where we are in ladder # (not always equal to true strand direction, if ladder.error is set; # that matters elsewhere (and is checked there) but doesn't matter here, # I think -- not sure, it might cause trouble at the ends ####REVIEW -- # can/should we just leave out end-Pls then??) chunk = self.chunk baseatoms = chunk.get_baseatoms() direction = chunk.idealized_strand_direction() # note: we never look at Pls cached on neighbor_baseatoms # since any such Pl would belong in a neighbor chunk, not ours if direction == Pl_STICKY_BOND_DIRECTION: # Pls want to stick to the right within baseatoms; # pass baseatom pairs in current order pairs = zip( [None] + baseatoms, baseatoms + [None] ) else: # Pls want to stick to the left; pass reversed pairs # (but no need to reverse the result) pairs = zip( baseatoms + [None], [None] + baseatoms ) res = [self._compute_one_Pl_atom(a1, a2) for (a1, a2) in pairs] if res[0] is res[-1] and len(res) > 1 and res[0] is not None: # The same Pl atom is at both ends of res # (possible for a ring strand). # Decide which one to replace with None so that we never # return a list that contains one atom twice. # (I don't know whether it matters which end we leave it on, # but we'll leave it on the "best one" anyway.) # [bruce 080516 bugfix] if direction == Pl_STICKY_BOND_DIRECTION: # Pls want to stick to the right, # so this one is happiest in res[0], # so remove it from res[-1] res[-1] = None else: res[0] = None pass return res def _compute_one_Pl_atom(self, a1, a2): """ Find or make the live or cached/nonlive Pl atom which binds, or should bind, adjacent baseatoms a1 and a2, where bond direction going from a1 to a2 agrees with Pl_STICKY_BOND_DIRECTION. One of those atoms might be passed as None, indicating we want a Pl at the end, bound to only one baseatom, or None if there should be no such Pl atom. @param a1: a baseatom or None @param a2: an adjacent baseatom or None @warning: for a ring strand in one chunk, we can return the same Pl atom at both ends. (Only when we find an existing one, I think.) """ chunk = self.chunk # If both atoms are real (not None), we store that Pl with a2, # since that is in the right direction from it, # namely Pl_STICKY_BOND_DIRECTION. assert a2 is not None or a1 is not None # first return the Pl if it's live (bonded to a2 or a1) if a2 is not None: # if a2 exists in chunk, a live Pl between a1 and a2 # would be preferentially bonded to a2, so also in chunk candidate = a2.next_atom_in_bond_direction( - Pl_STICKY_BOND_DIRECTION) if candidate is not None: # should be either a1 or our Pl if candidate.element is Pl5: # todo: assert bound to a1 if it exists, or to # neighbor_baseatom in that direction if *that* exists if candidate.molecule is chunk: # required for returning live ones return candidate else: print "bug? %r not in %r but should be" % \ (candidate, chunk,) pass else: # if only a1 is in chunk, a live Pl bonded to it # (in the right direction) is only ok if it's also in chunk, # or (should be equivalent) if it prefers a1 to other neighbors. # (This is not exactly equivalent, in the case of a ring strand in one # chunk. This is what leads to returning the same Pl in two places # in that case, I think. [bruce 080516 comment]) # For a live one, use "in chunk" as definitive test, to avoid bugs. candidate = a1.next_atom_in_bond_direction( + Pl_STICKY_BOND_DIRECTION) if candidate is not None: if candidate.element is Pl5: if candidate.molecule is chunk: # no error if not, unlike a2 case return candidate pass # now find or make a non-live Pl to return, iff conversion options desire this. if self._save_as_pam != MODEL_PAM5: return None ### REVIEW: is this also a good time to compute (and store in it?) its position? # guess yes, since we have a1 and a2 handy and know their bond directions. # Note that this only runs once per writemmp, but the position is fixed then # so that's fine. We don't cache it between those since it's so likely to # become invalid, so not worth tracking that. if a2 is not None: res = a2._f_get_fake_Pl( - Pl_STICKY_BOND_DIRECTION) # Note: res is not an Atom, and is not part of undoable state. # It can act like an Atom in a few ways we use here -- # most importantly, having a fixed .key not overlapping a real atom .key. assert res is None or isinstance(res, Fake_Pl) return res # might be None else: return None #??? # Note: reasoning: if neighbor baseatom exists, # put the Pl in that neighbor chunk. # (Which might be the other end of this chunk, # for a ring strand in one chunk, # but if so, we'll do that in a separate call.) # If not, there needn't be one (not sure about that). pass # end of def _compute_one_Pl_atom (not reached) pass # end of class DnaStrandChunk_writemmp_mapping_memo # == # helpers for DnaLadder class DnaLadder_writemmp_mapping_memo(writemmp_mapping_memo): def __init__(self, mapping, ladder): # assume never created except by chunks, so we know dna updater is enabled writemmp_mapping_memo.__init__(self, mapping) assert dna_updater_is_enabled() self.ladder = ladder self.save_as_pam = self._compute_save_as_pam() self.wrote_axis_chunks = [] # public attrs self.wrote_strand_chunks = [] return def _f_save_as_what_PAM_model(self): return self.save_as_pam def _compute_save_as_pam(self): common_answer = None mapping = self.mapping for chunk in self.ladder.all_chunks(): r = chunk._f_requested_pam_model_for_save(mapping) if not r: return None assert r in PAM_MODELS # todo: enforce in mmp read (silently) if not common_answer: common_answer = r if r != common_answer: return None continue assert common_answer return common_answer def advise_wrote_axis_chunk(self, chunk): # 080328 """ Record the fact that we finished writing the given axis chunk during the mmp save controlled by self.mapping. """ self.wrote_axis_chunks.append(chunk) return def advise_wrote_strand_chunk(self, chunk): # 080328 """ Record the fact that we finished writing the given strand chunk during the mmp save controlled by self.mapping. """ self.wrote_strand_chunks.append(chunk) return def write_rung_bonds(self, chunk1, chunk2): # 080328 """ Assuming the two given chunks of our ladder have just been written via self.mapping, and their rung bonds have not, write those compactly. """ mapping = self.mapping s1, e1 = chunk1._f_compute_baseatom_range(mapping) s2, e2 = chunk2._f_compute_baseatom_range(mapping) record = "dna_rung_bonds %s %s %s %s\n" % (s1, e1, s2, e2) mapping.write(record) return pass # == # TODO: (remember single strand domains tho -- what kind of chunks are they?) # == class Fake_Pl(object): #bruce 080327 """ not an Atom! but acts like one in a few ways -- especially, has an atom.key allocated from the same pool as real Atoms do. """ ## element = Pl5 # probably not needed ## display = diDEFAULT # probably not needed now, # though someday we might try to preserve this info # across PAM5 <-> PAM3+5 conversion owning_Ss_atom = None # not yet used bond_direction = 0 # not yet used (direction of self from that atom) # usually (or always?) this is (- Pl_STICKY_BOND_DIRECTION) def __init__(self, owning_Ss_atom, bond_direction): self.key = atKey.next() self.owning_Ss_atom = owning_Ss_atom # reference cycle -- either destroy self when atom is destroyed, # or just store owning_Ss_atom.key or so self.bond_direction = bond_direction return def posn(self): # stub - average posn of Ss neighbors (plus offset in case only one!) print "should use Pl_pos_from_neighbor_PAM3plus5_data for %r" % self ##### # note: average_value seems to work here res = average_value( [n.posn() for n in self.neighbors()], V(0, 0, 0) ) return res + V(0, 2, 0) # offset (kluge, wrong) def writemmp(self, mapping, dont_write_bonds_for_these_atoms = ()): """ Write a real mmp atom record for self (not a real atom), and whatever makes sense to write for a fake Pl atom out of the other mmp records written for a real atom: 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. @note: compatible with Atom.writemmp and Node.writemmp, though we're not a subclass of Atom or Node. """ # WARNING: has common code with Atom.writemmp num_str = mapping.encode_next_atom(self) ## display = self.display display = diDEFAULT disp = mapping.dispname(display) # note: affected by mapping.sim flag posn = self.posn() ## element = self.element element = Pl5 eltnum = element.eltnum #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 mapping.write_bonds_compactly: # no need to worry about how to write bonds, in this case! # it's done implicitly, just by writing self between its neighbor Ss atoms, # due to the directional_bond_chain mmp record. # (to make this work fully, we need to include the strand-end bondpoints... # and add a special case for a fake_Pl that bridges two chunks. # ###### NONTRIVIAL -- we might not even have written the other chunk yet...) pass else: mapping.write("# bug: writing fake_Pl bonds is nim, when not using directional_bond_chain mmp record\n") # TODO: summary redmsg, so I don't forget this is nim... # todo: use dont_write_bonds_for_these_atoms, # and self._neighbor_atoms, but note they might not be written out yet... # we might just assume we know which ones were written or not, # and write the atom and bond records in one big loop in the caller... # e.g. have our chunk copy & modify the atom writemmp loop and write # the between-atom bonds itself (like using the directional_bond_chain # record, but spelling it out itself). # (Would things be easiest if we made fake Ss atoms too, # or (similarly) just did an actual conversion (all new atoms) before writing? # The issue is, avoiding lots of overhead (and undo issues) from making new Atoms.) return def _neighbor_atoms(self): # needed? a1 = self.owning_Ss_atom a2 = a1.next_atom_in_bond_direction(self.bond_direction) # might be None assert a2 is not self res = [a1, a2] if self.bond_direction < 0: res.reverse() #k good? better to compare to +/- Pl_STICKY_BOND_DIRECTION?? print "_neighbor_atoms -> ", res ####### return res def neighbors(self): return filter(None, self._neighbor_atoms()) pass # end of class # end
NanoCAD-master
cad/src/dna/model/pam_conversion_mmp.py
# Copyright 2007-2009 Nanorex, Inc. See LICENSE file for details. """ DnaStrand.py - ... @author: Bruce, Ninad @version: $Id$ @copyright: 2007-2009 Nanorex, Inc. See LICENSE file for details. TODO: - See comments in self.getStrandSequence(), self.get_strand_atoms_in_bond_direction() """ import re from dna.model.DnaStrandOrSegment import DnaStrandOrSegment from dna.model.DnaLadderRailChunk import DnaStrandChunk from utilities.icon_utilities import imagename_to_pixmap from utilities.debug import print_compact_stack, print_compact_traceback from dna.model.Dna_Constants import getComplementSequence from operations.bond_chains import grow_directional_bond_chain from dna.model.Dna_Constants import MISSING_COMPLEMENTARY_STRAND_ATOM_SYMBOL from utilities.constants import MODEL_PAM3 from utilities.constants import MODEL_PAM5 from PyQt4.Qt import QFont, QString from model.bond_constants import bond_left_atom from utilities.Log import quote_html class DnaStrand(DnaStrandOrSegment): """ Model object which represents a Dna Strand as a kind of Dna Group. Internally, this is just a specialized Group containing various subobjects, described in the superclass docstring. These include its DnaStrandChunks, and its DnaStrandMarkers, exactly one of which is its controlling marker. [Note: we might decide to put the DnaStrandChunks inside the DnaSegment whose axis they attach to (as is done in InsertDna_EditCommand as of 080111), instead. This is purely an implementation issue but has implications for selection and copying code. bruce comment 080111] """ # This should be a tuple of classifications that appear in # files_mmp._GROUP_CLASSIFICATIONS, most general first. # See comment in class Group for more info. [bruce 080115] _mmp_group_classifications = ('DnaStrand',) iconPath = "ui/modeltree/Strand.png" hide_iconPath = "ui/modeltree/Strand-hide.png" autodelete_when_empty = True # (but only if current command permits that for this class -- # see comment near Group.autodelete_when_empty for more info, # and implems of Command.keep_empty_group) #Define highlighting policy for this object (whether it should responf to #highlighting). It returns True by default. For some commands it might #be switched off (usually by the user but can be done internally as well) #see self.getHighlightPolicy() for details _highlightPolicy = True def edit(self): """ Edit this DnaStrand. @see: DnaStrand_EditCommand """ commandSequencer = self.assy.w.commandSequencer commandSequencer.userEnterCommand('DNA_STRAND') assert commandSequencer.currentCommand.commandName == 'DNA_STRAND' commandSequencer.currentCommand.editStructure(self) def node_icon(self, display_prefs): """ Model Tree node icon for the dna group node @see: Group.all_content_is_hidden() """ del display_prefs # unused if self.all_content_is_hidden(): return imagename_to_pixmap( self.hide_iconPath) else: return imagename_to_pixmap( self.iconPath) def getColor(self): """ Returns the color of an arbitrary internal strand chunk. It iterates over the strand chunk list until it gets a valid color. If no color is assigned to any of its strand chunks, it simply returns None. """ color = None for m in self.members: if isinstance(m, DnaStrandChunk): color = m.color if color is not None: break return color def setColor(self, color): """ Public method provided for convenience. Delegates the color assignment task to self.setStrandColor() @see: DnaOrCntPropertyManager._changeStructureColor() """ self.setStrandColor(color) def setStrandColor(self, color): """ Set the color of the all the strand chunks within this strand group to the given color @param color: The new color of the strand chunks @see: BuildAtoms_GraphicsMode._singletLeftUp_joinstrands() @see: BuildAtoms_GraphicsMode._singletLeftUp() @see: self.setColor() """ m = None for m in self.members: if isinstance(m, DnaStrandChunk): m.setcolor(color) def isEmpty(self): """ Returns True if there are no strand chunks as its members @see: DnaGroup.getStrands where this test is used. """ if len(self.getStrandChunks()) == 0: return True def get_strand_end_base_atoms(self): """ Returns a tuple containing the end base atoms of a strand in the following order : (5' end base atom, 3' end base atom). If any or both of these doesn't exist it returns 'None' in place of that non existent atom """ member = None for member in self.members: if isinstance(member, DnaStrandChunk): break if not isinstance(member, DnaStrandChunk): # no DnaStrandChunk members (should not happen) return (None, None) end_baseatoms = member.wholechain.end_baseatoms() if not end_baseatoms: # ring return (None, None) three_prime_end_base_atom = None five_prime_end_base_atom = None for atm in end_baseatoms: if atm is not None: rail = atm.molecule.get_ladder_rail() bond_direction = 1 # absoulute bond direction here (1 == 5'->3') # instead of rail.bond_direction(), piotr 0803278 next_strand_atom = atm.strand_next_baseatom(bond_direction) previous_strand_atom = atm.strand_next_baseatom(-bond_direction) if next_strand_atom is None and previous_strand_atom: three_prime_end_base_atom = atm if previous_strand_atom is None and next_strand_atom: five_prime_end_base_atom = atm if next_strand_atom is None and previous_strand_atom is None: #We have a case where the current strand atom has no #strand atoms bonded. So simply return it twice. five_prime_end_base_atom = atm three_prime_end_base_atom = atm # chain return (five_prime_end_base_atom, three_prime_end_base_atom) def get_three_prime_end_base_atom(self): """ Returns the three prime end base atom of this strand. If one doesn't exist, returns None @see: self.get_strand_end_base_atoms() """ endbaseAtoms = self.get_strand_end_base_atoms() return endbaseAtoms[1] def get_five_prime_end_base_atom(self): """ Returns the five prime end base atom of this strand. If one doesn't exist, returns None @see: self.get_strand_end_base_atoms() """ endbaseAtoms = self.get_strand_end_base_atoms() return endbaseAtoms[0] def get_DnaSegment_with_content_atom(self, strand_atom): """ Returns a DnaSegment which is has the given strand atom as its 'logical content' . """ segment = None if strand_atom: axis_atom = strand_atom.axis_neighbor() if axis_atom: segment = axis_atom.molecule.parent_node_of_class( self.assy.DnaSegment) return segment def get_DnaSegment_axisEndAtom_connected_to(self, strand_atom): """ Returns end axis atom of a DnaSegment connected to the given strand base atom. Returns None if the axis atom is not an 'end' atom of a wholechain """ axisEndAtom = None #Safety check. strand_atom could be None if strand_atom: axis_atom = strand_atom.axis_neighbor() axis_rail = axis_atom.molecule.get_ladder_rail() if axis_atom in axis_rail.wholechain_end_baseatoms(): axisEndAtom = axis_atom #Alternative implementation ##dnaSegment = self.get_DnaSegment_with_content_atom(strand_atom) ##axisEndAtom1, axisEndAtom2 = dnaSegment.getAxisEndAtoms() return axisEndAtom def get_all_content_chunks(self): """ Return all the chunks including A) the chunks within the DnaSegments that this DnaStrand 'touches' (passes through). B) Its own member chunks (DnaStrandChunks) @see: SelectChunks_GraphicsMode.getMovablesForLeftDragging() where this is used [overrides superclass method] """ #ONLY WORKS in DNA DATA model. pre dna data model is unsupported all_content_chunk_list = [] for member in self.members: if isinstance(member, DnaStrandChunk): ladder = member.ladder all_content_chunk_list.extend(ladder.all_chunks()) return all_content_chunk_list def getDnaSegment_at_three_prime_end(self): """ Returns DnaSegment at the three prime end. i.e. the stand end base atom (at the three prime end) is a 'logical content' of the DnaSegment logical content means that the atom.molecule is not a direct member of DnaSegment group, but is connected to an axis atom whose chunk is a member of that DnaSegment. """ dnaSegment = None atom = self.get_three_prime_end_base_atom() if atom: dnaSegment = self.get_DnaSegment_with_content_atom(atom) return dnaSegment def getDnaSegment_at_five_prime_end(self): """ Returns DnaSegment at the five prime end. i.e. the stand end base atom (at the three prime end) is a 'logical content' of the DnaSegment """ dnaSegment = None atom = self.get_five_prime_end_base_atom() if atom: dnaSegment = self.get_DnaSegment_with_content_atom(atom) return dnaSegment def getStrandEndAtomAtPosition(self, position): """ Returns an end baseatom of this strand at the specified position. Returns None if no atom center is found at <position> @param position: The point at which the caller needs to find the strand end baseatom. @type position: B{A} """ strandEndAtom = None endAtom1, endAtom2 = self.get_strand_end_base_atoms() for atm in (endAtom1, endAtom2): if atm is not None and same_vals(position, atm.posn()): strandEndAtom = atm break return strandEndAtom def getNumberOfNucleotides(self): """ Method provided for conveneince. Returns the number of bases of this DnaStrand. @see: PM_DnaSearchResultTable """ return self.getNumberOfBases() def getNumberOfBases(self): """ @return: The total number of baseatoms of this DnaStrand @rtype: int """ numberOfBases = 0 strand_wholechain = self.get_strand_wholechain() if strand_wholechain: numberOfBases = len(strand_wholechain.get_all_baseatoms()) return numberOfBases def get_DnaStrandChunks_sharing_basepairs(self): """ Returns a list of strand chunk that have atleast one complementary strand baseatom with self. @see: ops_select_Mixin.expandDnaComponentSelection() @see: ops_select_Mixin._expandDnaStrandSelection() @see:ops_select_Mixin._contractDnaStrandSelection() @see: ops_select_Mixin._contractDnaSegmentSelection() @see: SelectChunks_GraphicsMode.chunkLeftDouble() """ #REVIEW-- method needs optimization -- Ninad 2008-04-12 complementary_strand_chunks = [] for c in self.getStrandChunks(): ladder = c.ladder for strandChunk in ladder.strand_chunks(): if not strandChunk is c: if strandChunk not in complementary_strand_chunks: complementary_strand_chunks.append(strandChunk) return complementary_strand_chunks def is_PAM3_DnaStrand(self): """ Returns true if all the baseatoms in the DnaLadders of this strand are PAM3 baseatoms (axis or strands) Otherwise returns False @see: DnaStrand_EditCommand.model_changed() @see: DnaStrand_EditCommand.hasResizableStructure() @see: DnaSegment.is_PAM3_DnaSegment() (similar implementation) """ is_PAM3 = False ladderList = self.getDnaLadders() if len(ladderList) == 0: is_PAM3 = False for ladder in ladderList: pam_model = ladder.pam_model() if pam_model == MODEL_PAM3: is_PAM3 = True else: is_PAM3 = False break return is_PAM3 def getDnaLadders(self): """ Returns a list of all DnaLadders within this strand """ ladderList = [] for member in self.members: if isinstance(member, DnaStrandChunk): ladder = member.ladder if ladder not in ladderList: ladderList.append(ladder) return ladderList def get_wholechain(self): """ Return the 'wholechain' of this DnaStrand. Method provided for convenience. Delegates this to self.get_strand_wholechain() """ return self.get_strand_wholechain() def get_strand_wholechain(self): """ @return: the 'wholechain' of this DnaStrand (same as wholechain of each of its DnaStrandChunks), or None if it doesn't have one (i.e. if it's empty -- should never happen if called on a live DnaStrand not modified since the last dna updater run). @note: the return value contains the same chunks which get selected when the user clicks on a strand group in the model tree. @see: Wholechain @see: get_segment_wholechain """ for member in self.members: if isinstance(member, DnaStrandChunk): return member.wholechain return None def getStrandChunks(self): """ Return a list of all strand chunks """ strandChunkList = [] for m in self.members: if isinstance(m, self.assy.Chunk) and m.isStrandChunk(): strandChunkList.append(m) return strandChunkList def getDefaultToolTipInfo(self): """ Default strand info in the tooltip when the cursor is over an atom """ strandInfo = "" strandInfo += "<font color=\"#0000FF\">Parent strand: </font>" + self.name + "<br>" allAtoms = self.get_strand_atoms_in_bond_direction(filterBondPoints = True) strandInfo += "<font color=\"#0000FF\">Number of bases: </font>%s"%(len(allAtoms)) return strandInfo def getAllAtoms(self): """ Method provided for convenience """ allAtoms = self.get_strand_atoms_in_bond_direction(filterBondPoints = True) return allAtoms def getToolTipInfoForBond(self, bond): """ Tooltip information when the cursor is over a strand bond. As of 2008-11-09, it gives the information in the following form: """ #Bond direction will always be atm1 --> atm2 #@see: Bond.bond_direction_from() atm1 = bond.atom1 atm2 = bond.atom2 strandInfo = "" if not (atm1 and atm2): strandInfo = self.getDefaultToolTipInfo() return strandInfo threePrimeEndAtom = self.get_three_prime_end_base_atom() fivePrimeEndAtom = self.get_five_prime_end_base_atom() allAtoms = self.get_strand_atoms_in_bond_direction(filterBondPoints = True) tooltipDirection = "3<--5" left_atom = bond_left_atom(bond, quat = self.assy.glpane.quat) right_atom = bond.other(left_atom) if bond.bond_direction_from(left_atom) == 1: tooltipDirection = "5-->3" else: tooltipDirection = "3<--5" left_atm_index = None try: left_atm_index = allAtoms.index(left_atom) except: print_compact_traceback("bug in getting strand info string "\ "atom %s not in list"%left_atom) if left_atm_index: #@BUG: The computation of numOfBases_next_crossover_5prime and #numOfBases_next_crossover_3prime is wrong in some cases. So, #that information is not displayed. numOfBases_next_crossover_5prime, numOfBases_next_crossover_3prime = \ self._number_of_atoms_before_next_crossover( left_atom, tooltipDirection = tooltipDirection) if threePrimeEndAtom and fivePrimeEndAtom: if tooltipDirection == "3<--5": numOfBasesDown_3PrimeDirection = len(allAtoms[left_atm_index:]) #Note: This does not include atm1 , which is intentional-- numOfBasesDown_5PrimeDirection = len(allAtoms[:left_atm_index]) ##strandInfo += " 3' < " + str(numOfBasesDown_3PrimeDirection) + "/" + str(numOfBases_next_crossover_3prime) strandInfo += " 3' < " + str(numOfBasesDown_3PrimeDirection) strandInfo += " --(%s)-- "%(len(allAtoms)) ##strandInfo += str(numOfBases_next_crossover_5prime) + "/" + str(numOfBasesDown_5PrimeDirection) + " < 5'" strandInfo += str(numOfBasesDown_5PrimeDirection) + " < 5'" else: numOfBasesDown_3PrimeDirection = len(allAtoms[left_atm_index + 1:]) #Note: This does not include atm1 , which is intentional-- numOfBasesDown_5PrimeDirection = len(allAtoms[:left_atm_index + 1]) ##strandInfo += " 5' > " + str(numOfBasesDown_5PrimeDirection) + "/" + str(numOfBases_next_crossover_5prime) strandInfo += " 5' > " + str(numOfBasesDown_5PrimeDirection) strandInfo += " --(%s)-- "%(len(allAtoms)) ##strandInfo += str(numOfBases_next_crossover_3prime) + "/" + str(numOfBasesDown_3PrimeDirection) + " > 3'" strandInfo += str(numOfBasesDown_3PrimeDirection) + " > 3'" #Make sure that symbol like > are converted to html strandInfo = quote_html(strandInfo) return strandInfo def _number_of_atoms_before_next_crossover(self, atm, tooltipDirection = ''): """ """ numOfBases_down_3prime = '' numOfBases_down_5prime = '' rail = atm.molecule.get_ladder_rail() atm_index = rail.baseatoms.index(atm) end_baseatoms = rail.end_baseatoms() if len(end_baseatoms) == 2: atm_a = end_baseatoms[0] atm_b = end_baseatoms[1] if atm_a and atm_b: atm_a_index = rail.baseatoms.index(atm_a) atm_b_index = rail.baseatoms.index(atm_b) if tooltipDirection == "3<--5": ##print "~~~~" ##print "***tooltipDirection =", tooltipDirection numOfBases_down_3prime = abs(atm_a_index - atm_index) + 1 numOfBases_down_5prime = abs(atm_b_index - atm_index) ##print "****numOfBases_down_3prime = ", numOfBases_down_3prime ##print "****numOfBases_down_5prime = ", numOfBases_down_5prime elif tooltipDirection == "5-->3": ##print "####################" numOfBases_down_3prime = abs(atm_b_index - atm_index) numOfBases_down_5prime = abs(atm_a_index - atm_index) + 1 ##print "****numOfBases_down_3prime = ", numOfBases_down_3prime ##print "****numOfBases_down_5prime = ", numOfBases_down_5prime return (str(numOfBases_down_5prime), str(numOfBases_down_3prime)) def get_neighboring_DnaStrands_in_same_DnaSegment(self): """ """ pass def _get_commandNames_honoring_highlightPolicy(self): """ Return a tuple containing the command names that honor the self._highlightPolicy of this object. @see: self.getHighlightPolicy() """ commandNames_that_honor_highlightPolicy = ('BUILD_DNA', 'DNA_STRAND', 'DNA_SEGMENT') return commandNames_that_honor_highlightPolicy def setHighlightPolicy(self, highlight = True): """ Set the highlighting flag that decides whether to highlight 'self' when self is the object under cursor. This is set as a property of self that helps enabling or disabling highlighting while in a particular command. Note that NE1 honors this property of the object overriding the 'hover_highligiting_enabled' flag of the current command/ Graphics mode Example: While in BuildDna_EditCommand and some of its its subcommands, the user may wish to switch off highlighting for a particular DNA strand as it gets in the way. (example the huge scaffold strand). The user may do so my going into the strand edit command and checking the option 'Don't highlight while in Dna.' This tells the structure not to get highlighted while in BuildDna mode and some of its subcommands (the structure can decide for which commands it should switch its highlighting off. Note that the other strands will still respond to the hover highlighting. In all other commands, this object (dnaStrand) will still respond to highlighting. @see: self.getHighlightPolicy() @see: self._get_commandNames_honoring_highlightPolicy() @see: DnaStrand_PropertyManager.change_struct_highlightPolicy() """ #@NOTE: This property is a temporary implementation for to be used by #Mark and Tom for the DNA Four hole tile project (the highlighting #for scaffold gets in their way as it takes long time.. so they need #to switch it off for the bug scaffold strand) If we think its a good #feature overall, then it can become an API method. More thought needs #to be put on whether its structure that checks the current command #to decide whether it needs to be highlighted (like the check done in #self.draw_highlighted() or its the command that sets the flag for #each and every structure. The former approach is followed right now #(see self.getHighlightPolicy for details) and it looks like a better #approach #Also note that this state is not saved to the mmp file. (we can do that #if we decide to make it a general API method) -- Ninad 2008-03-14 self._highlightPolicy = highlight def getHighlightPolicy(self): """ Returns the highlighting state of the object. Note that it doesn't always mean that the object won't get highlighted if this returns False In fact, this state will be used only in certain commands. @see self.setHighlightPolicy """ commandSequencer = self.assy.w.commandSequencer currentCommandName = commandSequencer.currentCommand.commandName if currentCommandName in self._get_commandNames_honoring_highlightPolicy(): highlighting_wanted = self._highlightPolicy else: highlighting_wanted = True return highlighting_wanted def draw_highlighted(self, glpane, color): """ Draw the strand and axis chunks as highlighted. (Calls the related methods in the chunk class) @param: GLPane object @param color: The highlight color @see: Chunk.draw_highlighted() @see: SelectChunks_GraphicsMode.draw_highlightedChunk() @see: SelectChunks_GraphicsMode._get_objects_to_highlight() """ # probably by Ninad highlighting_wanted = self.getHighlightPolicy() if highlighting_wanted: #Does DnaStrand group has any member other than DnastrandChunks? for c in self.members: if isinstance(c, DnaStrandChunk): c.draw_highlighted(glpane, color) def getStrandSequenceAndItsComplement(self): """ Returns the strand sequence and the sequence of the complementary strands of the for the DnaStrandChunks within this DnaStrand group. If the complementary strand base atom is not found (e.g. a single stranded DNA), it returns the corresponding sequence character (for the complementary sequence) as '*' meaning its missing. @return: strand Sequence string @rtype: str @see: getStrandSequence """ # probably by Ninad or Mark #@TODO: REFACTOR this. See how to split out common part of #this method and self.getStrandSequence() Basically we could have simply #replaced self.getStrandSequence with this method , but keeping #self.getStrandSequence has an advantage that we don't compute the #complement sequence (not sure if that would improve performance but, #in theory, that will improve it.) One possibility is to pass an argument #compute_complement_sequence = True' to this method. # TODO: Is there a way to make use of DnaStrandMarkers to get the strand # atoms in bond direction for this DnaStrandGroup?? # [A: they are not needed for that, but they could be used # to define an unambiguous sequence origin for a ring.] # # OR: does self.members alway return DnaStrandChunks in the # direction of bond direction? [A. no.] # # While the above questions remain unanswered, the following # makes use of a method self.get_strand_atoms_in_bond_direction # This method is mostly copied here from chunk class with some # modifications ... i.e. it accepts an atomList and uses a random # start atom within that list to find out the connected atoms # in the bond direction. Actually, sending the list # with *all atoms* of the strand isn't really necessary. All we are # interested in is a start Ss atom and bond direction which can # ideally be obtained by using even a single DnaStrandChunk within # this DnaStrand Group. For a short time, we will pass the whole # atom list. Will definitely be revised and refactored within the # coming days (need to discuss with Bruce) -- Ninad 2008-03-01 # see a todo comment about rawAtomList above ### REVIEW (performance): this looks quadratic time in number of bases. sequenceString = '' complementSequenceString = '' atomList = self.get_strand_atoms_in_bond_direction() for atm in atomList: baseName = str(atm.getDnaBaseName()) complementBaseAtom = atm.get_strand_atom_mate() if baseName: sequenceString = sequenceString + baseName else: #What if baseName is not assigned due to some error?? Example #while reading in an mmp file. #As a fallback, we should assign unassigned base letter 'X' #to all the base atoms that don't have a baseletter defined. # [later, bruce 090121: REVIEW: maybe this is no longer needed # due to changes in getDnaBaseName? unless bondpoint does this?] #also, make sure that the atom is not a bondpoint. if atm.element.symbol != 'X': baseName = 'X' sequenceString = sequenceString + baseName complementBaseName = '' if complementBaseAtom: complementBaseName = getComplementSequence(baseName) else: #This means the complementary strand base atom is not present #(its a single stranded dna). So just indicate the complementary #sequence as '*' which means its missing. if atm.element.symbol != 'X': complementBaseName = MISSING_COMPLEMENTARY_STRAND_ATOM_SYMBOL if complementBaseName: complementSequenceString = complementSequenceString + \ complementBaseName return (sequenceString, complementSequenceString) def getStrandSequence(self): """ Returns the strand sequence for the DnaStrandChunks within this DnaStrand group. @return: strand Sequence string @rtype: str @see: getStrandSequenceAndItsComplement """ # probably by Ninad or Mark # see comments in getStrandSequenceAndItsComplement (merge it with this) sequenceString = '' atomList = self.get_strand_atoms_in_bond_direction() for atm in atomList: baseName = str(atm.getDnaBaseName()) if baseName: sequenceString = sequenceString + baseName else: if atm.element.symbol != 'X': baseName = 'X' sequenceString = sequenceString + baseName return sequenceString def setStrandSequence(self, sequenceString, complement = True): """ Set self's strand sequence, i.e., assign the baseNames for the PAM atoms in this strand AND the complementary baseNames to the PAM atoms of the complementary strand ('mate strand'). @param sequenceString: sequence to be assigned to this strand chunk @type sequenceString: str """ # probably by Ninad or Mark #TO BE REVISED; SEE A TODO COMMENT AT THE TOP sequenceString = str(sequenceString) #Remove whitespaces and tabs from the sequence string sequenceString = re.sub(r'\s', '', sequenceString) #Maybe we set this beginning with an atom marked by the #Dna Atom Marker in dna data model? -- Ninad 2008-01-11 # [yes, see my longer reply comment above -- Bruce 080117] atomList = [] rawAtomList = self.get_strand_atoms_in_bond_direction() atomList = filter(lambda atm: not atm.is_singlet(), rawAtomList) for atm in atomList: atomIndex = atomList.index(atm) if atomIndex > (len(sequenceString) - 1): #In this case, set an unassigned base ('X') for the remaining #atoms baseName = 'X' else: baseName = sequenceString[atomIndex] atm.setDnaBaseName(baseName) #Also assign the baseNames for the PAM atoms on the complementary #('mate') strand. if complement: strandAtomMate = atm.get_strand_atom_mate() complementBaseName= getComplementSequence(str(baseName)) if strandAtomMate is not None: strandAtomMate.setDnaBaseName(str(complementBaseName)) # piotr 080319: # Invalidate display lists for chunks in DNA display style # so they'll be remade to reflect sequence changes # [bruce 09021 refactored this, in case chunks cache non-current styles] from utilities.constants import diDNACYLINDER for c in self.members: if isinstance(c, DnaStrandChunk): c.invalidate_display_lists_for_style(diDNACYLINDER) # do the same for all complementary chunks # [note: could be optimized] prev_cc = None for atom in c.atoms.itervalues(): atm_mate = atom.get_strand_atom_mate() if atm_mate: cc = atm_mate.molecule if cc is not prev_cc and isinstance(cc, DnaStrandChunk): prev_cc = cc cc.invalidate_display_lists_for_style(diDNACYLINDER) return def get_strand_atoms_in_bond_direction(self, inputAtomList = (), filterBondPoints = False): """ Return a list of atoms in a fixed direction -- from 5' to 3' @param inputAtomList: An optional argument. If its not provided, this method will return a list of all atoms within the strand, in the strand's bond direction. Otherwise, it will just return the list <inputAtomList> whose atoms are ordered in the strand's bond direction. @type inputAtomList: list (with default value as an empty tuple) @note: this is a stub and we can modify it so that it can accept other direction i.e. 3' to 5' , as an argument. BUG: ? : This also includes the bondpoints (X) .. I think this is from the atomlist returned by bond_chains.grow_directional_bond_chain. The caller -- self.getStrandSequence uses atom.getDnaBaseName to retrieve the DnaBase name info out of atom. So this bug introduces no harm (as dnaBaseNames are not assigned for bondpoints). [I think at most one atom at each end can be a bondpoint, so we could revise this code to remove them before returning. bruce 080205] @warning: for a ring, this uses an arbitrary start atom in self (so it is not yet useful in that case). ### VERIFY @warning: this only works for PAM3 chunks (not PAM5). [piotr 080411 modified it to work with PAM5, but only sugar atoms and bondpoints will be returned] @note: this would return all atoms from an entire strand (chain or ring) even if it spanned multiple chunks. """ # original version in Chunk by ninad 080205 (bruce revised docstring); # subsequently removed. This version was copied from that one, # with a minor modification. To be revised. # See self.getStrandSequence() for a comment. ### TODO: merge _get_pam5_strand_atoms_in_bond_direction into this # method, since they have lots of duplicated code. rawAtomList = [] if inputAtomList: rawAtomList = inputAtomList else: for c in self.members: if isinstance(c, DnaStrandChunk): rawAtomList.extend(c.atoms.itervalues()) startAtom = None atomList = [] #Choose startAtom randomly (make sure that it's a PAM3 Sugar atom # and not a bondpoint) for atm in rawAtomList: if atm.element.symbol == 'Ss3': startAtom = atm break elif atm.element.pam == MODEL_PAM5: # piotr 080411 # If inputAtomList contains PAM5 atoms, process it independently. atomList = self._get_pam5_strand_atoms_in_bond_direction( inputAtomList = rawAtomList) return atomList if startAtom is None: print_compact_stack("bug: no PAM3 Sugar atom (Ss3) found: " ) return [] #Build one list in each direction, detecting a ring too #ringQ decides whether the first returned list forms a ring. #This needs a better name in bond_chains.grow_directional_bond_chain ringQ = False atomList_direction_1 = [] atomList_direction_2 = [] b = None bond_direction = 0 for bnd in startAtom.directional_bonds(): if not bnd.is_open_bond(): # (this assumes strand length > 1) #Determine the bond_direction from the 'startAtom' direction = bnd.bond_direction_from(startAtom) if direction in (1, -1): b = bnd bond_direction = direction break if b is None or bond_direction == 0: return [] #Find out the list of new atoms and bonds in the direction #from bond b towards 'startAtom' . This can either be 3' to 5' direction #(i.e. bond_direction = -1 OR the reverse direction # Later, we will check the bond direction and do appropriate things. #(things that will decide which list (atomList_direction_1 or #atomList_direction_2) should be prepended in atomList so that it has #atoms ordered from 5' to 3' end. # 'atomList_direction_1' does NOT include 'startAtom'. # See a detailed explanation below on how atomList_direction_a will be # used, based on bond_direction ringQ, listb, atomList_direction_1 = grow_directional_bond_chain(b, startAtom) del listb # don't need list of bonds if ringQ: # The 'ringQ' returns True So its it's a 'ring'. #First add 'startAtom' (as its not included in atomList_direction_1) atomList.append(startAtom) #extend atomList with remaining atoms atomList.extend(atomList_direction_1) else: #Its not a ring. Now we need to make sure to include atoms in the #direction_2 (if any) from the 'startAtom' . i.e. we need to grow #the directional bond chain in the opposite direction. other_atom = b.other(startAtom) if not other_atom.is_singlet(): ringQ, listb, atomList_direction_2 = grow_directional_bond_chain(b, other_atom) assert not ringQ #bruce 080205 del listb #See a detailed explanation below on how #atomList_direction_2 will be used based on 'bond_direction' atomList_direction_2.insert(0, other_atom) atomList = [] # not needed but just to be on a safer side. if bond_direction == 1: # 'bond_direction' is the direction *away from* startAtom and # along the bond 'b' declared above. . # This can be represented by the following sketch -- # (3'end) <--1 <-- 2 <-- 3 <-- 4 <-- (5' end) # Let startAtom be '2' and bond 'b' be directional bond between # 1 and 2. In this case, the direction of bond *away* from # '2' and along 2 = bond direction of bond 'b' and thus # atoms traversed along bond_direction = 1 lead us to 3' end. # Now, 'atomList_direction_1' is computed by 'growing' (expanding) # a bond chain in the direction that goes from bond b # *towards* startAtom. That is, in this case it is the opposite # direction of one specified by 'bond_direction'. The last atom # in atomList_direction_1 is the (5' end) atom. # Note that atomList_direction_1 doesn't include 'startAtom' # Therefore, to get atomList ordered from 5'to 3' end we must #reverse atomList_direction_1 , then append startAtom to the #atomList (as its not included in atomList_direction_1) and then #extend atoms from atomList_direction_2. #What is atomList_direction_2 ? It is the list of atoms #obtained by growing bond chain from bond b, in the direction of #atom 1 (atom 1 is the 'other atom' of the bond) . In this case #these are the atoms in the direction same as 'bond_direction' #starting from atom 1. Thus the atoms in the list are already #arranged from 5' to 3' end. (also note that after computing #the atomList_direction_2, we also prepend 'atom 1' as the #first atom in that list. See the code above that does that. atomList_direction_1.reverse() atomList.extend(atomList_direction_1) atomList.append(startAtom) atomList.extend(atomList_direction_2) else: #See a detailed explanation above. #Here, bond_direction == -1. # This can be represented by the following sketch -- # (5'end) --> 1 --> 2 --> 3 --> 4 --> (3' end) #bond b is the bond betweern atoms 1 and 2. #startAtom remains the same ..i.e. atom 2. #As you can notice from the sketch, the bond_direction is #direction *away* from 2, along bond b and it leads us to # 5' end. #based on how atomList_direction_2 (explained earlier), it now #includes atoms begining at 1 and ending at 5' end. So #we must reverse atomList_direction_2 now to arrange them #from 5' to 3' end. atomList_direction_2.reverse() atomList.extend(atomList_direction_2) atomList.append(startAtom) atomList.extend(atomList_direction_1) #TODO: could zap first and/or last element if they are bondpoints #[bruce 080205 comment] if filterBondPoints: atomList = filter(lambda atm: not atm.is_singlet(), atomList) return atomList def _get_pam5_strand_atoms_in_bond_direction(self, inputAtomList = ()): """ Return a list of sugar atoms in a fixed direction -- from 5' to 3' @param inputAtomList: An optional argument. If its not provided, this method will return a list of all atoms within the strand, in the strand's bond direction. Otherwise, it will just return the list <inputAtomList> whose atoms are ordered in the strand's bond direction. @type inputAtomList: list (with default value as an empty tuple) @note: this is a stub and we can modify it so that it can accept other direction i.e. 3' to 5' , as an argument. [I think at most one atom at each end can be a bondpoint, so we could revise this code to remove them before returning. bruce 080205] piotr 080411: This is a helper method for 'get_strand_atoms_in_bond_direction'. It is called for PAM5 models and should be replaced by a properly modified caller method. Only bondpoints ('X') and sugar atoms ('Ss3', Ss5') are preserved. @warning: for a ring, this uses an arbitrary start atom in self (so it is not yet useful in that case). ### VERIFY @note: this would return all atoms from an entire strand (chain or ring) even if it spanned multiple chunks. """ ### TODO: merge this with its caller, since they have lots of duplicated code. startAtom = None atomList = [] rawAtomList = [] if inputAtomList: rawAtomList = inputAtomList else: for c in self.members: if isinstance(c, DnaStrandChunk): rawAtomList.extend(c.atoms.itervalues()) #Choose startAtom randomly (make sure that it's a Sugar atom # and not a bondpoint) for atm in rawAtomList: if atm.element.symbol == 'Ss3' or \ atm.element.symbol == 'Ss5': startAtom = atm break if startAtom is None: print_compact_stack("bug: no Sugar atom (Ss3 or Ss5) found: " ) return [] #Build one list in each direction, detecting a ring too #ringQ decides whether the first returned list forms a ring. #This needs a better name in bond_chains.grow_directional_bond_chain ringQ = False atomList_direction_1 = [] atomList_direction_2 = [] b = None bond_direction = 0 for bnd in startAtom.directional_bonds(): if not bnd.is_open_bond(): # (this assumes strand length > 1) #Determine the bond_direction from the 'startAtom' direction = bnd.bond_direction_from(startAtom) if direction in (1, -1): b = bnd bond_direction = direction break if b is None or bond_direction == 0: return [] #Find out the list of new atoms and bonds in the direction #from bond b towards 'startAtom' . This can either be 3' to 5' direction #(i.e. bond_direction = -1 OR the reverse direction # Later, we will check the bond direction and do appropriate things. #(things that will decide which list (atomList_direction_1 or #atomList_direction_2) should be prepended in atomList so that it has #atoms ordered from 5' to 3' end. # 'atomList_direction_1' does NOT include 'startAtom'. # See a detailed explanation below on how atomList_direction_a will be # used, based on bond_direction ringQ, listb, atomList_direction_1 = grow_directional_bond_chain(b, startAtom) del listb # don't need list of bonds if ringQ: # The 'ringQ' returns True So its it's a 'ring'. #First add 'startAtom' (as its not included in atomList_direction_1) atomList.append(startAtom) #extend atomList with remaining atoms atomList.extend(atomList_direction_1) else: #Its not a ring. Now we need to make sure to include atoms in the #direction_2 (if any) from the 'startAtom' . i.e. we need to grow #the directional bond chain in the opposite direction. other_atom = b.other(startAtom) if not other_atom.is_singlet(): ringQ, listb, atomList_direction_2 = grow_directional_bond_chain(b, other_atom) assert not ringQ #bruce 080205 del listb #See a detailed explanation below on how #atomList_direction_2 will be used based on 'bond_direction' atomList_direction_2.insert(0, other_atom) atomList = [] # not needed but just to be on a safer side. if bond_direction == 1: # 'bond_direction' is the direction *away from* startAtom and # along the bond 'b' declared above. . # This can be represented by the following sketch -- # (3'end) <--1 <-- 2 <-- 3 <-- 4 <-- (5' end) # Let startAtom be '2' and bond 'b' be directional bond between # 1 and 2. In this case, the direction of bond *away* from # '2' and along 2 = bond direction of bond 'b' and thus # atoms traversed along bond_direction = 1 lead us to 3' end. # Now, 'atomList_direction_1' is computed by 'growing' (expanding) # a bond chain in the direction that goes from bond b # *towards* startAtom. That is, in this case it is the opposite # direction of one specified by 'bond_direction'. The last atom # in atomList_direction_1 is the (5' end) atom. # Note that atomList_direction_1 doesn't include 'startAtom' # Therefore, to get atomList ordered from 5'to 3' end we must #reverse atomList_direction_1 , then append startAtom to the #atomList (as its not included in atomList_direction_1) and then #extend atoms from atomList_direction_2. #What is atomList_direction_2 ? It is the list of atoms #obtained by growing bond chain from bond b, in the direction of #atom 1 (atom 1 is the 'other atom' of the bond) . In this case #these are the atoms in the direction same as 'bond_direction' #starting from atom 1. Thus the atoms in the list are already #arranged from 5' to 3' end. (also note that after computing #the atomList_direction_2, we also prepend 'atom 1' as the #first atom in that list. See the code above that does that. atomList_direction_1.reverse() atomList.extend(atomList_direction_1) atomList.append(startAtom) atomList.extend(atomList_direction_2) else: #See a detailed explanation above. #Here, bond_direction == -1. # This can be represented by the following sketch -- # (5'end) --> 1 --> 2 --> 3 --> 4 --> (3' end) #bond b is the bond betweern atoms 1 and 2. #startAtom remains the same ..i.e. atom 2. #As you can notice from the sketch, the bond_direction is #direction *away* from 2, along bond b and it leads us to # 5' end. #based on how atomList_direction_2 (explained earlier), it now #includes atoms begining at 1 and ending at 5' end. So #we must reverse atomList_direction_2 now to arrange them #from 5' to 3' end. atomList_direction_2.reverse() atomList.extend(atomList_direction_2) atomList.append(startAtom) atomList.extend(atomList_direction_1) # Note: the bondpoint atoms are NOT included. # ONLY consecutive sugar stoms are returned. # piotr 080411 # extract only sugar atoms or bondpoints # the bondpoints are extracted to make the method compatible # with get_strand_atoms_in_bond_direction def filter_sugars(atm): return atm.element.symbol == 'Ss3' or \ atm.element.symbol == 'Ss5' or \ atm.element.symbol == 'X' atomList = filter(filter_sugars, atomList) return atomList pass # end
NanoCAD-master
cad/src/dna/model/DnaStrand.py
# Copyright 2008 Nanorex, Inc. See LICENSE file for details. """ DnaLadder_pam_conversion.py - PAM3+5 <-> PAM5 conversion methods for DnaLadder, and (perhaps in future) related helper functions. @author: Bruce @version: $Id$ @copyright: 2008 Nanorex, Inc. See LICENSE file for details. """ from model.elements import Pl5, Ss5, Ax5, Gv5 from model.elements import Ss3, Ax3 from model.elements import Singlet from model.bonds import bond_direction #e rename from model.bonds import bond_atoms_faster, bond_atoms from model.bond_constants import V_SINGLE from utilities.constants import Pl_STICKY_BOND_DIRECTION from utilities.constants import MODEL_PAM3, MODEL_PAM5, PAM_MODELS, MODEL_MIXED from utilities.constants import noop from utilities.constants import average_value from utilities.constants import white, gray, ave_colors from utilities import debug_flags from utilities.debug import print_compact_stack from utilities.Log import redmsg, orangemsg, quote_html from utilities.GlobalPreferences import debug_pref_enable_pam_convert_sticky_ends from geometry.VQT import V, Q, norm import math import foundation.env as env from dna.model.dna_model_constants import LADDER_ENDS from dna.model.dna_model_constants import LADDER_END0 from dna.model.dna_model_constants import LADDER_END1 from dna.model.dna_model_constants import LADDER_BOND_DIRECTION_TO_OTHER_AT_END_OF_STRAND1 from dna.model.pam3plus5_math import other_baseframe_data from dna.model.pam3plus5_math import compute_duplex_baseframes from dna.model.pam3plus5_math import correct_Ax3_relative_position from dna.model.pam3plus5_math import relpos_in_other_frame from dna.model.pam3plus5_math import SPRIME_D_SDFRAME from dna.model.pam3plus5_math import baseframe_rel_to_abs from dna.model.pam3plus5_ops import Gv_pos_from_neighbor_PAM3plus5_data from dna.model.pam3plus5_ops import insert_Pl_between from dna.model.pam3plus5_ops import find_Pl_between from dna.model.pam3plus5_ops import kill_Pl_and_rebond_neighbors from dna.updater.dna_updater_globals import _f_ladders_with_up_to_date_baseframes_at_ends from dna.updater.dna_updater_globals import _f_atom_to_ladder_location_dict from dna.updater.dna_updater_globals import _f_baseatom_wants_pam GHOST_BASE_COLOR = ave_colors( 0.7, white, gray ) # == class DnaLadder_pam_conversion_methods: """ """ def pam_model(self): #bruce 080401, revised 080408 """ Return an element of PAM_MODELS (presently MODEL_PAM3 or MODEL_PAM5) which indicates the PAM model of all atoms in self, if this is the same for all of self's baseatoms; if not, return MODEL_MIXED. Assume it's the same in any one rail of self. @note: we are considering allowing mixed-PAM ladders, as long as each rail is consistent. If we do, all uses of this method will need review, since they were written before it could return MODEL_MIXED in that case. """ results = [rail.baseatoms[0].element.pam for rail in self.all_rails()] res = results[0] for res1 in results: if res1 != res: print "fyi: inconsistent pam models %r in rails of %r" % (results, self) #### temporary return MODEL_MIXED # prevents pam conversion, may cause other bugs if callers not reviewed @@@ continue return res def _pam_conversion_menu_spec(self, selobj): #bruce 080401, split 080409 """ Return a menu_spec list of context menu entries related to PAM conversion, which is (or might be) specific to selobj being a PAM atom or chunk whose DnaLadder is self. (If we have no entries, return an empty menu_spec list, namely [].) (Other kinds of selobj might be permitted later.) """ del selobj # there's not yet any difference in this part of the cmenu # for different selobj or selobj.__class__ in same DnaLadder res = [] pam_model = self.pam_model() nwhats = self._n_bases_or_basepairs_string() if pam_model == MODEL_PAM3: res.append( ("Convert %s to PAM5" % nwhats, self.cmd_convert_to_pam5) ) elif pam_model == MODEL_PAM5: res.append( ("Convert %s to PAM3" % nwhats, self.cmd_convert_to_pam3) ) elif pam_model == MODEL_MIXED: res.append( ("Mixed PAM models in %s, conversion nim" % nwhats, noop, 'disabled') ) else: assert 0, "unexpected value %r of %r.pam_model()" % (pam_model, self) pass # TODO: # later, add conversions between types of ladders (duplex, free strand, sticky end) # and for subsections of a ladder (base pairs of selected atoms?) # and for larger parts of the model (duplex == segment, strand, DnaGroup), # and commands to do other things to those (e.g. select them). return res def cmd_convert_to_pam5(self): """ Command to convert all of self to PAM5. """ self._cmd_convert_to_pam(MODEL_PAM5) def cmd_convert_to_pam3(self): """ Command to convert all of self to PAM3. """ self._cmd_convert_to_pam(MODEL_PAM3) def _cmd_convert_to_pam(self, which_model): """ Command to convert all of self to one of the PAM_MODELS. """ # WARNING: _convert_to_pam and _cmd_convert_to_pam are partly redundant; # cleanup needed. [bruce 080519 comment in two places] # #revised, bruce 080411 if _f_baseatom_wants_pam: print "unexpected: something called %r._cmd_convert_to_pam(%r) " \ "but _f_baseatom_wants_pam is not empty" % \ ( self, which_model) # should be safe, so don't clear it [bruce 080413 revision] # Note: if general code (not just our own cmenu ops) could call this # method, that code might assume it could call it on more than one # DnaLadder during one user event handler. That would be reasonable # and ok, so if this is ever wanted, we'll just remove this print. pass env.history.graymsg(quote_html("Debug fyi: Convert %r to %s" % (self, which_model))) ##### for rail in self.all_rails(): for baseatom in rail.baseatoms: _f_baseatom_wants_pam[baseatom.key] = which_model self.arbitrary_baseatom().molecule.assy.changed() # might be needed for chunk in self.all_chunks(): chunk.display_as_pam = None del chunk.display_as_pam chunk.save_as_pam = None del chunk.save_as_pam # (see related code to the following, in class ops_pam_Mixin) # Tell dna updater to remake self and its connected ladders # (which would otherwise be invalidated during updater run (a bug) # by rebonding, or by adding/removing Pls to their chunks) # from scratch (when it next runs); # it will notice our atoms added to _f_baseatom_wants_pam, # and do the actual conversion [mostly working as of 080411 late] # (might not be needed due to upcoming code in dna updater which # processes _f_baseatom_wants_pam at the start of each updater run, # but safe, so kept for now -- bruce 080413) inval_these = [self] + self.strand_neighbor_ladders() # might contain Nones or duplicate entries; # including the neighbor ladders is # hoped to be a bugfix for messing up neighboring ladders # [bruce 080413 1040am pt...] # turns out not enough, but reason is finally known -- # not only Pl add/remove, but even just transmute doing changed # structure calls on neighbor atoms (I think), is enough to # inval the neighbor ladder at a time when this is not allowed # during the dna updater run. So I'll commit this explan, # partial fix, and accumulated debug code and minor changes, # then put in the real fix elsewhere. [update same day -- # after that commit I revised this code slightly] for ladder in inval_these: if ladder is not None: ladder._dna_updater_rescan_all_atoms() # should be ok to do this twice to one ladder # even though it sets ladder invalid the first time # just to be sure I'm right, do it again: ladder._dna_updater_rescan_all_atoms() continue return def _f_convert_pam_if_desired(self, default_pam_model): #bruce 080401 """ [friend method for dna updater] If self's atoms desire it, try to convert self to a different pam model for display. On any conversion error, report to history (summary message), mark self with an error, and don't convert anything in self. On success, only report to history if debug_prefs desire this. Return success-related flags. @note: if conversion is wanted and succeeded, it is unfinished regarding bridging Pl atoms between two strand-rail-ends (usually of this and another ladder, but possibly between two strand-rail-ends of this ladder). If any such atoms will ultimately be needed on self, they are present, but some atoms may be present which need to be killed; and the position of live Pl atoms, and the related +5 data on Ss3 atoms next to Pl atoms which need to be killed, may not yet be fully updated. So, after all ladders have been asked to convert, the caller needs to iterate over them again to find bridging Pls to fix, and fix those by calling _f_finish_converting_bridging_Pl_atoms on each ladder. @return: a pair of booleans: (conversion_wanted, conversion_succeeded). """ want = self._want_pam(default_pam_model) # might be None, which means, whatever you already are have = self.pam_model() # might be MODEL_MIXED if want == have or want is None: # no conversion needed # TODO: reenable this summary message when we're running due to manual # pam conversion command... I am disabling it since it also affects # file open, copy, etc. [bruce 080414 12:42pm PT, not in rc0] ## summary_format = "Note: [N] DnaLadder(s) were/was already in requested PAM model" ## env.history.deferred_summary_message( summary_format ) return False, False assert want in PAM_MODELS # can't be MODEL_MIXED succeeded = self._convert_to_pam(want) # someday this can work for self being MODEL_MIXED if succeeded == -1: # conversion not wanted/needed, or not implemented; # it already emitted appropriate message return False, False if not succeeded: summary_format = "Error: PAM conversion failed for [N] DnaLadder(s)" env.history.deferred_summary_message( redmsg( summary_format)) # Now change the chunk options so they don't keep trying to reconvert... # this is hard, since self's chunks haven't yet been remade, # so each atom might have different chunks and might share them with # other ladders. Not sure what the best solution is... it's good if # changing the ladder lets user try again, but nothing "automatically" # tries again. Maybe wait and revise chunk options after ladder chunks # are remade? For any error, or just a PAM error? I think any error. # Ok, do that right in DnaLadder.remake_chunks. But what do we change # them to? "nothing" is probably best, even though in some cases that # means we'll retry a conversion. Maybe an ideal fix needs to know, # per chunk, the last succeeding pam as well as the last desired one? return True, succeeded # REVIEW: caller bug (asfail) when we return True, False?? def _want_pam(self, default_pam_model): #bruce 080411 """ """ atom = self.arbitrary_baseatom() # by construction, all our baseatoms want the same pam_model try: return _f_baseatom_wants_pam[atom.key] # supersedes everything else except KeyError: pass ## want = atom.molecule.display_as_pam want = "" #bruce 080519 fix or mitigate bug 2842 (ignore .display_as_pam) # NOTE: all sets and uses of .display_as_pam will ultimately need # fixing, since users of v1.0.0 or v1.0.1 might have created # mmp files which have it set on their chunks but shouldn't # (by creating a PAM5 duplex and converting that to PAM3), # and since the manual conversion in ops_pam.py has the bug of # not clearing this (the older cmenu conversion ops do clear it # as they should). This mitigation removes its ability to cause # conversions (when debug_prefs are not set); it leaves its # ability to prevent some dna ladder merging, but that is either # ok or a rarer bug. A better mitigation or fix needs to be done # in time for v1.1. [bruce 080519 comment] if not want: want = default_pam_model # might be None, which means, whatever you already are return want def _convert_to_pam(self, pam_model): #bruce 080401 """ [private helper for _f_convert_pam_if_desired; other calls might be added] Assume self is not already in pam_model but wants to be. If conversion to pam_model can succeed, then do it by destructively modifying self's atoms, but preserve their identity (except for Pl) and the identity of self, and return True. (This usually or always runs during the dna updater, which means that the changes to atoms in self will be ignored, rather than causing self to be remade.) If conversion can't succeed due to an error, return False. Or if it should not run, or need not run, or is not yet implemented, return -1. Don't modify self or its atoms in these cases. """ # WARNING: _convert_to_pam and _cmd_convert_to_pam are partly redundant; # cleanup needed. [bruce 080519 comment in two places] # # various reasons for conversion to not succeed; # most emit a deferred_summary_message if not self.valid: # caller should have rejected self before this point # (but safer to not assert this, but just debug print for now) print "bug?: _convert_to_pam on invalid ladder:", self summary_format = "Bug: PAM conversion attempted on [N] invalid DnaLadder(s)" env.history.deferred_summary_message( redmsg( summary_format )) return -1 if self.error: # cmenu caller should have rejected self before this point # (but safer to not assert this, but just debug print for now); # but when called from the ui actions, self.error # is not a bug or even really an error... ## print "bug?: _convert_to_pam on ladder with error:", self summary_format = "Warning: PAM conversion refused for [N] DnaLadder(s) with errors" env.history.deferred_summary_message( redmsg( summary_format )) # red warning is intended return -1 self_pam_model = self.pam_model() if self_pam_model == MODEL_MIXED: summary_format = "Warning: PAM conversion not implemented for [N] DnaLadder(s) with mixed PAM models" env.history.deferred_summary_message( orangemsg( summary_format )) return -1 if self.axis_rail: element = self.axis_rail.baseatoms[0].element if element not in (Gv5, Ax3): # e.g. it might be Ax5 summary_format = "Warning: PAM conversion not implemented for [N] DnaLadder(s) with %s axis" % \ element.symbol env.history.deferred_summary_message( orangemsg( summary_format )) print "conversion from PAM axis element %r is not yet implemented (in %r)" % \ (self.axis_rail.baseatoms[0].element, self) return -1 pass if self_pam_model == pam_model: # note: should never happen (AFAIK) since caller handles it, # but preserve this just in case; meanwhile this code is copied into caller, # with a slight text revision here so we can figure out if this one happens summary_format = "Note: [N] DnaLadder(s) were/was already in desired PAM model" env.history.deferred_summary_message( summary_format ) return -1 # fail gracefully for not yet implemented cases; # keep this in sync with self.can_make_up_Pl_abs_position_for() if not self.axis_rail: summary_format = "Warning: PAM conversion not implemented for [N] DnaSingleStrandDomain(s)" env.history.deferred_summary_message( orangemsg( summary_format )) return -1 nstrands = len(self.strand_rails) if nstrands == 0: summary_format = "Warning: PAM conversion not implemented for [N] bare axis DnaLadder(s)" env.history.deferred_summary_message( orangemsg( summary_format )) return -1 elif nstrands == 1: # sticky end (might be PAM3 or PAM5) if not debug_pref_enable_pam_convert_sticky_ends(): summary_format = "Warning: PAM conversion not enabled for [N] sticky end DnaLadder(s)" # need to have a method to describe self, since if it's in the middle of a segment # then we should not call it a sticky end ###FIX env.history.deferred_summary_message( orangemsg( summary_format )) return -1 elif self_pam_model != MODEL_PAM3: # PAM5 sticky end -- conversion is not yet implemented (needs baseframes) (ghost bases also nim) summary_format = "Warning: PAM conversion not implemented for [N] PAM5 sticky end DnaLadder(s)" env.history.deferred_summary_message( redmsg( summary_format )) return -1 else: # PAM3 sticky end -- should be ok pass elif nstrands > 2: summary_format = "Bug: PAM conversion attempted on [N] DnaLadder(s) with more than two strands" env.history.deferred_summary_message( redmsg( summary_format )) return -1 # do the conversion. # first compute and store current baseframes on self, where private # methods can find them on demand. REVIEW: need to do this on connected ladders # not being converted, for sake of bridging Pl atoms? Not if we can do those # on demand, but then we'd better inval them all first! Instead, caller initializes # a global _f_ladders_with_up_to_date_baseframes_at_ends (formerly a parameter # ladders_dict) (search for mentions of that global in various places, for doc). ok = self._compute_and_store_new_baseframe_data() # note: this NO LONGER (as of 080528) calls make_ghost_bases [nim] # if necessary to make sure we temporarily have a full set of 2 strand_rails. # what to do for non-axis ladders is not yet reviewed or implemented. @@@@ if not ok: print "baseframes failed for", self # todo: summary message return False # print "fyi, %r._compute_and_store_new_baseframe_data computed this:" % self, self._baseframe_data # now we know we'll succeed (unless there are structural errors detected # only now, which shouldn't happen since we should detect them all # earlier and not form the ladder or mark it as an error, but might # happen anyway), and enough info is stored to do the rest per-atom # for all atoms entirely convertable inside this ladder (i.e. all except # bridging Pls). # we'll do the following things: # - if converting to PAM5, make a Pl at each corner that doesn't have # one but needs one (even if it belongs to the other ladder there, # in case that one is remaining PAM3 so won't make it itself). # Mark this Pl as non-definitive in position; it will be fixed later # (when its other ladder's baseframes are also surely available) # by self._f_finish_converting_bridging_Pl_atoms. # - create or destroy interior Pls as needed. # - transmute and reposition the atoms of each basepair or base. # - if we converted to PAM3, remove ghost bases if desired. # Most of these steps can be done in any order, since they rely on the # computed baseframes to know what to do. They are all most efficient # if we know the base indices as we go, so do them in a loop or loops # over base indices. self._convert_axis_to_pam(pam_model) # moves and transmutes axis atoms for rail in self.strand_rails: self._convert_strand_rail_to_pam(pam_model, rail) # moves and transmutes sugars, makes or removes Pls, # but does not notice or remove ghost bases continue if pam_model == MODEL_PAM5: self._make_bridging_Pls_as_needed() if pam_model == MODEL_PAM3: # (do this last) # todo: remove ghost bases if desired pass # optional: remove all baseframe data except at the ends # (in case needed by bridging Pls) -- might help catch bugs or save RAM return True # could put above in try/except and return False for exceptions def can_make_up_Pl_abs_position_for(self, ss, direction): #bruce 080413 """ Are we capable of making up an absolute Pl position in space for the given strand atom ss of ours, for the Pl in the given bond direction from it? """ # for now, assume yes if we're a duplex with no error and ok axis elements; # keep this in sync with the code in _convert_to_pam del ss, direction if not self.valid or self.error: print "reason 1" return False if len(self.strand_rails) != 2: print "reason 2" return False if not self.axis_rail: print "reason 3" return False if self.axis_rail.baseatoms[0].element not in (Ax3, Gv5): print "reason 4" return False return True def _convert_axis_to_pam(self, want_pam_model): """ moves and transmutes axis atoms, during conversion to specified pam_model """ # note: make this work even if not needed (already correct pam model) # for robustness (if in future we have mixed models, or if bugs call it twice), # but say this happens in a print (since unexpected) assert self.valid and not self.error axis_atoms = self.axis_rail.baseatoms if want_pam_model == MODEL_PAM5: # they are presumably Ax3, need to become Gv5 and get moved. # (but don't move if already Gv5 for some reason) for i in range( len(axis_atoms)): atom = axis_atoms[i] if atom.element is not Gv5: # move it in space to a saved or good position for a Gv5 # (this works even if the neighbors are Ss5 and atom # is Ax5, since it uses baseframes, not neighbor posns) newpos = Gv_pos_from_neighbor_PAM3plus5_data( atom.strand_neighbors(), remove_data_from_neighbors = True ) # fyi, done inside that (should optim by passing i at least): ## origin, rel_to_abs_quat, y_m = self._baseframe_data[i] assert newpos is not None, "can't compute new position for Gv5!" # should never happen, even for bare axis # (no strand_neighbors), since we made up ghost bases earlier atom.setposn(newpos) # transmute it atom.mvElement(Gv5) else: print "unexpected: %r is already Gv5" % atom # this might turn out to be normal if we can someday convert # PAM5-with-Ax5 (in old mmp files) to PAM5-with-Gv5. continue pass elif want_pam_model == MODEL_PAM3: # they might be already Ax3 (unexpected, no move needed (but might be ok or good?)) # or Ax5 (legal but not yet supported in callers; no move needed # if posn correct, but this is not guaranteed so move might be good) # or Gv5 (move needed). Either way, transmute to Ax3. for i in range( len(axis_atoms)): atom = axis_atoms[i] if atom.element is Gv5: atom._f_Gv_store_position_into_Ss3plus5_data() # always move in space (even if atom is already Ax5 or even Ax3), # since PAM3 specifies only one correct Ax3 position, given the # baseframes (ref: the wiki page mentioned in another file) origin, rel_to_abs_quat, y_m = self._baseframe_data[i] # it's ok to assume that data exists and is up to date, # since our callers (known since we're a private helper) # just recomputed it relpos = correct_Ax3_relative_position(y_m) newpos = baseframe_rel_to_abs(origin, rel_to_abs_quat, relpos) atom.setposn( newpos) # transmute it # don't bother checking for unexpected element, or whether this is needed atom.mvElement(Ax3) ###k check if enough invals done, atomtype updated, etc @@@ pass else: assert 0 return def _convert_strand_rail_to_pam(self, want_pam_model, rail): #bruce 080409, modified from _convert_axis_to_pam """ [private helper, during conversion to specified pam_model] moves and transmutes strand sugar PAM atoms, and makes or removes Pls, but does not notice ghost status of bases or remove ghost bases """ assert self.valid and not self.error # note: make this work even if not needed (already correct pam model) # for robustness (if in future we have mixed models, or if bugs call it twice), # but say this happens in a print (since unexpected) strand_baseatoms = rail.baseatoms is_strand2 = (rail is not self.strand_rails[0]) if want_pam_model == MODEL_PAM5: # atoms are presumably Ss3, need to become Ss5 and get moved # and get Pls inserted between them (inserting Pls at the ends # where self joins other ladders is handled by a separate method) for i in range( len(strand_baseatoms)): atom = strand_baseatoms[i] if atom.element is Ss3: # transmute it [just to prove we can do these steps # in whatever order we want] atom.mvElement(Ss5) # move it in space origin, rel_to_abs_quat, y_m = self._baseframe_data[i] if is_strand2: relpos = V(0, 2 * y_m, 0) else: relpos = V(0, 0, 0) # could optimize this case: newpos = origin newpos = baseframe_rel_to_abs(origin, rel_to_abs_quat, relpos) atom.setposn(newpos) if i + 1 < len(strand_baseatoms): # insert a Pl linker between atom i and atom i+1, # and put it at the correct position in space # (share code with the corner-Pl-inserter) # assume seeing one Ss3 means entire strand is Ss3 and # has no Pl linkers now Pl = insert_Pl_between(atom, strand_baseatoms[i+1]) # move that Pl to the correct position Pl._f_Pl_set_position_from_Ss3plus5_data() pass pass elif atom.element is Ss5: print "unexpected: strand rail %r (judging by atom %r) seems to be already PAM5" % (rail, atom) # don't break loop here, in case this repairs a bug from an earlier exception # partway through a pam conversion (not too likely, but then neither is this case at all, # so we don't need to optimize it) pass else: print "likely bug: %r is not Ss3 or Ss5" % atom continue pass elif want_pam_model == MODEL_PAM3: # atoms might be already Ss3 (unexpected, no move needed (but might be ok or good?)) # or Ss5 (move needed). Either way, transmute to Ss3, store Pl data, remove Pls. for i in range( len(strand_baseatoms)): atom = strand_baseatoms[i] # move it in space (doesn't matter what element it is) origin, rel_to_abs_quat, y_m = self._baseframe_data[i] relpos = SPRIME_D_SDFRAME if is_strand2: relpos = relpos_in_other_frame(relpos, y_m) newpos = baseframe_rel_to_abs(origin, rel_to_abs_quat, relpos) atom.setposn(newpos) # transmute it atom.mvElement(Ss3) if i + 1 < len(strand_baseatoms): # find a Pl linker between atom i and atom i+1 # (None if not there since they are directly bonded) Pl = find_Pl_between(atom, strand_baseatoms[i+1]) if Pl is not None: # store Pl data Pl._f_Pl_store_position_into_Ss3plus5_data() # remove Pl kill_Pl_and_rebond_neighbors(Pl) pass continue pass else: assert 0 return # from _convert_strand_rail_to_pam def _make_bridging_Pls_as_needed(self): #bruce 080410 """ We just converted self to PAM5 (or tried to). Find all places where self touches another ladder (or touches itself at the corners, where a strand rail ends), and if any of them now need, but don't yet have, a bridging Pl atom, make one, with a non-definitive position. (Also make one at strand ends, i.e. between Ss5-X, if needed and correct re bond directions.) ### REVIEW: is that case handled in _f_finish_converting_bridging_Pl_atoms? """ assert self.valid and not self.error # similar code to _bridging_Pl_atoms, and much of its checks are # redundant and not needed in both -- REVIEW which one to remove them from if self.error or not self.valid: # caller should have rejected self before this point # (but safer to not assert this, but just debug print for now) print "bug: _make_bridging_Pls_as_needed on ladder with error or not valid:", self return res = {} for end_atom, next_atom in self._corner_atoms_with_next_atoms_or_None(): # next_atom might be None (??) or a non-Pl atom if next_atom is not None and next_atom.element is Pl5: continue # nothing to do here (we never remove a Pl or move it) # review: is next_atom a bondpoint, None, or both, when a strand ends? I think a bondpoint, # this code only works properly for that case. if next_atom is None: print "***BUG: _make_bridging_Pls_as_needed(%r) doesn't handle next_atom is None" % self continue # assume it's a bondpoint or Ss3 or Ss5. We want Pl iff either atom is Ss5. def atom_wants_Pl(atom): return atom.element is Ss5 # maybe: also check for error on this atom? want_Pl = atom_wants_Pl(end_atom) or atom_wants_Pl(next_atom) if want_Pl: # inserting Pl5 between Ss5-X is only correct at one end # of a PAM5 strand ... see if the direction in which it prefers # to stick with Ss points to an X among these atoms, and if so, # don't insert it, though the function would work if we tried. if Pl_STICKY_BOND_DIRECTION == bond_direction(end_atom, next_atom): Pl_sticks_to = next_atom # not literally true if next_atom is a bondpoint, fyi else: Pl_sticks_to = end_atom if not Pl_sticks_to.is_singlet(): insert_Pl_between(end_atom, next_atom) continue return def _f_finish_converting_bridging_Pl_atoms(self): #bruce 080408 """ [friend method for dna updater] @see: _f_convert_pam_if_desired, for documentation. @note: the ladders in the dict are known to have valid baseframes (at least at the single basepairs at both ends); this method needs to look at neighboring ladders (touching self at corners) and use end-baseframes from them; if it sees one not in the dict, it makes it compute and store its baseframes (perhaps just at both ends as an optim) and also stores that ladder in the dict so this won't be done to it again (by some other call of this method from the same caller using the same dict). """ assert self.valid and not self.error for Pl in self._bridging_Pl_atoms(): Pl._f_Pl_finish_converting_if_needed() # note: this might kill Pl. return def _bridging_Pl_atoms(self): #bruce 080410 revised this to call _corner_atoms_with_next_atoms_or_None # (split out from this) """ [private helper] Return a list of all Pl atoms which bridge ends of strand rails between self and another ladder, or between self and self (which means the Pl is connecting end atoms not adjacent in self, not an interior Pl atom [but see note for a possible exception]). or between self and a bondpoint. Make sure this list includes any Pl atom only once. @note: a length-2 ring is not allowed, so this is not ambiguous -- a Pl connecting the end atoms of a length-2 strand rail is an interior one; two such Pls are possible in principle but are not allowed. (They might be constructible, so at least we should not crash then -- we'll try to use bond directions to decide which one is interior and which one is bridging.) """ if self.error or not self.valid: # caller should have rejected self before this point # (but safer to not assert this, but just debug print for now) print "bug: _bridging_Pl_atoms on ladder with error or not valid:", self return res = {} for end_atom, next_atom in self._corner_atoms_with_next_atoms_or_None(): if end_atom._dna_updater__error: print "bug: %r has _dna_updater__error %r in %r, returning no _bridging_Pl_atoms" % \ (end_atom, end_atom._dna_updater__error, self) return [] possible_Pl = next_atom # might be None or a non-Pl atom; if a Pl atom, always include in return value, # unless it has a _dna_updater__error, in which case complain and bail if possible_Pl is not None and possible_Pl.element is Pl5: if possible_Pl._dna_updater__error: print "bug: possible_Pl %r has _dna_updater__error %r in %r, returning no _bridging_Pl_atoms" % \ (possible_Pl, possible_Pl._dna_updater__error, self) return [] # bugfix: fixed indent level of this line [bruce 080412] res[possible_Pl.key] = possible_Pl continue res = res.values() return res def _corner_atoms_with_next_atoms_or_None(self): #bruce 080410 split this out of _bridging_Pl_atoms """ @note: we don't check for self.error or not self.valid, but our results can be wrong if caller didn't check for this and not call us then (since strand bond directions can be different than we assume). @return: a list of pairs (end_atom, next_atom), each describing one of our corners (ends of strand rails, of which we have 2 per strand rail); end_atom is always an Ss3 or Ss5 atom in self, but next_atom might be None, or a Pl in same or other ladder, or X in same ladder, or Ss3 or SS5 in other ladder; "other ladder" can be self if the strand connects to self. All these cases should be handled by callers; so must be checking result for repeated atoms, or for _dna_updater__error set on the atoms. """ # same implem is correct for axis ladders (superclass) and free floating # single strands (subclass) res = [] for rail in self.strand_rails: assert rail is not None for end in LADDER_ENDS: bond_direction_to_other = LADDER_BOND_DIRECTION_TO_OTHER_AT_END_OF_STRAND1[end] if rail is not self.strand_rails[0]: # note: ok if len(self.strand_rails) == 0, since we have no # itertions of the outer loop over rail in that case bond_direction_to_other = - bond_direction_to_other # ok since we don't pam_convert ladders with errors # (including parallel strand bonds) ### REVIEW: is that check implemented? end_atom = rail.end_baseatoms()[end] next_atom = end_atom.next_atom_in_bond_direction( bond_direction_to_other) # res.append( (end_atom, next_atom) ) continue continue return res def fix_bondpoint_positions_at_ends_of_rails(self): #bruce 080411 fix_soon = {} def _fix(atom): fix_soon[atom.key] = atom # first, strand rails [this is not working as of 080411 +1:14am PT] for end_atom, next_atom in self._corner_atoms_with_next_atoms_or_None(): _fix(end_atom) if next_atom is not None and next_atom.element is Pl5: # a Pl, maybe with a bondpoint _fix(next_atom) # next, axis rails [this seems to work] if self.axis_rail: _fix(self.axis_rail.baseatoms[0]) _fix(self.axis_rail.baseatoms[-1]) # now do it for atom in fix_soon.values(): if atom.element is Singlet: print "didn't expect X here:", atom continue atom.reposition_baggage() # Note: on baseatoms (and on Pl if we extend it for that), # this ends up setting a flag which causes a later call # by the same dna updater run as we're in now # to call self._f_reposition_baggage. As of now, # that only works for baseatoms, not Pls sticking out from them. # But maybe the direct code will work ok for Pl. continue return # == def clear_baseframe_data(self): assert self.valid # otherwise caller must be making a mistake to call this on self self._baseframe_data = None # if not deleted, None means it had an error, # not that it was never computed, so: del self._baseframe_data # probably not needed: ladders_dict = _f_ladders_with_up_to_date_baseframes_at_ends if ladders_dict.has_key(self): print "unexpected: %r in ladders_dict too early, when cleared" % self # only unexpected due to current usage, not an error in principle ladders_dict.pop(self, None) return def _f_store_locator_data(self): #bruce 080411 """ #doc @see: related method, whichrail_and_index_of_baseatom """ if debug_flags.DEBUG_DNA_UPDATER_VERBOSE: # 080413 print "storing locator data for", self locator = _f_atom_to_ladder_location_dict look_at_rails = self.rail_indices_and_rails() length = len(self) for index in range(length): for whichrail, rail in look_at_rails: if whichrail == 1: continue # KLUGE optim -- skip axis rail; # see LADDER_RAIL_INDICES (may exist only in docstrings) baseatom = rail.baseatoms[index] locator[baseatom.key] = (self, whichrail, index) # print "fyi: stored locator[%r.key] = %r" % (baseatom, locator[baseatom.key]) if index in (0, 1, length - 1): # slow, remove when works ### assert self.rail_at_index(whichrail).baseatoms[index] is baseatom assert self.whichrail_and_index_of_baseatom(baseatom) == (whichrail, index) # by search in self assert self._f_use_locator_data(baseatom) == (whichrail, index) # using locator global continue continue return def _f_use_locator_data(self, baseatom): #bruce 080411 # so far, used only for asserts above locator = _f_atom_to_ladder_location_dict ladder, whichrail, index = locator[baseatom.key] assert ladder is self return whichrail, index def _f_baseframe_data_at(self, whichrail, index): # bruce 080402 """ #doc """ if not self.valid: #bruce 080411 # maybe make this an assertion failure? print "likely bug: invalid ladder in _f_baseframe_data_at(%r, %r, %r)" % \ (self, whichrail, index) ladders_dict = _f_ladders_with_up_to_date_baseframes_at_ends # review: is this code needed elsewhere? # caller is not sure self._baseframe_data is computed and/or # up to date, and is keeping a set of ladders in which it's knowmn # to be up to date (at least at the ends, which is all it needs # for the ladders it's not sure about) in the above global known # locally as ladders_dict. # If we're not in there, compute our baseframe data and store it # (at least at the first and last basepair) and store self into # ladders_dict. [bruce 080409] assert type(ladders_dict) is type({}) if self not in ladders_dict: assert index == 0 or index == len(self) - 1, \ "_f_baseframe_data_at%r: index not at end but self not in ladders_dict" % \ ( (self, whichrail, index), ) self._compute_and_store_new_baseframe_data( ends_only = True) pass if index == 0 or index == len(self) - 1: assert ladders_dict.has_key(self) else: assert ladders_dict[self] == False, \ "_f_baseframe_data_at%r: index not at end but ladders_dict[self] != False, but %r" % \ ( (self, whichrail, index), ladders_dict[self]) # not ends_only, i.e. full recompute baseframe_data = self._baseframe_data if whichrail == 0: return baseframe_data[index] assert whichrail == 2 return other_baseframe_data( * baseframe_data[index] ) # maybe: store this too (precomputed), as an optim def _compute_and_store_new_baseframe_data(self, ends_only = False): #bruce 080408 """ @return: success boolean """ assert self.valid and not self.error # note: this implem is for an axis ladder, having any number of strands. # The DnaSingleStrandDomain subclass overrides this. #### DOIT # This version, when converting to PAM5, first makes up "ghost bases" # for missing strands, so that all strands are present. For PAM5->PAM3 # it expects those to be there, but if not, makes them up anyway; # then at the end (with PAM3) removes any ghost bases present. # Ghost bases are specially marked Ss or Pl atoms. # The ghost attribute is stored in the mmp file, and is copyable and undoable. #### DOIT self._baseframe_data = None assert self.axis_rail, "need to override this in the subclass" if ends_only: if debug_flags.DEBUG_DNA_UPDATER_VERBOSE: # 080413 print "fyi: %r._compute_and_store_new_baseframe_data was only needed at the ends, optim is nim" % self # using ends_only is an optim, not yet implemented assert len(self.strand_rails) == 2 data = [] for rail in self.all_rail_slots_from_top_to_bottom(): baseatoms = rail.baseatoms posns = [a.posn() for a in baseatoms] data.append(posns) baseframes = compute_duplex_baseframes(self.pam_model(), data) # even if this is None, we store it, and store something saying we computed it # so we won't try to compute it again -- though uses of it will fail. if debug_flags.DEBUG_DNA_UPDATER_VERBOSE: # 080413 print "fyi: computed baseframes (ends_only = %r) for %r; success == %r" % \ (ends_only, self, (baseframes is not None)) print " details of self: valid = %r, error = %r, assy = %r, contents:\n%s" % \ (self.valid, self.error, self.axis_rail.baseatoms[0].molecule.assy, self.ladder_string()) self._baseframe_data = baseframes # even if None ladders_dict = _f_ladders_with_up_to_date_baseframes_at_ends if ladders_dict.get(self, None) is not None: print "unexpected: %r was already computed (ends_only = %r), doing it again (%r)" % \ (self, ladders_dict[self], ends_only) if ends_only: # partial recompute: only record if first recompute for self ladders_dict.setdefault(self, ends_only) else: # full recompute: overrides prior record if ladders_dict.get(self, None) == True: print " in fact, very unexpected: was computed at ends and is now computed on whole" ladders_dict[self] = ends_only if baseframes is None: # todo: print summary message? give reason (hard, it's a math exception) # (warning: good error detection might be nim in there) return False return True def can_make_ghost_bases(self): #bruce 080528 """ Would a call to self.make_ghost_bases succeed in making any, or succeed by virtue of not needing to make any? """ res = len(self.strand_rails) > 0 and \ self.axis_rail and \ self.pam_model() == MODEL_PAM3 return res def make_ghost_bases(self, indices = None): #bruce 080514 unfinished (inside make_strand2_ghost_base_atom); revised 080528; REFILE some in pam3plus5_ops? """ @return: list of newly made atoms (*not* added to self as another strand_rail) @note: this is not meant to be called during a dna updater run -- it would fail or cause bugs then, except perhaps if called before the updater has dissolved ladders. """ del indices # just make all of them, for now (minor bug, but harmless in practice) assert len(self.strand_rails) != 0, \ "make_ghost_bases is NIM for bare-axis ladders like %r" % self if len(self.strand_rails) == 1: # need to make up a ghost strand rail # have one strand, need the other; use same element as in existing strand # BUT the following only works if we're PAM3, for several reasons: # - interleaving Pls is nim # - figuring out geometry assumes straight, central axis (Ax3, not Gv5) strand1 = self.strand_rails[0] axis = self.axis_rail axis_chunk = axis.baseatoms[0].molecule previous_atom = None atoms = [] # collects newly made ghost strand sugar atoms assy = self.assy ghost_chunk = assy.Chunk(assy) ghost_chunk.color = GHOST_BASE_COLOR # indicate ghost status (quick initial hack) for i in range(len(strand1)): axis_atom = axis.baseatoms[i] axis_vector = self.axis_vector_at_baseindex(i) new_atom = make_strand2_ghost_base_atom( ghost_chunk, axis_atom, axis_vector, strand1.baseatoms[i] ) # bond new_atom to axis_atom # note: new_atom has no bondpoints, but axis_atom has one # which we need to remove. We find the bondpoint farthest from # the axis and pass it, not only to specify which one to remove, # but to cause one to be removed at all. (Whether that's a bug # in bond_atoms is unclear -- see comment added to it, 080529.) bp = axis_atom.bondpoint_most_perpendicular_to_line( axis_vector) # might be None in case of bugs; that's ok for this code bond_atoms(new_atom, axis_atom, V_SINGLE, None, bp) #note: bond_atoms_faster (and probably also bond_atoms) # requires .molecule to be set on both atoms #note: bond_atoms_faster doesn't remove a bondpoint # bond it to the previous new strand atom if previous_atom: # warning: not yet implemented to correctly handle # intervening Pl for PAM5 (so don't call this for PAM5) bond = bond_atoms_faster(previous_atom, new_atom, V_SINGLE) bond.set_bond_direction_from( previous_atom, -1) # TODO: also set bond direction on the open bonds, # to avoid history warning # TODO: make Ss->Pl direction geometrically correct # in length 1 case (probably a bug in pam conversion # code elsewhere; conceivably influenced by bondpoint # positions and bond directions we can set here) # TODO: fix bug in length of open bonds (some are too long, # after conversion to PAM5 finishes) previous_atom = new_atom atoms.append(new_atom) # make bondpoints on ends of the new ghost strand. # note: this means there will be a nick between the ghost strand # and any adjacent regular strand. REVIEW: do the bondpoints overlap # in a problematic way? (Same issue for this and any other nick.) for atom in ( atoms[0], atoms[-1] ): # ok if same atom atom.make_enough_bondpoints() # not sure if this positions them well continue # picking it would be good, but causes problems (console prints # and stacks related to no .part during pick, # and to being picked when added); no time to fix them for v1.1: ## if axis_chunk.picked: ## ghost_chunk.pick() # note: for some reason it still ends up picked in the glpane. # # if the strands of original PAM3 duplex were selected when I first # entered Build Dna (which deselects them), then (running this code # by select all and then converting them to PAM5) I have bugs from this: # the PM strand list doesn't get updated right away; # but then selecting it from MT doesn't work and gives # tracebacks like "RuntimeError: underlying C/C++ object has been deleted" # about a strandListWidget. Guess: this has exposed some update bug # in the Build Dna command. I'll confer with Ninad about this ###BUG. # # but if the PAM3 strands were never selected before entering Build Dna, # I don't have those bugs. If I try to repeat them later, things behave # differently -- I still don't have the bugs, but this time, ghost strands # don't end up selected. # # [bruce 080530 1:20pm PT] # now add ghost_chunk to the right place in the model # (though dna updater will move it later) # ## assy.addnode(ghost_chunk) # revised 080530: add ghost_chunk to same DnaGroup as axis_chunk (but at toplevel within that). # Dna updater will move it, but this should avoid creating a new DnaGroup # (which hangs around empty) and the console print from doing that. dnaGroup = axis_chunk.getDnaGroup() # might be None # this only requires that axis_chunk is some kind of Chunk. # fyi: if we didn't know what kind of node it was, we'd need to use: ## node.parent_node_of_class(assy.DnaGroup) print "got DnaGroup:", dnaGroup #### if dnaGroup is not None: dnaGroup.addchild(ghost_chunk) else: # probably never happens assy.addnode(ghost_chunk) pass return atoms def axis_atom_at_extended_baseindex(self, i): #bruce 080523 """ Return the axis atom of self at the given baseindex, or if the baseindex is out of range by 1 (i.e. -1 or len(self)), return the appropriate axis atom from an adjacent axis in another DnaLadder (or the same ladder if self is a duplex ring), or None if self's axis ends on that side. """ # note: this had a bug when len(axis_atoms) == 1 # due to a bug in how axis_rail.neighbor_baseatoms was set then; # apparently nothing before this had cared about its order. # This is fixed by new code in _f_update_neighbor_baseatoms. # [080602] axis_rail = self.axis_rail axis_atoms = axis_rail.baseatoms if i == -1: res = axis_rail.neighbor_baseatoms[LADDER_END0] # might be None (or -1?) elif 0 <= i < len(axis_atoms): res = axis_atoms[i] elif i == len(axis_atoms): res = axis_rail.neighbor_baseatoms[LADDER_END1] # might be None else: assert 0, "%r.axis_atom_at_extended_baseindex len %d " \ "called with index %d, must be in [-1, len]" % \ (self, len(self), i) res = None if res == -1: # This would be a bug, but is not known to happen. # It would happen if this was called at the wrong time -- # i.e. during the dna updater, after it has dissolved # invalid ladders. Present code [080529] only calls this # outside of the dna updater, when the baseatoms # which need pam conversion are first set or are # extended to whole basepairs. msg = "bug: res == -1 for %r.axis_atom_at_extended_baseindex len %d " \ "index %d; returning None instead" % \ (self, len(self), i) print_compact_stack(msg + ": ") res = None return res def axis_vector_at_baseindex(self, i): #bruce 080514/080523 """ """ # todo: see if DnaCylinder display style code has a better version atoms = map( self.axis_atom_at_extended_baseindex, [i - 1, i, i + 1] ) candidates = [] if atoms[0] is not None: candidates.append( norm( atoms[1].posn() - atoms[0].posn() )) if atoms[2] is not None: candidates.append( norm( atoms[2].posn() - atoms[1].posn() )) if not candidates: # length 1 axis WholeChain print "BUG: length 1 axis vector nim, using V(1, 0, 0):", self, i return V(1, 0, 0) # unideal -- should return a perpendicular to a rung bond if we have one return average_value(candidates) pass # end of class DnaLadder_pam_conversion_methods # == def make_strand2_ghost_base_atom( chunk, axis_atom, axis_vector, strand1_atom ): ### REFILE - pam3plus5_ops? has imports too #bruce 080514 unfinished, see TODO comments """ Make a ghost base atom to go in the same basepair as axis_atom and strand1_atom (which must be bonded and of the correct elements). Assume axis_vector points towards the next base (strand1 direction of 1). Give the new atom the ghost base atom property [nim], but don't make any bonds or bondpoints on it (not even the bond from it to axis_atom), or add it to any chunk. If strand1_atom has sequence info assigned, assign its complement to the new atom. @return: the new ghost base atom @warning: not yet implemented for PAM5. """ origin = axis_atom.posn() assert axis_atom.element is Ax3 # wrong formulae otherwise s1pos = strand1_atom.posn() DEGREES = 2 * math.pi / 360 angle = 133 * DEGREES # value and sign are guesses, but seem to be right, or at least close ### REVIEW quat = Q(axis_vector, angle) s2pos = quat.rot(s1pos - origin) + origin from model.chem import Atom strand2_atom = Atom(strand1_atom, s2pos, chunk) ### TODO: complement sequence ## if strand1_atom._dnaBaseName: ## strand2_atom._dnaBaseName = some_function(strand1_atom._dnaBaseName) # set ghost property # (review: will we call these ghost bases or placeholder bases?) # (note: this property won't be set on bondpoints of strand2_atom, # since those get remade too often to want to maintain that, # but drawing code should implicitly inherit it onto them # once it has any drawing effects. It also won't be set on Pl atoms # between them, for similar reasons re pam conversion; drawing code # should handle that as well, if all Ss neighbors are ghosts.) strand2_atom.ghost = True print "made ghost baseatom", strand2_atom # not too verbose, since sticky ends should not be very long # (and this won't be set on free floating single strands) return strand2_atom # end
NanoCAD-master
cad/src/dna/model/DnaLadder_pam_conversion.py
# Copyright 2007-2008 Nanorex, Inc. See LICENSE file for details. """ elements_data_PAM5.py -- data for PAM5 pseudoatom elements @author: Mark, Eric D @version: $Id$ @copyright: 2007-2008 Nanorex, Inc. See LICENSE file for details. History: Bruce 071105 revised init code, and split PAM3 and PAM5 data out of elements_data.py into separate files. Bruce 080108 added Gv5 for use in Eric D's forthcoming PAM5 revision. """ from model.elements_data import tetra4, flat, tetra2, onebond from utilities.constants import MODEL_PAM5 _DIRECTIONAL_BOND_ELEMENTS_PAM5 = ('Ss5', 'Pl5', 'Sj5', 'Pe5', 'Sh5', 'Hp5') # == # mark 060129. New default colors for Alpha 7. _defaultRadiusAndColor = { "Ax5" : (5.0, [0.4, 0.4, 0.8]), "Ss5" : (4.0, [0.4, 0.8, 0.4]), "Pl5" : (3.2, [0.4, 0.1, 0.5]), "Sj5" : (4.0, [0.4, 0.8, 0.8]), "Ae5" : (3.5, [0.4, 0.4, 0.8]), "Pe5" : (3.0, [0.4, 0.1, 0.5]), "Sh5" : (2.5, [0.4, 0.8, 0.4]), "Hp5" : (4.0, [0.3, 0.7, 0.3]), "Gv5" : (5.0, [156./255, 83./255, 8./255]), #bruce 080108 "Gr5" : (5.0, [156./255, 83./255, 8./255]), "Ub5" : (2.5, [0.428, 0.812, 0.808]), #bruce 080117 guess, "light blue" "Ux5" : (2.5, [0.428, 0.812, 0.808]), #bruce 080410 stub "Uy5" : (2.5, [0.812, 0.428, 0.808]), #bruce 080410 stub "Ah5" : (2.5, [0.8, 0.8, 0.8]), #bruce 080515 guess, "very light gray" } _alternateRadiusAndColor = { } # Format of _mendeleev: see elements_data.py _mendeleev = [ # B-DNA PAM5 pseudo atoms (see also _DIRECTIONAL_BOND_ELEMENTS) # Note: the bond vector lists are mainly what we want in length, # not necessarily in geometry. # #bruce 070415: End->Hydroxyl per Eric D email, in "Sh5" == "PAM5-Sugar-Hydroxyl" #bruce 071106: added option dicts; deprecated_to options are good guesses but are untested #bruce 080410 added Ux5 and Uy5 and updated all general comments below # axis element (old, only semi-supported, not generated anymore) ("Ax5", "PAM5-Axis", 200, 1.0, [[4, 200, tetra4]], dict(role = 'axis')), # todo: convert to Gv5, moving it as you do # strand elements ("Ss5", "PAM5-Sugar", 201, 1.0, [[3, 210, flat]], dict(role = 'strand')), ("Pl5", "PAM5-Phosphate", 202, 1.0, [[2, 210, tetra2]], dict(role = 'strand')), # deprecated axis and strand elements # (btw, some of these say None, 'sp', which is probably wrong -- # don't imitate this in new elements) [bruce 080516 comment] ("Sj5", "PAM5-Sugar-Junction", 203, 1.0, [[3, 210, flat]], dict(role = 'strand', deprecated_to = 'Ss5')), ("Ae5", "PAM5-Axis-End", 204, 1.0, [[1, 200, None, 'sp']], dict(role = 'axis', deprecated_to = 'X')), ("Pe5", "PAM5-Phosphate-End", 205, 1.0, [[1, 210, None, 'sp']], dict(role = 'strand', deprecated_to = 'Pl5')), #bruce 080129 X->Pl5; UNCONFIRMED ("Sh5", "PAM5-Sugar-Hydroxyl", 206, 1.0, [[1, 210, None, 'sp']], dict(role = 'strand', deprecated_to = 'X')), ("Hp5", "PAM5-Hairpin", 207, 1.0, [[2, 210, tetra2]], dict(role = 'strand', deprecated_to = 'Ss5')), # REVIEW: Ss or Pl? # major groove (used instead of axis for PAM5, bonded same as axis) ("Gv5", "PAM5-Major-Groove", 208, 1.0, [[4, 200, tetra4]], dict(role = 'axis')), #bruce 080108 ("Gr5", "PAM5-Major-Groove-End",209,1.0, [[3, 210, flat]], dict(role = 'axis', deprecated_to = 'Gv5')), # unpaired base components (experimental and mostly stubs as of 080410): # old one-atom (besides backbone) unpaired base (never used, may or may not end up being useful, # mainly retained since the corresponding PAM3 element is more likely to be useful) ("Ub5", "PAM5-Unpaired-base", 210, 1.0, [[4, 200, tetra4]], dict(role = 'unpaired-base')), # newly proposed two-atom (besides backbone) unpaired base (never yet used but under active development): # # Ux means "unpaired base x-point" and is in the same direction from the # sugar (roughly) as the major groove or axis in a basepair # # Uy means "unpaired base y-point" and is in the same direction from the # sugar as the other sugar in a basepair (exactly) # # The mnemonic is that the sugar-Uy line is the "PAM3+5 baseframe Y axis" # and the sugar-Ux line is then enough to define the X axis # (though its actual direction is a combination of Y and X). # ("Ux5", "PAM5-Unpaired-base-x",211, 1.0, [[4, 200, tetra4]], dict(role = 'unpaired-base')), # (likely to be revised) ("Uy5", "PAM5-Unpaired-base-y",212, 1.0, [[4, 200, tetra4]], dict(role = 'unpaired-base')), # (likely to be revised) # basepair axis handle (defined as PAM5 to make it more convenient to permit its bonding with Gv5) # (see also: elements_data_other.py) ("Ah5", "PAM5-Axis-handle", 213, 1.0, [[1, 200, onebond]], dict(role = 'handle')), #bruce 080515, revised 080516 ] # Since these are not real chemical bonds, the electron accounting # need not be based on filled shells. We just specify that each atom # provides the same number of electrons as the bond count, and that it # needs twice that many. # 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 hyb FC need prov c-rad geometry _PAM5AtomTypeData = [ ["Ax5", None, 0, 8, 4, 2.00, tetra4], ["Ss5", None, 0, 6, 3, 2.10, flat], ["Pl5", None, 0, 4, 2, 2.10, tetra2], ["Sj5", None, 0, 6, 3, 2.10, flat], ["Ae5", None, 0, 2, 1, 2.00, None], ["Pe5", None, 0, 2, 1, 2.10, None], ["Sh5", None, 0, 2, 1, 2.10, None], ["Hp5", None, 0, 4, 2, 2.10, tetra2], ["Gv5", None, 0, 8, 4, 2.00, tetra4], ["Gr5", None, 0, 6, 3, 2.10, flat], ["Ub5", None, 0, 8, 4, 2.00, tetra4], ["Ux5", None, 0, 8, 4, 2.00, tetra4], ["Uy5", None, 0, 8, 4, 2.00, tetra4], ["Ah5", None, 0, 2, 1, 2.00, onebond], ] # == def init_PAM5_elements( periodicTable): periodicTable.addElements( _mendeleev, _defaultRadiusAndColor, _alternateRadiusAndColor, _PAM5AtomTypeData, _DIRECTIONAL_BOND_ELEMENTS_PAM5, default_options = dict(pam = MODEL_PAM5) ) return # end
NanoCAD-master
cad/src/dna/model/elements_data_PAM5.py
# Copyright 2007-2008 Nanorex, Inc. See LICENSE file for details. """ DnaMarker.py - marked positions on atom chains, moving to live atoms as needed Used internally for base indexing in strands and segments; perhaps used in the future to mark subsequence endpoints for relations or display styles. @author: Bruce @version: $Id$ @copyright: 2007-2008 Nanorex, Inc. See LICENSE file for details. TODO: complete the marker-moving code; don't kill markers instead of moving them. """ from dna.model.ChainAtomMarker import ChainAtomMarker from dna.model.DnaStrand import DnaStrand from dna.model.DnaSegment import DnaSegment # for parent_node_of_class: from dna.model.DnaGroup import DnaGroup from dna.model.DnaStrandOrSegment import DnaStrandOrSegment from dna.model.DnaGroup import find_or_make_DnaGroup_for_homeless_object from dna.updater.dna_updater_prefs import pref_draw_internal_markers from utilities import debug_flags from graphics.drawing.drawers import drawwirecube from utilities.constants import orange from files.mmp.files_mmp_registration import MMP_RecordParser from files.mmp.files_mmp_registration import register_MMP_RecordParser # == # constants _CONTROLLING_IS_UNKNOWN = True # represents an unknown value of self.controlling # note: this value of True is not strictly correct, but simplifies the code #e rename? # == # globals and their accessors [TODO -- move these to updater globals or so] _marker_newness_counter = 1 _homeless_dna_markers = {} def _f_get_homeless_dna_markers(): # MISNAMED, see is_homeless docstring in superclass. Maybe rename to # something that ends in "markers_that_need_update"? """ Return the homeless dna markers, and clear the list so they won't be returned again (unless they are newly made homeless). [Friend function for dna updater. Other calls would cause it to miss newly homeless markers, causing serious bugs.] """ res = _homeless_dna_markers.values() _homeless_dna_markers.clear() res = filter( lambda marker: marker.is_homeless(), res ) # review: is filtering needed? return res def _f_are_there_any_homeless_dna_markers(): # MISNAMED, see _f_get_homeless_dna_markers docstring """ [friend function for dna updater] Are there any DnaMarkers needing action by the dna updater? @see: _f_get_homeless_dna_markers @note: this function does not filter the markers that have been recorded as possibly needing update. _f_get_homeless_dna_markers does filter them. So this might return True even if that would return an empty list. This is ok, but callers should be aware of it. """ return not not _homeless_dna_markers # == #e refile these utilities def reversed_list(list1): """ Return a reversed copy of list1 (of the same class as list1), which can be a Python list, or any object obeying the same API. """ list1 = list1[:] list1.reverse() return list1 # == _superclass = ChainAtomMarker class DnaMarker( ChainAtomMarker): """ A ChainAtomMarker specialized for DNA axis or strand atoms (base atoms only, not Pl atoms). Abstract class; see subclasses DnaSegmentMarker and DnaStrandMarker. Description of how this object stays updated in various situations: ### UPDATE after details are coded @@@ When read from an mmp file, or copied, it is valid but has no cached chain, etc... these will be added when the dna updater creates a new chain and ladder and one of these "takes over this marker". Part of that "takeover" is for self to record info so next_atom is not needed for understanding direction, or anything else about the chain self is presently on, since that chain might not be valid when self later needs to move along it. (This info consists of self's index (which rail and where) and direction in a DnaLadder.) After copy, in self.fixup_after_copy(), ... ### NIM; spelling? (check atom order then, and record info so next_atom not needed) @@@ After Undo, our _undo_update method will arrange for equivalent checks or updates to be done... ### REVIEW, IMPLEM (also check atom order then, and record info so next_atom not needed) @@@ If our marker atom dies, self.remove_atom() records this so the dna updater will move self to a new marker atom, and make sure the new (or preexisting) chain/ladder there takes over self. ### DOIT for preexisting -- can happen! @@@ (We have a wholechain which can't be preexisting after we're moved, but our ladder and its ladder rail chain can be.) If our next_atom dies or becomes unbonded from our marker_atom, but our marker_atom remains alive, we can probably stay put but we might need a new direction indicator in place of next_atom. The dna updater handles this too, as a special case of "moving us". ### REVIEW, does it work? what call makes this happen? has to come out of changed_atoms, we might not be "homeless" @@@ After any of these moves or other updates, our marker_atom and next_atom are updated to be sufficient when taken alone to specify our position and direction on a chain of atoms. This is so those attrs are the only ones needing declaration for undo/copy/save for that purpose. We also maintain internal "cached" attrs like our index within a ladder, for efficiency and to help us move when those atoms become killed or get changed in other ways. """ ### REVIEW: what if neither atom is killed, but their bonding changes? # do we need to look for marker jigs on changed atoms # and treat them as perhaps needing to be moved? YES. DOIT. #### @@@@ # [same issue as in comment in docstring "we might not be homeless"] # Jig or Node API class constants: sym = "DnaMarker" # ?? maybe used only on subclasses for SegmentMarker & StrandMarker? maybe never visible? # TODO: not sure if this gets into mmp file, but i suppose it does... and it gets copied, and has undoable properties... # and in theory it could appear in MT, though in practice, probably only in some PM listwidget, but still, # doing the same things a "visible node" can do is good for that. # we'll define mmp_record_name differently in each subclass ## mmp_record_name = "DnaMarker" # @@@@ not yet read; also the mmp format might be verbose (has color) # icon_names = ("missing", "missing-hidden") icon_names = ('modeltree/DnaMarker.png', 'modeltree/DnaMarker-hide.png') # stubs; not normally seen for now copyable_attrs = _superclass.copyable_attrs + () # todo: add some more -- namely the user settings about how it moves, whether it lives, etc # future user settings, which for now are per-subclass constants: control_priority = 1 _wants_to_be_controlling = True # class constant; false variant is nim # default values of instance variables: wholechain = None _position_holder = None # mutable object which records our position # in self.wholechain, should be updated when we move # [080307, replacing _rail and _baseindex from 080306] controlling = _CONTROLLING_IS_UNKNOWN _inside_its_own_strand_or_segment = False # 080222 ### REVIEW: behavior when copied? undo? (copy this attr along with .dad?) @@@@ # whether self is inside the right DnaStrandOrSegment in the model tree # (guess: matters only for controlling markers) ## _advise_new_chain_direction = 0 ###k needed??? @@@ ## # temporarily set to 0 or -1 or 1 for use when moving self and setting a new chain _newness = None _info_for_step2 = None # rename -- just for asserts - says whether more action is needed to make it ok [revised 080311] # not needed I think [080311]: ## # guess: also needs a ladder, and indices into the ladder (which rail, rail/chain posn, rail/chain direction)@@@@ # == Jig or Node API methods (overridden or extended from ChainAtomMarker == _superclass): def __init__(self, assy, atomlist): """ """ _superclass.__init__(self, assy, atomlist) # see also super's _length_1_chain attr global _marker_newness_counter _marker_newness_counter += 1 self._newness = _marker_newness_counter if debug_flags.DEBUG_DNA_UPDATER_VERBOSE: # made verbose on 080201 print "dna updater: made %r" % (self,) return def kill(self): """ Extend Node method, for debugging and for notifying self.wholechain """ if debug_flags.DEBUG_DNA_UPDATER_VERBOSE: msg = "dna updater: killing %r" % (self,) print msg if self.wholechain: self.wholechain._f_marker_killed(self) self._clear_wholechain() self._inside_its_own_strand_or_segment = False # guess _superclass.kill(self) return def _draw_jig(self, glpane, color, highlighted = False): """ [overrides superclass method] """ if self._should_draw(): # this test is not present in superclass for a in self.atoms: chunk = a.molecule dispdef = chunk.get_dispdef(glpane) disp, rad = a.howdraw(dispdef) if self.picked: rad *= 1.01 drawwirecube(color, a.posn(), rad) # draw next_atom in a different color than marked_atom color = orange # this is the other thing that differs from superclass return def _should_draw(self): return pref_draw_internal_markers() def is_glpane_content_itself(self): #bruce 080319 """ @see: For documentation, see Node method docstring. @rtype: boolean [overrides Jig method, but as of 080319 has same implem] """ # Note: we want this return value even if self *is* shown # (due to debug prefs), provided it's an internal marker. # It might even be desirable for other kinds of markers # which are not internal. See comment in Jig method, # for the effect of this being False for things visible in GLPane. # [bruce 080319] return False def gl_update_node(self): # not presently used """ Cause whatever graphics areas show self to update themselves. [Should be made a Node API method, but revised to do the right thing for nodes drawn into display lists.] """ self.assy.glpane.gl_update() # == def get_oldness(self): """ Older markers might compete better for controlling their wholechain; return our "oldness" (arbitrary scale, comparable with Python standard ordering). """ return (- self._newness) def wants_to_be_controlling(self): return self._wants_to_be_controlling def set_wholechain(self, wholechain, position_holder, controlling = _CONTROLLING_IS_UNKNOWN): """ [to be called by dna updater] @param wholechain: a new WholeChain which now owns us (not None) """ # revised 080306/080307 assert wholechain self.wholechain = wholechain self._position_holder = position_holder self.set_whether_controlling(controlling) # might kill self def _clear_wholechain(self): # 080306 self.wholechain = None self._position_holder = None self.controlling = _CONTROLLING_IS_UNKNOWN # 080306; never kills self [review: is that ok?] return def forget_wholechain(self, wholechain): """ Remove any references we have to wholechain. @param wholechain: a WholeChain which refs us and is being destroyed """ assert wholechain if self.wholechain is wholechain: self._clear_wholechain() return def _undo_update(self): # in class DnaMarker """ """ ## print "note: undo_update is partly nim in %r" % self _homeless_dna_markers[id(self)] = self # ok?? sufficient?? [080118] # guess, 080227: this should be enough, since our own attrs (in superclass) # are declared as undoable state... but just to be safe, do these as well: self._clear_wholechain() # a new one will shortly be made by the dna updater and take us over self._inside_its_own_strand_or_segment = False self._info_for_step2 = None # precaution _superclass._undo_update(self) return def remove_atom(self, atom, **opts): """ [extends superclass method] """ _homeless_dna_markers[id(self)] = self # TODO: also do this when copied? not sure it's needed. _superclass.remove_atom(self, atom, **opts) return def changed_structure(self, atom): # 080118 """ [extends superclass method] """ # (we extend this method so that if bonds change so that marked_atom and # next_atom are no longer next to one another, we'll get updated as # needed.) _homeless_dna_markers[id(self)] = self _superclass.changed_structure(self, atom) return #e also add a method [nim in api] for influencing how we draw the atom? # guess: no -- might be sufficient (and is better, in case old markers lie around) # to just use the Jig.draw method, and draw the marker explicitly. Then it can draw # other graphics too, be passed style info from its DnaGroup/Strand/Segment, etc. # == ChainAtomMarker API methods (overridden or extended): # == other methods def getDnaGroup(self): """ Return the DnaGroup we are contained in, or None if we're not inside one. @note: if we are inside a DnaStrand or DnaSegment, then our DnaGroup will be the same as its DnaGroup. But we can be outside one (if this is permitted) and still have a DnaGroup. @note: returning None should never happen if we have survived a run of the dna updater. @see: get_DnaStrand, get_DnaSegment """ return self.parent_node_of_class( DnaGroup) def _get_DnaStrandOrSegment(self): """ [private] Non-friend callers should instead use the appropriate method out of get_DnaStrand or get_DnaSegment. """ return self.parent_node_of_class( DnaStrandOrSegment) def _f_get_owning_strand_or_segment(self, make = False): """ [friend method for dna updater] Return the DnaStrand or DnaSegment which owns this marker, or None if there isn't one, even if the internal model tree has not yet been updated to reflect this properly (which may only happen when self is newly made or perhaps homeless). @param make: if True, never return None, but instead make a new owning DnaStrandOrSegment and move self into it, or decide that one we happen to be in can own us. Note: non-friend callers (outside the dna updater, and not running just after creating this before the updater has a chance to run or gets called explicitly) should instead use the appropriate method out of get_DnaStrand or get_DnaSegment. """ # fyi - used in WholeChain.find_or_make_strand_or_segment # revised, and make added, 080222 if self._inside_its_own_strand_or_segment: return self._get_DnaStrandOrSegment() if make: # if we're in a good enough one already, just make it official in_this_already = self._already_in_suitable_DnaStrandOrSegment() if in_this_already: self._inside_its_own_strand_or_segment = True return in_this_already # optim of return self._get_DnaStrandOrSegment() # otherwise make a new one and move into it (and return it) return self._make_strand_or_segment() return None def _already_in_suitable_DnaStrandOrSegment(self): """ [private helper for _f_get_owning_strand_or_segment] We're some wholechain's controlling marker, but we have no owning strand or segment. Determine whether the one we happen to be inside (if any) can own us. If it can, return it (but don't make it actually own us). Otherwise return None. """ candidate = self._get_DnaStrandOrSegment() # looks above us in model tree if not candidate: return None if candidate is not self.dad: return None if not isinstance( candidate, self._DnaStrandOrSegment_class): return None # does it own anyone else already? for member in candidate.members: if isinstance(member, self.__class__): if member._inside_its_own_strand_or_segment: return None return candidate def _make_strand_or_segment(self): """ [private helper for _f_get_owning_strand_or_segment] We're some wholechain's controlling marker, and we need a new owning strand or segment. Make one and move into it (in the model tree). """ chunk = self.marked_atom.molecule # 080120 7pm untested [when written, in class WholeChain] # find the right DnaGroup (or make one if there is none). # ASSUME the chunk was created inside the right DnaGroup # if there is one. There is no way to check this here -- user # operations relying on dna updater have to put new PAM atoms # inside an existing DnaGroup if they want to use it. # We'll leave them there (or put them all into an arbitrary # one if different atoms in a wholechain are in different # DnaGroups -- which is an error by the user op). dnaGroup = chunk.parent_node_of_class(DnaGroup) if dnaGroup is None: # If it was not in a DnaGroup, it should not be in a DnaStrand or # DnaSegment either (since we should never make those without # immediately putting them into a valid DnaGroup or making them # inside one). But until we implement the group cleanup of just- # read mmp files, we can't assume it's not in one here! # However, we can ignore it if it is (discarding it and making # our own new one to hold our chunks and markers), # and just print a warning here, trusting that in the future # the group cleanup of just-read mmp files will fix things better. if chunk.parent_node_of_class(DnaStrandOrSegment): print "dna updater: " \ "will discard preexisting %r which was not in a DnaGroup" \ % (chunk.parent_node_of_class(DnaStrandOrSegment),), \ "(bug or unfixed mmp file)" dnaGroup = find_or_make_DnaGroup_for_homeless_object(chunk) # Note: all our chunks will eventually get moved from # whereever they are now into this new DnaGroup. # If some are old and have group structure around them, # it will be discarded. To avoid this, newly read old mmp files # should get preprocessed separately (as discussed also in # update_DNA_groups). # now make a strand or segment in that DnaGroup (review: in a certain subGroup?) strand_or_segment = dnaGroup.make_DnaStrandOrSegment_for_marker(self) strand_or_segment.move_into_your_members(self) # this is necessary for the following assignment to make sense # (review: is it ok that we ignore the return value here?? @@@@) assert self._get_DnaStrandOrSegment() is strand_or_segment self._inside_its_own_strand_or_segment = True return strand_or_segment # == def set_whether_controlling(self, controlling): """ our new chain tells us whether we control its atom indexing, etc, or not [depending on our settings, we might die or behave differently if we're not] """ self.controlling = controlling if not controlling and self.wants_to_be_controlling(): self.kill() # in future, might depend more on user-settable properties and/or on subclass return # == # marker move methods. These are called by dna updater and/or our new WholeChain # in this order: [### REVIEW, is this correct? @@@@@@] # - _f_move_to_live_atompair_step1, for markers that need to move; might kill self # - f_kill_during_move, if wholechain scan finds problem with a marker on one of its atoms; will kill self # - xxx_own_marker if a wholechain takes over self ### WRONG, called later # - _f_move_to_live_atompair_step2, for markers for which step1 returned true (even if they were killed by f_kill_during_move) # - this prints a bug warning if neither of f_kill_during_move or xx_own_marker was called since _step1 (or if _step1 not called?) def _f_move_to_live_atompair_step1(self): # rewritten 080311 ### RENAME, no step1 @@@ """ [friend method, called from dna_updater] One of our atoms died or changed structure (e.g. got rebonded). We still know our old wholechain and our position along it (since this is early during a dna updater run), so use that info to move a new location on our old wholechain so that we are on two live atoms which are adjacent on it. Track base position change as we do this (partly nim, since not used). If this works, return True; later updater steps must call one of XXX ###doc to verify our atoms are still adjacent on the same new wholechain, and record it and our position on it. (Also record any info they need to run, but for now, this is only used by assertions or debug prints, since just knowing our two atoms and total base index motion should be sufficient.) If this fails, die and return False. @return: whether this marker is still alive after this method runs. @rtype: boolean """ # REVIEW: should we not return anything and just make callers check marker.killed()? if self._info_for_step2 is not None: print "bug? _info_for_step2 is not None as _f_move_to_live_atompair_step1 starts in %r" % self self._info_for_step2 = None # Algorithm -- just find the nearest live atom in the right direction. # Do this by scanning old atom lists in chain objects known to markers, # so no need for per-atom stored info. # [Possible alternative (rejected): sort new atoms for best new home -- bad, # since requires storing that info on atoms, or lots of lookup.] if not self.is_homeless(): # was an assert, but now I worry that some code plops us onto that list # for other reasons so this might not always be true, so make it safe # and find out (ie debug print) [bruce 080306] print "bug or ok?? not %r.is_homeless() in _f_move_to_live_atompair_step1" % self # might be common after undo?? old_wholechain = self.wholechain if not old_wholechain: if debug_flags.DEBUG_DNA_UPDATER: print "fyi: no wholechain in %r._f_move_to_live_atompair_step1()" % self # I think this might be common after mmp read. If so, perhaps remove debug print. # In any case, tolerate it. Don't move, but do require new wholechain # to find us. Note: this seems to happen a lot for 1-atom chains, not sure why. @@@ DIAGNOSE self._info_for_step2 = True return not self.killed() #bruce 080318 bugfix, was return True # note: this can return False. I didn't verify it can return True, # but probably it can (e.g. after mmp read). # don't do: ## self.kill() ## return False old_atom1 = self.marked_atom old_atom2 = self.next_atom # might be at next higher or next lower index, or be the same if not old_atom1.killed() and not old_atom2.killed(): # No need to move (note, these atoms might be the same) # but (if they are not the same) we don't know if they are still # bonded so as to be adjacent in the new wholechain. I don't yet know # if that will be checked in this method or a later one. # Also, if we return True, we may need to record what self needs to do in a later method. # And we may want all returns to have a uniform debug print. # So -- call a common submethod to do whatever needs doing when we find the # atom pair we might move to. return self._move_to(old_atom1, old_atom2) # note: no pos arg means we're reusing old pos # We need to move (or die). Find where to move to if we can. if old_atom1 is old_atom2: # We don't know which way to scan, and more importantly, # either this means the wholechain has length 1 or there's a bug. # So don't try to move in this case. if len(old_wholechain) != 1: print "bug? marker %r has only one atom but its wholechain %r is length %d (not 1)" % \ (self, len(old_wholechain)) assert old_atom1.killed() # checked by prior code if debug_flags.DEBUG_DNA_UPDATER: print "kill %r since we can't move a 1-atom marker" % self self.kill() return False # Slide this pair of atoms along the wholechain # (using the pair to define a direction of sliding and the relative # index of the amount of slide) until we find two adjacent unkilled # atoms (if such exist). Try first to right, then (if self was not a # ring) to the left. # (Detect a ring by whether the initial position gets returned at the # end (which is detected by the generator and makes it stop after # returning that), or by old_wholechain.ringQ (easier, do that).) for direction_of_slide in (1, -1): if old_wholechain.ringQ and direction_of_slide == -1: break pos_holder = self._position_holder pos_generator = pos_holder.yield_rail_index_direction_counter( relative_direction = direction_of_slide, counter = 0, countby = direction_of_slide, ) # todo: when markers track their current base index, # pass its initial value to counter # and our direction of motion to countby. # (Maybe we're already passing the right thing to countby, # if base indexing always goes up in the direction # from marked_atom to next_atom, but maybe it doesn't # for some reason.) if direction_of_slide == 1: _check_atoms = [old_atom1, old_atom2] # for assertions only -- make sure we hit these atoms first, # in this order else: _check_atoms = [old_atom1] # if we knew pos of atom2 we could # start there, and we could save it from when we go to the # right, but there's no need. unkilled_atoms_posns = [] # the adjacent unkilled atoms and their posns, at current loop point NEED_N_ATOMS = 2 # todo: could optimize, knowing that this is 2 for pos in pos_generator: rail, index, direction, counter = pos atom = rail.baseatoms[index] if _check_atoms: popped = _check_atoms.pop(0) ## assert atom is popped - fails when i delete a few duplex atoms, then make bare axis atom if not (atom is popped): print "\n*** BUG: not (atom %r is _check_atoms.pop(0) %r), remaining _check_atoms %r, other data %r" % \ (atom, popped, _check_atoms, (unkilled_atoms_posns, self, self._position_holder)) if not atom.killed(): unkilled_atoms_posns.append( (atom, pos) ) else: unkilled_atoms_posns = [] if len(unkilled_atoms_posns) >= NEED_N_ATOMS: # we found enough atoms to be our new position. # (this is the only new position we'll consider -- # if anything is wrong with it, we'll die.) if direction_of_slide == -1: unkilled_atoms_posns.reverse() atom1, pos1 = unkilled_atoms_posns[-2] atom2, pos2 = unkilled_atoms_posns[-1] del pos2 return self._move_to(atom1, atom2, pos1) continue # next pos from pos_generator continue # next direction_of_slide # didn't find a good position to the right or left. if debug_flags.DEBUG_DNA_UPDATER_VERBOSE: print "kill %r since we can't find a place to move it to" % self self.kill() return False def _move_to(self, atom1, atom2, atom1pos = None): # revised 080311 """ [private helper for _move_step1; does its side effects for an actual or possible move, and returns its return value] Consider moving self to atom1 and atom2 at atom1pos. If all requirements for this being ok are met, do it (including telling wholechain and/or self where we moved to, in self.position_holder) (this might be done partly in _move_step2, in which case we must record enough info here for it to do that). Otherwise die. Return whether we're still alive after the step1 part of this. """ assert not atom1.killed() and not atom2.killed() if atom1pos is not None: # moving to a new position rail, index, direction, counter = atom1pos del counter # in future, use this to update our baseindex assert atom1 is rail.baseatoms[index] else: # moving to same position we're at now (could optimize) rail, index, direction = self._position_holder.pos atom1, atom2 = self.marked_atom, self.next_atom assert atom1 is rail.baseatoms[index] ok_for_step1 = True # semi-obs comment: # The atom pair we might move to is (atom1, atom2), at the relative # index relindex(?) from the index of self.marked_atom (in the direction # from that to self.next_atom). (This is in terms of # the implicit index direction in which atom2 comes after atom1, regardless # of internal wholechain indices, if those even exist. If we had passed # norepeat = False and old_wholechain was a ring, this might be # larger than its length as we wrapped around the ring indefinitely.) ## move some to docstring of method used in caller # We'll move to this new atom pair if they are adjacent in a new chain # found later (and consistent in bond direction if applicable? not sure). # # We can probably figure out whether they're adjacent right now, but for # now let's try waiting for the new chain and deciding then if we're # still ok. (Maybe we won't even have to -- maybe we could do it lazily # in set_whether_controlling, only checking this if we want to stay alive # once we know whether we're controlling. [review]) if ok_for_step1: self.setAtoms([atom1, atom2]) # maybe needed even in "move to same pos" case self._position_holder.set_position(rail, index, direction) # review: probably not needed, since if we actually moved, # a new wholechain will take us over, so we could probably # set this holder as invalid instead -- not 100% sure I'm right self._info_for_step2 = True # this means, we do need to check atom adjacency in a later method else: # in future, whether to die here will depend on settings in self. # review: if we don't die here, do we return False or True? self.kill() return ok_for_step1 def _f_kill_during_move(self, new_wholechain, why): # 080311 """ [friend method, called from WholeChain.__init__ during dna_updater run] """ if debug_flags.DEBUG_DNA_UPDATER: # SOON: _VERBOSE print "_f_kill_during_move(%r, %r %r)" % (self, new_wholechain, why) # I think we're still on an old wholechain, so we can safely # die in the usual way (which calls a friend method on it). assert self.wholechain is not new_wholechain # not sure we can assert self.wholechain is not None, but find out... # actually this will be normal for mmp read, or other ways external code # can create markers, so remove when seen: @@@@ if self.wholechain is None: print "\nfyi: remove when seen: self.wholechain is None during _f_kill_during_move(%r, %r, %r)" % \ ( self, new_wholechain, why) self.kill() self._info_for_step2 = None # for debug, record no need to do more to move self return def _f_new_position_for(self, new_wholechain, (atom1info, atom2info)): # 080311 """ Assuming self.marked_atom has the position info atom1info (a pair of rail and baseindex) and self.next_atom has atom2info (also checking this assumption by asserts), both in new_wholechain, figure out new position and direction for self in new_wholechain if we can. It's ok to rely on rail.neighbor_baseatoms when doing this. We need to work properly (and return proper direction) if one or both atoms are on a length-1 rail, and fail gracefully if atoms are the same and/or new_wholechain has only one atom. If we can, return new pos as a tuple (rail, baseindex, direction), where rail and baseindex are for atom1 (revise API if we ever need to swap our atoms too). Caller will make those into a PositionInWholeChain object for new_wholechain. If we can't, return None. This happens if our atoms are not adjacent in new_wholechain (too far away, or the same atom). Never have side effects. """ rail1, baseindex1 = atom1info rail2, baseindex2 = atom2info assert self.marked_atom is rail1.baseatoms[baseindex1] assert self.next_atom is rail2.baseatoms[baseindex2] if self.marked_atom is self.next_atom: return None # Note: now we know our atoms differ, which rules out length 1 # new_wholechain, which means it will yield at least two positions # below each time we scan its atoms, which simplifies following code. # Simplest way to work for different rails, either or both # of length 1, is to try scanning in both directions. try_these = [ (rail1, baseindex1, 1), (rail1, baseindex1, -1), ] for rail, baseindex, direction in try_these: pos = rail, baseindex, direction generator = new_wholechain.yield_rail_index_direction_counter( pos ) # I thought this should work, but it failed -- I now think it was # just a logic bug (since we might be at the wholechain end and # therefore get only one position from the generator), # but to remove sources of doubt, do it the more primitive # way below. ## pos_counter_A = generator.next() ## pos_counter_B = generator.next() # can get exceptions.StopIteration - bug? iter = 0 pos_counter_A = pos_counter_B = None for pos_counter in generator: iter += 1 if iter == 1: # should always happen pos_counter_A = pos_counter elif iter == 2: # won't happen if we start at the end we scan towards pos_counter_B = pos_counter break continue del generator assert iter in (1, 2) railA, indexA, directionA, counter_junk = pos_counter_A assert (railA, indexA, directionA) == (rail, baseindex, direction) if iter < 2: ## print "fyi: only one position yielded from %r.yield_rail_index_direction_counter( %r )" % \ ## ( new_wholechain, pos ) ## # remove when debugged, this is probably normal, see comment above # this direction doesn't work -- no atomB! pass else: # this direction works iff we found the right atom railB, indexB, directionB, counter_junk = pos_counter_B atomB = railB.baseatoms[indexB] if atomB is self.next_atom: return rail, baseindex, direction pass continue # try next direction in try_these return None def _f_new_pos_ok_during_move(self, new_wholechain): # 080311 """ [friend method, called from WholeChain.__init__ during dna_updater run] """ del new_wholechain self._info_for_step2 = None # for debug, record no need to do more to move self return def _f_should_be_done_with_move(self): # 080311 """ [friend method, called from dna_updater] """ if self.killed(): return if self._info_for_step2: # TODO: fix in _undo_update @@@@@ print "bug? marker %r was not killed or fixed after move" % self # Note about why we can probably assert this: Any marker # that moves either finds new atoms whose chain has a change # somewhere that leads us to find it (otherwise that chain would # be unchanged and could have no new connection to whatever other # chain lost atoms which the marker was on), or finds none, and # can't move, and either dies or is of no concern to us. self._info_for_step2 = None # don't report the same bug again for self return def DnaStrandOrSegment_class(self): return self._DnaStrandOrSegment_class pass # end of class DnaMarker # == class DnaSegmentMarker(DnaMarker): #e rename to DnaAxisMarker? guess: no... """ A kind of DnaMarker for marking an axis atom of a DnaSegment (and, therefore, a base-pair position within the segment). """ _DnaStrandOrSegment_class = DnaSegment featurename = "Dna Segment Marker" # might never be visible mmp_record_name = "DnaSegmentMarker" def get_DnaSegment(self): """ Return the DnaSegment that owns us, or None if none does. [It's not yet decided whether the latter case can occur normally if we have survived a run of the dna updater.] @see: self.controlling, for whether we control base indexing (and perhaps other aspects) of the DnaSegment that owns us. @see: getDnaGroup """ res = self._get_DnaStrandOrSegment() assert isinstance(res, DnaSegment) return res pass # == class DnaStrandMarker(DnaMarker): """ A kind of DnaMarker for marking an atom of a DnaStrand (and, therefore, a base position along the strand). """ _DnaStrandOrSegment_class = DnaStrand featurename = "Dna Strand Marker" # might never be visible mmp_record_name = "DnaStrandMarker" def get_DnaStrand(self): """ Return the DnaStrand that owns us, or None if none does. [It's not yet decided whether the latter case can occur normally if we have survived a run of the dna updater.] @see: self.controlling, for whether we control base indexing (and perhaps other aspects) of the DnaStrand that owns us. @see: getDnaGroup """ res = self._get_DnaStrandOrSegment() assert isinstance(res, DnaStrand) return res pass # == class _MMP_RecordParser_for_DnaSegmentMarker( MMP_RecordParser): #bruce 080227 """ Read the MMP record for a DnaSegmentMarker Jig. """ def read_record(self, card): constructor = DnaSegmentMarker jig = self.read_new_jig(card, constructor) # note: for markers with marked_atom == next_atom, # the mmp record will have exactly one atom; # current reading code trusts this and sets self._length_1_chain # in __init__, but it would be better to second-guess it and verify # that the chain is length 1, and mark self as invalid if not. # [bruce 080227 comment] # # note: this includes a call of self.addmember # to add the new jig into the model return pass class _MMP_RecordParser_for_DnaStrandMarker( MMP_RecordParser): #bruce 080227 """ Read the MMP record for a DnaStrandMarker Jig. """ def read_record(self, card): constructor = DnaStrandMarker jig = self.read_new_jig(card, constructor) # see comments in _MMP_RecordParser_for_DnaSegmentMarker return pass def register_MMP_RecordParser_for_DnaMarkers(): #bruce 080227 """ [call this during init, before reading any mmp files] """ register_MMP_RecordParser( DnaSegmentMarker.mmp_record_name, _MMP_RecordParser_for_DnaSegmentMarker ) register_MMP_RecordParser( DnaStrandMarker.mmp_record_name, _MMP_RecordParser_for_DnaStrandMarker ) return # end
NanoCAD-master
cad/src/dna/model/DnaMarker.py
# Copyright 2007-2008 Nanorex, Inc. See LICENSE file for details. """ DnaLadder.py - automatically recognized guide objects for understanding PAM DNA duplexes, sticky end regions, and single strands. @author: Bruce @version: $Id$ @copyright: 2007-2008 Nanorex, Inc. See LICENSE file for details. Context: [warning: some of this info might be obs] The PAM atoms in any PAM DNA structure will be internally divided into "ladders", in which all the bonding strictly follows the pattern ... -+-+-+-+-+-+-> ... (strand 1) | | | | | | ... -+-+-+-+-+-+- ... (axis; missing for free-floating single strand) | | | | | | ... <-+-+-+-+-+-+- ... (strand 2; missing for any kind of single strand) (with the strand bond directions antiparallel and standardized to 1 on top (measured left to right == towards increasing baseatoms index), -1 on bottom). The dna updater will maintain these ladders, updating them when their structure is changed. So a changed atom in a ladder will either dissolve or fragment its ladder (or mark it for the updater to do that when it next runs), and the updater, dealing with all changed atoms, will scan all the atoms not in valid ladders to make them into new ladders (merging new ladders end-to-end with old ones, when that's valid, and whe they don't become too long to be handled efficiently). A Dna Segment will therefore consist of a series of ladders (a new one at every point along it where either strand has a nick or crossover, or at other points to make it not too long). Each "ladder rail" (one of the three horizontal atom-bond chains in the figure") will probably be a separate Chunk, though the entire ladder should have a single display list for efficiency (so its rung bonds are in a display list) as soon as that's practical to implement. So the roles for a ladder include: - guide the dna updater in making new chunks - have display code and a display list A DnaLadder is not visible to copy or undo (i.e. it contains no undoable state), and is not stored in the mmp file. """ from Numeric import dot from geometry.VQT import cross from model.elements import Pl5 from utilities.constants import noop from utilities.constants import MODEL_PAM5 from utilities.Log import orangemsg, redmsg, quote_html from utilities import debug_flags from utilities.debug import print_compact_stack from platform_dependent.PlatformDependent import fix_plurals import foundation.env as env from model.bond_constants import atoms_are_bonded from dna.model.DnaChain import merged_chain from dna.model.DnaLadderRailChunk import make_or_reuse_DnaAxisChunk from dna.model.DnaLadderRailChunk import make_or_reuse_DnaStrandChunk # note: if these imports are an issue, they could be moved # to a controller class, since they are needed only by remake_chunks method from dna.model.pam_conversion_mmp import DnaLadder_writemmp_mapping_memo def _DEBUG_LADDER_FINISH_AND_MERGE(): return debug_flags.DEBUG_DNA_UPDATER_VERBOSE # for now def _DEBUG_REVERSE_STRANDS(): # same as _DEBUG_LADDER_FINISH_AND_MERGE, for now return debug_flags.DEBUG_DNA_UPDATER_VERBOSE from dna.model.dna_model_constants import LADDER_ENDS from dna.model.dna_model_constants import LADDER_END0 from dna.model.dna_model_constants import LADDER_END1 from dna.model.dna_model_constants import LADDER_BOND_DIRECTION_TO_OTHER_AT_END_OF_STRAND1 from dna.model.dna_model_constants import LADDER_STRAND1_BOND_DIRECTION from dna.model.dna_model_constants import MAX_LADDER_LENGTH from dna.model.DnaLadder_pam_conversion import DnaLadder_pam_conversion_methods from dna.model.PAM_atom_rules import PAM_atoms_allowed_in_same_ladder from dna.updater.dna_updater_prefs import pref_per_ladder_colors from dna.updater.dna_updater_prefs import pref_permit_bare_axis_atoms from dna.updater.dna_updater_globals import _f_ladders_with_up_to_date_baseframes_at_ends from dna.updater.dna_updater_globals import _f_atom_to_ladder_location_dict from dna.updater.dna_updater_globals import _f_invalid_dna_ladders from dna.updater.dna_updater_globals import get_dnaladder_inval_policy from dna.updater.dna_updater_globals import DNALADDER_INVAL_IS_OK from dna.updater.dna_updater_globals import DNALADDER_INVAL_IS_ERROR from dna.updater.dna_updater_globals import DNALADDER_INVAL_IS_NOOP_BUT_OK from dna.updater.dna_updater_globals import rail_end_atom_to_ladder # == ### REVIEW: should a DnaLadder contain any undoable state? # (guess: yes... maybe it'll be a Group subclass, for sake of copy & undo? # for now, assume just an object (not a Node), and try to fit it into # the copy & undo code in some other way... or I might decide it's entirely # implicit re them.) If that gets hard, make it a Group. (Where in the internal MT? # whereever the chunks would have been, without it.) class DnaLadder(object, DnaLadder_pam_conversion_methods): """ [see module docstring] @note: a valid ladder is not always in correspondence with atom chunks for its rails (since the chunks are only made or fixed after ladder merging), so the methods in self can't find an atom's ladder via atom.molecule. Instead we assume that no atom is in more than one valid ladder at a time, and set a private atom attribute to point to that ladder. """ #TODO: split this class into a common superclass with DnaSingleStrandDomain # (see comment there) and a specific subclass for when we have axis_rail. valid = False # public for read, private for set; whether structure is ok and we own our atoms error = "" # ditto; whether num_strands or strand bond directions are wrong (parallel), etc # todo: use more? # on error, should be set to a short string (suitable for tooltip) # without instance-specific data (i.e. one of a small fixed set of # possible strings, so also suitable as part of a summary_format string) _class_for_writemmp_mapping_memo = DnaLadder_writemmp_mapping_memo # subclass can override if needed (presumably with a subclass of this value) ### REVIEW: what about for single strands? (our subclass) @@@@@@ def __init__(self, axis_rail): self.axis_rail = axis_rail self.assy = axis_rail.baseatoms[0].molecule.assy #k self.strand_rails = [] assert self.assy is not None, "%r.__init__: assy is None" % self def _f_make_writemmp_mapping_memo(self, mapping): """ [friend method for class writemmp_mapping.get_memo_for(self)] """ # note: same code in some other classes that implement this method return self._class_for_writemmp_mapping_memo(mapping, self) def baselength(self): return len(self.axis_rail) def __len__(self): return self.baselength() def __nonzero__(self): # 080311 # avoid Python calling __len__ for this [review: need __eq__ as well?] return True def add_strand_rail(self, strand_rail): # review: _f_, since requires a lot of calling code? """ This is called while constructing a dna ladder (self) which already has an axis rail and 0 or 1 strand rails. Due to how the calling code works, it's guaranteed that the atomlist in the new strand rail corresponds to that in the existing axis rail, either directly or in reverse order -- even if one or both of those rails is a ring rather than a chain. (That is, it's never necessary to "rotate a ring" to make this alignment possible. The caller splits rings into chains if necessary to avoid this need.) We depend on this and assert it, in self.finished(). """ assert strand_rail.baselength() == self.axis_rail.baselength(), \ "baselengths in %r don't match: %r (%d) != %r (%d)" % \ (self, strand_rail, strand_rail.baselength(), self.axis_rail, self.axis_rail.baselength()) self.strand_rails.append(strand_rail) if _DEBUG_REVERSE_STRANDS(): strand_rail.debug_check_bond_direction("in %r.add_strand_rail" % self) return def finished(self): # Q. rename to 'finish'? """ This is called once to signify that construction of self is done as far as the caller is concerned (i.e. it's called add_strand_rail all the times it's going to), and it should be finished internally. This involves reversing rails as needed to make their baseatoms correspond (so each base pair's 3 PAM atoms (or each lone base's 2 PAM atoms) has one atom per rail, at the same relative baseindex), and perhaps(?) storing pointers at each rail-end to neighboring rails. See add_strand_rail docstring for why optional reversing is sufficient, even when some rails are rings. """ # note: this method is only for the subclass with axis_rail present; # at the end it calls a common method. assert not self.valid # not required, just a useful check on the current caller algorithm ## assert len(self.strand_rails) in (1, 2) # happens in mmkit - leave it as just a print at least until we implem "delete bare atoms" - from dna.updater.dna_updater_prefs import legal_numbers_of_strand_neighbors_on_axis legal_nums = legal_numbers_of_strand_neighbors_on_axis() if not ( len(self.strand_rails) in legal_nums ): print "error: axis atom %r has %d strand_neighbors (should be %s)" % \ (self, len(self.strand_rails), " or ".join(map(str, legal_nums))) self.error = "bug: illegal number (%d) of strand rails" % len(self.strand_rails) axis_rail = self.axis_rail # make sure rungs are aligned between the strand and axis rails # (note: this is unrelated to their index_direction, # and is not directly related to strand bond direction) # (note: it's trivially automatically true if our length is 1; # the following alg does nothing then, which we assert) axis_left_end_baseatom = axis_rail.end_baseatoms()[LADDER_END0] for strand_rail in self.strand_rails: if strand_rail.end_baseatoms()[LADDER_END0].axis_neighbor() is not axis_left_end_baseatom: # we need to reverse that strand # (note: we might re-reverse it below, if bond direction wrong) assert strand_rail.end_baseatoms()[LADDER_END1].axis_neighbor() is axis_left_end_baseatom assert self.baselength() > 1 # shouldn't happen otherwise strand_rail.reverse_baseatoms() assert strand_rail.end_baseatoms()[LADDER_END0].axis_neighbor() is axis_left_end_baseatom continue del axis_left_end_baseatom # would be wrong after the following code self._finish_strand_rails() return def _finish_strand_rails(self): # also used in DnaSingleStrandDomain """ verify strand bond directions are antiparallel, and standardize them; then self._ladder_set_valid() (note there might be only the first strand_rail; this code works even if there are none) """ if _DEBUG_REVERSE_STRANDS(): print "\n *** _DEBUG_REVERSE_STRANDS start for %r" % self for strand_rail in self.strand_rails: if _DEBUG_REVERSE_STRANDS(): print "deciding whether to reverse:", strand_rail if strand_rail is self.strand_rails[0]: desired_dir = 1 reverse = True # if dir is wrong, reverse all three rails else: desired_dir = -1 reverse = False # if dir is wrong, error # review: how to handle it in later steps? mark ladder error, don't merge it? have_dir = strand_rail.bond_direction() # 1 = right, -1 = left, 0 = inconsistent or unknown # @@@ IMPLEM note - this is implemented except for merged ladders; some bugs for length==1 chains. # strand_rail.bond_direction must check consistency of bond # directions not only throughout the rail, but just after the # ends (thru Pl too), so we don't need to recheck it for the # joining bonds as we merge ladders. BUT as an optim, it ought # to cache the result and use it when merging the rails, # otherwise we'll keep rescanning rails as we merge them. #e if have_dir == 0: # this should never happen now that fix_bond_directions is active # (since it should mark involved atoms as errors using _dna_updater__error # and thereby keep them out of ladders), so always print it [080201] msg = "bug: %r strand %r has unknown or inconsistent bond " \ "direction - should have been caught by fix_bond_directions" % \ (self, strand_rail) print "\n*** " + msg ## env.history.redmsg(quote_html(msg)) self.error = "bug: strand with unknown or inconsistent bond direction" reverse = True # might as well fix the other strand, if we didn't get to it yet else: if have_dir != desired_dir: # need to reverse all rails in this ladder (if we're first strand, # or if dir is arb since len is 1) # or report error (if we're second strand) if strand_rail.bond_direction_is_arbitrary(): if _DEBUG_REVERSE_STRANDS(): print "reversing %r (bond_direction_is_arbitrary)" % strand_rail strand_rail._f_reverse_arbitrary_bond_direction() have_dir = strand_rail.bond_direction() # only needed for assert assert have_dir == desired_dir elif reverse: if _DEBUG_REVERSE_STRANDS(): print "reversing all rails in %r:" % (self,) for rail in self.all_rails(): # works for ladder or single strand domain if _DEBUG_REVERSE_STRANDS(): print " including: %r" % (rail,) ### review: this reverses even the ones this for loop didn't get to, is that desired? @@@ rail.reverse_baseatoms() else: # this can happen for bad input (not a bug); # don't print details unless verbose, # use a summary message instead if debug_flags.DEBUG_DNA_UPDATER_VERBOSE: print "\ndna updater input data error: %r's strands have parallel bond directions." % self print "data about that:" print "this rail %r in list of rails %r" % (strand_rail, self.strand_rails) print "desired_dir = %r, reverse = %r, have_dir = %r" % (desired_dir, reverse, have_dir) print "self.error now = %r (is about to be set)" % (self.error,) if strand_rail.bond_direction_is_arbitrary(): print " *** bug: parallel strands but strand_rail.bond_direction_is_arbitrary() is true, should be false" self.error = "parallel strand bond directions" # should we just reverse them? no, unless we use minor/major groove to decide which is right. pass else: # strand bond direction is already correct if _DEBUG_REVERSE_STRANDS(): print "no need to reverse %r" % strand_rail continue if _DEBUG_REVERSE_STRANDS(): print "done reversing if needed; current rail baseatom order is:" for rail in self.all_rails(): print " %r" % rail.baseatoms # see if it gets it right after the first step for rail in self.strand_rails: strand_rail.debug_check_bond_direction("end of %r._finish_strand_rails" % self) print " *** _DEBUG_REVERSE_STRANDS end for %r\n" % self self._ladder_set_valid(True) # desired even if self.error was set above, or will be set below self._duplex_geometric_checks() # might set or append to self.error if self.error: # We want to display the error, but not necessarily by setting # atom._dna_updater__error for every atom (or at least not right here, # since we won't know all the atoms until we remake_chunks). # For now, just report it: [#e todo: fix inconsistent case in dna updater warnings @@@@] # Later display it in remake_chunks or in some ladder-specific display code. (And in tooltip too, somehow.) # Ideally we draw an unmissable graphic which points out the error. # (And same for the per-atom _dna_updater__error, which might be too missable # as mere pink wireframe.) @@@@ error_string = self.error if error_string.startswith("bug:"): prefix = "Bug" colorfunc = redmsg # remove "bug: " from error_string used in summary_format error_string = error_string[len("bug:"):].strip() else: prefix = "Warning" colorfunc = orangemsg summary_format = "%s: DNA updater: found [N] dna ladder(s) with %s" % \ ( prefix, error_string ) env.history.deferred_summary_message( colorfunc( summary_format)) # note: error prevents ladder merge, so no issue of reporting an error more than once # (as there would be otherwise, since same error would show up in the merged ladder) return def set_error(self, error_string): #bruce 080401 REVIEW: use this above? """ """ self.error = error_string # REVIEW: more? relation to valid? return def _duplex_geometric_checks(self): """ Set (or append to) self.error, if self has any duplex geometric errors. """ if len(self.strand_rails) == 2 and len(self) > 1: # use the middle two base pairs; check both strands i1 = (len(self) / 2) - 1 i2 = i1 + 1 axis_atoms = self.axis_rail.baseatoms[i1:i1+2] # note: for PAM5 these might be Gv, so formulas may differ... @@@ strand1_atoms = self.strand_rails[0].baseatoms[i1:i1+2] strand2_atoms = self.strand_rails[1].baseatoms[i1:i1+2] error_from_this = self._check_geom( axis_atoms, strand1_atoms, strand2_atoms) if not error_from_this: axis_atoms.reverse() strand1_atoms.reverse() strand2_atoms.reverse() self._check_geom( axis_atoms, strand2_atoms, strand1_atoms) return def _check_geom(self, axis_atoms, strand1_atoms, strand2_atoms ): """ Check the first 4 atoms (out of 6 passed to us, as 3 lists of 2) for geometric duplex errors. If strand2 is being passed in place of strand1 (and thus vice versa), all 3 atom lists should be reversed. If we set or add to self.error, return something true (which will be the error string we add, not including whatever separator we use to add it to an existing self.error). """ error_here = "" # sometimes modified below if axis_atoms[0].element.pam == MODEL_PAM5: # These tests don't yet work properly for PAM5. # This should be fixed -- but the error responses # also do more harm than good in some cases, # so those need fixing too. In the meantime it's # best to disable it for PAM5. [bruce 080516] return error_here old_self_error = self.error # for assert only axis_posns = [atom.posn() for atom in axis_atoms] strand1_posns = [atom.posn() for atom in strand1_atoms] rung0_vec = strand1_posns[0] - axis_posns[0] rung1_vec = strand1_posns[1] - axis_posns[1] axis_vec = axis_posns[1] - axis_posns[0] righthandedness = dot( cross(rung0_vec, rung1_vec), axis_vec ) # todo: make sure it's roughly the right magnitude, not merely positive if not self.error or not self.error.startswith("bug:"): # check strand1 for reverse twist (append to error string if we already have one) if righthandedness <= 0: error_here = "reverse twist" if not self.error: self.error = error_here else: self.error += "\n" + error_here # is '\n' what we want? if not self.error: assert not error_here # check for wrong strand directions re major groove # (since no self.error, we can assume strands are antiparallel and correctly aligned, # i.e. that bond directions point from strand1_atoms[0] to strand1_atoms[1]) strand2_posns = [atom.posn() for atom in strand2_atoms] rung0_vec_2 = strand2_posns[0] - axis_posns[0] minor_groove_where_expected_ness = dot( cross( rung0_vec, rung0_vec_2 ), axis_vec ) if minor_groove_where_expected_ness <= 0: error_here = "bond directions both wrong re major groove" if 0: # turn this on to know why it reported that error [080210] print "data for %s:" % error_here print axis_atoms, strand1_atoms, strand2_atoms print rung0_vec, rung0_vec_2, axis_vec self.error = error_here if old_self_error or error_here: assert self.error assert self.error.startswith(old_self_error) assert self.error.endswith(error_here) return error_here def num_strands(self): return len(self.strand_rails) def _ladder_set_valid(self, val): if val != self.valid: self.valid = val if val: # tell the rail end atoms their ladder; # see rail_end_atom_to_ladder for how this hint is interpreted for atom in self.rail_end_baseatoms(): # (could debug-warn if already set to a valid ladder) if atom._DnaLadder__ladder is not None and atom._DnaLadder__ladder.valid: print "\n*** likely bug: %r is owned by %r as %r takes it over" % \ (atom, atom._DnaLadder__ladder, self) atom._DnaLadder__ladder = self if debug_flags.DEBUG_DNA_UPDATER_VERBOSE: print "%r owning %r" % (self, atom) else: # un-tell them, but first, warn if this might cause or indicate # a bug in pam conversion ladders_dict = _f_ladders_with_up_to_date_baseframes_at_ends if self in ladders_dict: msg = "\n*** likely bug: %r is in ladders_dict (value %r) but is becoming invalid" % \ (self, ladders_dict[self]) print_compact_stack(msg + ": ") if self.strand_rails: locator = _f_atom_to_ladder_location_dict sample_atom = self.strand_rails[0].baseatoms[0] if sample_atom.key in locator: msg = "\n*** likely bug: %r's atom %r is in locator (value %r) but self is becoming invalid" % \ (self, sample_atom, locator[sample_atom.key]) print_compact_stack(msg + ": ") pass # now un-tell them (even if we warned) for atom in self.rail_end_baseatoms(): # (could debug-warn if not set to self) assert atom._DnaLadder__ladder is self # 080411 # don't do this: ## atom._DnaLadder__ladder = None ## del atom._DnaLadder__ladder # since it makes it harder to debug things; # uses of atom._DnaLadder__ladder check self.valid anyway if debug_flags.DEBUG_DNA_UPDATER_VERBOSE: print "%r de-owning %r" % (self, atom) # tell the next run of the dna updater we're invalid _f_invalid_dna_ladders[id(self)] = self return def rail_end_baseatoms(self): # rename? end_baseatoms is logical, but occurs too much in other code. # ladder_end_baseatoms is good too, but is too confusable # with ladder_end_atoms (which also needs renaming). # end_atoms occurs only as a localvar, but is misleading # re Pl or X at ends. """ yield the 3 or 6 atoms which are end-atoms for one of our 3 rails, in arbitrary order #k """ for rail in self.all_rails(): # note: rail is a DnaChain, not a DnaLadderRailChunk! atom1, atom2 = rail.end_baseatoms() yield atom1 if atom2 is not atom1: yield atom2 return # external invalidation methods, which check dnaladder_inval_policy # [bruce 080413 separated existing invalidate method calls into calls # of these two variants, also giving them text-searchable methodnames] # note: one of these is called from dna updater and from # DnaLadderRailChunk.delatom, so changed atoms inval their # entire ladders def ladder_invalidate_and_assert_permitted(self): #bruce 080413 dnaladder_inval_policy = get_dnaladder_inval_policy() if dnaladder_inval_policy != DNALADDER_INVAL_IS_OK: print "\n*** BUG: dnaladder_inval_policy is %r, but we'll inval %r anyway" % \ (dnaladder_inval_policy, self) self._ladder_set_valid(False) return def ladder_invalidate_if_not_disabled(self): #bruce 080413 dnaladder_inval_policy = get_dnaladder_inval_policy() if dnaladder_inval_policy == DNALADDER_INVAL_IS_OK: # usual case should be fastest self._ladder_set_valid(False) elif dnaladder_inval_policy == DNALADDER_INVAL_IS_NOOP_BUT_OK: print "fyi: disabled inval of %r" % self ### remove when works, or put under debug_flags pass # don't invalidate it elif dnaladder_inval_policy == DNALADDER_INVAL_IS_ERROR: # this will happen for true errors, but also for places where we # need to disable but permit the inval. To show those clearly, # also useful for true errors, we always print the stack, even # though this will be verbose when there are bugs. msg = "\n*** BUG: dnaladder inval is an error now, but we'll inval %r anyway" % \ (self, ) print_compact_stack( msg + ": " ) self._ladder_set_valid(False) # an error, but fewer bugs predicted from doing it than not else: assert 0, "unrecognized dnaladder_inval_policy %r" % dnaladder_inval_policy return # == def get_ladder_end(self, endBaseAtom): # by Ninad # todo: rename to indicate it gets it from an atom, not an end-index """ Return the end (as a value in LADDER_ENDS) of the ladder self which has the given end base atom, or None if the given atom is not one of self's end_baseatoms. (If self has length 1, either end might be returned.) @param endBaseAtom: One of the end atoms of the ladder (or any other value, for which we will return None, though passing a non-Atom is an error). """ for ladderEnd in LADDER_ENDS: if endBaseAtom in self.ladder_end_atoms(ladderEnd): return ladderEnd return None def get_endBaseAtoms_containing_atom(self, baseAtom): # by Ninad """ Returns a list of end base atoms that contain <baseAtom> (including that atom. @see: other methods that return these atoms, sometimes in reverse order depending on which end they are from, e.g. ladder_end_atoms. """ endBaseAtomList = [] sortedEndBaseAtomList = [] end_strand_base_atoms = () for ladderEnd in LADDER_ENDS: if baseAtom in self.ladder_end_atoms(ladderEnd): endBaseAtomList = self.ladder_end_atoms(ladderEnd) break if len(endBaseAtomList) > 2: end_strand_base_atoms = (endBaseAtomList[0], endBaseAtomList[2]) else: #@TODO: single stranded dna. Need to figure out if it has #strand1 or strand2 as its strand. # [always strand1, it guarantees this. --bruce] pass strand1Atom = None axisAtom = endBaseAtomList [1] strand2Atom = None for atom in end_strand_base_atoms: if atom is not None: temp_strand = atom.molecule rail = temp_strand.get_ladder_rail() #rail goes from left to right. (increasing chain index order) if rail.bond_direction() == 1: strand1Atom = atom elif rail.bond_direction() == -1: strand2Atom = atom endBaseAtomList = [strand1Atom, axisAtom, strand2Atom] return endBaseAtomList def is_ladder_end_baseatom(self, baseAtom): """ Returns true if the given atom is an end base atom of a ladder (either at ladder end0 or ladder end1) """ for ladderEnd in LADDER_ENDS: if endBaseAtom in self.ladder_end_atoms(ladderEnd): return True return False def whichrail_and_index_of_baseatom(self, baseatom): # bruce 080402 """ Given one of self's baseatoms, possibly on any rail at any baseindex, determine where it is among all self's baseatoms, and return this in the form described below. Error if baseatom is not found. basetom.element.role may be used to narrow down which rails of self to examine. @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. Current code is optimized for baseatom being an end-atom, or a strand atom. @return: (whichrail, index), where whichrail is in LADDER_RAIL_INDICES [i.e. 0, 1, or 2, maybe not yet formally defined] and index is from 0 to len(self) - 1, such that self.rail_at_index(whichrail).baseatoms[index] is baseatom. @see: related method, _f_store_locator_data """ if not self.valid: #bruce 080411 # maybe make this an assertion failure? print "likely bug: invalid ladder in whichrail_and_index_of_baseatom(%r, %r)" % \ (self, baseatom) # TODO: pass index hint to optimize? look_at_rails = self.rail_indices_and_rails(baseatom) for index in range(-1, len(self) - 1): # ends first (indices -1 and (if long enough) 0) for whichrail, rail in look_at_rails: if baseatom is rail.baseatoms[index]: # found it if index < 0: index += len(self) assert self.rail_at_index(whichrail).baseatoms[index] is baseatom # slow, remove when works ### return whichrail, index assert 0, "can't find %r in %r, looking at %r" % \ (baseatom, self, look_at_rails) pass def rail_indices_and_rails(self, baseatom = None): # bruce 080402 """ #doc @see: LADDER_RAIL_INDICES """ del baseatom # todo: optim: use .element.role to filter rails # note: to optim some callers, return strand rails first res = [] for i in range(len(self.strand_rails)): # assert i < 2 res.append( (i * 2, self.strand_rails[i]) ) if self.axis_rail is not None: res.append( (1, self.axis_rail) ) return res def rail_at_index(self, whichrail): # bruce 080402 """ #doc @note: call only on a value of whichrail that is known to correspond to a rail present in self, e.g. a value which was returned from a method in self, e.g. rail_indices_and_rails or whichrail_and_index_of_baseatom. @see: LADDER_RAIL_INDICES """ if whichrail == 1: return self.axis_rail return self.strand_rails[whichrail / 2] # == ladder-merge methods def can_merge(self): """ Is self valid, and mergeable (end-end) with another valid ladder? @return: If no merge is possible, return None; otherwise, for one possible merge (chosen arbitrarily if more than one is possible), return the tuple (other_ladder, merge_info) where merge_info is private info to describe the merge. """ if not self.valid or self.error: return None # not an error for end in LADDER_ENDS: other_ladder_and_merge_info = self._can_merge_at_end(end) # might be None if other_ladder_and_merge_info: return other_ladder_and_merge_info return None def do_merge(self, other_ladder_and_merge_info): """ Caller promises that other_ladder_and_merge_info was returned by self.can_merge() (and is not None). Do the specified permitted merge (with another ladder, end to end, both valid). Invalidate the merged ladders; return the new valid ladder resulting from the merge. """ other_ladder, merge_info = other_ladder_and_merge_info end, other_end = merge_info return self._do_merge_with_other_at_ends(other_ladder, end, other_end) def _can_merge_at_end(self, end): # TODO: update & clean up docstring """ Is the same valid other ladder (with no error) attached to each rail of self at the given end (0 or 1), and if so, can we merge to it at that end (based on which ends of which of its rails our rails attach to)? (If so, return other_ladder_and_merge_info, otherwise None.) ### REVIEW (what's done now, what;s best): Note that self or the other ladder might be length==1 (in which case only end 0 is mergeable, as an arbitrary decision to make only one case mergeable), ### OR we might use bond_dir, then use both cases again and that the other ladder might only merge when flipped. Also note that bond directions (on strands) need to match. ### really? are they always set? TODO: Also worry about single-strand regions. [guess: just try them out here, axis ends are None, must match] """ # algorithm: # use strand1 bond direction to find only possible other ladder # (since that works even if we're of baselength 1); # then if other ladder qualifies, # check both its orientations to see if all necessary bonds # needed for a merge are present. (Only one orientation can make sense, # given the bond we used to find it, but checking both is easier than # checking which one fits with that bond, especially if other or self # len is 1. But to avoid confusion when other len is 1, make sure only # one orientation of other can match, by using the convention # that the ladder-end-atoms go top to bottom on the right, # but bottom-to-top on the left.) if not self.strand_rails: # simplest just to never merge bare axis, for now, # especially since len 1 case would be nontrivial [bruce 080407] return False strand1 = self.strand_rails[0] assert 1 == LADDER_STRAND1_BOND_DIRECTION # since it's probably also hardcoded implicitly assert strand1.bond_direction() == LADDER_STRAND1_BOND_DIRECTION, \ "wrong bond direction %r in strand1 of %r" % \ (strand1.bond_direction, self) end_atom = strand1.end_baseatoms()[end] assert not end_atom._dna_updater__error # otherwise we should not get this far with it assert self is rail_end_atom_to_ladder(end_atom) # sanity check bond_direction_to_other = LADDER_BOND_DIRECTION_TO_OTHER_AT_END_OF_STRAND1[end] next_atom = end_atom.strand_next_baseatom(bond_direction = bond_direction_to_other) # (note: strand_next_baseatom returns None if end_atom or the atom it # might return has ._dna_updater__error set, or if it reaches a non-Ss atom.) if next_atom is None: # end of the chain (since bondpoints are not baseatoms), or # inconsistent bond directions at or near end_atom # (report error in that case??) return None assert not next_atom._dna_updater__error other = rail_end_atom_to_ladder(next_atom) # other ladder (might be self in case of ring) if other.error: return None # other.valid was checked in rail_end_atom_to_ladder if other is self: return None if len(self) + len(other) > MAX_LADDER_LENGTH: return None # Now a merge is possible and allowed, if all ladder-ends are bonded # in either orientation of other, AND if the ladders are compatible # for merging in attributes which we don't wish to mix (e.g. chunk.display_as_pam). # In checking those attrs, note that the atoms are still in their old chunks. if not self.compatible_for_merge_with(other): return None # optim: reject early if ladders have different numbers of rails -- # enable this optim once i verify it works without it: @@ ## if self.num_strands() != other.num_strands(): ## return None # optimization ## #e could also check axis present or not, same in both # try each orientation for other ladder; # first collect the atoms to test for bonding to other self_end_atoms = self.ladder_end_atoms(end) if debug_flags.DEBUG_DNA_UPDATER: assert end_atom in self_end_atoms for other_end in LADDER_ENDS: other_end_atoms = other.ladder_end_atoms(other_end, reverse = True) # note: .ladder_end_atoms returns a sequence of length 3, # with each element being a rail's end-atom or None for a missing rail; # the rail order is strand-axis-strand, which on the right is in # top to bottom order, but on the left is in bottom to top order. # strand1 is always present; strand2 is missing for either kind of # single strands; axis_rail is missing for free-floating single strands. # # bugfix 080122 (untested): reverse order for other_end to facilitate # comparison if the ladders abut (with standardized strand directions). # Not doing this presumably prevented all merges except those involving # length 1 ladders, and made those happen incorrectly when len(other) > 1. still_ok = True for atom1, atom2, strandQ in zip(self_end_atoms, other_end_atoms, (True, False, True)): ok = _end_to_end_bonded(atom1, atom2, strandQ) if not ok: still_ok = False break if still_ok: # success if debug_flags.DEBUG_DNA_UPDATER: # end_atom and next_atom are bonded (perhaps via Pl), # so if we succeeded then they ought to be in the same # positions in these lists: assert next_atom in other_end_atoms assert self_end_atoms.index(end_atom) == other_end_atoms.index(next_atom) merge_info = (end, other_end) other_ladder_and_merge_info = other, merge_info return other_ladder_and_merge_info return None def compatible_for_merge_with(self, other): #bruce 080401 our_atom = self.arbitrary_baseatom() other_atom = other.arbitrary_baseatom() return PAM_atoms_allowed_in_same_ladder( our_atom, other_atom) # note: above doesn't reject Pl5 bonded to Ss3... # review whether anything else will catch that. # Guess: yes, the ladder-forming code will catch it # (not sure what it would do with Ss3-Pl-Ss3, though -- REVIEW). # But note that Ss3-Pl-Ss5 is allowed, at the bond between a PAM3 ad PAM5 chunk. # (In which case the Pl should prefer to stay in the same chunk # as the Ss5 atom, not the Ss3 atom -- this is now implemented in Pl_preferred_Ss_neighbor.) def arbitrary_baseatom(self): #bruce 080401, revised 080407 # (this might also make it correct for ladders with different pam models per rail, # in its current use in this file, which it wasn't until now, # since now it returns an atom from a rail that's unchanged if self is flipped) """ [overridden in DnaSingleStrandDomain] """ return self.axis_rail.baseatoms[0] def ladder_end_atoms(self, end, reverse = False): # rename, and/or merge better with rail_end_baseatoms? """ Return a list of our 3 rail-end atoms at the specified end, using None for a missing atom due to a missing strand2 or axis_rail, in the order strand1, axis, strand2 for the right end, or the reverse order for the left end (since flipping self also reverses that rail order in order to preserve strand bond directions as a function of position in the returned list, and for other reasons mentioned in some caller comments). @param end: LADDER_END0 or LADDER_END1 @param reverse: caller wants result in reverse order compared to usual (it will still differ for the two ends) @warning: the order being flipped for different ends means that a caller looking for adjacent baseatoms from abutting ends of two ladders needs to reverse the result for one of them (always, given the strand direction convention). To facilitate and (nim)optimize this the caller can pass the reverse flag if it knows ahead of time it wants to reverse the result. """ # note: top to bottom on right, bottom to top on left # (when reverse option is false); # None in place of missing atoms for strand2 or axis_rail assert len(self.strand_rails) in (1,2) strand_rails = self.strand_rails + [None] # + [None] needed in case len is 1 rails = [strand_rails[0], self.axis_rail, strand_rails[1]] # order matters def atom0(rail): if rail is None: return None return rail.end_baseatoms()[end] res0 = map( atom0, rails) if end != LADDER_END1: assert end == LADDER_END0 res0.reverse() if reverse: res0.reverse() #e could optim by xoring those booleans return res0 def __repr__(self): ns = self.num_strands() if ns == 2: extra = "" elif ns == 1: extra = " (single strand)" elif ns == 0: # don't say it's an error if 0, since it might be still being made # (or be a bare axis ladder) extra = " (0 strands)" else: extra = " (error: %d strands)" % ns if not self.valid: extra += " (invalid)" if self.error: extra += " (.error set)" return "<%s at %#x, axis len %d%s>" % (self.__class__.__name__, id(self), self.axis_rail.baselength(), extra) def _do_merge_with_other_at_ends(self, other, end, other_end): # works in either class; when works, could optim for single strand """ Merge two ladders, at specified ends of each one: self, at end, with other, at other_end. Invalidate the merged ladders; return the new valid ladder resulting from the merge. """ # algorithm: (might differ for subclasses) # - make merged rails (noting possible flip of each ladder) # (just append lists of baseatoms) # - put them into a new ladder # - when debugging, could check all the same things that # finished does, assert no change flip_self = (end != LADDER_END1) flip_other = (other_end != LADDER_END0) if _DEBUG_LADDER_FINISH_AND_MERGE(): print "dna updater: fyi: _do_merge_with_other_at_ends(self = %r, other_ladder = %r, end = %r, other_end = %r)" % \ (self, other, end, other_end) if _DEBUG_LADDER_FINISH_AND_MERGE(): # following was useful for a bug: 080122 noon print self.ladder_string("self", mark_end = end, flipQ = flip_self) print other.ladder_string("other", mark_end = other_end, flipQ = flip_other) print self_baseatom_lists = [rail_to_baseatoms(rail, flip_self) for rail in self.all_rail_slots_from_top_to_bottom()] other_baseatom_lists = [rail_to_baseatoms(rail, flip_other) for rail in other.all_rail_slots_from_top_to_bottom()] if flip_self: # the individual lists were already reversed in rail_to_baseatoms self_baseatom_lists.reverse() if flip_other: other_baseatom_lists.reverse() # now (after flipping) we need to attach self END1 to other END0, # i.e. "self rail + other rail" for each rail. def concatenate_rail_atomlists((r1, r2)): assert (r1 and r2) or (not r1 and not r2) res = r1 + r2 assert res is not r1 assert res is not r2 return res new_baseatom_lists = map( concatenate_rail_atomlists, zip(self_baseatom_lists, other_baseatom_lists)) # flip the result if we flipped self, so we know it defines a legal # set of rails for a ladder even if some rails are missing # (todo: could optim by never flipping self, instead swapping # ladders and negating both flips) if flip_self: if _DEBUG_LADDER_FINISH_AND_MERGE(): print "dna updater: fyi: new_baseatom_lists before re-flip == %r" % (new_baseatom_lists,) new_baseatom_lists.reverse() # bugfix 080122 circa 2pm: .reverse -> .reverse() [confirmed] for listi in new_baseatom_lists: listi.reverse() if _DEBUG_LADDER_FINISH_AND_MERGE(): print "dna updater: fyi: new_baseatom_lists (after flip or no flip) == %r" % (new_baseatom_lists,) # invalidate old ladders before making new rails or new ladder self.ladder_invalidate_and_assert_permitted() other.ladder_invalidate_and_assert_permitted() # ok at this stage? should be -- in fact, caller # explicitly permits it to work, via global dnaladder_inval_policy # [new feature in caller, bruce 080413] # now make new rails and new ladder new_rails = [ _new_rail( baseatom_list, strandQ, bond_direction) for baseatom_list, strandQ, bond_direction in zip( new_baseatom_lists, (True, False, True), (1, 0, -1 ) # TODO: grab from a named constant? ) ] new_ladder = _new_ladder(new_rails) if debug_flags.DEBUG_DNA_UPDATER: print "dna updater: fyi: merged %r and %r to produce %r" % (self, other, new_ladder,) return new_ladder def ladder_string(self, name = None, flipQ = False, mark_end = None): """ Return a multi-line string listing all baseatoms in self, labelling self as name, marking one end of self if requested by mark_end, flipping self if requested (mark_end is interpreted as referring to the unflipped state). Even empty rails are shown. @type name: string or None @type flipQ: boolean @type mark_end: None or LADDER_END0 or LADDER_END1 """ if name is None: name = "%r" % self assert LADDER_END0 == 0 and LADDER_END1 == 1 # make it easier to compute left/right mark classname = self.__class__.__name__.split('.')[-1] flipped_string = flipQ and " (flipped)" or "" label = "%s %r%s:" % (classname, name, flipped_string) baseatom_lists = [rail_to_baseatoms(rail, flipQ) for rail in self.all_rail_slots_from_top_to_bottom()] if flipQ: # the individual lists were already reversed in rail_to_baseatoms baseatom_lists.reverse() if mark_end is not None: if flipQ: # make it relative to the printout mark_end = (LADDER_END0 + LADDER_END1) - mark_end left_mark = (mark_end == LADDER_END0) and "* " or " " right_mark = (mark_end == LADDER_END1) and " *" or " " strings = [left_mark + (baseatoms and ("%r" % baseatoms) or "------") + right_mark for baseatoms in baseatom_lists] return "\n".join([label] + strings) # == def all_rails(self): """ Return a list of all our rails (axis and 1 or 2 strands), in arbitrary order, not including missing rails. [implem is subclass-specific] """ return [self.axis_rail] + self.strand_rails # TODO: make self.strand_rails private; define a method of the same name for external use, # to be uniform with axis_rails and all_rails methods [bruce 080224 comment] def axis_rails(self): """ Return a list of all our axis rails (currently, 1 in this class, 0 in some subclasses), in arbitrary order, not including missing rails. [implem is subclass-specific] """ return [self.axis_rail] def all_rail_slots_from_top_to_bottom(self): """ Return a list of all our rails (axis and 1 or 2 strands), in top to bottom order, using None for missing rails. [implem is subclass-specific] """ if len(self.strand_rails) == 2: return [self.strand_rails[0], self.axis_rail, self.strand_rails[1]] elif len(self.strand_rails) == 1: return [self.strand_rails[0], self.axis_rail, None] elif len(self.strand_rails) == 0 and pref_permit_bare_axis_atoms(): return [None, self.axis_rail, None] # not sure this will work in callers; # note: this works even if self.axis_rail is None due to bugs else: # this happens, after certain bugs, in debug code with self.error already set; # make sure we notice if it happens without self.error being set: [bruce 080219] if not self.error: self.error = "late-detected wrong number of strands, %d" % len(self.strand_rails) print "\n***BUG: %r: %s" % (self, self.error) return [None, self.axis_rail, None] # same as above, see comment there pass # == def remake_chunks(self, rails = None): """ Make new chunks for self, as close to the old chunks as we can (definitely in the same Part; in the same Group if they were in one). @param rails: list of rails of self to make them for, or None (default) to make them for all rails of self @return: list of all newly made (by this method) DnaLadderRailChunks (or modified ones, if that's ever possible) """ assert self.valid # but don't assert not self.error res = [] ladder_color = None # might be reassigned if pref_per_ladder_colors(): from dna.model.Dna_Constants import getNextStrandColor # todo: apply this in Chunk.drawing_color (extend that method), # so it doesn't erase the saved color ladder_color = getNextStrandColor() # note: if self.error, Chunk.draw will notice this and use black # (within its call of DnaLadderRailChunk.modify_color_for_error); # we won't reassign ladder_color, since we want old chunk colors # to last, so they can be preserved until errors are removed. if rails is None: rails = self.all_rails() for rail in rails: if rail is self.axis_rail: constructor = make_or_reuse_DnaAxisChunk else: constructor = make_or_reuse_DnaStrandChunk old_chunk = rail.baseatoms[0].molecule # from arbitrary baseatom in rail part = old_chunk.part if not part: # will this happen in MMKit? get it from assy assy = old_chunk.assy print "\nbug: %r in assy %r has no .part" % \ (old_chunk, assy) assert assy is self.assy # note: when some bugs happen, assy is None here [080227] assert assy is not None, "%r.remake_chunks notices self.assy is None" % self part = assy.part assert part, "%r.remake_chunks(): %r.part is None" % (self, assy) # will this work in MMKit? # todo: assert rail atoms are in this part part.ensure_toplevel_group() group = old_chunk.dad # put new chunk in same group as old # (but don't worry about where inside it, for now) if group is None: # this happens for MMKit chunks with "dummy" in their names; # can it happen for anything else? should fix in mmkit code. if "dummy" not in old_chunk.name: print "dna updater: why is %r.dad == None? (old_chunk.assy = %r)" % (old_chunk, old_chunk.assy) ### group = part.topnode assert group.is_group() ## assert group.part is part, \ if not (group.part is part): print "\n*** BUG: " \ "group.part %r is not part %r, for old_chunk %r, .dad %r, part.topnode %r" % \ (group.part, part, old_chunk, old_chunk.dad, part.topnode) # this is failing in Undo of creating or bonding lone Ss3, or Undo/Redo/Undo of same, # with group.part None, group probably a DnaStrand which doesn't exist in new state(?). # [bruce 080405 comment, might relate to "tom's undo bug" reported by email yesterday] chunk = constructor(self.assy, rail, self) # Note: these constructors need to be passed self, # in case they reuse an old chunk, which self takes over. # (Even though in theory they could figure out self somehow.) # # this pulls in all atoms belonging to rail # (including certain kinds of attached atoms); # it also may copy in certain kinds of info # from their old chunk (e.g. its .hidden state?) if debug_flags.DEBUG_DNA_UPDATER_VERBOSE: print "%r.remake_chunks made %r" % (self, chunk) chunk.color = old_chunk.color # works, at least if a color was set #e put it into the model in the right place [stub - puts it in the same group] # (also - might be wrong, we might want to hold off and put it in a better place a bit later during dna updater) # also works: part.addnode(chunk), which includes its own ensure_toplevel_group if ladder_color is not None: chunk.color = ladder_color if self.error: #bruce 080401 kluge, not yet fully correct, explained in _f_convert_pam_if_desired chunk.display_as_pam = None group.addchild(chunk) # todo: if you don't want this location for the added node chunk, # just call chunk.moveto when you're done, # or if you know a group you want it in, call group.addchild(chunk) instead of this. res.append(chunk) return res def _f_reposition_baggage(self): #bruce 080404 """ [friend method for dna updater; unsafe to call until after self.remake_chunks()] """ DEBUG_BONDPOINTS = False # DO NOT COMMIT WITH TRUE # only for atoms with _f_dna_updater_should_reposition_baggage set # (and optimizes by knowing where those might be inside the ladder) if DEBUG_BONDPOINTS: print "_f_reposition_baggage called on", self for atom in self._atoms_needing_reposition_baggage_check(): # (for single strands, we need to scan all the baseatoms) if atom._f_dna_updater_should_reposition_baggage: if DEBUG_BONDPOINTS: print " calling %r.reposition_baggage_using_DnaLadder()" % atom atom.reposition_baggage_using_DnaLadder() # fyi: as of 080404, the only case this handles is giving # an Ax with one axis bond a parallel open bond. # Note: only safe to call this after our chunks were remade! # 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 caller to call it in a separate # loop over ladders than the one that calls remake_chunks # on all of them. atom._f_dna_updater_should_reposition_baggage = False # probably redundant with that method #e assert no other atoms have that flag? Not true! interior Ax for single strand might have it. return def _atoms_needing_reposition_baggage_check(self): #bruce 080405 """ [private helper for _f_reposition_baggage] [subclasses with interior bondpoints must override this implem] """ return self.rail_end_baseatoms() # for duplex ladders # == chunk access methods def strand_chunks(self): """ Return a list of all the strand chunks (DnaStrandChunk objects) of this DnaLadder. @see: our methods strand_chunks, all_chunks, axis_chunks, kill_ versions of each of those. """ ###FIX: self.strand_rails is an attr, self.axis_rails is a method. return [rail.baseatoms[0].molecule for rail in self.strand_rails] def axis_chunks(self): """ Return a list of all the axis chunks (DnaAxisChunk objects) of this DnaLadder. @see: our methods strand_chunks, all_chunks, axis_chunks, kill_ versions of each of those. """ return [rail.baseatoms[0].molecule for rail in self.axis_rails()] def all_chunks(self): """ Return a list of all the strand and axis chunks (DnaLadderRailChunk objects) of this DnaLadder. @see: our methods strand_chunks, all_chunks, axis_chunks, kill_ versions of each of those. """ return [rail.baseatoms[0].molecule for rail in self.all_rails()] # == convenience methods def kill_strand_chunks(self): """ Kill all the strand chunks (DnaStrandChunk objects) of this DnaLadder. @note: doesn't invalidate the ladder -- that's up to the dna updater to do later if it wants to. @see: our methods strand_chunks, all_chunks, axis_chunks, kill_ versions of each of those. """ for chunk in self.strand_chunks(): chunk.kill() def kill_axis_chunks(self): """ Kill all the axis chunks (DnaAxisChunk objects) of this DnaLadder. @note: doesn't invalidate the ladder -- that's up to the dna updater to do later if it wants to. @see: our methods strand_chunks, all_chunks, axis_chunks, kill_ versions of each of those. """ for chunk in self.axis_chunks(): chunk.kill() return def kill_all_chunks(self): """ Kill all the strand and axis chunks (DnaLadderRailChunk objects) of this DnaLadder. @note: doesn't invalidate the ladder -- that's up to the dna updater to do later if it wants to. @see: our methods strand_chunks, all_chunks, axis_chunks, kill_ versions of each of those. """ for chunk in self.all_chunks(): chunk.kill() return # == def dnaladder_menu_spec(self, selobj): #bruce 080401, renamed 080407, split 080409 """ [called by menu_spec methods for various selobj classes] Return a menu_spec list of context menu entries specific to selobj being a PAM atom or chunk whose DnaLadder is self. (If we have no entries, return an empty menu_spec list, namely [].) (Other kinds of selobj might be permitted later.) """ if isinstance(selobj, self.assy.Chunk): # don't add these entries to Chunk's cmenu. # [bruce 080723 refactoring of recent Mark change in Chunk.py] return res = [] nwhats = self._n_bases_or_basepairs_string() if self.error or not self.valid: # (this prevents reoffering a failed pam conversion # until you modify the ladder atoms enough for the # dna updater to remake the ladder) # If there's a problem with this ladder, report the status # and don't offer any other menu entries for it. if not self.valid: text = "invalid DnaLadder (bug?) (%s)" % nwhats res.append( (text, noop, 'disabled') ) if self.error: text = "%s (%s)" % (self.error, nwhats) res.append( (text, noop, 'disabled') ) if self.error and self.valid: text = "rescan %s for errors" % nwhats cmd = self.cmd_rescan_for_errors res.append( (text, cmd) ) pass else: # valid, no error res.extend( self._pam_conversion_menu_spec(selobj) ) text = "scan %s for errors" % nwhats cmd = self.cmd_rescan_for_errors res.append( (text, cmd) ) return res def _n_bases_or_basepairs_string(self): nstrands = len(self.strand_rails) if nstrands == 2: what = "basepair" elif nstrands == 1: what = "base" elif nstrands == 0: what = "bare axis atom" else: what = "wrongly structured base" text = "%d %s(s)" % (len(self), what) text = fix_plurals(text) # note: works here, wouldn't work if text had another ')' after it # (due to trivial bug in fix_plurals) return text def cmd_rescan_for_errors(self): #bruce 080412 self._dna_updater_rescan_all_atoms() # review: does this miss anything? # the following (or something like it) seems to be needed, # due to bugs in handling duplex errors I guess # (e.g. for relative motion of rails w/o distorting any rail) for chunk in self.all_chunks(): chunk.changeapp(0) # also gl_update? doesn't seem needed by test return def _dna_updater_rescan_all_atoms(self): #bruce 080412 split this out """ tells dna updater to remake self from scratch (when it next runs) """ self.ladder_invalidate_and_assert_permitted() # BUG (but will probably become officially ok, with the following # workaround officially required and documented; see comments in # initial code called by full_dna_update [comment revised, bruce 080413]): # the above, alone, doesn't cause dna updater to actually run. # KLUGE WORKAROUND -- also do this: self.arbitrary_baseatom()._changed_structure() return def strand_neighbor_ladders(self): #bruce 080408 # (mostly superseded by _f_ladders_with_up_to_date_baseframes_at_ends; # but still used for bug safety) """ Return a sequence of 0 to 4 ladders (or Nones) which includes all ladders which are connected to self at a "corner" (by a strand that leaves self and immediately enters the other ladder, possibly by crossing a "bridging Pl atom"). Always return them in the order strand1-left, strand1-right, strand2-left, strand2-right, even if this list contains None (for an end there), self, or the same ladder twice. The length of the returned list is always exactly twice the number of strand rails of self. @note: this is safe to call on freshly made valid ladders with no errors set which didn't yet remake their chunks. """ if not self.valid: # was assert, but happened for convert to pam3 of ladder # whose self & neighbor were converted to PAM5 [bruce 080413 336pm] print "possible bug: strand_neighbor_ladders called on %r " \ " which is not valid" % (self,) if self.error: print "possible bug: strand_neighbor_ladders called on %r " \ " which has error = %r" % (self, self.error) res = [] for rail in self.strand_rails: for end in LADDER_ENDS: res += [self.neighbor_ladder_at_corner(rail, end)] return res def neighbor_ladder_at_corner(self, rail, end): """ @param rail: an element of self.strand_rails (not checked) @end: an element of the constant sequence LADDER_ENDS @return: the neighbor ladder joined to self by a strand at the specified corner of self (perhaps self), or None if that strand ends at that corner. @note: can be wrong (or raise an exception) if self.error or not self.valid (not checked). @note: this is safe to call on freshly made valid ladders which didn't yet remake their chunks. """ bond_direction_to_other = LADDER_BOND_DIRECTION_TO_OTHER_AT_END_OF_STRAND1[end] if rail is not self.strand_rails[0]: bond_direction_to_other = - bond_direction_to_other # only correct if not self.error # this is not set yet: next_atom = rail.neighbor_baseatoms[end] end_atom = rail.end_baseatoms()[end] next_atom = end_atom.strand_next_baseatom(bond_direction = bond_direction_to_other) # (note: strand_next_baseatom returns None if end_atom or the atom it # might return has ._dna_updater__error set, or if it reaches a non-Ss atom.) if next_atom is not None: return rail_end_atom_to_ladder(next_atom) # note: if self.error is set due to wrong strand directions, # then we may have looked in the wrong bond direction for # next_atom, and probably found an interior atom of self, # in which case this will raise an exception. # [bruce 080523 comment] return None pass # end of class DnaLadder # == # @@ review points: # - this subclass should be a sibling class -- these are both kinds of # "ladder-like DnaDomains", and this has less not more code than DnaLadder; # maybe about half of DnaLadder's code looks like it's common code # (what's the right classname for the interface? # single or duplex domain? domain with some strands?) # - the ladder api from the rest of the code (e.g. chunk.ladder) # is really a "ladder-like dna domain" api, since it work for single strand # ladders too (i.e. DnaLadder is not a perfect name for the common superclass) class DnaSingleStrandDomain(DnaLadder): """ Represent a free floating single strand domain; act exactly like a ladder with no axis rail or second strand rail in terms of ability to interface with other code. """ valid = False # same as in super; set to True in _finish_strand_rails def __init__(self, strand_rail): self.axis_rail = None self.assy = strand_rail.baseatoms[0].molecule.assy self.strand_rails = [strand_rail] assert self.assy is not None, "%r.__init__: assy is None" % self self._finish_strand_rails() # check bond direction, reverse if needed return def baselength(self): return len(self.strand_rails[0]) def finished(self): assert 0, "illegal in this class" # or could be a noop def add_strand_rail(self, strand_rail): assert 0, "illegal in this class" def all_rails(self): """ Return a list of all our rails (1 strand). [implem is subclass-specific] """ return self.strand_rails def axis_rails(self): """ Return a list of all our axis rails (none, in this subclass). [implem is subclass-specific] """ return [] def all_rail_slots_from_top_to_bottom(self): """ Return a list of all our rails (1 strand), in top to bottom order, using None for missing rails (so length of return value is 3). [implem is subclass-specific] """ return [self.strand_rails[0], None, None] def arbitrary_baseatom(self): #bruce 080407 """ [overrides DnaLadder implem] """ return self.strand_rails[0].baseatoms[0] def _atoms_needing_reposition_baggage_check(self): #bruce 080405 """ [private helper for _f_reposition_baggage] [overrides duplex implem in superclass] """ return self.strand_rails[0].baseatoms def __repr__(self): ns = self.num_strands() if ns == 1: extra = "" else: extra = " (error: %d strands)" % ns if self.axis_rail: extra += " (error: has axis_rail)" classname = self.__class__.__name__.split('.')[-1] return "<%s at %#x, len %d%s>" % (classname, id(self), self.baselength(), extra) pass # == def _end_to_end_bonded( atom1, atom2, strandQ): """ Are the expected end-to-end bonds present between end atoms from different ladders? (The atoms are None if they are from missing rails, i.e. strand2 of any single-stranded ladder or axis_rail of a free-floating single-stranded ladder; we expect no bonds between two missing atoms, but we do need bonds between None and a real end-atom, so we return False then.) param atom1: an end atom of a ladder rail, or None (for a missing rail in a ladder) param atom2: like atom1, for a possibly-adjacent ladder param strandQ: whether these atoms are part of strand rails (vs axis rails). type strandQ: boolean """ if atom1 is None and atom2 is None: # note: this can happen for strandQ or not return True if atom1 is None or atom2 is None: # note: this can happen for strandQ or not return False if atoms_are_bonded(atom1, atom2): # note: no check for strand bond direction (assume caller did that) # (we were not passed enough info to check for it, anyway) return True if strandQ: # also check for an intervening Pl in case of PAM5 return strand_atoms_are_bonded_by_Pl(atom1, atom2) else: return False def strand_atoms_are_bonded_by_Pl(atom1, atom2): #e refile """ are these two strand base atoms bonded (indirectly) by means of a single intervening Pl atom (PAM5)? """ if atom1 is atom2: # assert 0?? return False # otherwise following code could be fooled! # one way to support PAM5: ## set1 = atom1.Pl_neighbors() # [this is defined as of 080122] ## set2 = atom2.Pl_neighbors() ## for Pl in set1: ## if Pl in set2: ## return True ## return False # another way, easier for now: set1 = atom1.neighbors() set2 = atom2.neighbors() for Pl in set1: if Pl in set2 and Pl.element is Pl5: return True return False # == # helpers for _do_merge_with_other_at_ends def rail_to_baseatoms(rail, flipQ): if not rail: return [] elif not flipQ: return rail.baseatoms else: res = list(rail.baseatoms) res.reverse() return res def _new_rail(baseatoms, strandQ, bond_direction): """ """ if baseatoms == []: # special case return None assert len(baseatoms) > 1 # since result of merge of nonempty rails # (might not be needed, but good to sanity-check) if strandQ: assert bond_direction else: assert not bond_direction if _DEBUG_LADDER_FINISH_AND_MERGE(): # print all calls print "\n_new_rail(%r, %r, %r)" % (baseatoms, strandQ, bond_direction) if debug_flags.DEBUG_DNA_UPDATER: # check bondedness of adjacent baseatoms for i in range(len(baseatoms) - 1): atom1, atom2 = baseatoms[i], baseatoms[i+1] if strandQ: assert atoms_are_bonded(atom1, atom2) or \ strand_atoms_are_bonded_by_Pl(atom1, atom2), \ "*** missing bond between adjacent baseatoms [%d,%d of %d]: %r and %r" % \ (i, i+1, len(baseatoms), atom1, atom2) else: assert atoms_are_bonded(atom1, atom2), \ "*** missing bond between adjacent baseatoms [%d,%d of %d]: %r and %r" % \ (i, i+1, len(baseatoms), atom1, atom2) return merged_chain( baseatoms, strandQ, bond_direction) def _new_ladder(new_rails): """ Make a new DnaLadder of the appropriate subclass, given 3 new rails-or-None in top to bottom order. @param new_rails: a sequence of length 3; each element is a new rail, or None; top to bottom order. """ strand1, axis, strand2 = new_rails assert strand1 if not axis: assert not strand2 return _new_single_strand_domain(strand1) else: return _new_axis_ladder(strand1, axis, strand2) pass def _new_single_strand_domain(strand1): """ [private helper for _new_ladder] """ return DnaSingleStrandDomain(strand1) def _new_axis_ladder(strand1, axis, strand2): """ [private helper for _new_ladder] """ ladder = DnaLadder(axis) ladder.add_strand_rail(strand1) if strand2: ladder.add_strand_rail(strand2) ladder.finished() return ladder # end
NanoCAD-master
cad/src/dna/model/DnaLadder.py
# Copyright 2008 Nanorex, Inc. See LICENSE file for details. """ PAM_atom_rules.py - functions that define rules for permissible PAM structure (note: not all such code is in this module; some of it is implicit or hardcoded in other files) @author: Bruce @version: $Id$ @copyright: 2008 Nanorex, Inc. See LICENSE file for details. """ from model.elements import Singlet from dna.updater.dna_updater_globals import _f_anyatom_wants_pam from model.bonds import find_bond # == def PAM_atoms_allowed_in_same_ladder(a1, a2): #bruce 080401 # has known bugs, see comment; in future may apply only within rails """ Are a1 and a2 both PAM atoms or bondpoints which are allowed in the same DnaLadder, during either formation or merging of ladders? If not, this might be for any reason we want, including cosmetic (e.g. chunk colors differ), but if different atoms in one base pair use different criteria, problems might ensue if the dna updater does not explicitly handle that somehow when forming ladders (since currently it requires all atoms in one full or partial basepair to be in one ladder). Presently, we allow bondpoints to go with anything; other than that, we require both atoms to have the same PAM model, and to be in chunks with the same PAM-related properties (display_as_pam, save_as_pam). """ # BUG: the following will be wrong, if the atoms in one full or partial # basepair disagree about this data. To fix, find the basepair here # (if too big, mark atoms as error, use default results), and combine # the properties to make a joint effective property on each atom, # before comparing. Not trivial to do that efficiently. Or, actually # modify the atoms in a basepair to agree, or mark them as errors so # they are excluded from chains, at earlier updater stages. ### TODO # # I'm ignoring this for now, though it means some operation bugs could # lead to updater exceptions. (And correct operations must change these # properties in sync across base pairs.) It may even mean the user can # cause those errors by piecing together base pairs from different # DnaLadders using direct bond formation. (Maybe make rung-bond-former # detect and fix those?) # # Review: how to treat atoms with dna_updater_errors? explain_false_when_printed = True explain_false_always = False # do not commit with true -- # too verbose if user makes mixed PAM models on purpose explain_false = explain_false_when_printed or explain_false_always # revised all explain_false logic, bruce 080413 print0 = [""] def doit(): if a1.element is Singlet or a2.element is Singlet: return True if a1.element.pam != a2.element.pam: # different pam models, or one has no pam model (non-PAM element) if explain_false: print0[0] = "different pam models: %s, %s" % (a1.element.pam, a2.element.pam) return False # we don't need to check for "both non-PAM", since we're not called # for such atoms (and if we were, we might as well allow them together) # compare manual pam conversion requests if _f_anyatom_wants_pam(a1) != _f_anyatom_wants_pam(a2): if explain_false: print0[0] = "different requested manual pam conversion: %s, %s" % \ ( _f_anyatom_wants_pam(a1), _f_anyatom_wants_pam(a2) ) return False # compare pam-related properties of chunks chunk1 = a1.molecule chunk2 = a2.molecule # assume atoms not killed, so these are real chunks if chunk1 is chunk2: # optimize common case return True if (chunk1.display_as_pam or None) != (chunk2.display_as_pam or None): # "or None" is kluge bug workaround [080407 late] if explain_false: print0[0] = "different display_as_pam: %r != %r" % ( chunk1.display_as_pam, chunk2.display_as_pam) return False if (chunk1.save_as_pam or None) != (chunk2.save_as_pam or None): if explain_false: print0[0] = "different save_as_pam: %r != %r" % ( chunk1.save_as_pam, chunk2.save_as_pam) return False return True res = doit() if not res: # should we print this as a possible bug, and/or explain why it's false? bond = find_bond(a1, a2) weird = False if bond is None: # can this happen, re find_bond semantics? I think so; # should not happen re how we are called, tho.. # oops, it's routine, since ladder merge is filtered by checking # this for arbitrary baseatoms, so nevermind. [bruce 080413 230pm] pass ## weird = "not bonded" elif bond.is_rung_bond(): weird = "rung bond" if weird: print "might cause bugs: %r and %r not allowed in same ladder, but %s" % (a1, a2, weird) if explain_false: print " reason not allowed: ", print0[0] elif explain_false_always: print "debug fyi: PAM_atoms_allowed_in_same_ladder(%r, %r) -> %r" % (a1, a2, res) print " reason not allowed: ", print0[0] return res # end
NanoCAD-master
cad/src/dna/model/PAM_atom_rules.py
NanoCAD-master
cad/src/dna/model/__init__.py
# Copyright 2007-2008 Nanorex, Inc. See LICENSE file for details. """ DnaSegment.py @author: Bruce, Ninad @version: $Id$ @copyright: 2007-2008 Nanorex, Inc. See LICENSE file for details. Note: *DnaSegment has the following direct members -- -- DnaAxisChunks, -- DnaSegmentMarkers *It can also have following logical contents -- -- DnaStrandChunks (can be accessed using DnaAxisChunk.ladder) -- DnaStrandMarkers -- maybe some more? """ import foundation.env as env from dna.model.DnaStrandOrSegment import DnaStrandOrSegment from dna.model.DnaLadderRailChunk import DnaAxisChunk from utilities.debug import print_compact_stack, print_compact_traceback from model.chunk import Chunk from model.chem import Atom from model.bonds import Bond from geometry.VQT import V, norm, vlen from dna.model.Dna_Constants import getDuplexRiseFromNumberOfBasePairs from utilities.icon_utilities import imagename_to_pixmap from utilities.Comparison import same_vals from utilities.constants import MODEL_PAM3 from dna.model.Dna_Constants import getNumberOfBasePairsFromDuplexLength _superclass = DnaStrandOrSegment class DnaSegment(DnaStrandOrSegment): """ Model object which represents a Dna Segment inside a Dna Group. Internally, this is just a specialized Group containing various subobjects, described in the superclass docstring. Among its (self's) Group.members are its DnaAxisChunks and its DnaSegmentMarkers, including exactly one controlling marker. These occur in undefined order (??). Note that its DnaStrand atoms are not inside it; they are easily found from the DnaAxisChunks. """ # This should be a tuple of classifications that appear in # files_mmp._GROUP_CLASSIFICATIONS, most general first. # See comment in class Group for more info. [bruce 080115] _mmp_group_classifications = ('DnaSegment',) _duplexRise = None _basesPerTurn = None # TODO: undo or copy code for those attrs, # and updating them when the underlying structure changes. # But maybe that won't be needed, if they are replaced # by computing them from the atom geometry as needed. # [bruce 080227 comment] autodelete_when_empty = True # (but only if current command permits that for this class -- # see comment near Group.autodelete_when_empty for more info, # and implems of Command.keep_empty_group) iconPath = "ui/modeltree/DnaSegment.png" hide_iconPath = "ui/modeltree/DnaSegment-hide.png" copyable_attrs = DnaStrandOrSegment.copyable_attrs + ('_duplexRise', '_basesPerTurn') def __init__(self, name, assy, dad, members = (), editCommand = None): self._duplexRise = 3.18 #Default value. self._basesPerTurn = 10 #Default value _superclass.__init__(self, name, assy, dad, members = members, editCommand = editCommand) ###BUG: not all callers pass an editCommand. It would be better # to figure out on demand which editCommand would be appropriate. # [bruce 080227 comment] return def edit(self): """ Edit this DnaSegment. @see: DnaSegment_EditCommand """ commandSequencer = self.assy.w.commandSequencer commandSequencer.userEnterCommand('DNA_SEGMENT') assert commandSequencer.currentCommand.commandName == 'DNA_SEGMENT' commandSequencer.currentCommand.editStructure(self) def draw_highlighted(self, glpane, color): """ Draw the strand and axis chunks as highlighted. (Calls the related methods in the chunk class) @param: GLPane object @param color: The highlight color @see: Chunk.draw_highlighted() @see: SelectChunks_GraphicsMode.draw_highlightedChunk() @see: SelectChunks_GraphicsMode._get_objects_to_highlight() """ #Note: As of 2008-04-07, there is no 'highlightPolicy' for #a DnaSegment like in DnaStrand. #(Not needed but can be easily implemented) for c in self.members: if isinstance(c, DnaAxisChunk): c.draw_highlighted(glpane, color) def getNumberOfNucleotides(self): """ Method provided for conveneince. Returns the number of basepairs of this dna segment. @see: PM_DnaSearchResultTable """ return self.getNumberOfAxisAtoms() def getNumberOfBasePairs(self): #@REVIEW: Is it okay to simply return the number of axis atoms within #the segment (like done below)? But what if there is a bare axis atom #within the segment?In any case, the way we compute the numberOfBase #pairs is again an estimatebased on the duplex length! (i.e. it doesn't #count the individual base-pairs. BTW, a segment may even have a single #strand,so the word basepair is not always correct. -- Ninad 2008-04-08 numberOfBasePairs = self.getNumberOfAxisAtoms() return numberOfBasePairs def getDefaultToolTipInfo(self): """ """ tooltipString = "" n = self.getNumberOfAxisAtoms() tooltipString += "<font color=\"#0000FF\">Parent segment:</font> %s"%(self.name) tooltipString += "<br><font color=\"#0000FF\">Number of axis atoms: </font> %d"%(n) return tooltipString def getNumberOfAxisAtoms(self): """ Returns the number of axis atoms present within this dna segment Returns None if more than one axis chunks are present This is a temporary method until dna data model is fully working. @see: DnaSegment_EditCommand.editStructure() where it is used. """ #THIS WORKS ONLY WITH DNA DATA MODEL. pre-dna data model implementation #rfor this method not supported -- Ninad 2008-04-08 numberOfAxisAtoms = 0 for m in self.members: if isinstance(m, DnaAxisChunk): numberOfAxisAtoms += len(m.get_baseatoms()) return numberOfAxisAtoms def isEmpty(self): """ Returns True if there are no axis chunks as its members. """ for m in self.members: if isinstance(m, DnaAxisChunk): return False return True #Following methods are likely to be revised in a fully functional dna data # model. These methods are mainly created to get working many core UI # operations for Rattlesnake. -- Ninad 2008-02-01 def kill(self): """ Overrides superclass method. For a Dnasegment , as of 2008-04-09, the default implementation is that deleting a segment will delete the segment along with its logical contents (see bug 2749). """ # It is tempting to call self.kill_with_contents , BUT DON'T CALL IT HERE! # ...as kill_with_contents is used elsewhere (before bug 2749 NFR was # suggested and it calls self.kill() at the end. So that will create # infinite recursions. ### TODO: code cleanup/ refactoring to resolve kill_with_content issue #The following block is copied over from self.kill_with_contents() #It implements behavior suggested in bug 2749 (deleting a segment will #delete the segment along with its logical contents ) #See method docsting above on why we shouldn't call that method instead for member in self.members: if isinstance(member, DnaAxisChunk): ladder = member.ladder try: #See a note in dna_model.kill_strand_chunks. Should we #instead call ladder.kill() and thus kill bothstrand #and axis chunks. ? ladder.kill_strand_chunks() except: print_compact_traceback("bug in killing the ladder chunk") DnaStrandOrSegment.kill(self) def kill_with_contents(self): """ Kill this Node including the 'logical contents' of the node. i.e. the contents of the node that are self.members as well as non-members. Example: A DnaSegment's logical contents are AxisChunks and StrandChunks Out of these, only AxisChunks are the direct members of the DnaSegment but the 'StrandChunks are logical contents of it (non-members) . So, some callers may specifically want to delete self along with its members and logical contents. These callers should use this method. The default implementation just calls self.kill() @see: B{Node.DnaSegment.kill_with_contents} which is overridden here method. @see: EditCommand._removeStructure() which calls this Node API method @see: InsertDna_EditCommand._removeSegments() @see: dna_model.DnaLadder.kill_strand_chunks() for a comment. @see: A note in self.kill() about NFR bug 2749 """ for member in self.members: if isinstance(member, DnaAxisChunk): ladder = member.ladder try: #See a note in dna_model.kill_strand_chunks. Should we #instead call ladder.kill() and thus kill bothstrand #and axis chunks. ? ladder.kill_strand_chunks() except: print_compact_traceback("bug in killing the ladder chunk") DnaStrandOrSegment.kill_with_contents(self) def get_DnaSegments_reachable_thru_crossovers(self): """ Return a list of DnaSegments that are reachable through the crossovers. @see: ops_select_Mixin.expandDnaComponentSelection() @see: ops_select_Mixin.contractDnaComponentSelection() @see: ops_select_Mixin._expandDnaStrandSelection() @see:ops_select_Mixin._contractDnaStrandSelection() @see: ops_select_Mixin._contractDnaSegmentSelection() @see: DnaStrand.get_DnaStrandChunks_sharing_basepairs() @see: DnaSegment.get_DnaSegments_reachable_thru_crossovers() @see: NFR bug 2749 for details. @see: SelectChunks_GraphicsMode.chunkLeftDouble() """ neighbor_segments = [] content_strand_chunks = self.get_content_strand_chunks() for c in content_strand_chunks: strand_rail = c.get_ladder_rail() for atm in strand_rail.neighbor_baseatoms: if not atm: continue axis_neighbor = atm.axis_neighbor() if not axis_neighbor: continue dnaSegment = axis_neighbor.molecule.parent_node_of_class(DnaSegment) if dnaSegment and dnaSegment is not self: if dnaSegment not in neighbor_segments: neighbor_segments.append(dnaSegment) return neighbor_segments def get_content_strand_chunks(self): """ """ content_strand_chunks = [] for member in self.members: if isinstance(member, DnaAxisChunk): ladder = member.ladder content_strand_chunks.extend(ladder.strand_chunks()) return content_strand_chunks def getAllAxisAtoms(self): allAtomList = [] for member in self.members: if isinstance(member, DnaAxisChunk): allAtomList.extend(member.atoms.values()) return allAtomList def get_all_content_strand_rail_end_baseatoms(self): """ Return a list of all strand end baseatoms of the 'strand rails' contained within this DnaSegment """ ladders = self.getDnaLadders() strand_rails = [] for ladder in ladders: strand_rails.extend(ladder.strand_rails) strand_atoms = [] for rail in strand_rails: strand_atoms.extend(rail.end_baseatoms()) return strand_atoms def get_all_content_three_prime_ends(self): """ Return a list of all the three prime end base atoms, contained within this DnaSegment @see:self.get_all_content_strand_rail_end_baseatoms() @see:self.get_all_content_five_prime_ends() """ strand_atoms = self.get_all_content_strand_rail_end_baseatoms() three_prime_end_atoms = filter(lambda atm: atm.isThreePrimeEndAtom(), strand_atoms) return three_prime_end_atoms def get_all_content_five_prime_ends(self): """ Return a list of all the five prime end base atoms, contained within this DnaSegment @see:self.get_all_content_strand_rail_end_baseatoms() @see:self.get_all_content_three_prime_ends() """ strand_atoms = self.get_all_content_strand_rail_end_baseatoms() five_prime_end_atoms = filter(lambda atm: atm.isFivePrimeEndAtom(), strand_atoms) return five_prime_end_atoms def is_PAM3_DnaSegment(self): """ Returns true if all the baseatoms in the DnaLadders of this segment are PAM3 baseatoms (axis or strands) Otherwise returns False @see: DnaSegment_EditCommand.model_changed() @see: DnaSegment_EditCommand.isResizableStructure() """ is_PAM3 = False ladderList = self.getDnaLadders() if len(ladderList) == 0: is_PAM3 = False for ladder in ladderList: pam_model = ladder.pam_model() if pam_model == MODEL_PAM3: is_PAM3 = True else: is_PAM3 = False break return is_PAM3 def getDnaLadders(self): """ Returns a list of all DnaLadders within this segment """ ladderList = [] for member in self.members: if isinstance(member, DnaAxisChunk): ladder = member.ladder if ladder not in ladderList: ladderList.append(ladder) return ladderList def get_wholechain(self): """ Return the 'wholechain' of this DnaSegment. Method provided for convenience. Delegates this to self.get_segment_wholechain() """ return self.get_segment_wholechain() def get_segment_wholechain(self): """ @return: the 'wholechain' of this DnaSegment (same as wholechain of each of its DnaAxisChunks), or None if it doesn't have one (i.e. if it's empty -- should never happen if called on a live DnaSegment not modified since the last dna updater run). @see: Wholechain @see: get_strand_wholechain """ for member in self.members: if isinstance(member, DnaAxisChunk): return member.wholechain return None def get_all_content_chunks(self): """ Return all the chunks contained within this DnaSegment. This includes the chunks which are members of the DnaSegment groups, and also the ones which are not 'members' but are 'logical contents' of this DnaSegment. I.e. in dna data model, the DnaSegment only has DnaAxisChunks as its members. But the DnaStrand chunks to which these axis atoms are connected can be treated as logical contents of the DnaSegment. This method returns all such chunks (including the direct members). @see: DnaSegment_GraphicsMode.leftDrag() where this list is used to drag the whole DnaSegment including the logical contents. [overrides superclass method] """ all_content_chunk_list = [] for member in self.members: if isinstance(member, DnaAxisChunk): ladder = member.ladder all_content_chunk_list.extend(ladder.all_chunks()) #Now search for any strand chunks whose strand atoms are not connected #to the axis atoms, but still logically belong to the DnaSegment. #A hairpin loop is an example of such a strand chunk axis_end_atoms = self.getAxisEndAtoms() for atm in axis_end_atoms: if not atm: continue strand_atoms = atm.strand_neighbors() for s_atom in strand_atoms: rail = s_atom.molecule.get_ladder_rail() next_rail_base_atoms = rail.neighbor_baseatoms ##print "*** next_rail_base_atoms = ", next_rail_base_atoms for a in next_rail_base_atoms: if a is None: continue ##print "***a.axis_neighbor() = ", a.axis_neighbor() if not a.axis_neighbor(): if a.molecule not in all_content_chunk_list: all_content_chunk_list.append(a.molecule) return all_content_chunk_list def getAxisEndAtomAtPosition(self, position): """ Given a position, return the axis end atom at that position (if it exists) """ axisEndAtom = None endAtom1, endAtom2 = self.getAxisEndAtoms() for atm in (endAtom1, endAtom2): if atm is not None and same_vals(position, atm.posn()): axisEndAtom = atm break return axisEndAtom def getOtherAxisEndAtom(self, axisEndAtom): """ Return the axis end atom at the opposite end @param axisEndAtom: Axis end atom at a given end. We will use this to find the axis end atom at the opposite end. """ #@TODO: #1. Optimize this further? #2. Can a DnaSegment have more than two axis end atoms? #I guess 'No' . so okay to do the following -- Ninad 2008-03-24 other_axisEndAtom = None endAtom1, endAtom2 = self.getAxisEndAtoms() for atm in (endAtom1, endAtom2): if atm is not None and not atm is axisEndAtom: other_axisEndAtom = atm return other_axisEndAtom def getAxisEndAtoms(self): """ THIS RETURNS AXIS END ATOMS ONLY FOR DNA DATA MODEL. DOESN'T ANYMORE SUPPORT THE PRE DATA MODEL CASE -- 2008-03-24 """ #pre dna data model ##return self._getAxisEndAtoms_preDataModel() #post dna data model return self._getAxisEndAtoms_postDataModel() def _getAxisEndAtoms_postDataModel(self): """ """ atm1, atm2 = self.get_axis_end_baseatoms() #Figure out which end point (atom) is which. endPoint1 will be the #endPoint #on the left side of the 3D workspace and endPoint2 is the one on #the 'more right hand side' of the 3D workspace. #It uses some code from bond_constants.bonded_atoms_summary # [following code is also duplicated in a method below] if atm1 and atm2: atmPosition1 = atm1.posn() atmPosition2 = atm2.posn() glpane = self.assy.o quat = glpane.quat vec = atmPosition2 - atmPosition1 vec = quat.rot(vec) if vec[0] < 0.0: atm1, atm2 = atm2, atm1 elif vec[0] == 0.0 and vec[1] < 0.0: atm1, atm2 = atm2, atm1 return atm1, atm2 def _getAxisEndAtoms_preDataModel(self): """ To be removed post dna data model """ endAtomList = [] for member in self.members: if isinstance(member, Chunk) and member.isAxisChunk(): for atm in member.atoms.itervalues(): if atm.element.symbol == 'Ae3': endAtomList.append(atm) if len(endAtomList) == 2: atm1 = endAtomList[0] atm2 = endAtomList[1] #Figure out which end point (atom) is which. endPoint1 will be the #endPoint #on the left side of the 3D workspace and endPoint2 is the one on #the 'more right hand side' of the 3D workspace. #It uses some code from bond_constants.bonded_atoms_summary # [following code is also duplicated in a method below] atmPosition1 = atm1.posn() atmPosition2 = atm2.posn() glpane = self.assy.o quat = glpane.quat vec = atmPosition2 - atmPosition1 vec = quat.rot(vec) if vec[0] < 0.0: atm1, atm2 = atm2, atm1 return atm1, atm2 elif len(endAtomList) > 2: print_compact_stack("bug: The axis chunk has more than 2 'Ae3' atoms: ") else: return None, None return endAtomList def getStrandEndAtomsFor(self, strand): """ TODO: To be revised/ removed post dna data model. returns the strand atoms connected to the ends of the axis atoms. The list could return 1 or 2 strand atoms. The caller should check for the correctness. @see: DnaStrand_EditCommand.updateHandlePositions() """ assert strand.dad is self strandNeighbors = [] strandEndAtomList = [] for axisEndAtom in self.getAxisEndAtoms(): strandNeighbors = axisEndAtom.strand_neighbors() strand_end_atom_found = False for atm in strandNeighbors: if atm.molecule is strand: strandEndAtomList.append(atm) strand_end_atom_found = True break if not strand_end_atom_found: strandEndAtomList.append(None) return strandEndAtomList def getStrandEndPointsFor(self, strand): """ TODO: To be revised/ removed post dna data model. @see: DnaStrand_EditCommand.updateHandlePositions() @see: self.getStrandEndAtomsFor() """ strandEndAtoms = self.getStrandEndAtomsFor(strand) strandEndPoints = [] for atm in strandEndAtoms: if atm is not None: strandEndPoints.append(atm.posn()) else: strandEndPoints.append(None) return strandEndPoints def getAxisEndPoints(self): """ Derives and returns the two axis end points based on the atom positions of the segment. @note: this method definition doesn't fully make sense, since a segment can be a ring. @return: a list containing the two endPoints of the Axis. @rtype: list """ endpoint1, endpoint2 = self._getAxisEndPoints_preDataModel() if endpoint1 is None: return self._getAxisEndPoints_postDataModel() else: return (endpoint1, endpoint2) def _getAxisEndPoints_preDataModel(self): #Temporary implementation that uses chunk class to distinguish an #axis chunk from an ordinary chunk. This method can be revised after #Full dna data model implementation -- Ninad 2008-01-21 # (Note, this seems to assume that the axis is a single chunk. # This may often be true pre-data-model, but I'm not sure -- # certainly it's not enforced, AFAIK. This will print_compact_stack # when more than one axis chunk is in a segment. [bruce 080212 comment]) endPointList = [] for atm in self.getAxisEndAtoms(): if atm is not None: endPointList.append(atm.posn()) else: endPointList.append(None) if len(endPointList) == 2: atmPosition1 = endPointList[0] atmPosition2 = endPointList[1] return atmPosition1, atmPosition2 return None, None def _getAxisEndPoints_postDataModel(self): # bruce 080212 atom1, atom2 = self.get_axis_end_baseatoms() if atom1 is None: return None, None atmPosition1, atmPosition2 = [atom.posn() for atom in (atom1, atom2)] # following code is duplicated from a method above glpane = self.assy.o quat = glpane.quat vec = atmPosition2 - atmPosition1 vec = quat.rot(vec) if vec[0] < 0.0: atmPosition1, atmPosition2 = atmPosition2, atmPosition1 return atmPosition1, atmPosition2 def get_axis_end_baseatoms(self): # bruce 080212 """ Return a sequence of length 2 of atoms or None: for a chain: its two end baseatoms (arbitrary order); for a ring: None, None. """ # this implem only works in the dna data model # find an arbitrary DnaAxisChunk among our members # (not the best way in theory, once we have proper attrs set, # namely our controlling marker) member = None for member in self.members: if isinstance(member, DnaAxisChunk): break if not isinstance(member, DnaAxisChunk): # no DnaAxisChunk members (should not happen) return None, None end_baseatoms = member.wholechain.end_baseatoms() if not end_baseatoms: # ring return None, None # chain return end_baseatoms def getAxisVector(self, atomAtVectorOrigin = None): """ Returns the unit axis vector of the segment (vector between two axis end points) """ endPoint1, endPoint2 = self.getAxisEndPoints() if endPoint1 is None or endPoint2 is None: return V(0, 0, 0) if atomAtVectorOrigin is not None: #If atomAtVectorOrigin is specified, we will return a vector that #starts at this atom and ends at endPoint1 or endPoint2 . #Which endPoint to choose will be dicided by the distance between #atomAtVectorOrigin and the respective endPoints. (will choose the #frthest endPoint origin = atomAtVectorOrigin.posn() if vlen(endPoint2 - origin ) > vlen(endPoint1 - origin): return norm(endPoint2 - endPoint1) else: return norm(endPoint1 - endPoint2) return norm(endPoint2 - endPoint1) def setProps(self, props): """ Sets some properties. These will be used while editing the structure. (but if the structure is read from an mmp file, this won't work. As a fall back, it returns some constant values) @see: InsertDna_EditCommand.createStructure which calls this method. @see: self.getProps, DnaSegment_EditCommand.editStructure """ duplexRise, basesPerTurn = props self.setDuplexRise(duplexRise) self.setBasesPerTurn(basesPerTurn) def getProps(self): """ Returns some properties such as duplexRise. This is a temporary @see: DnaSegment_EditCommand.editStructure where it is used. @see: DnaSegment_PropertyManager.getParameters @see: DnaSegmentEditCommand._createStructure """ props = (self.getBasesPerTurn(), self.getDuplexRise() ) return props def getDuplexRise(self): return self._duplexRise def setDuplexRise(self, duplexRise): if duplexRise: self._duplexRise = duplexRise def getBasesPerTurn(self): return self._basesPerTurn def setBasesPerTurn(self, basesPerTurn): if basesPerTurn: self._basesPerTurn = basesPerTurn def setColor(self, color): """ Public method provided for convenience. Delegates the color assignment task to self.setStrandColor() @see: DnaOrCntPropertyManager._changeStructureColor() """ self.setSegmentColor(color) def setSegmentColor(self, color): """ Set the color of the all the axis chunks within this DNA segment group to the given color @see: self.setColor() """ m = None for m in self.members: if isinstance(m, DnaAxisChunk): m.setcolor(color) def getColor(self): """ Returns the color of an arbitrary internal axis chunk. It iterates over the axisChunk list until it gets a valid color. If no color is assigned to any of its axis chunks, it simply returns None. """ color = None for m in self.members: if isinstance(m, DnaAxisChunk): color = m.color if color is not None: break return color def writemmp_other_info_opengroup(self, mapping): """ """ #This method is copied over from NanotubeSegment class . #Retaining comments by Bruce in that method. Method added to write #bases per turn and related info to the mmp file. -- Ninad 2008-06-26 #bruce 080507 refactoring (split this out of Group.writemmp) # (I think the following condition is always true, but I didn't # prove this just now, so I left in the test for now.) encoded_classifications = self._encoded_classifications() if encoded_classifications == "DnaSegment": # Write the parameters into an info record so we can read and #restore them in the next session. mapping.write("info opengroup dnaSegment-parameters = %0.3f, %0.3f \n" % (self.getBasesPerTurn(), self.getDuplexRise())) pass return def readmmp_info_opengroup_setitem( self, key, val, interp ): """ [extends superclass method] """ #bruce 080507 refactoring (split this out of the superclass method) if key == ['dnaSegment-parameters']: # val includes all the parameters, separated by commas. basesPerTurn, duplexRise = val.split(",") self.setBasesPerTurn(float(basesPerTurn)) self.setDuplexRise(float(duplexRise)) else: _superclass.readmmp_info_opengroup_setitem( self, key, val, interp) return def _computeDuplexRise(self): """ Compute the duplex rise @see: self.getProps TODO: THIS METHOD IS DEPRECATED AS OF 2008-03-05 AND IS SCHEDULED FOR REMOVAL. IT MIGHT HAVE BUGS. """ duplexRise = None numberOfAxisAtoms = self.getNumberOfAxisAtoms() if numberOfAxisAtoms: numberOfBasePairs = numberOfAxisAtoms duplexLength = self.getSegmentLength() duplexRise = getDuplexRiseFromNumberOfBasePairs(numberOfBasePairs, duplexLength) return duplexRise def getSegmentLength(self): """ Returns the length of the segment. """ endPoint1, endPoint2 = self.getAxisEndPoints() if endPoint1 is None: #bruce 080212 mitigate a bug env.history.orangemsg("Warning: segment length can't be determined") return 10 segmentLength = vlen(endPoint1 - endPoint2) return segmentLength def isAncestorOf(self, obj): """ Checks whether the object <obj> is contained within the DnaSegment Example: If the object is an Atom, it checks whether the atom's chunk is a member of this DnaSegment (chunk.dad is self) It also considers all the logical contents of the DnaSegment to determine whetehr self is an ancestor. (returns True even for logical contents) @see: self.get_all_content_chunks() @see: DnaSegment_GraphicsMode.leftDrag @Note: when dna data model is fully implemented, the code below that is flaged 'pre-Dna data model' and thus the method should be revised """ #start of POST DNA DATA MODEL IMPLEMENTATION =========================== c = None if isinstance(obj, Atom): c = obj.molecule elif isinstance(obj, Bond): chunk1 = obj.atom1.molecule chunk2 = obj.atom1.molecule if chunk1 is chunk2: c = chunk1 elif isinstance(obj, Chunk): c = obj if c is not None: if c in self.get_all_content_chunks(): return True #end of POST DNA DATA MODEL IMPLEMENTATION ============================= #start of PRE- DNA DATA MODEL IMPLEMENTATION =========================== #NOTE: Need to check if the isinstance checks are acceptable (apparently #don't add any import cycle) Also this method needs to be revised #after we completely switch to dna data model. if isinstance(obj, Atom): chunk = obj.molecule if chunk.dad is self: return True else: ladder = getattr(chunk, 'ladder', None) if ladder: pass elif isinstance(obj, Bond): chunk1 = obj.atom1.molecule chunk2 = obj.atom1.molecule if (chunk1.dad is self) or (chunk2.dad is self): return True elif isinstance(obj, Chunk): if obj.dad is self: return True #end of PRE- DNA DATA MODEL IMPLEMENTATION =========================== return False def node_icon(self, display_prefs): del display_prefs # unused if self.all_content_is_hidden(): return imagename_to_pixmap( self.hide_iconPath) else: return imagename_to_pixmap( self.iconPath) # end
NanoCAD-master
cad/src/dna/model/DnaSegment.py
# Copyright 2007-2009 Nanorex, Inc. See LICENSE file for details. """ DnaLadderRailChunk.py - Chunk subclasses for axis and strand rails of a DnaLadder @author: Bruce @version: $Id$ @copyright: 2007-2009 Nanorex, Inc. See LICENSE file for details. """ from dna.model.pam_conversion_mmp import DnaLadderRailChunk_writemmp_mapping_memo from dna.model.pam_conversion_mmp import DnaStrandChunk_writemmp_mapping_memo from model.chunk import Chunk from model.elements import Singlet from model.elements import Pl5 from files.mmp.files_mmp_writing import writemmp_mapping from utilities.constants import gensym from utilities.constants import black from utilities.constants import ave_colors from utilities.constants import diDEFAULT from utilities.constants import MODEL_PAM5 from dna.model.dna_model_constants import LADDER_STRAND1_BOND_DIRECTION from utilities import debug_flags def _DEBUG_REUSE_CHUNKS(): return debug_flags.DEBUG_DNA_UPDATER_VERBOSE import foundation.env as env from utilities.Log import orangemsg, graymsg from PyQt4.Qt import QFont, QString # for debug code from utilities.debug_prefs import debug_pref, Choice_boolean_False from dna.updater.dna_updater_globals import rail_end_atom_to_ladder # == _FAKENAME = '[fake name, bug if seen]' # should be permitted by Node.__init__ but should not "look correct" _DEBUG_HIDDEN = False # soon, remove the code for this @@@@ _superclass = Chunk class DnaLadderRailChunk(Chunk): """ Abstract class for our two concrete Chunk subclasses for the axis and strand rails of a DnaLadder. """ # initial values of instance variables: wholechain = None # will be a WholeChain once dna_updater is done; # set by update_PAM_chunks in the updater run that made self, # and again in each updater run that made a new wholechain # running through self. Can be set to None by Undo. ladder = None # will be a DnaLadder in finished instances; # can be set to None by Undo; # can be set to a new value (after self is modified or unmodified) # by _f_set_new_ladder. _num_old_atoms_hidden = 0 _num_old_atoms_not_hidden = 0 # review: undo, copy for those attrs? as of 080227 I think that is not needed # except for resetting some of them in _undo_update. # default value of variable used to return info from __init__: _please_reuse_this_chunk = None # == init methods def __init__(self, assy, name = None, chain = None, reuse_old_chunk_if_possible = False): """ @note: init method signature is compatible with _superclass.__init__, since it needs to work in _superclass._copy_empty_shell_in_mapping passing just assy and name, expecting us to have no atoms. """ # TODO: check if this arg signature is ok re undo, copy, etc; # and if ok for rest of Node API if that matters for this kind of chunk; # for now just assume chain is a DnaChain # actual name is set below, but only if we don't return early _superclass.__init__(self, assy, name or _FAKENAME ) if chain is not None: self._init_atoms_from_chain( chain, reuse_old_chunk_if_possible) if self._please_reuse_this_chunk is not None: return if not name: # choose a name -- probably never seen by users, so don't spend # lots of runtime or coding time on it -- we use gensym only to # make names unique for debugging. (If it did become user-visible, # we might want to derive and reuse a common prefix, except that # there's no fast way to do that.) assy_to_pass_to_gensym = debug_flags.atom_debug and assy or None self.name = gensym(self.__class__.__name__.split('.')[-1], assy_to_pass_to_gensym ) # note 1: passing assy is only useful here if gensym is not yet # optimized to not look at node names never seen by user # when finding node names to avoid returning. If we do optim # it like that, give it an option to pass here to turn that off, # but, for speed, maybe only pass it when debugging. # note 2: since passing assy might be a bit slow, only do it in the # first place when debugging. # [bruce 080407 comment] return def _init_atoms_from_chain( self, chain, reuse_old_chunk_if_possible): """ [private helper for __init__ when a chain is supplied] """ if _DEBUG_HIDDEN: self._atoms_were_hidden = [] self._atoms_were_not_hidden = [] self._num_extra_bondpoints = 0 # add atoms before setting self.ladder, so adding them doesn't invalidate it use_disp = diDEFAULT # display style to use at end of __init__, if not reset use_picked = False # ditto for self.picked if reuse_old_chunk_if_possible: # Decide whether to abandon self and tell caller to reuse an old # chunk instead (by setting self._please_reuse_this_chunk to the # old_chunk to reuse, and immediately returning, without adding # any atoms to self). # # (Ideally we'd refactor this to be decided by a helper function, # modified from self._old_chunk_we_could_reuse and its submethods, # and never create self in that case.) # # Details: # before we add our atoms, count the ones we would add (and how # many chunks they come from) to see if we can just reuse their # single old chunk; this is both an Undo bugfix (since when Undo # recreates an old state and might do so again from the same # Undo stack, it doesn't like it if we replace objects that # are used in that state without counting it as a change which # branches off that timeline and destroys the redo stack # [theory, not yet proven to cause the bugs being debugged now]), # and probably a general optimization (since atoms can change in # various ways, many of which make the dna updater run but don't # require different DnaLadders -- this will remake ladders and # chains anyway but let them share the same chunks) [bruce 080228] old_chunk = self._old_chunk_we_could_reuse(chain) if old_chunk is not None: if _DEBUG_REUSE_CHUNKS(): print "dna updater will reuse %r rather than new %r" % \ (old_chunk, self) # to do this, set a flag and return early from __init__ # (we have no atoms; caller must kill us, and call # _f_set_new_ladder on the old chunk it's reusing). assert not self.atoms self._please_reuse_this_chunk = old_chunk return if _DEBUG_REUSE_CHUNKS(): print "not reusing an old chunk for %r (will grab %d atoms)" % (self, self._counted_atoms) print " data: atoms were in these old chunks: %r" % (self._counted_chunks.values(),) # Now use the data gathered above to decide how to set some # properties in the new chunk. Logically we should do this even if # not reuse_old_chunk_if_possible, but the implem would need to # differ (even if only by gathering self._counted_chunks some other # way), so since that option is never false as of 080303, just do it # here. # # There might be one or more old chunks -- # see if they all agree about properties, and if so, # use those for self; in some cases some per-atom work by _grab_atom # (below) might be needed. if self._counted_chunks: old_chunks = self._counted_chunks.values() # 1 or more one_old_chunk = old_chunks.pop() # faster than [0] and [1:] # for each property handled here, if all old_chunks same as # one_old_chunk, use that value, otherwise a default value. # Optimize for a single old chunk or a small number of them # (so have only one loop over them). other_old_chunks = old_chunks use_disp = one_old_chunk.display use_picked = one_old_chunk.picked use_display_as_pam = one_old_chunk.display_as_pam use_save_as_pam = one_old_chunk.save_as_pam for chunk in other_old_chunks: # todo: make a helper method to do this loop over each attr; # make decent error messages by knowing whether use_xxx was reset yet # (use deferred_summary_message) if chunk.display != use_disp: use_disp = diDEFAULT # review: # - do we need atoms with individually set display styles # to not contribute their chunks to this calc? # - (depending on what later code does) # do we need to distinguish this being result of # a conflict (like here) or an agreed value? if not chunk.picked: use_picked = False if chunk.display_as_pam != use_display_as_pam: # should never happen, since DnaLadder merging should be disallowed then # (simplifies mmp read conversion) use_display_as_pam = "" if chunk.save_as_pam != use_save_as_pam: # should never happen, since DnaLadder merging should be disallowed then # (simplifies mmp save conversion) use_save_as_pam = "" continue # review: # - what about being (or containing) glpane.selobj? # also set self.part. Ideally we ought to always do this, # but we only need it when use_picked is true, and we only # have a .part handy here, so for now just do it here # and assert we did it as needed. [bruce 080314] self.inherit_part(one_old_chunk.part) pass pass if use_picked: assert self.part is not None # see comment near inherit_part call self._grab_atoms_from_chain(chain, False) #e we might change when we call this, if we implem copy for this class if reuse_old_chunk_if_possible: # check that it counted correctly vs the atoms we actually grabbed ## assert self._counted_atoms == len(self.atoms), \ if not (self._counted_atoms == len(self.atoms)): print \ "\n*** BUG: self._counted_atoms %r != len(self.atoms) %r" % \ ( self._counted_atoms, len(self.atoms) ) # should print the missing atoms if we can, but for now print the present atoms: print " present atoms are", self.atoms.values() self.ladder = rail_end_atom_to_ladder( chain.baseatoms[0] ) self._set_properties_from_grab_atom_info( use_disp, use_picked, use_display_as_pam, use_save_as_pam) # uses args and self attrs to set self.display and self.hidden # and possibly call self.pick() return # from _init_atoms_from_chain def _f_set_new_ladder(self, ladder): """ We are being reused by a new ladder. Make sure the old one is invalid or missing (debug print if not). Then properly record the new one. """ if self.ladder and self.ladder.valid: print "bug? but working around it: reusing %r but its old ladder %r was valid" % (self, self.ladder) self.ladder.ladder_invalidate_and_assert_permitted() self.ladder = ladder # can't do this, no self.chain; could do it if passed the chain: ## assert self.ladder == rail_end_atom_to_ladder( self.chain.baseatoms[0] ) return _counted_chunks = () # kluge, so len is always legal, # but adding an element is an error unless it's initialized def _old_chunk_we_could_reuse(self, chain): #bruce 080228 """ [it's only ok to call this during __init__, and early enough, i.e. before _grab_atoms_from_chain with justcount == False] If there is an old chunk we could reuse, find it and return it. (If we "just miss", debug print.) """ self._counted_atoms = 0 self._counted_chunks = {} self._grab_atoms_from_chain(chain, True) if len(self._counted_chunks) == 1: # all our atoms come from the same old chunk (but are they all of its atoms?) old_chunk = self._counted_chunks.values()[0] assert not old_chunk.killed(), "old_chunk %r should not be killed" % (old_chunk,) # sanity check on old_chunk itself if self._counted_atoms == len(old_chunk.atoms): for atom in old_chunk.atoms.itervalues(): # sanity check on old_chunk itself (also valid outside this if, but too slow) assert atom.molecule is old_chunk # remove when works - slow - or put under SLOW_ASSERTS (otherfile baseatom check too?) # caller can reuse old_chunk in place of self, if class is correct if self.__class__ is old_chunk.__class__: return old_chunk else: # could reuse, except for class -- common in mmp read # or after dna generator, but could happen other times too. if _DEBUG_REUSE_CHUNKS(): print "fyi: dna updater could reuse, except for class: %r" % old_chunk # todo: OPTIM: it might be a useful optim, for mmp read, to just change that chunk's class and reuse it. # To decide if this would help, look at cumtime of _grab_atoms_from_chain in a profile. # I think this is only safe if Undo never saw it in a snapshot. This should be true after mmp read, # and maybe when using the Dna Generator, so it'd be useful. I'm not sure how to detect it -- we might # need to add a specialcase flag for Undo to set, or notice a method it already calls. @@@ # [bruce 080228] return None def _grab_atoms_from_chain(self, chain, just_count): # if this is slow, see comment at end of _old_chunk_we_could_reuse # for a possible optimization [bruce 080228] """ Assume we're empty of atoms; pull in all baseatoms from the given DnaChain, plus whatever bondpoints or Pl atoms are attached to them (but only Pl atoms which are not already in other DnaLadderRailChunks). """ # common code -- just pull in baseatoms and their bondpoints. # subclass must extend as needed. assert not self._num_old_atoms_hidden #bruce 080227 assert not self._num_old_atoms_not_hidden #bruce 080227 for atom in chain.baseatoms: self._grab_atom(atom, just_count) # note: this immediately kills atom's old chunk if it becomes empty return def _grab_atom(self, atom, just_count): """ Grab the given atom (and its bondpoints; atom itself must not be a bondpoint) to be one of our own, recording info about its old chunk which will be used later (in self._set_properties_from_grab_atom_info, called at end of __init__) in setting properties of self to imitate those of our atoms' old chunks. If just_count is true, don't really grab it, just count up some things that will help __init__ decide whether to abandon making self in favor of the caller just reusing an old chunk instead of self. """ assert not atom.element is Singlet if just_count: self._count_atom(atom) # also counts chunks and bondpoints return # first grab info old_chunk = atom.molecule # maybe: self._old_chunks[id(old_chunk)] = old_chunk # could assert old_chunk is not None or _nullMol if old_chunk and old_chunk.hidden: self._num_old_atoms_hidden += 1 if _DEBUG_HIDDEN: self._atoms_were_hidden.append( (atom, old_chunk) ) else: self._num_old_atoms_not_hidden += 1 if _DEBUG_HIDDEN: self._atoms_were_not_hidden.append( (atom, old_chunk) ) # unused, unfinished, remove soon [080303]: ## if len(self._counted_chunks) != 1: ## # (condition is optim; otherwise it's easy) ## if atom.display == diDEFAULT and old_chunk: ## # usually true; if this is too slow, just do it from chunks alone # then grab the atom if _DEBUG_HIDDEN: have = len(self.atoms) atom.hopmol(self) # note: hopmol immediately kills old chunk if it becomes empty if _DEBUG_HIDDEN: extra = len(self.atoms) - (have + 1) self._num_extra_bondpoints += extra return def _count_atom(self, atom): #bruce 080312 revised to fix PAM5 bug """ [private helper for _grab_atom when just_count is true] count atom and its bondpoints and their chunk """ chunk = atom.molecule # no need to check chunk for being None, killed, _nullMol, etc -- # caller will do that if necessary self._counted_chunks[id(chunk)] = chunk if 0: print "counted atom", atom, "from chunk", chunk bondpoints = atom.singNeighbors() self._counted_atoms += (1 + len(bondpoints)) if 0 and bondpoints: ### slow & verbose debug code print "counted bondpoints", bondpoints print "their base atom lists are", [bp.neighbors() for bp in bondpoints] for bp in bondpoints: assert len(bp.neighbors()) == 1 and bp.neighbors()[0] is atom and bp.molecule is chunk return def _set_properties_from_grab_atom_info(self, use_disp, use_picked, use_display_as_pam, use_save_as_pam): # 080201 """ If *all* atoms were in hidden chunks, hide self. If any or all were hidden, emit an appropriate summary message. Set other properties as given. """ if self._num_old_atoms_hidden and not self._num_old_atoms_not_hidden: self.hide() if debug_flags.DEBUG_DNA_UPDATER: summary_format = "DNA updater: debug fyi: remade [N] hidden chunk(s)" env.history.deferred_summary_message( graymsg(summary_format) ) elif self._num_old_atoms_hidden: summary_format = "Warning: DNA updater unhid [N] hidden atom(s)" env.history.deferred_summary_message( orangemsg(summary_format), count = self._num_old_atoms_hidden ) if debug_flags.DEBUG_DNA_UPDATER: ## todo: summary_format2 = "Note: it unhid them due to [N] unhidden atom(s)" summary_format2 = "Note: DNA updater must unhide some hidden atoms due to [N] unhidden atom(s)" env.history.deferred_summary_message( graymsg(summary_format2), ## todo: sort_after = summary_format, -- or orangemsg(summary_format)?? count = self._num_old_atoms_not_hidden ) if self._num_old_atoms_hidden + self._num_old_atoms_not_hidden > len(self.atoms): env.history.redmsg("Bug in DNA updater, see console prints") print "Bug in DNA updater: _num_old_atoms_hidden %r + self._num_old_atoms_not_hidden %r > len(self.atoms) %r, for %r" % \ ( self._num_old_atoms_hidden , self._num_old_atoms_not_hidden, len(self.atoms), self ) if _DEBUG_HIDDEN: mixed = not not (self._atoms_were_hidden and self._atoms_were_not_hidden) if not len(self._atoms_were_hidden) + len(self._atoms_were_not_hidden) == len(self.atoms) - self._num_extra_bondpoints: print "\n***BUG: " \ "hidden %d, unhidden %d, sum %d, not equal to total %d - extrabps %d, in %r" % \ ( len(self._atoms_were_hidden) , len(self._atoms_were_not_hidden), len(self._atoms_were_hidden) + len(self._atoms_were_not_hidden), len(self.atoms), self._num_extra_bondpoints, self ) missing_atoms = dict(self.atoms) # copy here, modify this copy below for atom, chunk in self._atoms_were_hidden + self._atoms_were_not_hidden: del missing_atoms[atom.key] # always there? bad bug if not, i think! print "\n *** leftover atoms (including %d extra bondpoints): %r" % \ (self._num_extra_bondpoints, missing_atoms.values()) else: if not ( mixed == (not not (self._num_old_atoms_hidden and self._num_old_atoms_not_hidden)) ): print "\n*** BUG: mixed = %r but self._num_old_atoms_hidden = %d, len(self.atoms) = %d, in %r" % \ ( mixed, self._num_old_atoms_hidden , len(self.atoms), self) if mixed: print "\n_DEBUG_HIDDEN fyi: hidden atoms = %r \n unhidden atoms = %r" % \ ( self._atoms_were_hidden, self._atoms_were_not_hidden ) # display style self.display = use_disp # selectedness if use_picked: assert self.part is not None # caller must guarantee this # motivation: avoid trouble in add_part from self.pick self.pick() if use_display_as_pam: self.display_as_pam = use_display_as_pam if use_save_as_pam: self.save_as_pam = use_save_as_pam return # from _set_properties_from_grab_atom_info # == def set_wholechain(self, wholechain): """ [to be called by dna updater] @param wholechain: a new WholeChain which owns us (not None) """ assert wholechain is not None # note: self.wholechain might or might not be None when this is called # (it's None for new chunks, but not for old ones now on new wholechains) self.wholechain = wholechain # == invalidation-related methods overridden from superclass def _undo_update(self): if self.wholechain: self.wholechain.destroy() self.wholechain = None self.invalidate_ladder_and_assert_permitted() # review: sufficient? set it to None? self.ladder = None #bruce 080227 guess, based on comment where class constant default value is assigned for atom in self.atoms.itervalues(): atom._changed_structure() #bruce 080227 precaution, might be redundant with invalidating the ladder... @@@ _superclass._undo_update(self) return def invalidate_ladder(self): #bruce 071203 # separated some calls into invalidate_ladder_and_assert_permitted, 080413; # it turns out nothing still calls this version, but something might in future, # so I left it in the API and in class Chunk """ [overrides Chunk method] [only legal after init, not during it, thus not in self.addatom -- that might be obs as of 080120 since i now check for self.ladder... not sure] """ if self.ladder: # cond added 080120 # possible optim: see comment in invalidate_ladder_and_assert_permitted self.ladder.ladder_invalidate_if_not_disabled() return def invalidate_ladder_and_assert_permitted(self): #bruce 080413 """ [overrides Chunk method] """ if self.ladder: # possible optim: ' and not self.ladder.valid' above -- # not added for now so that the debug prints and checks # in the following are more useful [bruce 080413] self.ladder.ladder_invalidate_and_assert_permitted() return def in_a_valid_ladder(self): #bruce 071203 """ Is this chunk a rail of a valid DnaLadder? [overrides Chunk method] """ return self.ladder and self.ladder.valid def addatom(self, atom): _superclass.addatom(self, atom) if self.ladder and self.ladder.valid: # this happens for bondpoints (presumably when they're added since # we broke a bond); I doubt it happens for anything else, # but let's find out (in a very safe way, tho a bit unclear): # (update, 080120: I think it would happen in self.merge(other) # except that we're inlined there! So it might happen if an atom # gets deposited on self, too. ### REVIEW) # update 080413: I expect it to be an issue for adding bridging Pl # during conversion to PAM5, but didn't yet see it happen then. ### # when it does, disable the inval, for Pl. (not for bondpoints!) # Note the debug print was off for bondpoints, that might be why I didn't see it, # if there is a bug that causes one to be added... can't think why there would be tho. if atom.element.eltnum != 0: print "dna updater, fyi: addatom %r to %r invals_if_not_disabled %r" % (atom, self, self.ladder) self.ladder.ladder_invalidate_if_not_disabled() return def delatom(self, atom): _superclass.delatom(self, atom) if self.ladder and self.ladder.valid: print "dna updater, fyi: delatom %r from %r invals_if_not_disabled %r" % (atom, self, self.ladder) self.ladder.ladder_invalidate_if_not_disabled() return def merge(self, other): # overridden just for debug, 080120 9pm """ [overrides Chunk.merge] """ # note: this will work, but its work will be undone by the next # dna updater run, since our new atoms get into # _changed_parent_Atoms, which the dna updater is watching # for changed_atoms it needs to process. [bruce 080313 comment] if debug_flags.DEBUG_DNA_UPDATER: print "dna updater debug: fyi: calling %r.merge(%r)" % (self, other) return _superclass.merge(self, other) def invalidate_atom_lists(self): """ override superclass method, to catch some inlinings of addatom/delatom: * in undo_archive * in chunk.merge * in chunk.copy_full_in_mapping (of the copy -- won't help unless we use self.__class__ to copy) ### REVIEW @@@@ also catches addatom/delatom themselves (so above overrides are not needed??) """ if self.ladder and self.ladder.valid: self.ladder.ladder_invalidate_if_not_disabled() # 080120 10pm bugfix return _superclass.invalidate_atom_lists(self) # == other invalidation-related methods def forget_wholechain(self, wholechain): """ Remove any references we have to wholechain. @param wholechain: a WholeChain which refs us and is being destroyed """ assert wholechain is not None if self.wholechain is wholechain: self.wholechain = None return # == convenience methods for external use, e.g. access methods def get_ladder_rail(self): # todo: use more widely (but only when safe!) # revised 080411 """ @warning: This is only legitimate to call if you know that self is a chunk which was made by a valid DnaLadder's remake_chunks method and that ladder was not subsequently invalidated. When this is false (i.e. when not self.ladder and self. ladder.valid), it ought to assert 0, but to mitigate bugs in callers, it instead debug prints and does its best, sometimes returning a rail in an invalid ladder and sometimes returning None. It also prints and returns None if the rail can't be found in self.ladder. """ ladder = self.ladder if not ladder: print "BUG: %r.get_ladder_rail() but self.ladder is None" % self return None if not ladder.valid: print "BUG: %r.get_ladder_rail() but self.ladder %r is not valid" % \ (self, ladder) # but continue and return the rail if you can find it for rail in self.ladder.all_rails(): if rail.baseatoms[0].molecule is self: return rail # This might be reached if this is called too early during a dna updater run. # Or, this can definitely be reached as of late 080405 by depositing Ss3 on an interior bondpoint # of a single strand chain of otherwise-bare Ss3's (making an Ss3 with 3 Ss3 neighbors). # guess about the cause: atoms in a DnaLadderRailChunk become erroneous # and get left behind in an "invalid" one... looks like its ladder does not even # get cleared in that case (though probably it gets marked invalid). # Probably we need to do something about those erroneous DnaLadderRailChunks -- # they might cause all kinds of trouble (e.g. not all their ladder's baseatoms # are in them). This might be related to some existing bugs, maybe even undo bugs... # so we need to turn them into regular chunks, I think. (Not by class assignment, # due to Undo.) [bruce 080405 comment] print "BUG: %r.get_ladder_rail() can't find the rail using self.ladder %r" % \ (self, ladder) return None def get_baseatoms(self): return self.get_ladder_rail().baseatoms def idealized_strand_direction(self): #bruce 080328; renamed/revised to permit self.error, 080406 (bugfix) """ Return the bond_direction which this strand would have, relative to the internal base indices of self.ladder (which must exist) (i.e. to the order of self.get_ladder_rail().baseatoms), if it had the correct one for this ladder to be finished with no errors, based on which strand of self.ladder it is. (If self.ladder.valid and not self.ladder.error, then this corresponds to the actual strand bond_direction, assuming no bugs.) @note: it's not an error to call this if self.ladder.error or not self.ladder.valid, but for some kinds of self.ladder.error, the return value might not correspond to the *actual* strand direction in those cases (or that direction might not even be well defined -- not sure that can happen). Some callers depend on being allowed to call this under those conditions (e.g. writemmp, when writing ladders with errors). """ ladder = self.ladder ## assert ladder and not ladder.error and ladder.valid, \ ## "%r.ladder = %r not valid and error-free" % \ ## (self, ladder) assert ladder # no way to avoid requiring this; might be an issue for # Ss3 left out of ladders due to atom errors, unless we fix # their chunk class or detect this sooner during writemmp (untested) rail = self.get_ladder_rail() assert rail in ladder.strand_rails if rail is ladder.strand_rails[0]: direction = LADDER_STRAND1_BOND_DIRECTION else: direction = - LADDER_STRAND1_BOND_DIRECTION return direction # == graphics methods def modify_color_for_error(self, color): """ Given the drawing color for this chunk, or None if element colors should be used, either return it unchanged, or modify it to indicate an error or warning condition (if one exists on this chunk). [overrides Chunk method] """ error = self.ladder and self.ladder.error # maybe: use self.ladder.drawing_color(), if not None?? if error: # use black, or mix it into the selection color [bruce 080210] if self.picked and color is not None: # color is presumably the selection color color = ave_colors(0.75, black, color) else: color = black return color def draw(self, glpane, dispdef): """ [extends Chunk.draw] """ # note: for now this can continue to extend Chunk.draw # rather than being in a ChunkDrawer subclass and extending # one of that class's drawing methods, since it only does # immediate mode drawing (no effect on any display list). # [bruce 090212 comment] _superclass.draw(self, glpane, dispdef) if not self.__ok(): return if debug_pref("DNA: draw ladder rail atom indices?", Choice_boolean_False, prefs_key = True): font = QFont( QString("Helvetica"), 9) # WARNING: Anything smaller than 9 pt on Mac OS X results in # un-rendered text. out = glpane.out * 3 # bug: 3 is too large baseatoms = self.get_baseatoms() for atom, i in zip(baseatoms, range(len(baseatoms))): baseLetter = atom.getDnaBaseName() # "" for axis if baseLetter == 'X': baseLetter = "" text = "(%d%s)" % (i, baseLetter) pos = atom.posn() + out glpane.renderText(pos[0], pos[1], pos[2], \ QString(text), font) continue pass return def __ok(self): #bruce 080405 [todo: move this method earlier in class] # TODO: all uses of get_baseatoms or even self.ladder should test this @@@@@@ # (review whether get_baseatoms should return [] when this is False) # (see also the comments in get_ladder_rail) # see also: self._ladder_is_fully_ok() ladder = self.ladder return ladder and ladder.valid # ok even if ladder.error # == mmp methods def atoms_in_mmp_file_order(self, mapping = None): #bruce 080321 """ [overrides Chunk method] @note: the objects returned can be of class Atom or (if mapping is provided, and permits) class Fake_Pl. """ # basic idea: first write some of the atoms in a definite order, # including both real atoms and (if self and mapping options permit) # optional "conversion atoms" (fake Pl atomlike objects created just # for write operations that convert to PAM5); then write the # remaining atoms (all real) in the same order as the superclass # would have. # #update, bruce 080411: # We do this even if not mapping.write_bonds_compactly, # though AFAIK there is no need to in that case. But I'm not sure. # Need to review and figure out if doing it then is needed, # and if not, if it's good, and if not, if it's ok. # Also I heard of one bug from this, suspect it might be caused # by doing it in a chunk with errors, so I will add a check in # initial atoms for ladder to exist and be valid (not sure # about error-free), and if not, not do this. There was already # a check for that about not honoring write_bonds_compactly then # (which I split out and called self._ladder_is_fully_ok). if mapping is None: # We need a real mapping, in order to produce and use a # memo object, even though we'll make no conversion atoms, # since (if this happens to be a PAM5 chunk) we use the memo # to interleave the Pl atoms into the best order for writing # (one that permits an upcoming mmp format optimization). mapping = writemmp_mapping(self.assy) initial_atoms = self.indexed_atoms_in_order(mapping = mapping) # (implem is per-subclass; should be fast for repeated calls ###CHECK) # the initial_atoms need to be written in a definite order, # and (nim, elsewhere) we might also need to know their mmp encodings # for use in info records. (If we do, no need to worry # about that here -- just look them up from mapping for the # first and last atoms in this order, after writing them.) number_of_atoms = len(self.atoms) + \ self.number_of_conversion_atoms(mapping) if len(initial_atoms) == number_of_atoms: # optimization; might often be true for DnaAxisChunk # (when no open bonds are present), # and for DnaStrandChunk when not doing PAM3 -> PAM5 conversion return initial_atoms all_real_atoms = _superclass.atoms_in_mmp_file_order(self, mapping) # preserve this "standard order" for non-initial atoms (all are real). assert len(all_real_atoms) == len(self.atoms) # maybe not needed; assumes superclass contributes no conversion atoms ## if len(all_atoms) != number_of_atoms: ## print "\n*** BUG: wrong number of conversion atoms in %r, %d + %d != %d" % \ ## (self, len(self.atoms), self.number_of_conversion_atoms(mapping), len(all_atoms)) ## print " more info:" ## print "self.atoms.values()", self.atoms.values() ## print "initial_atoms", initial_atoms ## print "all_atoms", all_atoms dict1 = {} # helps return each atom exactly once some_atom_occurred_twice = False for atom in initial_atoms: if dict1.has_key(atom.key): #bruce 080516 debug print (to keep) print "\n*** BUG: %r occurs twice in %r.indexed_atoms_in_order(%r)" % \ ( atom, self, mapping) if not some_atom_occurred_twice: print "that entire list is:", initial_atoms some_atom_occurred_twice = True dict1[atom.key] = atom #e could optim: do directly from list of keys if some_atom_occurred_twice: # bruce 080516 bug mitigation print "workaround: remove duplicate atoms (may not work;" print " underlying bug needs fixing even if it works)" newlist = [] dict1 = {} for atom in initial_atoms: if not dict1.has_key(atom.key): dict1[atom.key] = atom newlist.append(atom) continue print "changed length from %d to %d" % (len(initial_atoms), len(newlist)) print initial_atoms = newlist pass res = list(initial_atoms) # extended below for atom in all_real_atoms: # in this order if not dict1.has_key(atom.key): res.append(atom) ## assert len(res) == number_of_atoms, \ # can fail for ladder.error or atom errors, don't yet know why [080406 1238p]; # also failed for Ninad reproducing Eric D bug (which I could not reproduce) # in saving 8x21RingB1.mmp after joining the last strand into a ring (I guess); # so I'll make it a debug print only [bruce 080516] if not ( len(res) == number_of_atoms ): print "\n*** BUG in atoms_in_mmp_file_order for %r: " % self, \ "len(res) %r != number_of_atoms %r" % \ (len(res), number_of_atoms) return res def indexed_atoms_in_order(self, mapping): #bruce 080321 """ [abstract method of DnaLadderRailChunk] Return the atoms of self which need to be written in order of base index or interleaved between those atoms. This may or may not include all writable atoms of self, which consist of self.atoms plus possible "conversion atoms" (extra atoms due to pam conversion, written but not placed into self.atoms). """ assert 0, "subclass must implement" def write_bonds_compactly_for_these_atoms(self, mapping): #bruce 080328 """ [overrides superclass method] """ if not mapping.write_bonds_compactly: return {} if not self._ladder_is_fully_ok(): # self.idealized_strand_direction might differ from actual # bond directions, so we can't abbreviate them this way return {} atoms = self.indexed_atoms_in_order(mapping) return dict([(atom.key, atom) for atom in atoms]) def _ladder_is_fully_ok(self): #bruce 080411 split this out; it might be redundant with other methods # see also: self.__ok() ladder = self.ladder return ladder and ladder.valid and not ladder.error def write_bonds_compactly(self, mapping): #bruce 080328 """ [overrides superclass method] """ # write the new bond_chain and/or directional_bond_chain records -- # subclass must decide which one. assert 0, "subclass must implement" def _compute_atom_range_for_write_bonds_compactly(self, mapping): #bruce 080328 """ [private helper for subclass write_bonds_compactly methods] """ atoms = self.indexed_atoms_in_order(mapping) assert atoms if debug_flags.DNA_UPDATER_SLOW_ASSERTS: # warning: not well tested, since this flag was turned off # by default 080702, but write_bonds_compactly is not yet # used by default as of then. codes = [mapping.encode_atom_written(atom) for atom in atoms] for i in range(len(codes)): # it might be an int or a string version of an int assert int(codes[i]) > 0 if i: assert int(codes[i]) == 1 + int(codes[i-1]) continue pass res = mapping.encode_atom_written(atoms[0]), \ mapping.encode_atom_written(atoms[-1]) # ok if same atom, can happen # print "fyi, compact bond atom range for %r is %r" % (self, res) return res def _f_compute_baseatom_range(self, mapping): #bruce 080328 """ [friend method for mapping.get_memo_for(self.ladder), an object of class DnaLadder_writemmp_mapping_memo] """ atoms = self.get_baseatoms() res = mapping.encode_atom_written(atoms[0]), \ mapping.encode_atom_written(atoms[-1]) # ok if same atom, can happen return res def number_of_conversion_atoms(self, mapping): #bruce 080321 """ [abstract method of DnaLadderRailChunk] How many atoms are written to a file, when controlled by mapping, which are not in self.atoms? (Note: self.atoms may or may not contain more atoms than self.baseatoms. Being a conversion atom and being not in self.baseatoms are independent properties.) """ assert 0, "subclass must implement" _class_for_writemmp_mapping_memo = DnaLadderRailChunk_writemmp_mapping_memo # subclass can override if needed (presumably with a subclass of this value) def _f_make_writemmp_mapping_memo(self, mapping): """ [friend method for class writemmp_mapping.get_memo_for(self)] """ # note: same code in some other classes that implement this method return self._class_for_writemmp_mapping_memo(mapping, self) def save_as_what_PAM_model(self, mapping): #bruce 080326 """ Return None or an element of PAM_MODELS which specifies into what PAM model, if any, self should be converted, when saving it as controlled by mapping. @param mapping: an instance of writemmp_mapping controlling the save. """ assert mapping def doit(): res = self._f_requested_pam_model_for_save(mapping) if not res: # optimize a simple case (though not the usual case); # only correct since self.ladder will return None # for its analogous decision if any of its chunks do. return None # memoize the rest in mapping, not for speed but to # prevent repeated error messages for same self and mapping # (and to enforce constant behavior as bug precaution) memo = mapping.get_memo_for(self) return memo._f_save_as_what_PAM_model() res = doit() ## print "save_as_what_PAM_model(%r,...) -> %r" % (self, res) return res def _f_requested_pam_model_for_save(self, mapping): """ Return whatever the mapping and self options are asking for (without checking whether it's doable). For no conversion, return None. For conversion to a PAM model, return an element of PAM_MODELS. """ ## print " mapping.options are", mapping.options ## print " also self.save_as_pam is", self.save_as_pam if mapping.honor_save_as_pam: res = self.save_as_pam or mapping.convert_to_pam else: res = mapping.convert_to_pam if not res: res = None return res pass # end of class DnaLadderRailChunk # == def _make_or_reuse_DnaLadderRailChunk(constructor, assy, chain, ladder): """ """ name = "" new_chunk = constructor(assy, name, chain, reuse_old_chunk_if_possible = True) res = new_chunk # tentative if new_chunk._please_reuse_this_chunk: res = new_chunk._please_reuse_this_chunk # it's an old chunk assert not new_chunk.atoms new_chunk.kill() # it has no atoms, but can't safely do this itself # review: is this needed, and safe? maybe it's not in the model yet? res._f_set_new_ladder(ladder) return res # == these subclasses might be moved to separate files, if they get long class DnaAxisChunk(DnaLadderRailChunk): """ Chunk for holding part of a Dna Segment Axis (the part in a single DnaLadder). Internal model object; same comments as in DnaStrandChunk docstring apply. """ def isAxisChunk(self): """ [overrides Chunk method] """ return True def isStrandChunk(self): """ [overrides Chunk method] """ return False def indexed_atoms_in_order(self, mapping): #bruce 080321 """ [implements abstract method of DnaLadderRailChunk] """ del mapping if not self._ladder_is_fully_ok(): # in this case, it's even possible get_baseatoms will fail # (if we are a leftover DnaLadderRailChunk full of error atoms # rejected when making new ladders, and have no .ladder ourselves # (not sure this is truly possible, needs review)) # [bruce 080411 added this check] return [] return self.get_baseatoms() def number_of_conversion_atoms(self, mapping): #bruce 080321 """ [implements abstract method of DnaLadderRailChunk] """ del mapping return 0 def write_bonds_compactly(self, mapping): #bruce 080328 """ [overrides superclass method] """ # LOGIC BUG (fixable without revising mmp reading code): # we may have excluded more bonds from Atom.writemmp # than we ultimately write here, if the end atoms of # our rail are bonded together, or if there are other (illegal) # bonds between atoms in it besides the along-rail bonds. # (Applies to both axis and strand implems.) # To fix, just look for those bonds and write them directly, # or, be more specific about which bonds to exclude # (e.g. pass a set of atom pairs; maybe harder when fake_Pls are involved). # Not urgent, since rare and doesn't affect mmp reading code or mmpformat version. # I don't think the same issue affects the dna_rung_bonds record, but review. # [bruce 080328] # write the new bond_chain record code_start, code_end = \ self._compute_atom_range_for_write_bonds_compactly(mapping) record = "bond_chain %s %s\n" % (code_start, code_end) mapping.write(record) # write compact rung bonds to previously-written strand chunks ladder_memo = mapping.get_memo_for(self.ladder) for chunk in ladder_memo.wrote_strand_chunks: ladder_memo.write_rung_bonds(chunk, self) # make sure not-yet-written strand chunks can do the same with us ladder_memo.advise_wrote_axis_chunk(self) return pass def make_or_reuse_DnaAxisChunk(assy, chain, ladder): """ """ return _make_or_reuse_DnaLadderRailChunk( DnaAxisChunk, assy, chain, ladder) # == class DnaStrandChunk(DnaLadderRailChunk): """ Chunk for holding part of a Dna Strand (the part in a single DnaLadder). Internal model object -- won't be directly user-visible (for MT, selection, etc) when dna updater is complete. But it's a normal member of the internal model tree for purposes of copy, undo, mmp file, internal selection, draw. (Whether copy implem makes another chunk of this class, or relies on dna updater to make one, is not yet decided. Likewise, whether self.draw is normally called is not yet decided.) """ _class_for_writemmp_mapping_memo = DnaStrandChunk_writemmp_mapping_memo # overrides superclass version (with a subclass of it) def isAxisChunk(self): """ [overrides Chunk method] """ return False def isStrandChunk(self): """ [overrides Chunk method] """ return True def _grab_atoms_from_chain(self, chain, just_count): # misnamed, doesn't take them out of chain """ [extends superclass version] """ DnaLadderRailChunk._grab_atoms_from_chain(self, chain, just_count) for atom in chain.baseatoms: # pull in Pls too (if they prefer this Ss to their other one) # and also directly bonded unpaired base atoms (which should # never be bonded to more than one Ss) ### review: can't these atoms be in an older chunk of the same class # from a prior step?? I think yes... so always pull them in, # regardless of class of their current chunk. for atom2 in atom.neighbors(): grab_atom2 = False # might be changed to True below is_Pl = atom2.element is Pl5 if is_Pl: # does it prefer to stick with atom (over its other Ss neighbors, if any)? # (note: usually it sticks based on bond direction, but if # it has only one real neighbor it always sticks to that # one.) if atom is atom2.Pl_preferred_Ss_neighbor(): # an Ss or None grab_atom2 = True elif atom2.element.role in ('unpaired-base', 'handle'): grab_atom2 = True if grab_atom2: if atom2.molecule is self: assert not just_count # since that implies no atoms yet in self print "\n***BUG: dna updater: %r is already in %r" % \ (atom2, self) # since self is new, just now being made, # and since we think only one Ss can want to pull in atom2 else: ## atom2.hopmol(self) self._grab_atom(atom2, just_count) # review: does this harm the chunk losing it if it too is new? @@@ # (guess: yes; since we overrode delatom to panic... not sure about Pl etc) # academic for now, since it can't be new, afaik # (unless some unpaired-base atom is bonded to two Ss atoms, # which we ought to prevent in the earlier bond-checker @@@@ NIM) # (or except for inconsistent bond directions, ditto) pass pass continue continue return # from _grab_atoms_from_chain def indexed_atoms_in_order(self, mapping): #bruce 080321 """ [implements abstract method of DnaLadderRailChunk] """ if not self._ladder_is_fully_ok(): # in this case, it's even possible get_baseatoms will fail # (if we are a leftover DnaLadderRailChunk full of error atoms # rejected when making new ladders, and have no .ladder ourselves # (not sure this is truly possible, needs review)) # [bruce 080411 added this check] return [] # TODO: optimization: also include bondpoints at the end. # This can be done later without altering mmp reading code. # It's not urgent. # TODO: optimization: cache this in mapping.get_memo_for(self). baseatoms = self.get_baseatoms() # for PAM3+5: # now interleave between these (or before/after for end Pl atom) # the real and/or converted Pl atoms. # (Always do this, even if no conversion is active, # so that real Pl atoms get into this list.) # (note: we cache the conversion atoms so they have constant keys; # TODO: worry about undo of those atoms, etc; # we cache them on their preferred Ss neighbor atoms) Pl_atoms = self._Pl_atoms_to_interleave(mapping) # len(baseatoms) + 1 atoms, can be None at the ends, # or in the middle when not converting to PAM5 # (or can be None to indicate no Pl atoms -- rare) if Pl_atoms is None: return baseatoms assert len(Pl_atoms) == len(baseatoms) + 1 def interleave(seq1, seq2): #e refile (py seq util) assert len(seq1) >= len(seq2) for i in range(len(seq1)): yield seq1[i] if i < len(seq2): yield seq2[i] continue return interleaved = interleave(Pl_atoms, baseatoms) return [atom for atom in interleaved if atom is not None] def number_of_conversion_atoms(self, mapping): #bruce 080321 """ [implements abstract method of DnaLadderRailChunk] """ if self.save_as_what_PAM_model(mapping) != MODEL_PAM5: # optimization (conversion atoms are not needed # except when converting to PAM5). return 0 assert mapping # otherwise, save_as_what_PAM_model should return None ### REVIEW: if not self._ladder_is_fully_ok(), should we return 0 here # and refuse to convert in other places? [bruce 080411 Q] # Our conversion atoms are whatever Pl atoms we are going to write # which are not in self.atoms (internally they are Fake_Pl objects). # For efficiency and simplicity we'll cache the answer in our chunk memo. memo = mapping.get_memo_for(self) return memo._f_number_of_conversion_atoms() def _Pl_atoms_to_interleave(self, mapping): """ [private helper for mmp write methods] Assuming (not checked) that this chunk should be saved in PAM5 (and allowing it to presently be in either PAM3 or PAM3+5 or PAM5), return a list of Pl atoms to interleave before/between/after our baseatoms. (Not necessarily in the right positions in 3d space, or properly bonded to our baseatoms, or atoms actually in self.atoms.) Length is always 1 more than len(baseatoms). First and last entries might be None if those Pl atoms should belong to different chunks or should not exist. Middle entries might be None if we're not converting to PAM5 and no real Pl atoms are present there, or if we're converting to PAM3 (maybe nim). The Pl atoms returned exist as Atom or Fake_Pl objects, but might be in self, or killed(??), or perhaps some of each. Don't alter this. It's ok to memoize data in mapping (index by self, private to self and/or self.ladder) which depends on our current state and can be used when writing every chunk in self.ladder. """ # note: we must proceed even if not converting to PAM5 here, # since we interleave even real Pl atoms. assert mapping # needed for the memo... too hard to let it be None here memo = mapping.get_memo_for(self) return memo.Pl_atoms def write_bonds_compactly(self, mapping): #bruce 080328 """ Note: this also writes all dnaBaseName (sequence) info for our atoms. [overrides superclass method] """ # write the new directional_bond_chain record code_start, code_end = \ self._compute_atom_range_for_write_bonds_compactly(mapping) # todo: override that to assert the bond directions are as expected? bond_direction = self.idealized_strand_direction() sequence = self._short_sequence_string() # might be "" if sequence: record = "directional_bond_chain %s %s %d %s\n" % \ (code_start, code_end, bond_direction, sequence) else: # avoid trailing space, though our own parser wouldn't care about it record = "directional_bond_chain %s %s %d\n" % \ (code_start, code_end, bond_direction) mapping.write(record) # write compact rung bonds to previously-written axis chunk, if any ladder_memo = mapping.get_memo_for(self.ladder) for chunk in ladder_memo.wrote_axis_chunks: ladder_memo.write_rung_bonds(chunk, self) # make sure not-yet-written axis chunk (if any) can do the same with us ladder_memo.advise_wrote_strand_chunk(self) return def _short_sequence_string(self): """ [private helper for write_bonds_compactly] Return the dnaBaseNames (letters) of our base atoms, as a single string, in the same order as they appear in indexed_atoms_in_order, leaving off trailing X's. (If all sequence is unassigned == 'X', return "".) """ baseatoms = self.get_baseatoms() n = len(baseatoms) while n and not baseatoms[n-1]._dnaBaseName: # KLUGE, optimization: access private attr ### TODO: make it a friend attr # (this inlines atom.getDnaBaseName() != 'X') n -= 1 if not n: return "" # common optimization return "".join([atom.getDnaBaseName() for atom in baseatoms[:n]]) pass # end of class DnaStrandChunk def make_or_reuse_DnaStrandChunk(assy, chain, ladder): """ """ return _make_or_reuse_DnaLadderRailChunk(DnaStrandChunk, assy, chain, ladder) # end
NanoCAD-master
cad/src/dna/model/DnaLadderRailChunk.py
# Copyright 2007 Nanorex, Inc. See LICENSE file for details. """ AtomChainOrRing.py - cache info about atom/bond chains or rings of various types @author: Bruce @version: $Id$ @copyright: 2007 Nanorex, Inc. See LICENSE file for details. Note: this is not specific to DNA, so it probably doesn't belong inside the dna_model package, though it was written to support that. This module has no dna-specific knowledge, and that should remain true. See also: class DnaChain, which inherits this. """ class AtomChainOrRing(object): """ Abstract class, superclass of AtomChain and AtomRing. Used internally to cache information about atom chains or rings. Contains no undoable state; never appears in internal model tree or mmp file The atom and bond lists are not modifiable after init. Some of all of the atoms and bonds might be killed. """ # subclass constant ringQ = None # subclasses set this to True or False def __init__(self, listb, lista): assert self.ringQ in (False, True) # i.e. we're in a concrete subclass self.bond_list = listb self.atom_list = lista if self.ringQ: assert len(listb) == len(lista) #e and more conditions about how they relate [see calling code asserts] # (which also make sure caller didn't reverse the arg order) else: assert len(listb) + 1 == len(lista) #e ditto return def iteratoms(self): # REVIEW: different if self.index_direction < 0? """ # get doc from calling method """ return self.atom_list pass class AtomChain(AtomChainOrRing): ringQ = False pass class AtomRing(AtomChainOrRing): ringQ = True pass # end
NanoCAD-master
cad/src/dna/model/AtomChainOrRing.py
# Copyright 2008 Nanorex, Inc. See LICENSE file for details. """ pam3plus5_ops.py - PAM3+5 conversion helpers that modify model objects (but that are not writemmp-specific -- those have their own module) @author: Bruce (based on algorithms proposed by Eric D) @version: $Id$ @copyright: 2008 Nanorex, Inc. See LICENSE file for details. Reference and explanation for PAM3+5 conversion process and formulas: http://www.nanoengineer-1.net/privatewiki/index.php?title=PAM-3plus5plus_coordinates """ # WARNING: this list of imports must be kept fairly clean, # especially of most things from dna module, or of chem.py # (which indirectly imports this module). For explanation # see import comment near top of PAM_Atom_methods.py. # [bruce 080409] from utilities.constants import average_value from utilities.constants import Pl_STICKY_BOND_DIRECTION from model.elements import Pl5, Gv5, Singlet from utilities import debug_flags import foundation.env as env from utilities.Log import redmsg, graymsg from utilities.debug import print_compact_traceback from geometry.VQT import norm from model.bond_constants import find_bond, find_Pl_bonds from model.bond_constants import V_SINGLE from model.bonds import bond_atoms_faster from dna.updater.dna_updater_globals import DNALADDER_INVAL_IS_NOOP_BUT_OK from dna.updater.dna_updater_globals import DNALADDER_INVAL_IS_OK from dna.updater.dna_updater_globals import temporarily_set_dnaladder_inval_policy from dna.updater.dna_updater_globals import restore_dnaladder_inval_policy from dna.updater.dna_updater_globals import _f_atom_to_ladder_location_dict from dna.updater.dna_updater_globals import rail_end_atom_to_ladder from dna.model.pam3plus5_math import BASEPAIR_HANDLE_DISTANCE_FROM_SS_MIDPOINT # == def Pl_pos_from_neighbor_PAM3plus5_data( bond_directions_to_neighbors, remove_data_from_neighbors = False ): #bruce 080402 """ Figure out where a new Pl atom should be located based on the PAM3plus5_data (related to its position) in its neighbor Ss3 or Ss5 atoms (whose positions are assumed correct). (If the neighbors are Ss5 it's because they got converted from Ss3 recently, since this info is normally only present on Ss3 atoms.) Assume the neighbors are in DnaLadders with up to date baseframe info already computed and stored (but not necessarily that these ladders have remade their chunks, meaning atom.molecule.ladder might not exist or point to the new DnaLadders). The up to dateness of the baseframe info may not be checked, and out of date info would cause hard-to-notice bugs. @return: new absolute position, or None if we can't compute one (error). @see: related method (stores data in the other direction), _f_Pl_store_position_into_Ss3plus5_data @see: analogous function for Gv: Gv_pos_from_neighbor_PAM3plus5_data """ proposed_posns = [] for direction_to, ss in bond_directions_to_neighbors: # neighbors of Pl if ss.element.role == 'strand': # (avoid bondpoints or (erroneous) non-PAM or axis atoms) try: #bruce 080516: protect from exceptions on each neighbor # (so it can still work if the other one works -- # can happen for bridging Pls with bugs on one ladder) pos = ss._f_recommend_PAM3plus5_Pl_abs_position( - direction_to, # the sign makes this the Ss -> Pl direction remove_data = remove_data_from_neighbors, make_up_position_if_necessary = True # doesn't prevent all returns of None ) except: msg = "bug: exception in " \ "%r._f_recommend_PAM3plus5_Pl_abs_position, " \ "skipping it for that strand_neighbor" % (ss,) print_compact_traceback( msg + ": ") pos = None # following print is redundant; nevermind pass if pos is None: # can happen in theory, in spite of # make_up_position_if_necessary = True, # if ss is not a valid atom for this; # but the loop above tries not to call it then, # so this should not happen unless there are bugs... # oops, it can be called for ss in a single strand domain, for example. # todo: debug_flags for this: print "fyi: _f_recommend_PAM3plus5_Pl_abs_position returned None for %r" % ss # remove when works if routine; leave in if never seen, to notice bugs else: proposed_posns.append(pos) continue if not proposed_posns: # neither neighbor was able to make up a position -- error. # caller might have ways of handling this, but we don't... print "bug: Pl_pos_from_neighbor_PAM3plus5_data can't compute pos " \ "for Pl between these neighbors:", bond_directions_to_neighbors return None if len(proposed_posns) == 1: # optimization return proposed_posns[0] return average_value( proposed_posns) # == def kill_Pl_and_rebond_neighbors(atom): # note: modified and moved here [bruce 080408] from function # _convert_Pl5 in obsolete file convert_from_PAM5.py # [written/debugged/tested there, bruce 080327 or earlier] """ Assume atom is a live and correctly structured Pl5 atom (but also check this for safety, at least for now). If atom's neighbors have the necessary structure (Ss-Pl-Ss or X-Pl-Ss, with fully set and consistent bond_directions), then kill atom, replacing its bonds with a direct bond between its neighbors (same bond_direction). Summarize results (ok or error) to history. ### REVIEW """ assert atom.element is Pl5 # remove when works assert not atom.killed() # could also assert no dna updater error _old = temporarily_set_dnaladder_inval_policy( DNALADDER_INVAL_IS_NOOP_BUT_OK) # REVIEW: can this ever be called outside dna updater? # If so, we might not want to change the policy then # (i.e. only change it if it's DNALADDER_INVAL_IS_ERROR). # To notice this if it happens and force a review, we assert # _old is not what it would be outside the updater: assert _old != DNALADDER_INVAL_IS_OK # see comment for explanation try: return _kill_Pl_and_rebond_neighbors_0(atom) finally: restore_dnaladder_inval_policy( _old) pass def _kill_Pl_and_rebond_neighbors_0(atom): # Note: we optimize for the common case (nothing wrong, conversion happens) ### NOTE: many of the following checks have probably also been done by # calling code before we get here. Optimize this sometime. [bruce 080408] bonds = atom.bonds # change these during the loop bad = False saw_plus = saw_minus = False num_bondpoints = 0 neighbors = [] direction = None # KLUGE: set this during loop, but use it afterwards too for bond in bonds: other = bond.other(atom) neighbors += [other] element = other.element direction = bond.bond_direction_from(atom) if direction == 1: saw_plus = True elif direction == -1: saw_minus = True if element is Singlet: num_bondpoints += 1 elif element.symbol in ('Ss3', 'Ss5'): # [in the 080408 copy, will often be one of each!] pass else: bad = True continue if not (len(bonds) == 2 and saw_minus and saw_plus and num_bondpoints < 2): bad = True if bad: summary_format = \ "Warning: dna updater left [N] Pl5 pseudoatom(s) unconverted" env.history.deferred_summary_message( redmsg(summary_format) ) # orange -> red [080408] return del saw_plus, saw_minus, num_bondpoints, bad # Now we know it is either Ss-Pl-Ss or X-Pl-Ss, # with fully set and consistent bond_directions. # But we'd better make sure the neighbors are not already bonded! # # (This is weird enough to get its own summary message, which is red. # Mild bug: we're not also counting it in the above message.) # # (Note: there is potentially slow debug code in rebond which is # redundant with this. It does a few other things too that we don't # need, so if it shows up in a profile, just write a custom version # for this use. ### OPTIM) n0, n1 = neighbors del neighbors b0, b1 = bonds del bonds # it might be mutable and we're changing it below, # so be sure not to use it again if find_bond(n0, n1): summary_format = \ "Error: dna updater noticed [N] Pl5 pseudoatom(s) whose neighbors are directly bonded" env.history.deferred_summary_message( redmsg(summary_format) ) return # Pull out the Pl5 and directly bond its neighbors, # reusing one of the bonds for efficiency. # (This doesn't preserve its bond_direction, so set that again.) # Kluge: the following code only works for n1 not a bondpoint # (since bond.bust on an open bond kills the bondpoint), # and fixing that would require inlining and modifying a # few Atom methods, # so to avoid this case, reverse everything if needed. if n1.element is Singlet: direction = - direction n0, n1 = n1, n0 b0, b1 = b1, b0 # Note: bonds.reverse() might modify atom.bonds itself, # so we shouldn't do it even if we didn't del bonds above. # (Even though no known harm comes from changing an atom's # order of its bonds. It's not reviewed as a problematic # change for an undo snapshot, though. Which is moot here # since we're about to remove them all. But it still seems # safer not to do it.) pass ## # save atom_posn before modifying atom (not known to be needed), and # set atom.atomtype to avoid bugs in reguess_atomtype during atom.kill # (need to do that when it still has the right number of bonds, I think) ## atom_posn = atom.posn() atom.atomtype # side effect: set atomtype old_nbonds_neighbor1 = len(n1.bonds) # for assert old_nbonds_neighbor0 = len(n0.bonds) # for assert b1.bust(make_bondpoints = False) # n1 is now missing one bond; so is atom # note: if n1 was a Singlet, this would kill it (causing bugs); # see comment above, where we swap n1 and n0 if needed to prevent that. b0.rebond(atom, n1) # now n1 has enough bonds again; atom is missing both bonds assert len(atom.bonds) == 0, "Pl %r should have no bonds but has %r" % (atom, atom.bonds) assert not atom.killed() assert len(n1.bonds) == old_nbonds_neighbor1 assert len(n0.bonds) == old_nbonds_neighbor0 ## # KLUGE: we know direction is still set to the direction of b1 from atom ## # (since b1 was processed last by the for loop above), ## # which is the overall direction from n0 thru b0 to atom thru b1 to n1, ## # so use this to optimize recording the Pl info below. ## # (Of course we really ought to just rewrite this whole conversion in Pyrex.) ## ## ## assert direction == b1.bond_direction_from(atom) # too slow to enable by default ## ## # not needed, rebond preserves it: ## ## b0.set_bond_direction_from(n0, direction) ## ## assert b0.bond_direction_from(n0) == direction # too slow to enable by default ## ## # now save the info we'll need later (this uses direction left over from for-loop) ## ## if n0.element is not Singlet: ## _save_Pl_info( n0, direction, atom_posn) ## ## if n1.element is not Singlet: ## _save_Pl_info( n1, - direction, atom_posn) # note the sign on direction # get the Pl atom out of the way atom.kill() ## # (let's hope this happened before an Undo checkpoint ever saw it -- ## # sometime verify that, and optimize if it's not true) if 0: # for now; bruce 080413 356pm # summarize our success -- we'll remove this when it becomes the default, # or condition it on a DEBUG_DNA_UPDATER flag ### debug_flags.DEBUG_DNA_UPDATER # for use later summary_format = \ "Note: dna updater removed [N] Pl5 pseudoatom(s) while converting to PAM3+5" env.history.deferred_summary_message( graymsg(summary_format) ) return # == def insert_Pl_between(s1, s2): #bruce 080409/080410 """ Assume s1 and s2 are directly bonded atoms, which can each be Ss3 or Ss5 (PAM strand sugar atoms) or bondpoints (but not both bondpoints -- impossible since such can never be directly bonded). Insert a Pl5 between them (bonded to each of them, replacing their direct bond), set it to have non-definitive position, and return it. @note: inserting Pl5 between Ss5-X is only correct at one end of a PAM5 strand, but we depend on the caller to check this and only call us if it's correct (since we just insert it without checking). @return: the Pl5 atom we made. (Never returns None. Errors are either not detected or cause exceptions.) """ _old = temporarily_set_dnaladder_inval_policy( DNALADDER_INVAL_IS_NOOP_BUT_OK) # REVIEW: can this ever be called outside dna updater? # If so, we might not want to change the policy then # (i.e. only change it if it's DNALADDER_INVAL_IS_ERROR). # To notice this if it happens and force a review, we assert # _old is not what it would be outside the updater: assert _old != DNALADDER_INVAL_IS_OK # see comment for explanation try: return _insert_Pl_between_0(s1, s2) finally: restore_dnaladder_inval_policy( _old) pass def _insert_Pl_between_0(s1, s2): direct_bond = find_bond(s1, s2) assert direct_bond direction = direct_bond.bond_direction_from(s1) # from s1 to s2 # Figure out which atom the Pl sticks to (joins the chunk of). # Note: the following works even if s1 or s2 is a bondpoint, # which is needed for putting a Pl at the end of a newly-PAM5 strand. # But whether to actually put one there is up to the caller -- # it's only correct at one end, but this function will always do it. if direction == Pl_STICKY_BOND_DIRECTION: Pl_prefers = [s2, s1] else: Pl_prefers = [s1, s2] # The Pl sticks to the first thing in Pl_prefers which is not a bondpoint # (which always exists, since two bondpoints can't be bonded): # (see also the related method Pl_preferred_Ss_neighbor()) Pl_sticks_to = None # for pylint for s in Pl_prefers: if not s.is_singlet(): Pl_sticks_to = s break continue # break the old bond... wait, do this later, # so as not to kill s1 or s2 if one of them is a Singlet ## direct_bond.bust(make_bondpoints = False) # make the new Pl atom ## Atom = s1.__class__ ## # kluge to avoid import of chem.py, for now ## # (though that would probably be ok (at least as a runtime import) ## # even though it might expand the import cycle graph) ## # needs revision if we introduce Atom subclasses ## # TODO: check if this works when Atom is an extension object ## # (from pyrex atoms) Atom = s1.molecule.assy.Atom #bruce 080516 chunk = Pl_sticks_to.molecule pos = (s1.posn() + s2.posn()) / 2.0 # position will be corrected by caller before user sees it Pl = Atom('Pl5', pos, chunk) Pl._f_Pl_posn_is_definitive = False # tell caller it needs to, and is allowed to, correct pos # bond it to s1 and s2 b1 = bond_atoms_faster(Pl, s1, V_SINGLE) b2 = bond_atoms_faster(Pl, s2, V_SINGLE) # now it should be safe to break the old bond direct_bond.bust(make_bondpoints = False) # set bond directions: s1->Pl->s2 same as s1->s2 was before b1.set_bond_direction_from(s1, direction) b2.set_bond_direction_from(Pl, direction) return Pl # or None if error? caller assumes not possible, so do we def find_Pl_between(s1, s2): #bruce 080409 """ Assume s1 and s2 are Ss3 and/or Ss5 atoms which might be directly bonded or might have a Pl5 between them. If they are directly bonded, return None. If they have a Pl between them, return it. If neither is true, raise an exception. """ # optimize for the Pl being found bond1, bond2 = find_Pl_bonds(s1, s2) if bond1: return bond1.other(s1) else: assert find_bond(s1, s2) return None pass # == def Gv_pos_from_neighbor_PAM3plus5_data( neighbors, remove_data_from_neighbors = False ): #bruce 080409, modified from Pl_pos_from_neighbor_PAM3plus5_data """ Figure out where a new Gv atom should be located based on the PAM3plus5_data (related to its position) in its neighbor Ss3 or Ss5 atoms (whose positions are assumed correct). (If the neighbors are Ss5 it's because they got converted from Ss3 recently, since this info is normally only present on Ss3 atoms.) Assume the neighbors are in the same basepair in a DnaLadder with up to date baseframe info already computed and stored. (See warning in Pl_pos_from_neighbor_PAM3plus5_data about atom. molecule.ladder perhaps being wrong or missing.) This up to dateness may not be checked, and out of date info would cause hard-to-notice bugs. @return: new absolute position, or None if we can't compute one (error). @see: related method (stores data in the other direction), _f_Gv_store_position_into_Ss3plus5_data @see: analogous function for Pl: Pl_pos_from_neighbor_PAM3plus5_data """ proposed_posns = [] for ss in neighbors: assert ss.element.role == 'strand' # (avoid bondpoints or (erroneous) non-PAM or axis atoms) pos = ss._f_recommend_PAM3plus5_Gv_abs_position( remove_data = remove_data_from_neighbors, make_up_position_if_necessary = True # doesn't prevent all returns of None ) if pos is None: # see comment in Pl_pos_from_neighbor_PAM3plus5_data print "fyi: _f_recommend_PAM3plus5_Gv_abs_position returned None for %r" % ss # remove when works if routine; leave in if never seen, to notice bugs else: proposed_posns.append(pos) continue if not proposed_posns: # neither neighbor was able to make up a position -- error. # caller might have ways of handling this, but we don't... print "bug: Gv_pos_from_neighbor_PAM3plus5_data can't compute pos " \ "for Gv between these neighbors:", neighbors return None if len(proposed_posns) == 1: # optimization return proposed_posns[0] return average_value( proposed_posns) # == def _f_find_new_ladder_location_of_baseatom(self): # note: used in this file and in PAM_Atom_methods """ param self: a PAM atom. [#doc more] """ #bruce 080411 split common code out of several methods, # then totally rewrote it to stop assuming wrongly # that atom.molecule.ladder can find fresh ladders # that didn't yet remake their chunks locator = _f_atom_to_ladder_location_dict data = locator.get(self.key) if data: return data # (ladder, whichrail, index) # otherwise it must be an end atom on a non-fresh ladder ladder = rail_end_atom_to_ladder(self) whichrail, index = ladder.whichrail_and_index_of_baseatom(self) # by search in ladder, optimized to try the ends first return ladder, whichrail, index def _f_baseframe_data_at_baseatom(self): # note: used in PAM_Atom_methods """ param self: a PAM atom. [#doc more] """ # old buggy version. magically transformed to new correct version # by merely adding a new assert (and rewriting the subroutine it calls) ladder, whichrail, index = _f_find_new_ladder_location_of_baseatom(self) assert ladder.valid, \ "bug: got invalid ladder %r (and whichrail %r, index %r) " \ "from _f_find_new_ladder_location_of_baseatom(%r)" % \ ( ladder, whichrail, index, self) origin, rel_to_abs_quat, y_m_junk = ladder._f_baseframe_data_at(whichrail, index) # we trust caller to make sure this is up to date (no way to detect if not) # implem note: if we only store top baseframes, this will derive bottom ones on the fly return origin, rel_to_abs_quat, y_m_junk # == def add_basepair_handles_to_atoms(atoms): #bruce 080515 """ """ goodcount, badcount = 0, 0 for atom in atoms: atom.unpick() if atom.element is Gv5 and len(atom.strand_neighbors()) == 2: goodcount += 1 # Figure out the position from the Gv5 and its presumed-to-be Ss5 # neighbors. [Fixed per Eric D spec, bruce 080516] sn = atom.strand_neighbors() ss_midpoint = average_value([a.posn() for a in sn]) towards_Gv = norm(atom.posn() - ss_midpoint) newpos = ss_midpoint + \ BASEPAIR_HANDLE_DISTANCE_FROM_SS_MIDPOINT * towards_Gv ## if 0: # stub for computing new position ## oldposns = [a.posn() for a in ([atom] + sn)] ## newpos = average_value(oldposns) Atom = atom.molecule.assy.Atom # (avoid model.chem import cycle) newatom = Atom( 'Ah5', newpos, atom.molecule ) # PAM5-Axis-handle bond_atoms_faster( newatom, atom, V_SINGLE) # note: no bondpoints need creation or removal newatom.pick() pass else: badcount += 1 continue return goodcount, badcount # == # TODO: fix a dna updater bug in which (I am guessing) reading an mmp file with Ss3-Pl5-Ss3 # makes a DnaChain containing only the Pl5, which has no baseatoms, # and assertfails about that. I have an example input file, Untitled-bug-Ss3-Pl5-Ss3.mmp, # for which I guess this is the issue (not verified). # Low priority, since no such files (or lone Pl5 atoms in that sense) will normally exist. # OTOH, this bug seems to ruin the session, by making a DnaLadder with no strand rails # which never goes away even when we read more than one new file afterwards. # Correct fix is to kill that Pl and (even lower pri) put its position data onto its neighbors. # Or, leave it there but don't make it into a chain. # [bruce 080402 comment] # end
NanoCAD-master
cad/src/dna/model/pam3plus5_ops.py
# Copyright 2007-2008 Nanorex, Inc. See LICENSE file for details. """ elements_data_PAM3.py -- data for PAM3 pseudoatom elements @author: Mark @version: $Id$ @copyright: 2007-2008 Nanorex, Inc. See LICENSE file for details. History: Bruce 071105 revised init code, and split PAM3 and PAM5 data out of elements_data.py into separate files. """ from model.elements_data import tetra4, flat, tetra2, tetra3, onebond from utilities.constants import MODEL_PAM3 _DIRECTIONAL_BOND_ELEMENTS_PAM3 = ('Ss3', 'Pl3', 'Sj3', 'Se3', 'Sh3', 'Hp3') # == # mark 060129. New default colors for Alpha 7. _defaultRadiusAndColor = { "Ax3" : (4.5, [0.4, 0.4, 0.8]), "Ss3" : (4.5, [0.4, 0.8, 0.4]), "Sj3" : (4.5, [0.4, 0.8, 0.8]), "Pl3" : (3.0, [0.4, 0.1, 0.5]), # (unused) "Ae3" : (4.5, [0.1, 0.1, 0.5]), "Se3" : (4.5, [0.4, 0.8, 0.4]), "Sh3" : (3.0, [0.6, 0.2, 0.6]), "Hp3" : (4.5, [0.3, 0.7, 0.3]), "Ub3" : (2.3, [0.428, 0.812, 0.808]), #bruce 080117 guess, "light blue" "Ux3" : (2.3, [0.428, 0.812, 0.808]), #bruce 080410 stub "Uy3" : (2.3, [0.812, 0.428, 0.808]), #bruce 080410 stub } _alternateRadiusAndColor = {} # Format of _mendeleev: see elements_data.py _mendeleev = [ # B-DNA PAM3 v2 pseudo atoms (see also _DIRECTIONAL_BOND_ELEMENTS) # # Note: the bond vector lists are mainly what we want in length, # not necessarily in geometry. # #bruce 071106: added option dicts; deprecated_to options are good or bad # guesses or unfinished; the X ones might be WRONG #bruce 080410 added Ux3 and Uy3 and updated all general comments below # axis and strand sugar -- these make up all the PAM atoms in a simple PAM3 duplex ("Ax3", "PAM3-Axis", 300, 1.0, [[4, 200, tetra4]], dict(role = 'axis')), ("Ss3", "PAM3-Sugar", 301, 1.0, [[3, 210, flat]], dict(role = 'strand')), # PAM3 version of Pl5 (never used, in past, present or future) ("Pl3", "PAM3-Phosphate", 302, 1.0, [[2, 210, tetra2]], dict(role = 'strand', deprecated_to = 'remove')), ### ?? unused atom? # deprecated PAM3 elements # (btw, some of these say None, 'sp', which is probably wrong -- # don't imitate this in new elements) [bruce 080516 comment] ("Sj3", "PAM3-Sugar-Junction", 303, 1.0, [[3, 210, flat]], dict(role = 'strand', deprecated_to = 'Ss3')), ("Ae3", "PAM3-Axis-End", 304, 1.0, [[3, 200, tetra3]], dict(role = 'axis', deprecated_to = 'Ax3')), ("Se3", "PAM3-Sugar-End", 305, 1.0, [[2, 210, tetra2]], dict(role = 'strand', deprecated_to = 'X')), # might be WRONG # WARNING: Se3 is a confusing name, since Se with no '3' or '5' is Selenium (unrelated). # Fortunately Se3 is one of the deprecated PAM elements, and there is no Se5. [bruce 080320] ("Sh3", "PAM3-Sugar-Hydroxyl", 306, 1.0, [[1, 210, None, 'sp']], dict(role = 'strand', deprecated_to = 'X')), # might be WRONG ("Hp3", "PAM3-Hairpin", 307, 1.0, [[2, 210, tetra2]], dict(role = 'strand', deprecated_to = 'Ss3')), # note: 308 and 309 are not used because they correspond to PAM5 atoms # with no PAM3 analogue. # unpaired base elements: # one-atom (besides backbone) unpaired base -- might be used, don't know yet ("Ub3", "PAM3-Unpaired-base", 310, 1.0, [[4, 200, tetra4]], dict(role = 'unpaired-base')), # two-atom (besides backbone) unpaired base -- the PAM5 version of this # (see elements_data_PAM5.py for an explanation of these element symbols # and names, and something about their purpose) # is a recent proposal under active development and is very likely to # be used; the PAM3 translation is undecided, and might be a single Ub3, # but seems a bit more likely to be a pair of these two, Ux3 and Uy3, # because that way their positions will transform properly with no extra # work when we rotate a set of atoms, and will define a PAM3+5 baseframe: ("Ux3", "PAM3-Unpaired-base-x", 311, 1.0, [[4, 200, tetra4]], dict(role = 'unpaired-base')), # (likely to be revised) ("Uy3", "PAM3-Unpaired-base-y", 312, 1.0, [[4, 200, tetra4]], dict(role = 'unpaired-base')), # (likely to be revised) # note: 313 won't be used unless we decide we want a PAM3-Axis-handle, # which is unlikely. ] # Since these are not real chemical bonds, the electron accounting # need not be based on filled shells. We just specify that each atom # provides the same number of electrons as the bond count, and that it # needs twice that many. # 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 hyb FC need prov c-rad geometry _PAM3AtomTypeData = [ ["Ax3", None, 0, 8, 4, 2.00, tetra4], ["Ss3", None, 0, 6, 3, 2.10, flat], ["Pl3", None, 0, 4, 2, 2.10, tetra2], ["Sj3", None, 0, 6, 3, 2.10, flat], ["Ae3", None, 0, 6, 3, 2.00, tetra3], ["Se3", None, 0, 4, 2, 2.10, tetra2], ["Sh3", None, 0, 2, 1, 2.10, None], ["Hp3", None, 0, 4, 2, 2.10, tetra2], ["Ub3", None, 0, 8, 4, 2.00, tetra4], ["Ux3", None, 0, 8, 4, 2.00, tetra4], ["Uy3", None, 0, 8, 4, 2.00, tetra4], ] # == def init_PAM3_elements( periodicTable): periodicTable.addElements( _mendeleev, _defaultRadiusAndColor, _alternateRadiusAndColor, _PAM3AtomTypeData, _DIRECTIONAL_BOND_ELEMENTS_PAM3, default_options = dict(pam = MODEL_PAM3) ) return # end
NanoCAD-master
cad/src/dna/model/elements_data_PAM3.py
# Copyright 2007-2008 Nanorex, Inc. See LICENSE file for details. """ DnaStrandOrSegment.py - abstract superclass for DnaStrand and DnaSegment @author: Bruce @version: $Id$ @copyright: 2007-2008 Nanorex, Inc. See LICENSE file for details. """ from foundation.LeafLikeGroup import LeafLikeGroup _superclass = LeafLikeGroup class DnaStrandOrSegment(LeafLikeGroup): """ Abstract superclass for DnaStrand and DnaSegment, which represent a Dna Strand or Dna Segment inside a Dna Group. Internally, this is just a specialized Group containing various subobjects: - as Group members (not visible in MT, but for convenience of reusing preexisting copy/undo/mmp code): - one or more DnaMarkers, one of which determines this strand's or segment's base indexing, and whether/how it survives if its chains of PAM atoms are broken or merged with other strands or segments - this DnaStrands's DnaStrandChunks, or this DnaSegment's DnaAxisChunks (see docstrings of DnaStrand/DnaSegment for details) - As other attributes: - (probably) a WholeChain, which has a chain of DnaAtomChainOrRings (sp?) which together comprise all the PAM atoms in this strand, or all the PAM atoms in the axis of this segment. From these, related objects like DnaLadders and connected DnaSegments/DnaStrands can be found. This is used to help the dna updater reconstruct the PAM atom chunks after a change by old code which didn't do that itself. - whatever other properties the user needs to assign, which are not covered by the member nodes or superclass attributes. However, some of these might be stored on the controlling DnaMarker, so that if we are merged with another strand or segment, and later separated again, that marker can again control the properties of a new strand or segment (as it will in any case control its base indexing). """ def permit_as_member(self, node, pre_updaters = True, **opts): # in DnaStrandOrSegment """ [friend method for enforce_permitted_members_in_groups and subroutines] Does self permit node as a direct member, when called from enforce_permitted_members_in_groups with the same options as we are passed? @rtype: boolean [extends superclass method] """ #bruce 080319 if not LeafLikeGroup.permit_as_member(self, node, pre_updaters, **opts): # reject if superclass would reject [bruce 081217] return False del opts assy = self.assy res = isinstance( node, assy.DnaMarker) or \ isinstance( node, assy.DnaLadderRailChunk) or \ pre_updaters and isinstance( node, assy.Chunk) return res def getDnaGroup(self): """ Return the DnaGroup we are contained in, or None if we're not inside one. @note: Returning None should never happen if we have survived a run of the dna updater. """ return self.parent_node_of_class( self.assy.DnaGroup) def move_into_your_members(self, node): """ Move node into self's members, and if node was not already there but left some other existing Group, return that Group. @param node: a node of a suitable type for being our direct child @type node: a DnaLadderRailChunk or DnaMarker (see: permit_as_member) @return: Node's oldgroup (if we moved it out of a Group other than self) or None @rtype: Group or None """ # note: this is not yet needed in our superclass LeafLikeGroup, # but if it someday is, nothing in it is dna-specific except # the docstring. oldgroup = node.dad # might be None self.addchild(node) newgroup = node.dad assert newgroup is self if oldgroup and oldgroup is not newgroup: if oldgroup.part is newgroup.part: #k guess return oldgroup return None pass # end of class DnaStrandOrSegment # end
NanoCAD-master
cad/src/dna/model/DnaStrandOrSegment.py
# Copyright 2007-2008 Nanorex, Inc. See LICENSE file for details. """ DnaChain.py - Dna-aware AtomChainOrRing subclasses, AxisChain and StrandChain @author: Bruce @version: $Id$ @copyright: 2007-2008 Nanorex, Inc. See LICENSE file for details. """ from dna.model.DnaMarker import DnaSegmentMarker from dna.model.DnaMarker import DnaStrandMarker from utilities import debug_flags from utilities.debug import print_compact_stack, print_compact_traceback from dna.model.dna_model_constants import LADDER_ENDS from dna.model.dna_model_constants import LADDER_END0 from dna.updater.dna_updater_globals import rail_end_atom_to_ladder import foundation.env as env from utilities.Log import redmsg from model.bond_constants import find_bond, find_Pl_bonds from model.bond_constants import atoms_are_bonded # == DEBUG_NEIGHBOR_BASEATOMS = False # DO NOT COMMIT WITH True #bruce 080530 for bug in length 1 sticky end ghost bases # == try: _chain_id_counter except NameError: _chain_id_counter = 0 # == ### REVIEW: should a DnaChain contain any undoable state? (it doesn't now) (guess: no) class DnaChain(object): """ Base class for various kinds of DnaChain. Mostly abstract -- just has baseatoms (which must be set by subclass), index_direction, and methods that only depend on those. """ # default values of public instance variables: strandQ = None # will be set to a boolean saying whether we're made of strand or axis atoms baseatoms = () # public for read; sequence of all our atoms with a baseindex # (whether in strand or axis) (leaves out Pl, bondpoints, termination atoms) # note: subclass-specific __init__ must set this; used in __repr__ neighbor_baseatoms = (-1, -1) # when set, each element is None or a # neighboring baseatom (in a directly connected chain, possibly self # if self is a ring) # note: set by _f_update_neighbor_baseatoms, some doc is there index_direction = 1 # instances negate this when they reverse baseatoms # (and thus its indexing) using reverse_baseatoms. It records the # relation between the current and original baseindex direction. # # note: baseindex direction is not necessarily the same as bond # direction for strands (which is not even defined for axis bonds). # note: i'm not sure index_direction is needed -- it's used, but it # might be that it's only changed after it doesn't matter to the # current overall algorithm. OTOH, it might turn out that when # merging ladders and reversing it, we have to tell their markers # we did that, which is not done now [071204]. # # update 080602: this is NO LONGER USED (as of long ago, probably when # DnaMarkers got two atoms each) except to maintain its own value # (in self and other chains made from self). TODO: remove it. def __repr__(self): classname = self.__class__.__name__.split('.')[-1] if self.strandQ is None: basetype = 'strandQ-unknown' else: basetype = self.strandQ and 'strand' or 'axis' res = "<%s (%d %s bases) at %#x>" % \ (classname, len(self), basetype, id(self)) return res def _reverse_neighbor_baseatoms(self): self.neighbor_baseatoms = list(self.neighbor_baseatoms) self.neighbor_baseatoms.reverse() if DEBUG_NEIGHBOR_BASEATOMS: if self.neighbor_baseatoms[0] != -1 or \ self.neighbor_baseatoms[1] != -1: msg = "reversed %r.neighbor_baseatoms to get %r" % (self, self.neighbor_baseatoms) print_compact_stack( "\n" + msg + ": ") return def baseatom_index_pairs(self): """ Return a list of pairs (baseatom, baseindex) for every pseudoatom in self.chain_or_ring which corresponds to a base or basepair, using an arbitrary origin for baseindex, and a direction corresponding to how we store the atoms, which is arbitrary until something corrects it; ###REVIEW whether to correct it by list reversal or setting index_direction, and whether to also store a base_offset for use by this function. (This skips PAM5 Pl atoms in strands, and would skip any bondpoint-like termination atoms if we still had them. [###REVIEW -- do we, in PAM5? nim if so?]) """ # doc - iterator or just return a list? for now, return list, for simplicity & robustness #e would it be an optim to cache this? note the reverse method would have to redo or inval it. baseatoms = self.baseatoms return zip(baseatoms, range(len(baseatoms))) def start_baseindex(self): return 0 def baselength(self): return len(self.baseatoms) def __len__(self): return self.baselength() def __nonzero__(self): # 080311 # avoid Python calling __len__ for this [review: need __eq__ as well?] return True def end_baseatoms(self): return (self.baseatoms[0], self.baseatoms[-1]) # might be same atom def reverse_baseatoms(self): if debug_flags.DEBUG_DNA_UPDATER: self.debug_check_bond_direction("reverse_baseatoms start") self.baseatoms = list(self.baseatoms) self.baseatoms.reverse() self.index_direction *= -1 self._bond_direction *= -1 self._reverse_neighbor_baseatoms() if debug_flags.DEBUG_DNA_UPDATER: self.debug_check_bond_direction("reverse_baseatoms end") return # == # kluge: bond direction code/attrs are also here, even though it only applies to strands, # since strands can have different classes with no more specific common superclass. _bond_direction = 0 # 0 = not yet computed, or error (unset or inconsistent); # 1 or -1 means it was set by _recompute_bond_direction # (see bond_direction docstring for meaning) _bond_direction_error = False # False = error, or not yet known # to interpret those: if both are default, we've never run _recompute_bond_direction, # since it either sets a specific direction or signals an error. def bond_direction(self): """ Only legal if self is a chain of strand base atoms. If self has a known, consistently set bond direction, throughout its length and also in the directional bonds to the next strand base atoms just outside it (which can be two actual bonds each if a PAM5 Pl intervenes), return that direction; 1 means left to right, -1 means right to left, treating baseindex as growing from left to right (self.index_direction is ignored). Otherwise set self._bond_direction_error and return 0. The value is cached to avoid recomputing it when known, and (nim; externally implemented) set when merging ladders to avoid recomputing it on merged ladders. The cached value is negated by self.reverse_baseatoms(). """ if not self._bond_direction and not self._bond_direction_error: self._recompute_bond_direction() return self._bond_direction def _recompute_bond_direction(self): # probably won't ever be needed; if so, remove once everything's working """ Set self._bond_direction and self._bond_direction_error correctly. See self.bond_direction() docstring for definition of correct values. """ # 1 = right, -1 = left, 0 = inconsistent or unknown # implem? maybe not needed, now that we have _f_set_bond_direction... assert 0, "nim (and never will be) in %r" % self #### this means more things must call _f_set_bond_direction, eg merge_ladders def _f_set_bond_direction(self, dir, error = None): """ [friend method, for self (certain subclasses) or to optimize merging strand chains] #doc """ assert dir in (-1, 0, 1) if error is None: error = (dir == 0) self._bond_direction = dir self._bond_direction_error = error return def bond_direction_is_arbitrary(self): """ Are we so short that our bond direction (relative to index direction) is arbitrary, so caller could reverse it using self._f_reverse_arbitrary_bond_direction(), with no problematic effect? """ # review: also condition result on self._bond_direction?? return len(self.baseatoms) <= 1 # even if original chain's atom_list was longer def _f_reverse_arbitrary_bond_direction(self): assert self.bond_direction_is_arbitrary() self._bond_direction *= -1 self._reverse_neighbor_baseatoms() # REVIEW: is _reverse_neighbor_baseatoms correct here? # This might depend on whether the caller of this also # called self.reverse_baseatoms()! @@@ return def debug_check_bond_direction(self, when = ""): """ Verify our bond direction is set correctly (if possible), and assertfail and/or print a debug warning if not. """ ## assert self.strandQ assert self.baseatoms, "%r has no baseatoms" % self if not self.strandQ: return assert self._bond_direction assert not self._bond_direction_error if self.bond_direction_is_arbitrary(): return # no way to check it # verify it by comparing it to actual bonds if when: when = " (%s)" % when # STUB: only works fully for PAM3 atom1 = self.baseatoms[0] atom2 = self.baseatoms[1] bond = find_bond(atom1, atom2) errormsg = "" # might be set to an error string actual_direction = 0 # might be set to a bond direction if bond: actual_direction = bond.bond_direction_from(atom1) elif atom1.Pl_neighbors() or atom2.Pl_neighbors(): # look for atom1-Pl-atom2 (2 bonds, same direction) bond1, bond2 = find_Pl_bonds(atom1, atom2) # might be None, None if not bond1: errormsg = "no Pl5 between adjacent baseatoms %r and %r" % (atom1, atom2) else: dir1 = bond1.bond_direction_from(atom1) dir2 = - bond2.bond_direction_from(atom2) if dir1 == dir2: actual_direction = dir1 # might be 0 else: errormsg = "Pl5 between %r and %r has inconsistent or unset bond directions" % (atom1, atom2) else: errormsg = "no bond between adjacent baseatoms %r and %r" % (atom1, atom2) if not errormsg: # check actual_direction ## not needed: assert actual_direction recorded_direction = self._bond_direction assert recorded_direction # redundant with earlier assert if actual_direction != recorded_direction: # error errormsg = "bond direction from %r to %r: recorded %r, actual %r" % \ (atom1, atom2, recorded_direction, actual_direction) # now errormsg tells whether there is an error. if errormsg: prefix = "debug_check_bond_direction%s in %r" % (when, self) msg = "%s: ERROR: %s" % (prefix, errormsg) print "\n*** %s ***\n" % msg summary_format = "DNA updater: bug: [N] failure(s) of debug_check_bond_direction, see console prints" env.history.deferred_summary_message( redmsg(summary_format)) return # == def _f_update_neighbor_baseatoms(self): """ [friend method for dna updater] This must be called at least once per ladder rail chain (i.e. _DnaChainFragment object, I think, 080116), during each dna updater run which encounters it (whether as a new or preexisting rail chain). It computes or recomputes whichever attributes carry info about the neighboring baseatoms in neighboring rail chains (which connect to self at the ends), based on current bonding. Specifically, it sets self.neighbor_baseatoms[end] for end in LADDER_ENDS to either None (if this chain ends on that ladder-end) or to the next atom in the next chain (if it doesn't end). (Atoms with _dna_updater__error set are not allowed as "next atoms" -- None will be set instead.) For end atom order (used as index in self.neighbor_baseatoms), it uses whatever order has been established by the DnaLadder we're in, which may or may not have reversed our order. (Ladders have been made, finished, and merged, before we're called.) For strands, it finds neighbors using bond direction, and knows about skipping Pl atoms; for axes, in the ambiguous length==1 case, it uses an arbitrary order, but makes sure this is consistent with strands when at least one strand has no nick at one end of this chain's ladder. [#todo: explain better] If this doesn't force an order, then if this had already been set before this call and either of the same non-None atoms are still in it now, preserve their position. The attrs we set are subsequently reversed by our methods _f_reverse_arbitrary_bond_direction and reverse_baseatoms. [###REVIEW whether it's correct in _f_reverse_arbitrary_bond_direction; see comment there.] @note: the ordering/reversal scheme described above may need revision. The special case for length==1 axis described above is meant to ensure that axis and strand order correspond between two ladders which are connected on the axis and one strand, but not the other strand (i.e. which have an ordinary nick), if the ladder we're on has length 1 (i.e. if there are two nicks in a row, on the same or opposite strands). If this ever matters, we might need to straighten out this order in DnaLadder.finished() for length==1 ladders. The ladders are already made and merged by the time we're called, so whatever reversals they'll do are already done. [update, 080602: this was implemented today, to fix a bug; no change to DnaLadder.finished() seemed to be needed.] """ assert self.strandQ in (False, True) self.neighbor_baseatoms = list(self.neighbor_baseatoms) # do most atoms one end at a time... for end in LADDER_ENDS: # end_baseatoms needs ladder end, not chain end next_atom = -1 # will be set to None or an atom, if possible if self.strandQ: # similar to code in DnaLadder._can_merge_at_end end_atom = self.end_baseatoms()[end] assert self._bond_direction # relative to LADDER_ENDS directions # (since that's in the same direction as our baseatoms array) # (review: not 100% sure this is set yet; # but the assert is now old and has never failed) if end == LADDER_END0: arrayindex_dir_to_neighbor = -1 else: arrayindex_dir_to_neighbor = 1 bond_dir_to_neighbor = self._bond_direction * arrayindex_dir_to_neighbor next_atom = end_atom.strand_next_baseatom(bond_direction = bond_dir_to_neighbor) assert next_atom is None or next_atom.element.role == 'strand' # (note: strand_next_baseatom returns None if end_atom or the atom it # might return has ._dna_updater__error set.) # store next_atom at end of loop if len(self.baseatoms) > 1: #080602 debug code if arrayindex_dir_to_neighbor == 1: next_interior_atom = self.baseatoms[1] else: next_interior_atom = self.baseatoms[-2] if next_interior_atom is next_atom: print "\n*** PROBABLE BUG: next_interior_atom is next_atom %r for end_atom %r in %r" % \ (next_atom, end_atom, self) pass else: # do axis atoms in this per-end loop, only if chain length > 1; # otherwise do them both at once, after this loop. if len(self.baseatoms) > 1: # easy case - unambiguous other-chain neighbor atom # (Note: length-2 axis ring is not possible, since it would # require two bonds between the same two Ax pseudoatoms. # It's also not physically possible, so that's fine.) end_atom = self.end_baseatoms()[end] next_atom_candidates = end_atom.axis_neighbors() # len 1 or 2, # and one should always be the next one in this chain # (I guess it can't have _dna_updater__error set, # since such atoms are not made into chains; # so I assert this, 080206); # the other one (if present) might have it set if end == LADDER_END0: next_to_end_index = 1 else: next_to_end_index = -2 not_this_atom = self.baseatoms[next_to_end_index] assert not not_this_atom._dna_updater__error # 080206 next_atom_candidates.remove(not_this_atom) # it has to be there, so we don't mind raising an # exception when it's not assert len(next_atom_candidates) <= 1, \ "too many candidates: %r" % (next_atom_candidates,) # Note: got exception here when lots of Ss had two # Ax neighbors due to errors in an mmp file; # assertion message untested [080304] if next_atom_candidates: next_atom = next_atom_candidates[0] if next_atom._dna_updater__error: ## print "avoiding bug 080206 by not seeing next axis atom with error", next_atom next_atom = None else: next_atom = None pass pass if next_atom != -1: self.neighbor_baseatoms[end] = next_atom # None or an atom assert next_atom is None or not next_atom._dna_updater__error # 080206 if DEBUG_NEIGHBOR_BASEATOMS: msg = "set %r.neighbor_baseatoms[%r] = %r, whole list is now %r" % \ (self, end, next_atom, self.neighbor_baseatoms) print_compact_stack( "\n" + msg + ": ") continue # ... but in length==1 case, do axis atoms both at once if not self.strandQ and len(self.baseatoms) == 1: end_atom = self.baseatoms[0] next_atoms = end_atom.axis_neighbors() # len 0 or 1 or 2 # remove atoms with errors [fix predicted bug, 080206] # (review: should axis_neighbors, or a variant method, do this?) ###### SHOULD REVIEW ALL USES OF axis_neighbors FOR NEEDING THIS @@@@@ next_atoms = filter( lambda atom: not atom._dna_updater__error , next_atoms ) while len(next_atoms) < 2: next_atoms.append(None) # if order matters, reverse this here, if either strand # in the same ladder indicates we ought to, by its next atom # bonding to one of these atoms (having no nick); I think any # advice we get from this (from 1 of 4 possible next atoms) # can't be inconsistent, but I haven't proved this. (Certainly # it can't be for physically reasonable structures.) # [bruce 080116 proposed, bruce 080602 implemented, as bugfix] order_was_forced_by_strands = False # might be set below try: # very near a release, so cause no new harm... ladder = rail_end_atom_to_ladder(end_atom) assert self is ladder.axis_rail evidence_counters = [0, 0] # [wrong order, right order] for strand in ladder.strand_rails: strand._f_update_neighbor_baseatoms() # redundant with caller, but necessary since we don't # know whether it called this already or not; # calling it twice on a strand is ok (2nd call is a noop); # not important to optimize since length-1 ladders are rare. for strand_end in LADDER_ENDS: for axis_end in LADDER_ENDS: axis_next_atom = next_atoms[axis_end] # might be None strand_next_atom = strand.neighbor_baseatoms[strand_end] # might be None if axis_next_atom and strand_next_atom and \ atoms_are_bonded( axis_next_atom, strand_next_atom): evidence_counters[ strand_end == axis_end ] += 1 continue continue continue badvote, goodvote = evidence_counters # note: current order of next_atoms is arbitrary, # so we need symmetry here between badvote and goodvote if badvote != goodvote: if badvote > goodvote: next_atoms.reverse() badvote, goodvote = goodvote, badvote pass order_was_forced_by_strands = True if badvote and goodvote: # should never happen for physically reasonable structures, # but is probably possible for nonsense structures print "\nBUG or unreasonable structure: " \ "badvote %d goodvote %d for next_atoms %r " \ "around %r with %r" % \ (badvote, goodvote, next_atoms, self, end_atom) pass pass except: msg = "\n*** BUG: ignoring exception while disambiguating " \ "next_atoms %r around %r with %r" % \ (next_atoms, self, end_atom) print_compact_traceback( msg + ": " ) pass reverse_count = 0 # for debug prints only if not order_was_forced_by_strands: # For stability of arbitrary choices in case self.neighbor_baseatoms # was already set, let non-None atoms still in it determine the order # to preserve their position, unless the order was forced above. for end in LADDER_ENDS: old_atom = self.neighbor_baseatoms[end] if old_atom and old_atom is next_atoms[1-end]: assert old_atom != -1 # next_atoms can't contain -1 next_atoms.reverse() # (this can't happen twice) reverse_count += 1 self.neighbor_baseatoms = next_atoms if DEBUG_NEIGHBOR_BASEATOMS: msg = "set %r.neighbor_baseatoms = next_atoms %r, " \ "order_was_forced_by_strands = %r, reverse_count = %r" % \ (self, next_atoms, order_was_forced_by_strands, reverse_count) print_compact_stack( "\n" + msg + ": ") pass pass # we're done assert len(self.neighbor_baseatoms) == 2 assert type(self.neighbor_baseatoms) == type([]) for atom in self.neighbor_baseatoms: assert atom is None or atom.element.role in ['axis', 'strand'] # note: 'unpaired-base' won't appear in any chain return # from _f_update_neighbor_baseatoms def at_wholechain_end(self): # bruce 080212 """ Return True if we are located at one or both ends of our wholechain (if it has any ends -- if it's a ring, it has none), based on self.neighbor_baseatoms. """ next1, next2 = self.neighbor_baseatoms assert next1 != -1 assert next2 != -1 return (next1 is None) or (next2 is None) def wholechain_end_baseatoms(self): # bruce 080212 """ Return a list of whichever end baseatoms of our wholechain we have (as end baseatoms of self). (Length will be 0 to 2.) Only correct if self.neighbor_baseatoms has already been set. AssertionError if it hasn't. """ next1, next2 = self.neighbor_baseatoms assert next1 != -1 assert next2 != -1 res = [] if next1 is None: res.append(self.baseatoms[0]) if next2 is None: res.append(self.baseatoms[-1]) # note: for a len 1 wholechain, this has two copies of same atom -- good, i think return res pass # end of class DnaChain # == class _DnaChainFragment(DnaChain): #e does it need to know ringQ? is it misnamed?? """ [as of 080109 these are created in make_new_ladders() and passed into DnaLadder as its rail chains via init arg and add_strand_rail] """ def __init__(self, atom_list, index_direction = None, bond_direction = None, bond_direction_error = None, strandQ = None ): self.strandQ = strandQ self.baseatoms = atom_list if index_direction is not None: self.index_direction = index_direction else: pass # use default index_direction (since arbitrary) if bond_direction is not None or bond_direction_error is not None: bond_direction = bond_direction or 0 bond_direction_error = bond_direction_error or False self._f_set_bond_direction( bond_direction, bond_direction_error) if debug_flags.DEBUG_DNA_UPDATER: self.debug_check_bond_direction("_DnaChainFragment.__init__") pass # == class DnaChain_AtomChainWrapper(DnaChain): ###### TODO: refactor into what code is on this vs what is on a higher-level WholeChain #e inherit ChainAPI? (we're passed to a DnaMarker as its chain -- no, more likely, as an element of a list which is that@@@) """ Abstract class, superclass of AxisChain and StrandChain. Owns and delegates to an AtomChainOrRing, providing DNA-specific navigation and indexing. Used internally for base indexing in strands and segments, mainly while updating associations between the user-visible nodes for those and the pseudoatoms comprising them. Note: this base indexing is for purposes of moving origin markers for user convenience when editing several associated chains (e.g. the axis and two strand of a duplex). By default it is likely to be assigned as a "base pair index", which means that on the "2nd strand" it will go backwards compared to the actual "physical" base index within that strand. So it should not be confused with that. Further, on rings it may jump in value at a different point than whatever user- visible index is desired. If in doubt, consider it an internal thing, not to be user-exposed without using markers, relative directions, offsets, and ring-origins to interpret it. Note: some of the atoms in our chain_or_ring might be killed; we never remove atoms or modify our atom list after creation (except perhaps to reverse or reorder it). Instead, client code makes new chain objects. """ # default values of instance variables: # @@@ move to WholeChain, I think - 080114 ## controlling_marker = None # REVIEW: need to delegate ringQ, or any other vars or methods, to self.chain_or_ring? def __init__(self, chain_or_ring): self.chain_or_ring = chain_or_ring self.ringQ = chain_or_ring.ringQ #e possible optim: can we discard the bonds stored in chain_or_ring, and keep only the atomlist, # maybe not even in that object? # (but we do need ringQ, and might need future chain_or_ring methods that differ for it.) # decision 071203: yes, and even more, discard non-base atoms, optimize base scanning. # make sure we can iterate over all atoms incl bos and Pls, sometime, for some purposes. # use a method name that makes that explicit. # For now, just store a separate list of baseatoms (in each subclass __init__ method). return def iteratoms(self): # REVIEW: different if self.index_direction < 0? """ # get doc from calling method """ return self.chain_or_ring.iteratoms() _chain_id = None def chain_id(self): #k this is used, but as of 071203 i'm not sure the use will survive, so review later whether it's needed @@ """ Return a unique, non-reusable id (with a boolean value of true) for "this chain" (details need review and redoc). """ #e revise/refile (object_id_mixin?); # REVIEW whether on self or self.chain_or_ring (related: which is stored in the marker?) if not self._chain_id: global _chain_id_counter _chain_id_counter += 1 self._chain_id = _chain_id_counter return self._chain_id # guessing this is for WholeChain, not here... 080114 ## def _f_own_atoms(self): # @@@ review: is this really a small chain or whole chain method? ## """ ## Own our atoms, for chain purposes. ## This does not presently store anything on the atoms, even indirectly, ## but we do take over the markers and decide between competing ones ## and tell them their status, and record the list of markers (needs update??) ## and the controlling marker for our chain identity (needs update??). ## This info about markers might be DNA-specific ... ## and it might be only valid during the dna updater run, before ## more model changes are made. [#todo: update docstring when known] ## """ ## ## # NOTE/TODO: if useful, this might record a list of all live markers ## # found on that chain in the chain, as well as whatever marker ## # is chosen or made to control it. (But note that markers might ## # get removed or made independently without the chain itself ## # changing. If so, some invalidation of those chain attributes ## # might be needed.) ## ## if debug_flags.DEBUG_DNA_UPDATER_VERBOSE: ## print "%r._f_own_atoms() is a stub - always makes a new marker" % self #####FIX ## chain = self.chain_or_ring ## # stub -- just make a new marker! we'll need code for this anyway... ## # but it's WRONG to do it when an old one could take over, so this is not a correct stub, just one that might run. ## atom = chain.atom_list[0] ## assy = atom.molecule.assy ## marker_class = self._marker_class ## assert issubclass(marker_class, DnaMarker) ## marker = marker_class(assy, [atom], chain = self) ## # note: chain has to be self, not self.chain ## # (the marker calls some methods that are only on self). ## self.controlling_marker = marker ## marker.set_whether_controlling(True) ## ## and call that with False for the other markers, so they die if needed -- ### IMPLEM ## #e For a chosen old marker, we get advice from it about chain direction, ## # then call a direction reverser if needed; see comments around index_direction. def virtual_fragment(self, start_baseindex, baselength): #e misnamed if not virtual -- review """ #doc [as of 080109 these are created in make_new_ladders() and passed into DnaLadder as its rail chains via init arg and add_strand_rail] """ if debug_flags.DEBUG_DNA_UPDATER: self.debug_check_bond_direction("entering DnaChain_AtomChainWrapper.virtual_fragment") # current implem always returns a real fragment; might be ok baseindex = start_baseindex - self.start_baseindex() subchain = self.baseatoms[baseindex : baseindex + baselength] # note: if self._bond_direction_error, self._bond_direction will be 0 # and cause the subchain direction to be recomputed... but it can't # be recomputed on that kind of chain (using the current code)... # so we pass the error flag too. return _DnaChainFragment(subchain, index_direction = self.index_direction, bond_direction = self._bond_direction, bond_direction_error = self._bond_direction_error, strandQ = self.strandQ ) #e more args? does it know original indices? (i doubt it) pass # end of class DnaChain_AtomChainWrapper # == def merged_chain(baseatoms, strandQ, bond_direction, bond_direction_error = False): res = _DnaChainFragment( baseatoms, bond_direction = bond_direction, bond_direction_error = bond_direction_error, strandQ = strandQ ) return res # == class AxisChain(DnaChain_AtomChainWrapper): """ A kind of DnaChain for just-found axis chains or rings. @warning: as of 080116, these are *not* used directly as DnaLadder rail chains. Instead, objects returned by self.virtual_fragment are used for that. """ strandQ = False _marker_class = DnaSegmentMarker def __init__(self, chain_or_ring): DnaChain_AtomChainWrapper.__init__(self, chain_or_ring) self.baseatoms = chain_or_ring.atom_list return pass # == class StrandChain(DnaChain_AtomChainWrapper): """ A kind of DnaChain for just-found strand chains or rings. @warning: as of 080116, these are *not* used directly as DnaLadder rail chains. Instead, objects returned by self.virtual_fragment are used for that. Knows to skip Pl atoms when indexing or iterating over "base atoms" (but covers them in iteratoms). Also knows to look at bond_direction on all the bonds (in self and to neighbors), for being set and consistent, and to cache this info. """ strandQ = True _marker_class = DnaStrandMarker def __init__(self, chain_or_ring): # nevermind: ## if debug_flags.DEBUG_DNA_UPDATER: ## chain_or_ring.debug_check_bond_direction("init arg to %r" % self) ## ## AttributeError: 'AtomChain' object has no attribute 'debug_check_bond_direction' DnaChain_AtomChainWrapper.__init__(self, chain_or_ring) baseatoms = filter( lambda atom: not atom.element.symbol.startswith('P') , # KLUGE, should use an element attribute, whether it's base-indexed chain_or_ring.atom_list ) self.baseatoms = baseatoms # in order of rungindex (called baseindex in methods) # note: baseatoms affects methods with "base" in their name, # but not e.g. iteratoms (which must cover Pl) # Now check all bond directions, inside and just outside this chain. # Use the all-atom version, which includes Pl atoms. # Assume that every Pl atom ends up in some chain, # and gets checked here, so that all inter-chain bonds are covered. # (This is assumed when setting bond_direction on merged chains. #doc in what code) dir_so_far = None chain = self.chain_or_ring # 1. check bonds inside the chain. # if it's a chain, it contains: atom, bond, atom, bond, atom # (each bond connects the adjacent atoms). # if it's a ring, it's like that but missing the *first* atom # (due to a perhaps-arbitrary choice in the alg in # find_chain_or_ring_from_bond), so it's bond, atom, bond, atom. # So we'll ignore the first atom in a chain to make these cases # the same, and then loop over the (bond, atom) pairs in that order, # which means the bond direction relative to left-to-right in this # scheme (i.e. relative to baseatoms index) is the negative of the one # we get from each bond, atom pair. (I recently changed the ring-finding # code in a way which changed this scheme and introduced a bug in this # code, though comments here suggest the sign factor was just a guess # anyway. Fixed the bug here [confirmed], 080121 10pm or so.) bonds = chain.bond_list ## atoms = chain.atom_list[:len(bonds)] # buggy atoms = chain.atom_list[-len(bonds):] # bugfix part 1 for bond, atom in zip(bonds, atoms): thisdir = - bond.bond_direction_from(atom) # minus sign is bugfix part 2 if dir_so_far is None: # first iteration #e could optim by moving out of loop dir_so_far = thisdir if not thisdir: # missing bond direction break else: # subsequent iterations assert dir_so_far in (-1, 1) if dir_so_far != thisdir: # inconsistent or missing bond direction dir_so_far = 0 break continue # 2. check pairs of bonds on the same atom, on the "end atoms". # (It doesn't matter which end-atom we dropped in the bond-inside-chain # loop above, since that only affects how we measure bond directions, # not which bonds we measure (all of them).) if not chain.atom_list[0].bond_directions_are_set_and_consistent() or \ not chain.atom_list[-1].bond_directions_are_set_and_consistent(): dir_so_far = 0 if dir_so_far is None: assert len(chain.atom_list) == 1 and len(bonds) == 0 # direction remains unknown, i guess... # but I think we can legally set it to either value, # and doing so simplifies the code that wants it to be set. # (That code may need to know it's arbitrary since we're # so short that reverse is a noop (except for negating directions), # but there's no point in marking it as arbitrary here, since # there might be other ways of making such short chains. # So instead, let that code detect that we're that short, # using our superclass method bond_direction_is_arbitrary, which says yes # even if this code didn't run (e.g. if atom_list had a Pl).) dir_so_far = 1 # at this point, dir_so_far can be: # 0: error (inconsistent or missing bond direction) # 1 or -1: every bond inside and adjacent to chain has this direction assert dir_so_far, "bond direction error in %r, no point in continuing" % self self._f_set_bond_direction(dir_so_far) if debug_flags.DEBUG_DNA_UPDATER: self.debug_check_bond_direction("end of init") # note: this assertfails if direction is 0, # and if it didn't, later code would have bugs, # so we might as well assert dir_so_far above [done], # and really we ought to fix that error here or earlier. # So decide which is best: #### @@@@ # - find wholechains w/o knowing bond dir, then fix it; # - or fix it earlier when we notice local bond direction # errors (also requires propogation; not too hard). return # atoms bonds pass # end
NanoCAD-master
cad/src/dna/model/DnaChain.py
# Copyright 2008 Nanorex, Inc. See LICENSE file for details. """ pam3plus5_math.py -- mathematical helper functions for PAM3+5 <-> PAM5 conversion @author: Bruce (based on formulas developed by Eric D) @version: $Id$ @copyright: 2008 Nanorex, Inc. See LICENSE file for details. Reference and explanation for PAM3+5 conversion formulas: http://www.nanoengineer-1.net/privatewiki/index.php?title=PAM-3plus5plus_coordinates """ from geometry.VQT import Q, V, norm, vlen, cross, X_AXIS, Y_AXIS, Z_AXIS from utilities.debug import print_compact_traceback from utilities.constants import MODEL_PAM3, MODEL_PAM5 __USE_OLD_VALUES__ = False # PAM3+5 conversion constants (in Angstroms) # # for explanation, see: # # http://www.nanoengineer-1.net/privatewiki/index.php?title=PAM-3plus5plus_coordinates # == ######## NOT YET FINAL VALUES ######## # Note: these are approximate numbers (from Eric M, a few days before 080412) # based on what the current PAM3 and PAM5 generators are producing: # # x_a' = 2.695 # x_s' = -0.772 # y_s' = -0.889 # x_g = 8.657 # y_m = 6.198 if (__USE_OLD_VALUES__): X_APRIME = 2.695 # x_a' (where _ means subscript) X_SPRIME = -0.772 # x_s' Y_SPRIME = -0.889 # y_s' SPRIME_D_SDFRAME = V(X_SPRIME, Y_SPRIME, 0.0) # position of PAM3 strand sugar 'd' in baseframe 'd' coordinates # (for position of sugar 'u' in 'd' coords, see relpos_in_other_frame) DEFAULT_X_G = 8.657 # x_g DEFAULT_Y_M = 6.198 # y_m # confirmed from my debug print (converting from PAM5 duplex from our # current generator, bruce 080412: ## ... for data_index 2 stored relpos array([ 8.65728085e+00, 6.19902777e+00, -1.33226763e-15]) # (and similar numbers) # the debug prints that generate those lines look like this in the source code in another file: ## print "fyi, on %r for data_index %r stored relpos %r" % (self, direction, relpos) #### DEFAULT_GV5_RELPOS = V(DEFAULT_X_G, DEFAULT_Y_M, 0.0) # most likely, only x (DEFAULT_X_G) actually matters out of these three coords DEFAULT_Ss_plus_to_Pl5_RELPOS = V(-3.459, -0.489, -1.59) # derived, bruce 080412, for data_index True stored relpos array([-3.45992359, -0.48928416, -1.59 ]) # the prior stub value was -0.772, -0.889, -1 DEFAULT_Ss_minus_to_Pl5_RELPOS = V(1.645 , -2.830, 1.59) # derived, bruce 080412, for data_index False stored relpos array([ 1.6456331 , -2.83064599, 1.59 ]) # the prior stub value was -0.772, -0.889, +1 # see below for how these are used: default_Pl_relative_position, default_Gv_relative_position # == # Here's another set of numbers from EricD as of 2008/04/13. "[D]on't # expect full mutual consistency in the last digit or so." # # Ss5-Ss5 1.0749 nm # Ss5-Gv5 0.9233 nm # Ax3-Gv5 0.4996 nm # # measured off of current PAM3 generator output: # # Ss3-Ss3 1.5951 nm (no corresponding value in sim-params.txt) # Ss3-Ax3 0.8697 nm (0.8700 nm in sim-params.txt) # # formulas for computing the below numbers from the above: # # y_m = Ss5-Ss5 / 2 = 0.53745 # x_g = sqrt(Ss5-Gv5^2 - y_m^2) = 0.750753213446 # x_a' = x_g - Ax3-Gv5 = 0.251153213446 # x_s' = x_a' - sqrt(Ss3-Ax3^2 - (Ss3-Ss3 / 2)^2) = -0.095678283826 # y_s' = y_m - (Ss3-Ss3 / 2) = -0.2601 # # to a more reasonable number of significant figures: # # x_a' = 0.2512 nm # x_s' = -0.0957 nm # y_s' = -0.2601 nm # x_g = 0.7508 nm # y_m = 0.5375 nm # # (where _ means subscript) # # The Pl positioning data comes from the following email from EricD: # # Reading data from a slightly imprecise on-screen model, # the FNANO 08 PAM5 Pl offsets (in base coordinates and nm) # are: # # Ss->Pl+ 0.2875 -0.4081 0.0882 # Ss->Pl- -0.2496 -0.2508 -0.2324 # # To be redundant, the origin and sign conventions # in base coordinates are: # # (0,0,0) is the location of Ss # +x is toward the major groove # +y is toward the opposite Ss # +z is in the 5'-3'direction if (not __USE_OLD_VALUES__): # (x_a', y_m) is the location of the PAM3 Ax, relative to a PAM5 Ss. X_APRIME = 2.512 # x_a' X_SPRIME = -0.957 # x_s' Y_SPRIME = -2.601 # y_s' SPRIME_D_SDFRAME = V(X_SPRIME, Y_SPRIME, 0.0) # position of PAM3 strand sugar 'd' in baseframe 'd' coordinates # (for position of sugar 'u' in 'd' coords, see relpos_in_other_frame) DEFAULT_X_G = 7.508 # x_g DEFAULT_Y_M = 5.375 # y_m DEFAULT_GV5_RELPOS = V(DEFAULT_X_G, DEFAULT_Y_M, 0.0) # most likely, only x (DEFAULT_X_G) actually matters out of these three coords # The labels on these are different from the above email, so I've # selected them to correspond to the signs in the old data. # -EricM DEFAULT_Ss_plus_to_Pl5_RELPOS = V(-2.496, -2.508, -2.324) DEFAULT_Ss_minus_to_Pl5_RELPOS = V(2.875, -4.081, 0.882) # see below for how these are used: default_Pl_relative_position, default_Gv_relative_position BASEPAIR_HANDLE_DISTANCE_FROM_SS_MIDPOINT = 2.4785 # used to position Ah5 as a basepair handle. # The number comes from Eric D mail of 080515: # The point (0.0, 0.0) in the Standard Reference Frame coordinates # [citation omitted] is on the symmetry axis of the Ss-Gv-Ss triangle, # 0.24785 nm above the Ss-Ss base of the triangle. # Eric M's code generates virtual sites from positions specified # in these coordinates. # # I would have thought this should be the same as X_APRIME = 2.512 (x_a')... # maybe that's not true, or maybe one of them is slightly wrong. # Anyway, this is close, and it probably doesn't matter if it's exactly # right (depending on how basepair handles are implemented in ND-1). # [bruce 080516] # == def baseframe_from_pam5_data(ss1, gv, ss2): """ Given the positions of the Ss5-Gv5-Ss5 atoms in a PAM5 basepair, return the first Ss5's baseframe (and y_m) as a tuple of (origin, rel_to_abs_quat, y_m). @note: this is correct even if gv is actually an Ax5 position. """ # y axis is parallel to inter-sugar line # base plane orientation comes from the other atom, Gv # so get x and z axis around that line origin = ss1 y_vector = ss2 - ss1 y_length = vlen(y_vector) ## y_direction = norm(ss2 - ss1) y_direction = y_vector / y_length # optimization z_direction = norm(cross(gv - ss1, y_direction)) # BUG: nothing checks for cross product being too small x_direction = norm(cross(y_direction, z_direction)) # this norm is redundant, but might help with numerical stability rel_to_abs_quat = Q(x_direction, y_direction, z_direction) y_m = y_length / 2.0 return ( origin, rel_to_abs_quat, y_m ) def baseframe_from_pam3_data(ss1, ax, ss2): """ Given the positions of the Ss3-Ax3-Ss3 atoms in a PAM3 basepair, return the first Ss3's baseframe (and y_m) as a tuple of (origin, rel_to_abs_quat, y_m). """ yprime_vector = ss2 - ss1 yprime_length = vlen(yprime_vector) y_direction = yprime_vector / yprime_length # optimization of norm z_direction = norm(cross(ax - ss1, y_direction)) # BUG: nothing checks for cross product being too small x_direction = norm(cross(y_direction, z_direction)) # this norm is redundant, but might help with numerical stability rel_to_abs_quat = Q(x_direction, y_direction, z_direction) # still need origin, easy since we know SPRIME_D_SDFRAME -- but we do have to rotate that, using the quat # rel_to_abs_quat.rot( SPRIME_D_SDFRAME ) # this is Ss5 to Ss3 vector, abs coords Ss3_d_abspos = ss1 Ss5_d_abspos = Ss3_d_abspos - rel_to_abs_quat.rot( SPRIME_D_SDFRAME ) origin = Ss5_d_abspos # y_m = (|S'_u - S'_d| / 2) + y_s' y_m = yprime_length / 2.0 + Y_SPRIME return ( origin, rel_to_abs_quat, y_m ) # == def other_baseframe_data( origin, rel_to_abs_quat, y_m): # bruce 080402 """ Given baseframe data for one base in a base pair, compute it and return it for the other one. """ # todo: optim: if this shows up in profiles, it can be optimized # in various ways, or most simply, we can compute and return both # baseframes at once from the baseframe_maker functions above, # which already know these direction vectors. # # note: if this needs debugging, turn most of it into a helper function # and assert that doing it twice gets values close to starting values. direction_x = rel_to_abs_quat.rot(X_AXIS) direction_y = rel_to_abs_quat.rot(Y_AXIS) direction_z = rel_to_abs_quat.rot(Z_AXIS) # todo: optim: extract these more directly from the quat other_origin = origin + 2 * y_m * direction_y #k other_quat = Q( direction_x, - direction_y, - direction_z) return ( other_origin, other_quat, y_m) # == def baseframe_rel_to_abs(origin, rel_to_abs_quat, relpos): """ Using the baseframe specified by origin and rel_to_abs_quat, transform the baseframe-relative position relpos to an absolute position. """ # optimization: use 2 args, not a baseframe class with 2 attrs return origin + rel_to_abs_quat.rot( relpos ) def baseframe_abs_to_rel(origin, rel_to_abs_quat, abspos): """ Using the baseframe specified by origin and rel_to_abs_quat, transform the absolute position abspos to a baseframe-relative position. """ # optimization: use 2 args, not a baseframe class with 2 attrs return rel_to_abs_quat.unrot( abspos - origin ) def relpos_in_other_frame(relpos, y_m): x, y, z = relpos return V(x, 2 * y_m - y, - z) # == def default_Pl_relative_position(direction): # revised to principled values (though still not final), bruce 080412 late """ """ # print "stub for default_Pl_relative_position" #### ## return V(X_SPRIME, Y_SPRIME, - direction) # stub # use direction to choose one of two different values) if direction == 1: return DEFAULT_Ss_plus_to_Pl5_RELPOS else: assert direction == -1 return DEFAULT_Ss_minus_to_Pl5_RELPOS pass def default_Gv_relative_position(): # print "stub for default_Gv_relative_position" #### return DEFAULT_GV5_RELPOS # assume ok to return same value (mutable Numeric array) # note this in another file: ## print "fyi, on %r for data_index %r stored relpos %r" % (self, direction, relpos) #### ## ##### use these prints to get constants for default_Pl_relative_position (and Gv) @@@@ def correct_Ax3_relative_position(y_m): # print "stub for correct_Ax3_relative_position" #### return V( X_APRIME, y_m, 0.0) # note: the analogue for Ss3 position is hardcoded, near the call of # correct_Ax3_relative_position. # == def compute_duplex_baseframes( pam_model, data ): """ Given a list of three lists of positions (for the 3 rails of a duplex DnaLadder, in the order strand1, axis, strand2), and one of the baseframe_maker functions baseframe_from_pam3_data or baseframe_from_pam5_data, construct and return a list of baseframes for the strand sugars in the first rail, strand1. @raise: various exceptions are possible if the data is degenerate (e.g. if any minor groove angle is 0 or 180 degrees, or if any atoms overlap within one basepair, or if these are almost the case). @warning: no sanity checks are done, beyond whatever is done inside baseframe_maker. """ # This could be optimized, either by using Numeric to reproduce # the calculations in the baseframe_makers on entire arrays in parallel, # or (probably better) by recoding this and everything it calls above # into C and/or Pyrex. We'll see if it shows up in a profile. if pam_model == MODEL_PAM3: baseframe_maker = baseframe_from_pam3_data elif pam_model == MODEL_PAM5: # assume data comes from Gv5 posns, not Ax5 posns baseframe_maker = baseframe_from_pam5_data else: assert 0, "pam_model == %r is not supported" % pam_model # to support mixed, caller would need to identify each rail's model... # ideally, if len(data) == 2 and pam_model == MODEL_PAM3, we could append # another array of ghost base positions to data, and continue -- # but this would require knowing axis vector at each base index, # but (1) we don't have the atoms in this function, (2) even if our caller # passed them, that's hard to do at the axis ends, especially for len == 1, # except between dna updater runs or before the dna updater dissolves old # ladders -- but this is probably called after that stage during dna updater # (not sure ###k). # [bruce 080528 comment] r1, r2, r3 = data try: return [baseframe_maker(a1,a2,a3) for (a1,a2,a3) in zip(r1,r2,r3)] except: print_compact_traceback("exception computing duplex baseframes: ") # hmm, we don't know for what ladder here, though caller can say return None pass # end
NanoCAD-master
cad/src/dna/model/pam3plus5_math.py
# Copyright 2008 Nanorex, Inc. See LICENSE file for details. """ BaseIterator.py - stub, not yet used -- probably superseded by class PositionInWholeChain in WholeChain.py, being written now. @author: Bruce @version: $Id$ @copyright: 2008 Nanorex, Inc. See LICENSE file for details. Plan: - write this code as proto of marker move code, also can be used by user ops between updater runs (bfr they change stuff or after they change and run updater -- uses old info in between (that might be useful??)): - find ladder and index for an atom, via .molecule -- atom method - scan on these indices using rail.neighbor_baseatoms -- atom or ladder method? ladder is best i think. ### update: from one ladder to next, need to use wholechain, can't trust atom.molecule... can use ladders inside rails if useful but it might be more useful to use rails directly. ###decide maybe global helpers are good, or even a flyweight for doing the scan (can have attrs like ringQ, base index, etc). hmm, that flyweight base scanner could be used in dna sequence code (edit, write to file, etc), for this, for marker move... seems like a good idea. methods: - make one from atom, or ladder/whichrail/whichbase - scan it both dirs - get things from it (as attrs or get methods) - ask it things like whether there's a nick or crossover? scan to next nick or crossover? etc See also: * obsolete scratch file outtakes/BasePair.py (might have some methodname ideas) """ class BaseIterator(object): def __init__(self, ladder, whichrail, whichbase): """ @param ladder: the DnaLadder our current base atom is on @type ladder: DnaLadder @param whichrail: which rail in the ladder (as a "rail index"(#doc)) our current base atom is on @type whichrail: ### (depends on strand or axis; or might cause us to choose proper subclass) @param whichbase: index of our current base atom within the rail """ # init args are saved as public read-only attrs self.ladder = ladder self.whichrail = whichrail self.whichbase = whichbase self.check_init_args() # in debug, we also call this other times when we change these self._update_after_changing_init_args() def check_init_args(self): pass # nim @@@ def _update_after_changing_init_args(): """ our methods must call this after any change to the public init arg attrs @see: check_init_args """ self._rail = self.ladder.get_rail_by_index(self.whichrail) # IMPLEM get_rail_by_index (and #doc the rail index convention) assert self._rail ## assert isinstance(self._rail, self._rail_class) # IMPLEM self._rail_class (strandQ affects it) pass # nim @@@ def move_to_next_base(self, delta = 1): # rename to move? assert 0 ### LOGIC BUG [noticed much later, 080307]: # our index direction of motion can differ on each rail. # this code treats it as always 1. # This code probably superseded by class PositionInWholeChain # in WholeChain.py being written now. self.whichbase += delta # do we need all, some, or none of self._update_after_changing_init_args() # if we only change whichbase? guess for now: none, except the following loop conds. error = False while not error and self.whichbase >= len(self._rail.baseatoms): error = self._move_to_next_rail() # also decrs self.whichbase assert self.whichbase >= 0 # other loop won't be needed while not error and self.whichbase < 0: error = self._move_to_prior_rail() assert self.whichbase < len(self._rail.baseatoms) # other loop won't be needed # note: submethods should have reported the error (maybe saved in self.error??) @@@ # note: submethods should have done needed updates @@@ # Q: if we move off the end of a chain, do we remember whichbase so we can move back?? # Q: is it not an error to move off the end, if we plan to call methods to make more DNA "up to here"?? # maybe add an optional arg to permit that, otherwise error... return def _move_to_prior_rail(self): ### def _move_to_next_rail(self): """ Assume... ### # also decrs self.whichbase # should report an error and return True then (maybe saved in self.error) # do needed updates """ next_atom = self._rail.neighbor_baseatoms[LADDER_END1] # might be an atom, None, or -1 assert next_atom != -1 # if this fails, prior dna updater run didn't do enough of its job # todo: handle exceptions in the following ## next_chunk = next_atom.molecule ### BUG: invalid during updater, chunks get broken. ##### BIG LOGIC BUG, uhoh @@@@@@ ## # can we use rail_end_atom_to_ladder? i guess so, it got set by last updater run... ladder is still valid... ###DOIT ## assert next_chunk ## next_ladder = next_chunk.ladder ## next_ladder = rail_end_atom_to_ladder(next_atom) # IMPORT - nevermind, see below ## assert next_ladder #k redundant? # now scan through whichrail and whichend until we find next_atom... what about len==1 case?? # ah, in that case use new rail's neighbor_baseatoms to find our own... or can we use wholechain for all this? ###DECIDE # YES, that is what the wholechain is for. ###DOIT # we might even use its index cache to skip many rails at once, if we ever need to optim large delta (unlikely). # WRONG: next_rail = None # will be set if we find it for candidate in next_ladder.all_rails(): if candidate.baseatoms[0].molecule is next_chunk: ### BUG: invalid during updater, chunks get broken. self._update_after_changing_init_args() pass class StrandBaseIterator(BaseIterator): strandQ = True ## _rail_class = pass class AxisBaseIterator(BaseIterator): strandQ = False ## _rail_class = pass # end
NanoCAD-master
cad/src/dna/model/outtakes/BaseIterator.py
# Copyright 2007 Nanorex, Inc. See LICENSE file for details. """ BasePair.py - BasePair, StackedBasePairs flyweight objects WARNING -- this is not yet used; it's really just a scratch file. Furthermore, it will probably never be used, since the recognition of base pairs by the dna updater will occur differently, but once it's happened, the scanning of them can occur more efficiently by using the already-recognized DnaLadders. So I'll probably move it to outtakes soon. In fact, why not now? Ok, moving it now. @author: Bruce @version: $Id$ @copyright: 2007 Nanorex, Inc. See LICENSE file for details. TODO: split into several files. """ from model.chem import Atom # for isinstance ## see also crossovers.py from model.bond_constants import atoms_are_bonded, find_bond # == class DnaStructureError(Exception): #e tentative #e refile #e inherit from a more specific subclass of Exception? """ Exception for structure errors in DNA pseudoatoms or bonds. Should not be seen by users except when there are bugs in the code for making or updating such structures, but should be raised and handled as appropriate internally. """ pass class DnaGeometryError(Exception): """ [for when we need to use geom to guess higher level structure, but can't] """ pass class Flyweight(object): """ Abstract superclass for flyweight objects. (May not mean anything except to indicate what they are informally?) """ pass # == class BasePair(Flyweight): #e Q: needs __eq__? if so, does it compare strand-alignment (strand1 vs strand2)? axis_atom = None # must always exist strand1_atom = None # can be None for "single strand2" (rare?) strand2_atom = None # can be None for "single strand1" def __init__(self, axis_atom, strand1_atom = None, strand2_atom = None, _trustme = False): """ @param _trustme: (default False) optimize by doing no validation of arguments. """ self.axis_atom = axis_atom self.strand1_atom = strand1_atom self.strand2_atom = strand2_atom if _trustme: # Warning to developers who modify this class: # in skipping validations, don't also skip any necessary # initialization of caches or other derived attributes! # For now, there are none.. review whether still true. @@@ return assert axis_atom is not None assert isinstance(axis_atom, Atom) ### or a more specific class? if strand1_atom is None: assert strand2_atom is None ## ??? not if a "lone strand2" is permitted when we're created! # following code tries not to depend on that assertion, while we review whether it's valid if strand1_atom is None and strand2_atom is None: self._find_both_strand_atoms() # this might set only one if only one is there, # or raise a DnaStructureError exception; # implem: _find_first, _find_second elif strand1_atom is None or strand2_atom is None: # Logic issue: did caller mean we're single, or to find the other strand atom? # Answer: only one can be correct, since the axis atom either does or doesn't # have two strand atoms on it. So just look at see. self._find_second_strand_atom() # this might leave it as None if only one is there, # or raise a DnaStructureError exception self._validate() return def _find_both_strand_atoms(self): """ """ assert 0 # nim def _find_first_strand_atom(self): """ """ assert 0 # nim def _find_second_strand_atom(self): """ """ assert 0 # nim def _validate(self): """ """ assert 0 # nim def stacked_base_pairs(self): """ Determine and return a list of the 0, 1, or 2 base pairs which are stacked to this one, as objects of this class, in a corresponding internal alignment of the strands. """ # just make one for each axis neighbor, then align them to this one, # perhaps by making a StackedBasePairs and asking it to do that. # (or we might be called by that? no, only if its init is not told them both...) # or perhaps by a method on this class, "align strands to this base pair" # which can switch them, with option/retval about whether to do it geometrically. assert 0 # nim def align_to_basepair(self, other, guess_from_geometry = True, axis_unbonded_ok = False): """ Switch our strands if necessary so as to align them to the given other BasePair (which must be stacked to us by an axis bond), in terms of backbone bonding. @param other: another basepair. We modify self, not other, to do the alignment. @type other: BasePair (same class as self) @param guess_from_geometry: If there is no backbone bonding, this option (when true, the default) permits us to use geometric info to guess strand correspondence for doing the alignment. Our return value will be True if we did that. (If we have to but can't, we raise DnaGeometryError.) @param axis_unbonded_ok: default False; if true, permits axis atoms to be unbonded. We pretend they are going to become bonded in order to do our work, but don't change them. @return: whether we had to guess from geometry, and did so successfully. """ if not axis_unbonded_ok: assert atoms_are_bonded( self.axis_atom, other.axis_atom ) # TODO: just look for bonds (direct or via Pl) between the 4 involved strand atoms; # exception if anything is inconsistent. assert 0 # nim pass # == class StackedBasePairs(Flyweight): """ Represent a pointer to two adjacent (stacked) base pairs, which understands the correspondence between their axes (bonded) and strands (not necessarily bonded). """ #e Q: needs __eq__? if so, does it compare strand-alignment (strand1 vs strand2), and direction (bp1 vs bp2)? #e need copy method? if so, shallow or deep (into base pairs)? #e need immutable flag? basepair1 = None basepair2 = None def __init__(self, bp1, bp2): #e hmm, doesn't seem like convenient init info, unless helper funcs are usually used to make one # (how was it done for recognizing PAM5 crossover-making sites? ### REVIEW) self.basepair1 = bp1 self.basepair2 = bp2 self._check_if_stacked() self._update_backbone_info() # whether nicked, which strand is which in bp2 -- # might use geom to guess, if both strands go to other axes here # (same thing happens if we move across a place like that... # can we record the answer on the strands somehow?? # maybe just save a copy of self at that point on the atoms involved? # as a jig which gets invalidated as needed? then this class is not a Jig # but can be owned by one, in a form whose mutability is not used. ####) assert 0 # nim? #e need copy method? def move_right(self, amount = 1): """ Move right (usually towards higher-numbered bases on strand 1, but depends on whether we've reversed direction) by the given amount. @param amount: how many base pairs to move right. (Negative values mean to move left.) @type amount: int """ if amount > 1: for i in range(amount): self.move_right() # accumulate result code? stop if it fails? raise a special exception, CantMove? if amount <= 0: for i in range(amount): self.move_left() assert amount == 1 ... assert 0 # nim def move_left(self, amount = 1): """ Move left (usually towards lower-numbered bases on strand 1, but depends on whether we've reversed direction) by the given amount. @param amount: how many base pairs to move left. (Negative values mean to move right.) @type amount: int """ if amount != 1: return self.move_right( - amount) # primitive: move one step left ... assert 0 # nim def interchange_strands_same_direction(self): """ """ assert 0 # nim def interchange_strands_reverse_direction(self): """ """ assert 0 # nim def reverse_direction(self): """ """ assert 0 # nim def in_standard_orientation(self): """ Are we now in standard orientation (moving towards increasing base indexes on strand 1, and with the primary strand being strand 1 if this is defined)? @note: it might not be useful to find out "no" without knowing which of those Qs has "no" separately, so we might split this into two methods. """ assert 0 # nim def is_strand1_nicked(self): assert 0 # nim - maybe just return atoms_are_bonded (approp atoms)? check if atoms exist first? if not, what is result? #Q def is_strand2_nicked(self): assert 0 # nim def nick_strand1(self): #k desired? """ Break the backbone bond connecting strand1 across these two base pairs. """ assert 0 # nim pass ## next_base_pair( base_pair_stacking, base_pair) # like bond, atom # end
NanoCAD-master
cad/src/dna/model/outtakes/BasePair.py
from Numeric import sign class PositionInWholeChain(object): """ """ def __init__(self, wholechain, rail, index, direction): self.wholechain = wholechain self.rail = rail self.index = index # base index in current rail self.direction = direction # in current rail only # note: our direction in each rail can differ. self.off_end = False # might not be true, but if so we'll find out # review: should we now move_by 0 to normalize index if out of range? return def move_by(self, relindex): # don't i recall code similar to this somewhere? yes, BaseIterator.py - stub, not yet used self.index += self.direction * relindex self.off_end = False # be optimistic, we might be back on if we were off assert 0 # LOGIC BUG: if rail dirs alternate as we move, then the following conds alternate too -- # we're not always in the same loop below!! (better find out if i need to write it this way # or only as the scanner which yields the atoms -- might be easier that way) ### DECIDE while self.index < 0 and not self.off_end: self._move_to_prior_rail(sign(relindex)) while self.index >= len(self.rail) and not self.off_end: self._move_to_next_rail(sign(relindex)) return def _move_to_prior_rail(self, motion_direction): assert self.index < 0 and not self.off_end self._move_to_neighbor_rail(END0, motion_direction)# IMPORT, which variant of END0? def _move_to_next_rail(self, motion_direction): assert self.index >= len(self.rail) and not self.off_end self._move_to_neighbor_rail(END1, motion_direction) def _move_to_neighbor_rail(self, end, motion_direction): neighbor_rail, index, direction = self.find_neighbor_rail(end) # IMPLEM # index is on end we get onto first, direction is pointing into that rail, # but does this correspond to our dir of motion or its inverse? depends on sign of relindex that got us here! if not neighbor_rail: self.off_end = True # self.index is negative but remains valid for self.rail return self.rail = neighbor_rail # now set index, direction to match def yield_atom_posns(self, counter = 0, countby = 1, pos = None): # maybe 1: might be a method on WholeChain which is passed rail, index, direction, then dispense with this object, # OR, maybe 2: might yield a stream of objects of this type, instead grab the vars if pos is None: # if pos passed, self is useless -- so use WholeChain method which is always passed pos; in here, no pos arg pos = self.pos while 1: # or, while not hitting end condition, like hitting start posn again if direction > 0: while index < len(rail): yield rail, index, direction # and counter? index += 1 now jump into next rail, no data needed except jump off END1 of this rail else: while index >= 0: yield rail, index, direction # and counter? index -= 1 now jump off END0 of this rail, and continue this might be correct: class PositionInWholeChain(object): """ """ def __init__(self, wholechain, rail, index, direction): self.wholechain = wholechain self.rail = rail self.index = index # base index in current rail self.direction = direction # in current rail only # note: our direction in each rail can differ. self.pos = (rail, index, direction) ##k or use property for one or the other? return def yield_rail_index_direction_counter(self, **options): return self.wholechain.yield_rail_index_direction_counter( self.pos, **options ) def _that_method_in_WholeChain(self, pos, counter = 0, countby = 1): """ @note: the first position we yield is always pos, with the initial value of counter. """ rail, index, direction = pos # assert one of our rails, valid index in it assert direction in (-1, 1) while 1: # yield, move, adjust, check, continue yield rail, index, direction, counter # move counter += countby index += direction # adjust def jump_off(end): neighbor_atom = rail.neighbor_baseatoms[end] # neighbor_atom might be None, atom, or -1 if not yet set assert neighbor_atom != -1 if neighbor_atom is None: rail = None # outer code will return due to this index, direction = None, None # illegal values (to detect bugs in outer code) else: rail, index, direction = self._find_end_atom_chain_and_index(neighbor_atom) assert rail return rail, index, direction if index < 0: # jump off END0 of this rail rail, index, direction = jump_off(LADDER_END0) elif index >= len(rail): # jump off END1 of this rail rail, index, direction = jump_off(LADDER_END1) else: pass # check if not rail: return assert 0 <= index < len(rail) assert direction in (-1, 1) } # TODO: or if reached starting pos or passed ending pos, return continue assert 0 # not reached pass
NanoCAD-master
cad/src/dna/model/outtakes/PositionInWholeChain-outtakes.py
# Copyright 2007-2008 Nanorex, Inc. See LICENSE file for details. """ Block.py - ... DEPRECATED CLASS (as of shortly before 080331) @author: Bruce @version: $Id$ @copyright: 2007-2008 Nanorex, Inc. See LICENSE file for details. Note: this is likely to not always be Dna-specific, and accordingly might be moved into a more general package. (Except now that it's deprecated, there is no point in that.) """ from foundation.Group import Group from utilities.debug_prefs import debug_pref, Choice_boolean_False class Block(Group): """ DEPRECATED CLASS (as of shortly before 080331). DO NOT USE IN NEW CODE. Model object which represents a user-visible grouping of nodes inside a DnaGroup (or similar object, if we have any). Most child nodes of a DnaGroup are not visible in the MT, but its Blocks are visible there (though their contents are not, except for their sub-Blocks). [this statement is partly obsolete] @see: DnaGroup, which [used to] inherit Block. """ # This should be a tuple of classifications that appear in # files_mmp._GROUP_CLASSIFICATIONS, most general first. # See comment in class Group for more info. [bruce 080115] # #update: bruce 080331 removed this (to affect writemmp), # since Block is deprecated. Should not matter, since there is # now no known way to create a Block (not counting subclasses). # (And the only known way before now was to hand-edit an mmp file.) # ## _mmp_group_classifications = ('Block',) def is_block(self): """ [overrides Node API method] """ return True def permits_ungrouping(self): #bruce 080207 overriding this in Block """ Should the user interface permit users to dissolve this Group using self.ungroup? [overridden from Group] """ return self._show_all_kids_for_debug() def apply_to_groups(self, fn): #bruce 080207 overriding this in Block """ Like apply2all, but only applies fn to all Group nodes (at or under self) (not including Blocks). [overridden from Group implem] """ pass # even if self._show_all_kids_for_debug() # removing this [ninad 080315] ## def MT_kids(self, display_prefs = {}): #bruce 080108 revised semantics ## return self._raw_MT_kids() def _raw_MT_kids(self): if self._show_all_kids_for_debug(): return self.members return filter( lambda member: member.is_block(), self.members ) def _show_all_kids_for_debug(self): classname_short = self.__class__.__name__.split('.')[-1] debug_pref_name = "Model Tree: show content of %s?" % classname_short # typical examples (for text searches to find them here): # Model Tree: show content of DnaGroup? # Model Tree: show content of Block? return debug_pref( debug_pref_name, Choice_boolean_False ) def openable(self): return not not self._raw_MT_kids() # REVIEW: if we are open and lose our _raw_MT_kids, we become open but # not openable. Does this cause any bugs or debug prints? # Should it cause our open state to be set to false (as a new feature)? # [bruce 080107 Q] # TODO: need more attrs or methods to specify more properties # (note: there might be existing Node API methods already good enough for these): # is DND into self permitted? # is DND of self permitted? # is DND of visible members (subblocks) of self permitted? # and maybe more... pass # end
NanoCAD-master
cad/src/dna/model/outtakes/Block.py
NanoCAD-master
cad/src/dna/commands/__init__.py
NanoCAD-master
cad/src/dna/commands/DnaStrand/__init__.py
# Copyright 2008 Nanorex, Inc. See LICENSE file for details. """ DnaStrand_ResizeHandle.py @author: Ninad @copyright: 2008 Nanorex, Inc. See LICENSE file for details. @version: $Id$ @license: GPL History: Created on 2008-02-14 TODO: as of 2008-02-14 - Attributes such as height_ref need to be renamed. But this should really be done in the superclass exprs.DraggableHandle_AlongLine. - Needs refactoring. Shares common things with DnaSegment_ResizeHandle . Really the only difference is the handle appearance. See if renaming DnaSegment_ResizeHandle and then using it as a common class makes sense. """ from exprs.attr_decl_macros import Option from exprs.attr_decl_macros import State from exprs.Set import Action from exprs.__Symbols__ import _self from exprs.Overlay import Overlay from exprs.ExprsConstants import Drawable from exprs.ExprsConstants import Color from exprs.ExprsConstants import Boolean from exprs.ExprsConstants import Width from exprs.ExprsConstants import Point from exprs.ExprsConstants import ORIGIN, DX from exprs.If_expr import If_expr from exprs.dna_ribbon_view import Cylinder from exprs.Rect import Sphere 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 purple from geometry.VQT import V from exprs.DraggableHandle import DraggableHandle_AlongLine class DnaStrand_ResizeHandle(DraggableHandle_AlongLine): """ Provides a resize handle for editing the length of an existing Dna Strand. """ #Handle color will be changed depending on whether the handle is grabbed # [bruce 080409 revised some details of this to fix bug 2747] handleColor = Option(Color, purple) # formula from caller # (in current usage, a state variable in caller) handleIsGrabbed = State(Boolean, False) # Note: this might not be needed if we passed more args to # Highlightable (namely, the appearance when pressed); # that would also be more reliable, since as it is, any failure for # on_release to be called would leave the handle stuck in the # grabbed state; client code would be wise to sometimes reset # this state. Also, it seems rare to ever see this selection color # since the handle is usually highlighted and yellow while dragging it. # [Depending on the highlight and selection drawing mode. Russ 080530] # So this state could probably just be removed, with all uses of # _currentHandleColor changes to uses of handleColor. # [bruce 080409] _currentHandleColor = If_expr( handleIsGrabbed, env.prefs[selectionColor_prefs_key], _self.handleColor) #The caller-specified formula that determines the radius (of the sphere) of this handle. #See DnaStrand_EditCommand._determine_resize_handle_radius() for more #details sphereRadius = Option(Width, 1.5) #Appearance of the handle. (note that it uses all the code from exprs module # and needs more documentation there). #See exprs.Rect.Sphere for definition of a drawable 'Sphere' object. appearance = Overlay( Sphere(_self.sphereRadius, _self._currentHandleColor, center = ORIGIN + _self.direction * 3.0 * _self.sphereRadius), Cylinder((ORIGIN, ORIGIN + _self.direction * 2.2 * _self.sphereRadius), 0.6 * _self.sphereRadius, _self._currentHandleColor)) #Handle appearance when highlighted # [this probably doesn't need to be an Option, since the client never # passes it [bruce 080409 comment]] HHColor = env.prefs[hoverHighlightingColor_prefs_key] appearance_highlighted = Option( Drawable, Overlay( Sphere(_self.sphereRadius, HHColor, center = ORIGIN + _self.direction * 3.0 * _self.sphereRadius), Cylinder((ORIGIN, ORIGIN + _self.direction * 2.2 * _self.sphereRadius), 0.6* _self.sphereRadius , HHColor)), doc = "handle appearance when highlighted") #Stateusbar text. Variable needs to be renamed in superclass. sbar_text = Option(str, "Drag the handle to resize the strand", doc = "Statusbar text on mouseover") #Command object specified as an 'Option' during instantiation of the class #see DnaSegment_EditCommand class definition. command = Option(Action, doc = 'The Command which instantiates this handle') #Current position of the handle. i.e. it is the position of the handle #under the mouse. (its differert than the 'orifinal position) #This variable is used in self.command.graphicsMode to draw a rubberband #line and also to specify the endPoint2 of the structure while modifying #it. See DnaSegment_EditCommand.modifyStructure for details. if _self.origin is not None: currentPosition = _self.origin + _self.direction * _self.height_ref.value else: currentPosition = ORIGIN #Fixed end of the structure (self.command.struct) ..meaning that end won't #move while user grabbs and draggs this handle (attached to a the other #'moving endPoint) . This variable is used to specify endPoint1 of the #structure while modifyin it. See DnaSegment_EditCommand.modifyStructure #and self.on_release for details. fixedEndOfStructure = Option(Point, V(0, 0, 0)) #If this is false, the 'highlightable' object i.e. this handle #won't be drawn. See DraggableHandle.py for the declararion of #the delegate(that defines a Highlightable) We define a If_Exprs to check #whether to draw the highlightable object. should_draw = State(bool, True) def ORIG_NOT_USED_hasValidParamsForDrawing(self): """ NOT USED AS OF 2008-04-02 Returns True if the handles origin and direction are not 'None'. @see: DnaStrand_GraphicsMode._draw_handles() where the caller uses this to decide whether this handle can be drawn without a problem. """ #NOTE: Better to do it in the drawing code of this class? #But it uses a delegate to draw stuff (see class Highlightable) #May be we should pass this method to that delegate as an optional #argument -- Ninad 2008-04-02 if self.origin is None or self.direction is None: return False return True def hasValidParamsForDrawing(self): """ Returns True if the handles origin and direction are not 'None'. @see: DnaStrand_GraphicsMode._draw_handles() where the caller uses this to decide whether this handle can be drawn without a problem. """ #NOTE: Better to do it in the drawing code of this class? #But it uses a delegate to draw stuff (see class Highlightable) #May be we should pass this method to that delegate as an optional #argument -- Ninad 2008-04-02 #@Bug: Create a duplex; Enter Dna strand edit command, # then shorten it such that it removes some bases of the strand from the #original duplex. Hit undo; click on the right handle, and shorten it again #sometimes it gives a traceback. in drawing the highlightable #this could be because self.should_draw flag is not getting updated. #NOTES: If this method is used, you will also need to define the #delegate in class DraggableHandle as -- #delegate = If_Exprs(_self.should_draw, Highlightable(....)) if self.origin is None or self.direction is None: self.should_draw = False else: self.should_draw = True return self.should_draw def on_press(self): """ Actions when handle is pressed (grabbed, during leftDown event) @see: B{SelectChunks.GraphicsMode.leftDown} @see: B{DnaStrand_EditCommand.grabbedHandle} @see: B{DnaStrand_GraphicsMode.Draw} (which uses some attributes of the current grabbed handle of the command. @see: B{DragHandle_API} """ #Change the handle color when handle is grabbed. See declaration of #self.handleColor in the class definition. ## self._currentHandleColor = env.prefs[selectionColor_prefs_key] self.handleIsGrabbed = True #assign 'self' as the curent grabbed handle of the command. self.command.grabbedHandle = self def on_drag(self): """ Method called while dragging this handle . @see: B{DragHandle_API} """ pass #The following call is disabled. Instead updating this spinbox #is done by the command.getCursorText method . See that method for #details ##self.command.update_numberOfBases() def on_release(self): """ This method gets called during leftUp (when the handle is released) @see: B{DnaStrand_EditCommand.modifyStructure} @see: self.on_press @see: B{SelectChunks.GraphicsMode.leftUp} @see: B{DragHandle_API} """ ## self._currentHandleColor = self.handleColor self.handleIsGrabbed = False if self.command and hasattr(self.command, 'modifyStructure'): self.command.modifyStructure() #Clear the grabbed handle attribute (the handle is no longer #grabbed) self.command.grabbedHandle = None
NanoCAD-master
cad/src/dna/commands/DnaStrand/DnaStrand_ResizeHandle.py
# Copyright 2008-2009 Nanorex, Inc. See LICENSE file for details. """ @author: Ninad @version: $Id$ @copyright: 2008-2009 Nanorex, Inc. See LICENSE file for details. History: Created on 2008-02-14 TODO: as of 2008-02-14 - Post dna data model implementation: - We need to make sure that the strand doesn't form a ring ( in other words no handles when strand is a ring). The current code ignores that. - implement/ revise methods such as self.modifyStructure(), self._gather_parameters() etc. - self.updateHandlePositions() may need revision if the current supporting methods in class dna_model.DnaSegment change. """ import foundation.env as env from utilities.debug import print_compact_stack from utilities.constants import gensym from utilities.constants import purple from utilities.Comparison import same_vals from geometry.VQT import V from geometry.VQT import vlen from geometry.VQT import norm from Numeric import dot from exprs.State_preMixin import State_preMixin from exprs.attr_decl_macros import Instance, State from exprs.__Symbols__ import _self from exprs.Exprs import call_Expr from widgets.prefs_widgets import ObjAttr_StateRef from exprs.ExprsConstants import Width, Point, ORIGIN, Color from exprs.ExprsConstants import Vector from model.chunk import Chunk from model.chem import Atom from model.bonds import Bond from dna.commands.DnaStrand.DnaStrand_GraphicsMode import DnaStrand_GraphicsMode from dna.commands.DnaStrand.DnaStrand_ResizeHandle import DnaStrand_ResizeHandle from dna.model.Dna_Constants import getNumberOfBasePairsFromDuplexLength from dna.model.Dna_Constants import getDuplexLength from dna.generators.B_Dna_PAM3_SingleStrand_Generator import B_Dna_PAM3_SingleStrand_Generator from command_support.EditCommand import EditCommand from utilities.constants import noop from utilities.constants import red, black from utilities.Comparison import same_vals from utilities.prefs_constants import dnaStrandEditCommand_cursorTextCheckBox_changedBases_prefs_key from utilities.prefs_constants import dnaStrandEditCommand_cursorTextCheckBox_numberOfBases_prefs_key from utilities.prefs_constants import dnaStrandEditCommand_showCursorTextCheckBox_prefs_key from utilities.prefs_constants import cursorTextColor_prefs_key from dna.commands.DnaStrand.DnaStrand_PropertyManager import DnaStrand_PropertyManager CYLINDER_WIDTH_DEFAULT_VALUE = 0.0 HANDLE_RADIUS_DEFAULT_VALUE = 1.5 ORIGIN = V(0,0,0) _superclass = EditCommand class DnaStrand_EditCommand(State_preMixin, EditCommand): """ Command to edit a DnaStrand (chunk object as of 2008-02-14) To edit a Strand, first enter BuildDna_EditCommand (accessed using Build> Dna) then, select a strand chunk of an existing DnaSegment within the DnaGroup you are editing. When you select the strand chunk, it enters DnaStrand_Editcommand, shows its property manager and also shows the resize handles if any. """ #Graphics Mode GraphicsMode_class = DnaStrand_GraphicsMode #Property Manager PM_class = DnaStrand_PropertyManager cmd = 'Dna Strand' prefix = 'Strand ' # used for gensym cmdname = "DNA_STRAND" commandName = 'DNA_STRAND' featurename = "Edit Dna Strand" from utilities.constants import CL_SUBCOMMAND command_level = CL_SUBCOMMAND command_parent = 'BUILD_DNA' command_should_resume_prevMode = True command_has_its_own_PM = True # Generators for DNA, nanotubes and graphene have their MT name # generated (in GeneratorBaseClass) from the prefix. create_name_from_prefix = True call_makeMenus_for_each_event = True #@see: self.updateHandlePositions for details on how these variables are #used in computation. #@see: DnaStrand_ResizeHandle and handle declaration in this class #definition handlePoint1 = State( Point, ORIGIN) handlePoint2 = State( Point, ORIGIN) handleDirection1 = State(Vector, ORIGIN) handleDirection2 = State(Vector, ORIGIN) #See self._update_resizeHandle_radius where this gets changed. #also see DnaSegment_ResizeHandle to see how its implemented. handleSphereRadius1 = State(Width, HANDLE_RADIUS_DEFAULT_VALUE) handleSphereRadius2 = State(Width, HANDLE_RADIUS_DEFAULT_VALUE) #handleColors handleColor1 = State(Color, purple) handleColor2 = State(Color, purple) #TODO: 'cylinderWidth attr used for resize handles -- needs to be renamed #along with 'height_ref attr in exprs.DraggableHandle_AlongLine cylinderWidth = State(Width, CYLINDER_WIDTH_DEFAULT_VALUE) cylinderWidth2 = State(Width, CYLINDER_WIDTH_DEFAULT_VALUE) #Resize Handles for Strand. See self.updateHandlePositions() leftHandle = Instance( DnaStrand_ResizeHandle( command = _self, height_ref = call_Expr( ObjAttr_StateRef, _self, 'cylinderWidth'), origin = handlePoint1, fixedEndOfStructure = handlePoint2, direction = handleDirection1, sphereRadius = handleSphereRadius1, handleColor = handleColor1 )) rightHandle = Instance( DnaStrand_ResizeHandle( command = _self, height_ref = call_Expr( ObjAttr_StateRef, _self, 'cylinderWidth2'), origin = handlePoint2, fixedEndOfStructure = handlePoint1, direction = handleDirection2, sphereRadius = handleSphereRadius2, handleColor = handleColor2 )) def __init__(self, commandSequencer): """ Constructor for InsertDna_EditCommand """ glpane = commandSequencer.assy.glpane State_preMixin.__init__(self, glpane) EditCommand.__init__(self, commandSequencer) #It uses BuildDna_EditCommand.flyoutToolbar ( in other words, that #toolbar is still accessible and not changes while in this command) flyoutToolbar = None #Graphics handles for editing the structure . self.handles = [] self.grabbedHandle = None #This is used for comarison purpose in model_changed method to decide #whether to update the sequence. self._previousNumberOfBases = None #New Command API method -- implemented on 2008-08-27 def command_update_UI(self): """ Extends superclass method. @see: baseCommand.command_update_UI() """ #This MAY HAVE BUG. WHEN -- #debug pref 'call model_changed only when needed' is ON #See related bug 2729 for details. #The following code that updates te handle positions and the strand #sequence fixes bugs like 2745 and updating the handle positions #updating handle positions in command_update_UI instead of in #self.graphicsMode._draw_handles() is also a minor optimization #This can be further optimized by debug pref #'call command_update_UI only when needed' but its NOT done because of #an issue mentioned in bug 2729 - Ninad 2008-04-07 _superclass.command_update_UI(self) if self.grabbedHandle is not None: return #For Rattlesnake, PAM5 segment resizing is not supported. #@see: self.hasResizableStructure() if self.hasValidStructure(): isStructResizable, why_not = self.hasResizableStructure() if not isStructResizable: self.handles = [] return elif len(self.handles) == 0: self._updateHandleList() self.updateHandlePositions() #NOTE: The following also updates self._previousParams self._updateStrandSequence_if_needed() def keep_empty_group(self, group): """ Returns True if the empty group should not be automatically deleted. otherwise returns False. The default implementation always returns False. Subclasses should override this method if it needs to keep the empty group for some reasons. Note that this method will only get called when a group has a class constant autdelete_when_empty set to True. (and as of 2008-03-06, it is proposed that dna_updater calls this method when needed. @see: Command.keep_empty_group() which is overridden here. """ bool_keep = EditCommand.keep_empty_group(self, group) if not bool_keep: if self.hasValidStructure(): if group is self.struct: bool_keep = True elif group is self.struct.parent_node_of_class(self.assy.DnaGroup): bool_keep = True return bool_keep def _gatherParameters(self): """ Return the parameters from the property manager UI. Delegates this to self.propMgr """ return self.propMgr.getParameters() def _createStructure(self): """ Creates and returns the structure -- TO BE IMPLEMENTED ONCE DNA_MODEL IS READY FOR USE. @return : DnaStrand. @rtype: L{Group} @note: This needs to return a DNA object once that model is implemented """ pass def _modifyStructure(self, params): """ Modify the structure based on the parameters specified. Overrides EditCommand._modifystructure. This method removes the old structure and creates a new one using self._createStructure. This was needed for the structures like this (Dna, Nanotube etc) . . See more comments in the method. """ #It could happen that the self.struct is killed before this method #is called. For example: Enter Edit Dna strand, select the strand, hit #delete and then hit Done to exit strand edit. Whenever you hit Done, #modify structure gets called (if old params don't match new ones) #so it needs to return safely if the structure was not valid due #to some previous operation if not self.hasValidStructure(): return # parameters have changed, update existing structure self._revertNumber() # self.name needed for done message if self.create_name_from_prefix: # create a new name name = self.name = gensym(self.prefix, self.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 self.dna = B_Dna_PAM3_SingleStrand_Generator() numberOfBases, \ dnaForm, \ dnaModel, \ color_junk, \ name_junk = params #see a note about color_junk in DnaSegment_EditCommand._modifyStructure() numberOfBasesToAddOrRemove = self._determine_numberOfBases_to_change() if numberOfBasesToAddOrRemove != 0: resizeEndStrandAtom, resizeEndAxisAtom = \ self.get_strand_and_axis_endAtoms_at_resize_end() if resizeEndAxisAtom: dnaSegment = resizeEndAxisAtom.molecule.parent_node_of_class( self.assy.DnaSegment) if dnaSegment: #A DnaStrand can have multiple DNA Segments with different #basesPerTurn and duplexRise so make sure that while #resizing the strand, use the dna segment of the #resizeEndAxisAtom. Fixes bug 2922 - Ninad 2008-08-04 basesPerTurn = dnaSegment.getBasesPerTurn() duplexRise = dnaSegment.getDuplexRise() resizeEnd_final_position = self._get_resizeEnd_final_position( resizeEndAxisAtom, abs(numberOfBasesToAddOrRemove), duplexRise ) self.dna.modify(dnaSegment, resizeEndAxisAtom, numberOfBasesToAddOrRemove, basesPerTurn, duplexRise, resizeEndAxisAtom.posn(), resizeEnd_final_position, resizeEndStrandAtom = resizeEndStrandAtom ) return def _finalizeStructure(self): """ Overrides EditCommand._finalizeStructure. @see: EditCommand.preview_or_finalize_structure """ if self.struct is not None: #@TODO 2008-03-19:Should we always do this even when strand sequence #is not changed?? Should it waste time in comparing the current #sequence with a previous one? Assigning sequence while leaving the #command will be slow for large files.Need to be optimized if #problematic. #What if a flag is set in self.propMgr.updateSequence() when it #updates the seq for the second time and we check that here. #Thats not good if the method gets called multiple times for some #reason other than the user entered sequence. So not doing here. #Better fix would be to check if sequence gets changed (textChanged) #in DnaSequence editor class .... Need to be revised EditCommand._finalizeStructure(self) self._updateStrandSequence_if_needed() self.assignStrandSequence() def _previewStructure(self): EditCommand._previewStructure(self) self.updateHandlePositions() self._updateStrandSequence_if_needed() def _updateStrandSequence_if_needed(self): if self.hasValidStructure(): new_numberOfBases = self.struct.getNumberOfBases() #@TODO Update self._previousParams again? #This NEEDS TO BE REVISED. BUG MENTIONED BELOW---- #we already update this in EditCommand class. But, it doesn't work for #the following bug -- 1. create a duplex with 5 basepairs, 2. resize #red strand to 2 bases. 3. Undo 4. Redo 5. Try to resize it again to #2 bases -- it doesn't work because self.previousParams stil stores #bases as 2 and thinks nothing got changed! Can we declare #self._previewStructure as a undiable state? Or better self._previousParams #should store self.struct and should check method return value #like self.struct.getNumberOfBases()--Ninad 2008-04-07 if self.previousParams is not None: if new_numberOfBases != self.previousParams[0]: self.propMgr.numberOfBasesSpinBox.setValue(new_numberOfBases) self.previousParams = self._gatherParameters() if not same_vals(new_numberOfBases, self._previousNumberOfBases): self.propMgr.updateSequence() self._previousNumberOfBases = new_numberOfBases def _get_resizeEnd_final_position(self, resizeEndAxisAtom, numberOfBases, duplexRise): final_position = None if self.grabbedHandle: final_position = self.grabbedHandle.currentPosition else: dnaSegment = resizeEndAxisAtom.molecule.parent_node_of_class(self.assy.DnaSegment) other_axisEndAtom = dnaSegment.getOtherAxisEndAtom(resizeEndAxisAtom) axis_vector = resizeEndAxisAtom.posn() - other_axisEndAtom.posn() segment_length_to_add = getDuplexLength('B-DNA', numberOfBases, duplexRise = duplexRise) final_position = resizeEndAxisAtom.posn() + norm(axis_vector)*segment_length_to_add return final_position def getStructureName(self): """ Returns the name string of self.struct if there is a valid structure. Otherwise returns None. This information is used by the name edit field of this command's PM when we call self.propMgr.show() @see: DnaStrand_PropertyManager.show() @see: self.setStructureName """ if self.hasValidStructure(): return self.struct.name else: return None def setStructureName(self, name): """ Sets the name of self.struct to param <name> (if there is a valid structure). The PM of this command callss this method while closing itself @param name: name of the structure to be set. @type name: string @see: DnaStrand_PropertyManager.close() @see: self.getStructureName() @see: DnaSegment_GraphicsMode.leftUp , DnaSegment_editCommand.setStructureName for comments about some issues. """ if self.hasValidStructure(): self.struct.name = name return def assignStrandSequence(self): """ Assigns the sequence typed in the sequence editor text field to the selected strand chunk. The method it invokes also assigns complimentary bases to the mate strand(s). @see: DnaStrand.setStrandSequence """ if not self.hasValidStructure(): #Fixes bug 2923 return sequenceString = self.propMgr.sequenceEditor.getPlainSequence() sequenceString = str(sequenceString) #assign strand sequence only if it not the same as the current sequence seq = self.struct.getStrandSequence() if seq != sequenceString: self.struct.setStrandSequence(sequenceString) return def editStructure(self, struct = None): """ Edit the structure @param struct: structure to be edited (in this case its a strand chunk) @type struct: chunk or None (this will change post dna data model) """ EditCommand.editStructure(self, struct) if self.hasValidStructure(): self._updatePropMgrParams() #For Rattlesnake, we do not support resizing of PAM5 model. #So don't append the exprs handles to the handle list (and thus #don't draw those handles. See self.model_changed() isStructResizable, why_not = self.hasResizableStructure() if not isStructResizable: self.handles = [] else: self._updateHandleList() self.updateHandlePositions() def _updatePropMgrParams(self): """ Subclasses may override this method. Update some property manager parameters with the parameters of self.struct (which is being edited) @see: self.editStructure() """ #Format in which params need to be provided to the Property manager #numberOfBases, #dnaForm, #dnaModel, #color self._previousNumberOfBases = self.struct.getNumberOfBases() numberOfBases = self._previousNumberOfBases color = self.struct.getColor() name = self.getStructureName() params_for_propMgr = ( numberOfBases, None, None, color, name ) #TODO 2008-03-25: better to get all parameters from self.struct and #set it in propMgr? This will mostly work except that reverse is #not true. i.e. we can not specify same set of params for #self.struct.setProps ...because endPoint1 and endPoint2 are derived. #by the structure when needed. Commenting out following line of code #UPDATE 2008-05-06 Fixes a bug due to which the parameters in propMGr #of DnaSegment_EditCommand are not same as the original structure #(e.g. bases per turn and duplexrise) self.propMgr.setParameters(params_for_propMgr) return def _getStructureType(self): """ Subclasses 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: EditCommand._getStructureType() (overridden here) """ return self.win.assy.DnaStrand def updateSequence(self): """ Public method provided for convenience. If any callers outside of this command need to update the sequence in the sequence editor, they can simply call currentCommand.updateSequence() rather than currentCommand.propMgr.updateSequence(). @see: Ui_DnaSequenceEditor.updateSequence() which does the actual job of updating the sequence string in the sequence editor. """ if self.propMgr is not None: self.propMgr.updateSequence() return def hasResizableStructure(self): """ For Rattlesnake release, we dont support strand resizing for PAM5 models. If the structure is not resizable, the handles won't be drawn @see:self.model_changed() @see:DnaStrand_PropertyManager.model_changed() @see: self.editStructure() @see: DnaSegment.is_PAM3_DnaStrand() """ #Note: This method fixes bugs similar to (and including) bug 2812 but #the changes didn't made it to Rattlesnake rc2 -- Ninad 2008-04-16 isResizable = True why_not = '' if not self.hasValidStructure(): isResizable = False why_not = 'It is invalid.' return isResizable, why_not isResizable = self.struct.is_PAM3_DnaStrand() if not isResizable: why_not = 'It needs to be converted to PAM3 model.' return isResizable, why_not #The following fixes bug 2812 strandEndBaseAtom1, strandEndBaseAtom2 = self.struct.get_strand_end_base_atoms() if strandEndBaseAtom1 is strandEndBaseAtom2: isResizable = False why_not = "It is probably a \'closed loop\'." return isResizable, why_not return True, '' def _updateHandleList(self): """ Updates the list of handles (self.handles) @see: self.editStructure @see: DnaSegment_GraphicsMode._drawHandles() """ # note: if handlePoint1 and/or handlePoint2 can change more often than # this runs, we'll need to rerun the two assignments above whenever they # change and before the handle is drawn. An easy way would be to rerun # these assignments in the draw method of our GM. [bruce 080128] self.handles = [] # guess, but seems like a good idea [bruce 080128] self.handles.append(self.leftHandle) self.handles.append(self.rightHandle) def updateHandlePositions(self): """ Update handle positions """ if len(self.handles) == 0: #No handles are appended to self.handles list. #@See self.model_changed() and self._updateHandleList() return self.cylinderWidth = CYLINDER_WIDTH_DEFAULT_VALUE self.cylinderWidth2 = CYLINDER_WIDTH_DEFAULT_VALUE axisAtom1 = None axisAtom2 = None strandEndBaseAtom1 = None strandEndBaseAtom2 = None #It could happen (baecause of bugs) that standEndBaseAtom1 and #strandEndBaseAtom2 are one and the same! i.e strand end atom is #not bonded. If this happens, we should throw a traceback bug #exit gracefully. The possible cause of this bug may be --- #(just an example): For some reason, the modify code is unable to #determine the correct bond direction of the resized structure #and therefore, while fusing the original strand with the new one created #by DnaDuplex.modify, it is unable to find bondable pairs! # [- Ninad 2008-03-31] strandEndBaseAtom1, strandEndBaseAtom2 = self.struct.get_strand_end_base_atoms() if strandEndBaseAtom1 is strandEndBaseAtom2: print_compact_stack("bug in updating handle positions, some resized DnaStrand " \ "has only one atom") return if strandEndBaseAtom1: axisAtom1 = strandEndBaseAtom1.axis_neighbor() if axisAtom1: self.handleDirection1 = self._get_handle_direction(axisAtom1, strandEndBaseAtom1) self.handlePoint1 = axisAtom1.posn() if strandEndBaseAtom2: axisAtom2 = strandEndBaseAtom2.axis_neighbor() if axisAtom2: self.handleDirection2 = self._get_handle_direction(axisAtom2, strandEndBaseAtom2) self.handlePoint2 = axisAtom2.posn() # UPDATE 2008-04-15: # Before 2008-04-15 the state attrs for exprs handles were always reset to None #at the beginning of the method. But it is calling model_changed signal #recursively. (se also bug 2729) So, reset thos state attrs only when #needed -- Ninad [ this fix was not in RattleSnake rc1] # Set handlePoints (i.e. their origins) and the handle directions to # None if the atoms used to compute these state attrs are missing. # The GraphicsMode checks if the handles have valid placement # attributes set before drawing it. if strandEndBaseAtom1 is None and strandEndBaseAtom2 is None: #probably a ring self.handles = [] if strandEndBaseAtom1 is None or axisAtom1 is None: self.handleDirection1 = None self.handlePoint1 = None if strandEndBaseAtom2 is None or axisAtom2 is None: self.handleDirection2 = None self.handlePoint2 = None #update the radius of resize handle self._update_resizeHandle_radius(axisAtom1, axisAtom2) #update the display color of the handles self._update_resizeHandle_color(strandEndBaseAtom1, strandEndBaseAtom2) def _update_resizeHandle_radius(self, axisAtom1, axisAtom2): """ Finds out the sphere radius to use for the resize handles, based on atom /chunk or glpane display (whichever decides the display of the end atoms. The default value is 1.2. @see: self.updateHandlePositions() @see: B{Atom.drawing_radius()} """ if axisAtom1 is not None: self.handleSphereRadius1 = max(1.005*axisAtom1.drawing_radius(), 1.005*HANDLE_RADIUS_DEFAULT_VALUE) if axisAtom2 is not None: self.handleSphereRadius2 = max(1.005*axisAtom2.drawing_radius(), 1.005*HANDLE_RADIUS_DEFAULT_VALUE) def _update_resizeHandle_color(self, strandEndBaseAtom1, strandEndBaseAtom2): """ Update the color of resize handles using the current color of the *chunk* of the corresponding strand end atoms. @Note: If no specific color is set to the chunk, it uses 'purple' as the default color (and doesn't use the atom.element.color) . This can be changed if needed. """ if strandEndBaseAtom1 is not None: color = strandEndBaseAtom1.molecule.color if color: self.handleColor1 = color if strandEndBaseAtom2 is not None: color = strandEndBaseAtom2.molecule.color if color: self.handleColor2 = color def _get_handle_direction(self, axisAtom, strandAtom): """ Get the handle direction. """ handle_direction = None strand_rail = strandAtom.molecule.get_ladder_rail() for bond_direction in (1, -1): next_strand_atom = strandAtom.strand_next_baseatom(bond_direction) if next_strand_atom: break if next_strand_atom: next_axis_atom = next_strand_atom.axis_neighbor() if next_axis_atom: handle_direction = norm(axisAtom.posn() - next_axis_atom.posn()) return handle_direction def getDnaRibbonParams(self): """ Returns parameters for drawing the dna ribbon. If the dna rubberband line should NOT be drawn (example when you are removing bases from the strand or if its unable to get dnaSegment) , it retuns None. So the caller should check if the method return value is not None. @see: DnaStrand_GraphicsMode._draw_handles() """ if self.grabbedHandle is None: return None if self.grabbedHandle.origin is None: return None direction_of_drag = norm(self.grabbedHandle.currentPosition - \ self.grabbedHandle.origin) #If the strand bases are being removed (determined by checking the #direction of drag) , no need to draw the rubberband line. if dot(self.grabbedHandle.direction, direction_of_drag) < 0: return None strandEndAtom, axisEndAtom = self.get_strand_and_axis_endAtoms_at_resize_end() #DnaStrand.get_DnaSegment_with_content_atom saely handles the case where #strandEndAtom is None. dnaSegment = self.struct.get_DnaSegment_with_content_atom(strandEndAtom) ribbon1_direction = None if dnaSegment: basesPerTurn = dnaSegment.getBasesPerTurn() duplexRise = dnaSegment.getDuplexRise() ribbon1_start_point = strandEndAtom.posn() if strandEndAtom: ribbon1_start_point = strandEndAtom.posn() for bond_direction, neighbor in strandEndAtom.bond_directions_to_neighbors(): if neighbor and neighbor.is_singlet(): ribbon1_direction = bond_direction break ribbon1Color = strandEndAtom.molecule.color if not ribbon1Color: ribbon1Color = strandEndAtom.element.color return (self.grabbedHandle.origin, self.grabbedHandle.currentPosition, basesPerTurn, duplexRise, ribbon1_start_point, ribbon1_direction, ribbon1Color ) return None def get_strand_and_axis_endAtoms_at_resize_end(self): resizeEndStrandAtom = None resizeEndAxisAtom = None strandEndAtom1, strandEndAtom2 = self.struct.get_strand_end_base_atoms() if self.grabbedHandle is not None: for atm in (strandEndAtom1, strandEndAtom2): axisEndAtom = atm.axis_neighbor() if axisEndAtom: if same_vals(axisEndAtom.posn(), self.grabbedHandle.origin): resizeEndStrandAtom = atm resizeEndAxisAtom = axisEndAtom return (resizeEndStrandAtom, resizeEndAxisAtom) def getCursorText(self): """ Used by DnaStrand_GraphicsMode._draw_handles() @TODO: It also updates the number of bases """ if self.grabbedHandle is None: return #@TODO: This updates the PM as the cursor moves. #Need to rename this method so that you that it also does more things #than just to return a textString. Even better if its called in #self.model_changed but at the moment there is a bug thats why we #are doing this update by calling getCursorText in the #GraphicscMode._draw_handles-- Ninad 2008-04-05 self.update_numberOfBases() text = "" textColor = env.prefs[cursorTextColor_prefs_key] # Mark 2008-08-28 if not env.prefs[dnaStrandEditCommand_showCursorTextCheckBox_prefs_key]: return text, textColor numberOfBases = self.propMgr.numberOfBasesSpinBox.value() numberOfBasesString = self._getCursorText_numberOfBases( numberOfBases) changedBases = self._getCursorText_changedBases( numberOfBases) text = numberOfBasesString if text and changedBases: text += " " # Removed comma. Mark 2008-07-03 text += changedBases return (text , textColor) def _getCursorText_numberOfBases(self, numberOfBases): """ Return the cursor textstring that gives information about the number of bases if the corresponding prefs_key returns True. """ numberOfBasesString = '' if env.prefs[ dnaStrandEditCommand_cursorTextCheckBox_numberOfBases_prefs_key]: numberOfBasesString = "%db"%numberOfBases return numberOfBasesString def _getCursorText_changedBases(self, numberOfBases): """ @see: self.getCursorText() """ changedBasesString = '' if env.prefs[ dnaStrandEditCommand_cursorTextCheckBox_changedBases_prefs_key]: original_numberOfBases = self.struct.getNumberOfBases() changed_bases = numberOfBases - original_numberOfBases if changed_bases > 0: changedBasesString = "(" + "+" + str(changed_bases) + ")" else: changedBasesString = "(" + str(changed_bases) + ")" return changedBasesString def modifyStructure(self): """ Called when a resize handle is dragged to change the length of the segment. (Called upon leftUp) . This method assigns the new parameters for the segment after it is resized and calls preview_or_finalize_structure which does the rest of the job. Note that Client should call this public method and should never call the private method self._modifyStructure. self._modifyStructure is called only by self.preview_or_finalize_structure @see: B{DnaStrand_ResizeHandle.on_release} (the caller) @see: B{SelectChunks_GraphicsMode.leftUp} (which calls the the relevent method in DragHandler API. ) @see: B{exprs.DraggableHandle_AlongLine}, B{exprs.DragBehavior} @see: B{self.preview_or_finalize_structure } @see: B{self._modifyStructure} """ #TODO: need to cleanup this and may be use use something like #self.previousParams = params in the end -- 2008-03-24 (midnight) if self.grabbedHandle is None: return #TODO: Important note: How does NE1 know that structure is modified? #Because number of base pairs parameter in the PropMgr changes as you #drag the handle . This is done in self.getCursorText() ... not the #right place to do it. OR that method needs to be renamed to reflect #this as suggested in that method -- Ninad 2008-03-25 self.preview_or_finalize_structure(previewing = True) self.glpane.gl_update() def update_numberOfBases(self): """ Updates the numberOfBases in the PM while a resize handle is being dragged. @see: self.getCursorText() where it is called. """ #@Note: originally (before 2008-04-05, it was called in #DnaStrand_ResizeHandle.on_drag() but that 'may' have some bugs #(not verified) also see self.getCursorText() to know why it is #called there (basically a workaround for bug 2729 if self.grabbedHandle is None: return currentPosition = self.grabbedHandle.currentPosition resize_end = self.grabbedHandle.origin new_duplexLength = vlen( currentPosition - resize_end ) numberOfBasePairs_to_change = getNumberOfBasePairsFromDuplexLength('B-DNA', new_duplexLength) original_numberOfBases = self.struct.getNumberOfBases() #If the dot product of handle direction and the direction in which it #is dragged is negative, this means we need to subtract bases direction_of_drag = norm(currentPosition - resize_end) if dot(self.grabbedHandle.direction, direction_of_drag ) < 0: total_number_of_bases = original_numberOfBases - numberOfBasePairs_to_change self.propMgr.numberOfBasesSpinBox.setValue(total_number_of_bases) else: total_number_of_bases = original_numberOfBases + numberOfBasePairs_to_change self.propMgr.numberOfBasesSpinBox.setValue(total_number_of_bases - 1) def _determine_numberOfBases_to_change(self): """ """ #The Property manager will be showing the current number #of base pairs (w. May be we can use that number directly here? #The following is safer to do so lets just recompute the #number of base pairs. (if it turns out to be slow, we will consider #using the already computed calue from the property manager original_numberOfBases = self.struct.getNumberOfBases() numberOfBasesToAddOrRemove = self.propMgr.numberOfBasesSpinBox.value()\ - original_numberOfBases if numberOfBasesToAddOrRemove > 0: #dna.modify will remove the first base pair it creates #(that basepair will only be used for proper alignment of the #duplex with the existing structure) So we need to compensate for #this basepair by adding 1 to the new number of base pairs. numberOfBasesToAddOrRemove += 1 return numberOfBasesToAddOrRemove def makeMenus(self): """ Create context menu for this command. """ if not hasattr(self, 'graphicsMode'): return selobj = self.glpane.selobj if selobj is None: return self.Menu_spec = [] highlightedChunk = None if isinstance(selobj, Chunk): highlightedChunk = selobj if isinstance(selobj, Atom): highlightedChunk = selobj.molecule elif isinstance(selobj, Bond): chunk1 = selobj.atom1.molecule chunk2 = selobj.atom2.molecule if chunk1 is chunk2 and chunk1 is not None: highlightedChunk = chunk1 if highlightedChunk is None: return if self.hasValidStructure(): ### REVIEW: these early returns look wrong, since they skip running # the subsequent call of highlightedChunk.make_glpane_cmenu_items # for no obvious reason. [bruce 090114 comment, in two commands] if (self.struct is highlightedChunk) or \ (self.struct is highlightedChunk.parent_node_of_class( self.assy.DnaStrand)): item = (("Currently editing %r"%self.struct.name), noop, 'disabled') self.Menu_spec.append(item) return #following should be self.struct.getDnaGroup or self.struct.getDnaGroup #need to formalize method name and then make change. dnaGroup = self.struct.parent_node_of_class(self.assy.DnaGroup) if dnaGroup is None: return if not dnaGroup is highlightedChunk.parent_node_of_class(self.assy.DnaGroup): item = ("Edit unavailable: Member of a different DnaGroup", noop, 'disabled') self.Menu_spec.append(item) return highlightedChunk.make_glpane_cmenu_items(self.Menu_spec, self)
NanoCAD-master
cad/src/dna/commands/DnaStrand/DnaStrand_EditCommand.py
# Copyright 2008-2009 Nanorex, Inc. See LICENSE file for details. """ Graphics mode intended to be used while in DnaStrand_EditCommand. @author: Ninad @version: $Id$ @copyright: 2008-2009 Nanorex, Inc. See LICENSE file for details. History: Created 2008-02-14 """ from dna.commands.BuildDna.BuildDna_GraphicsMode import BuildDna_GraphicsMode from graphics.drawing.drawDnaRibbons import drawDnaSingleRibbon from utilities.constants import black _superclass = BuildDna_GraphicsMode class DnaStrand_GraphicsMode(BuildDna_GraphicsMode): _handleDrawingRequested = True cursor_over_when_LMB_pressed = '' def Draw_other(self): """ Draw this DnaStrand object and its contents including handles (if any) @see:self._drawCursorText() @see:self._drawHandles() """ # review: docstring may be wrong now that this method doesn't # draw the model [bruce 090310 comment] _superclass.Draw_other(self) if self._handleDrawingRequested: self._drawHandles() def _drawHandles(self): """ Draw the handles for the command.struct @see: DnaStrand_ResizeHandle.hasValidParamsForDrawing () @see:self._drawCursorText() @see:self.Draw_other() """ if self.command and self.command.hasValidStructure(): for handle in self.command.handles: #Check if handle's center (origin) and direction are #defined. (ONLY checks if those are not None) if handle.hasValidParamsForDrawing(): handle.draw() if self.command.grabbedHandle is not None: params = self.command.getDnaRibbonParams() if params: end1, end2, basesPerTurn, duplexRise, \ ribbon1_start_point, ribbon1_direction, ribbon1Color = params drawDnaSingleRibbon(self.glpane, end1, end2, basesPerTurn, duplexRise, self.glpane.scale, self.glpane.lineOfSight, self.glpane.displayMode, ribbon1_start_point = ribbon1_start_point, ribbon1_direction = ribbon1_direction, ribbonThickness = 4.0, ribbon1Color = ribbon1Color, ) #Draw the text next to the cursor that gives info about #number of base pairs etc self._drawCursorText()
NanoCAD-master
cad/src/dna/commands/DnaStrand/DnaStrand_GraphicsMode.py
# Copyright 2008 Nanorex, Inc. See LICENSE file for details. """ DnaStrand_PropertyManager.py @author: Ninad @version: $Id$ @copyright: 2008 Nanorex, Inc. See LICENSE file for details. Special notes: - Sequence editor is also created in BuildDna_PropertyManager (of course its a child of that PM) . See if that creates any issues. - Copied some methods from BuildDna_PropertyManager. """ from utilities import debug_flags from utilities.debug import print_compact_stack from utilities.Comparison import same_vals from utilities.Log import redmsg from PyQt4.Qt import SIGNAL from PyQt4.Qt import QString from PyQt4.Qt import Qt from command_support.DnaOrCnt_PropertyManager import DnaOrCnt_PropertyManager from PM.PM_Constants import PM_DONE_BUTTON from PM.PM_Constants import PM_WHATS_THIS_BUTTON from PM.PM_LineEdit import PM_LineEdit from PM.PM_GroupBox import PM_GroupBox from PM.PM_CheckBox import PM_CheckBox from PM.PM_SpinBox import PM_SpinBox from PM.PM_DoubleSpinBox import PM_DoubleSpinBox from widgets.prefs_widgets import connect_checkbox_with_boolean_pref from utilities.prefs_constants import dnaStrandEditCommand_cursorTextCheckBox_changedBases_prefs_key from utilities.prefs_constants import dnaStrandEditCommand_cursorTextCheckBox_numberOfBases_prefs_key from utilities.prefs_constants import dnaStrandEditCommand_showCursorTextCheckBox_prefs_key _superclass = DnaOrCnt_PropertyManager class DnaStrand_PropertyManager( DnaOrCnt_PropertyManager): """ The DnaStrand_PropertyManager class provides a Property Manager for the DnaStrand_EditCommand. @ivar title: The title that appears in the property manager header. @type title: str @ivar pmName: The name of this property manager. This is used to set the name of the PM_Dialog object via setObjectName(). @type name: str @ivar iconPath: The relative path to the PNG file that contains a 22 x 22 icon image that appears in the PM header. @type iconPath: str """ title = "DnaStrand Properties" iconPath = "ui/actions/Properties Manager/Strand.png" def __init__( self, command ): """ Constructor for the Build DNA property manager. """ self.sequenceEditor = None self._numberOfBases = 0 self._conformation = 'B-DNA' self.dnaModel = 'PAM3' _superclass.__init__( self, command) self.showTopRowButtons( PM_DONE_BUTTON | \ PM_WHATS_THIS_BUTTON) return def _addGroupBoxes( self ): """ Add group boxes to this PM. """ self._pmGroupBox1 = PM_GroupBox( self, title = "Parameters" ) self._loadGroupBox1( self._pmGroupBox1 ) self._displayOptionsGroupBox = PM_GroupBox( self, title = "Display Options" ) self._loadDisplayOptionsGroupBox( self._displayOptionsGroupBox ) #Sequence Editor. This is NOT a groupbox, needs cleanup. Doing it here #so that the sequence editor gets connected! Perhaps #superclass should define _loadAdditionalWidgets. -- Ninad2008-10-03 self._loadSequenceEditor() return def _loadGroupBox1(self, pmGroupBox): """ Load widgets in group box 1. """ self.nameLineEdit = PM_LineEdit( pmGroupBox, label = "Name:", text = "", setAsDefault = False) self.numberOfBasesSpinBox = \ PM_SpinBox( pmGroupBox, label = "Number of bases:", value = self._numberOfBases, setAsDefault = False, minimum = 2, maximum = 10000 ) self.disableStructHighlightingCheckbox = \ PM_CheckBox( pmGroupBox, text = "Don't highlight while editing DNA", widgetColumn = 0, state = Qt.Unchecked, setAsDefault = True, spanWidth = True ) #As of 2008-03-31, the properties such as number of bases will be #editable only by using the resize handles. self.numberOfBasesSpinBox.setEnabled(False) return def _loadSequenceEditor(self): """ Temporary code that shows the Sequence editor ..a doc widget docked at the bottom of the mainwindow. The implementation is going to change before 'rattleSnake' product release. As of 2007-11-20: This feature (sequence editor) is waiting for the ongoing dna model work to complete. """ self.sequenceEditor = self.win.createDnaSequenceEditorIfNeeded() self.sequenceEditor.hide() return def _loadDisplayOptionsGroupBox(self, pmGroupBox): """ Overrides superclass method. Also loads the color chooser widget. """ self._loadColorChooser(pmGroupBox) _superclass._loadDisplayOptionsGroupBox(self, pmGroupBox) return def _connect_showCursorTextCheckBox(self): """ Connect the show cursor text checkbox with user prefs_key. Overrides DnaOrCnt_PropertyManager._connect_showCursorTextCheckBox """ connect_checkbox_with_boolean_pref( self.showCursorTextCheckBox , dnaStrandEditCommand_showCursorTextCheckBox_prefs_key) return def _params_for_creating_cursorTextCheckBoxes(self): """ 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: Superclass method which is overridden here -- DnaOrCnt_PropertyManager._params_for_creating_cursorTextCheckBoxes() """ params = \ [ #Format: (" checkbox text", prefs_key) ("Number of bases", dnaStrandEditCommand_cursorTextCheckBox_numberOfBases_prefs_key), ("Number of bases to be changed", dnaStrandEditCommand_cursorTextCheckBox_changedBases_prefs_key) ] return params def getParameters(self): name = self.nameLineEdit.text() numberOfBases = self.numberOfBasesSpinBox.value() dnaForm = self._conformation dnaModel = self.dnaModel color = self._colorChooser.getColor() return (numberOfBases, dnaForm, dnaModel, color, name ) def setParameters(self, params): """ This is usually called when you are editing an existing structure. It also gets called when selecting a new strand (within this command). Some property manager ui elements then display the information obtained from the object being edited. TODO: - Make this a EditCommand_PM API method? - See also the routines GraphicsMode.setParams or object.setProps ..better to name them all in one style? """ numberOfBases, \ dnaForm, \ dnaModel, \ color, \ name = params if numberOfBases is not None: self.numberOfBasesSpinBox.setValue(numberOfBases) if dnaForm is not None: self._conformation = dnaForm if dnaModel is not None: self.dnaModel = dnaModel if color is not None: self._colorChooser.setColor(color) if name: # Minimal test. Should add a validator. --Mark 2008-12-16 self.nameLineEdit.setText(name) # This gets called when we enter the command *and* when selecting a new # strand. In either case, we must update the sequence in the sequenece # editor. Fixes bug 2951. --Mark 2008-12-16 if self.command and self.command.hasValidStructure(): #print "setParameters(): loading sequence in sequence editor for ", name self.updateSequence(strand = self.command.struct) return 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 """ #TODO: This is a temporary fix for a bug. When you invoke a temporary # mode Entering such a temporary mode keeps the signals of #PM from the previous mode connected ( #but while exiting that temporary mode and reentering the #previous mode, it atucally reconnects the signal! This gives rise to #lots of bugs. This needs more general fix in Temporary mode API. # -- Ninad 2008-01-09 (similar comment exists in MovePropertyManager.py if isConnect and self.isAlreadyConnected: if debug_flags.atom_debug: print_compact_stack("warning: attempt to connect widgets"\ "in this PM that are already connected." ) return if not isConnect and self.isAlreadyDisconnected: if debug_flags.atom_debug: print_compact_stack("warning: attempt to disconnect widgets"\ "in this PM that are already disconnected.") return self.isAlreadyConnected = isConnect self.isAlreadyDisconnected = not isConnect if isConnect: change_connect = self.win.connect else: change_connect = self.win.disconnect if self.sequenceEditor: self.sequenceEditor.connect_or_disconnect_signals(isConnect) _superclass.connect_or_disconnect_signals(self, isConnect) change_connect(self.disableStructHighlightingCheckbox, SIGNAL('stateChanged(int)'), self.change_struct_highlightPolicy) change_connect(self.showCursorTextCheckBox, SIGNAL('stateChanged(int)'), self._update_state_of_cursorTextGroupBox) change_connect(self.nameLineEdit, SIGNAL("editingFinished()"), self._nameChanged) return def _update_UI_do_updates(self): """ @see: Command_PropertyManager. _update_UI_do_updates() @see: DnaStrand_EditCommand.command_update_UI() @see: DnaStrand_EditCommand.hasResizableStructure() """ if not self.command.hasValidStructure(): print "DnaStrand not a valid structure." self._pmGroupBox1.setEnabled(False) self._displayOptionsGroupBox.setEnabled(False) self.sequenceEditor.updateSequence(strand = " ") self.sequenceEditor.setEnabled(False) self.nameLineEdit.setText("") self.numberOfBasesSpinBox.setValue(0) return else: self._pmGroupBox1.setEnabled(True) self._displayOptionsGroupBox.setEnabled(True) self.sequenceEditor.setEnabled(True) isStructResizable, why_not = self.command.hasResizableStructure() if not isStructResizable: #disable all widgets if self._pmGroupBox1.isEnabled(): self._pmGroupBox1.setEnabled(False) msg1 = ("Attention: ") % (self.command.struct.name) msg2 = redmsg("DnaStrand <b>%s</b> is not resizable. Reason: %s" % \ (self.command.struct.name, why_not)) self.updateMessage(msg1 + msg2) else: if not self._pmGroupBox1.isEnabled(): self._pmGroupBox1.setEnabled(True) msg1 = ("Editing <b>%s</b>. ") % (self.command.struct.name) msg2 = "Use resize handles to resize the strand. "\ "Use the <i>Sequence Editor</i> to edit the sequence." self.updateMessage(msg1 + msg2) return def close(self): """ Close this property manager. Also sets the name of the self.command's structure to the one displayed in the line edit field. @see self.show() @see: DnaSegment_EditCommand.setStructureName """ if self.command is not None: name = str(self.nameLineEdit.text()) self.command.setStructureName(name) if self.sequenceEditor: self.sequenceEditor.close() _superclass.close(self) return def updateSequence(self, strand = None): """ Public method provided for convenience. If any callers outside of this command need to update the sequence in the sequence editor, they can simply do DnaStrand_ProprtyManager.updateSequence() rather than DnaStrand_ProprtyManager.sequenceEditor.updateSequence() @see: Ui_DnaSequenceEditor.updateSequence() """ if self.sequenceEditor: self.sequenceEditor.updateSequence(strand = strand) return def change_struct_highlightPolicy(self,checkedState = False): """ Change the 'highlight policy' of the structure being edited (i.e. self.command.struct) . @param checkedState: The checked state of the checkbox that says 'Don't highlight while editing DNA'. So, it its True, the structure being edited won't get highlighted. @see: DnaStrand.setHighlightPolicy for more comments """ if self.command and self.command.hasValidStructure(): highlight = not checkedState self.command.struct.setHighlightPolicy(highlight = highlight) return def _addWhatsThisText(self): """ Add what's this text. Abstract method. """ pass def _nameChanged(self): # Added by Mark. 2008-12-16 """ Slot for "Name" field. Changes the name of the strand if the user types in a new name. @warning: this lacks a validator. User can type in a name with invalid characters. """ if not self.command.hasValidStructure(): return name = str(self.nameLineEdit.text()) if not name: # Minimal test. Should add a validator. Ask Bruce for example validator code somewhere. --Mark 2008-12-16 if self.command.hasValidStructure(): self.nameLineEdit.setText(self.command.getStructureName()) return self.command.setStructureName(name) self._update_UI_do_updates() # Updates the message box. return
NanoCAD-master
cad/src/dna/commands/DnaStrand/DnaStrand_PropertyManager.py
# Copyright 2007-2008 Nanorex, Inc. See LICENSE file for details. """ InsertDna_EditCommand.py InsertDna_EditCommand that provides an editCommand object for generating DNA Duplex . This command should be invoked only from BuildDna_EditCommand @author: Mark Sims, Ninad Sathaye @version: $Id$ @copyright: 2007-2008 Nanorex, Inc. See LICENSE file for details. History: Ninad 2007-10-24: Created. Rewrote almost everything to implement EdiController as a superclass thereby deprecating the DnaDuplexGenerator class. Ninad 2007-12-20: Converted this editController as a command on the commandSequencer. TODO: - Need to cleanup docstrings. - Methods such as createStructure need some cleanup in this class and in the EditCommand superclass - Method editStructure is not implemented. It will be implemented after the DNA object model gets implemented. - Editing existing structures is not done correctly (broken) after converting this editController into a command. This is a temporary effect. Once the dna data model is fully implemented, the dna group will supply the endPoints necessary to correctly edit the dna structure ad this problem will be fixed -- Ninad 2007-12-20 """ import foundation.env as env from command_support.EditCommand import EditCommand from dna.model.DnaSegment import DnaSegment from dna.model.DnaGroup import DnaGroup from utilities.debug import print_compact_stack from utilities.Log import redmsg, greenmsg from geometry.VQT import V, Veq, vlen from dna.generators.B_Dna_PAM3_Generator import B_Dna_PAM3_Generator from dna.generators.B_Dna_PAM5_Generator import B_Dna_PAM5_Generator from utilities.exception_classes import PluginBug, UserError from dna.commands.InsertDna.InsertDna_PropertyManager import InsertDna_PropertyManager from utilities.constants import gensym from utilities.constants import black from dna.model.Dna_Constants import getNumberOfBasePairsFromDuplexLength from dna.model.Dna_Constants import getDuplexLength from dna.commands.InsertDna.InsertDna_GraphicsMode import InsertDna_GraphicsMode from utilities.prefs_constants import dnaDuplexEditCommand_cursorTextCheckBox_angle_prefs_key from utilities.prefs_constants import dnaDuplexEditCommand_cursorTextCheckBox_length_prefs_key from utilities.prefs_constants import dnaDuplexEditCommand_cursorTextCheckBox_numberOfBasePairs_prefs_key from utilities.prefs_constants import dnaDuplexEditCommand_cursorTextCheckBox_numberOfTurns_prefs_key from utilities.prefs_constants import dnaDuplexEditCommand_showCursorTextCheckBox_prefs_key from utilities.prefs_constants import cursorTextColor_prefs_key _superclass = EditCommand class InsertDna_EditCommand(EditCommand): """ InsertDna_EditCommand that provides an editCommand object for generating DNA Duplex . This command should be invoked only from BuildDna_EditCommand User can create as many Dna duplexes as he/she needs just by specifying two end points for each dna duplex.This uses DnaLineMode_GM class as its GraphicsMode """ #Graphics Mode set to DnaLine graphics mode GraphicsMode_class = InsertDna_GraphicsMode #Property Manager PM_class = InsertDna_PropertyManager cmd = greenmsg("Insert DNA: ") prefix = 'DnaSegment' # used for gensym cmdname = "Duplex" commandName = 'INSERT_DNA' featurename = "Insert DNA" from utilities.constants import CL_SUBCOMMAND command_level = CL_SUBCOMMAND command_parent = 'BUILD_DNA' command_should_resume_prevMode = True command_has_its_own_PM = True # Generators for DNA, nanotubes and graphene have their MT name # generated (in GeneratorBaseClass) from the prefix. create_name_from_prefix = True #required by DnaLine_GM mouseClickPoints = [] #This is the callback method that the previous command #(which is BuildDna_Editcommand as of 2008-01-11) provides. When user exits #this command and returns back to the previous one (BuildDna_EditCommand), #it calls this method and provides a list of segments created while this #command was running. (the segments are stored within a temporary dna group #see self._fallbackDnaGroup callback_addSegments = None #This is set to BuildDna_EditCommand.flyoutToolbar (as of 2008-01-14, #it only uses flyoutToolbar = None def __init__(self, commandSequencer): """ Constructor for InsertDna_EditCommand """ _superclass.__init__(self, commandSequencer) #_fallbackDnaGroup stores the DnaSegments created while in #this command. This temporary dnaGroup is created IF AND ONLY IF #InsertDna_EditCommand is unable to access the dnaGroup object of the #parent BuildDna_EditCommand. (so if this group gets created, it should #be considered as a bug. While exiting the command the list of segments #of this group is given to the BuildDna_EditCommand where they get #their new parent. @see self.command_will_exit() self._fallbackDnaGroup = None #_parentDnaGroup is the dnagroup of BuildDna_EditCommand self._parentDnaGroup = None #Maintain a list of segments created while this command was running. #Note that the segments , when created will be added directly to the # self._parentDnaGroup (or self._fallbackDnaGroup if there is a bug) # But self._parentDnaGroup (which must be = the dnaGroup of # BuildDna_EditCommand.) may already contain DnaSegments (added earlier) # so, we can not use group.steal_members() in case user cancels the #structure creation (segment addition). self._segmentList = [] def _createFallbackDnaGroup(self): """ Creates a temporary DnaGroup object in which all the DnaSegments created while in this command will be added as members. While exiting this command, these segments will be added first taken away from the temporary group and then added to the DnaGroup of BuildDna_EditCommand @see: self.command_will_exit() @see: BuildDna_EditCommand.callback_addSegments() """ if self._fallbackDnaGroup is None: self.win.assy.part.ensure_toplevel_group() self._fallbackDnaGroup = DnaGroup("Fallback Dna", self.win.assy, self.win.assy.part.topnode ) def _getFlyoutToolBarActionAndParentCommand(self): """ See superclass for documentation. @see: self.command_update_flyout() """ flyoutActionToCheck = 'dnaDuplexAction' parentCommandName = None return flyoutActionToCheck, parentCommandName def command_entered(self): """ Overrides superclass method. See superclass for documentation. """ _superclass.command_entered(self) if isinstance(self.graphicsMode, InsertDna_GraphicsMode): self._setParamsForDnaLineGraphicsMode() self.mouseClickPoints = [] #Clear the segmentList as it may still be maintaining a list of segments #from the previous run of the command. self._segmentList = [] if self.parentCommand.commandName == self.command_parent: params = self.parentCommand.provideParamsForTemporaryMode_in_BuildDna() #bruce 080801 revised this; that method should be renamed self._parentDnaGroup = params else: #Should this be an assertion? Should we always kill _parentDnaGroup #if its not None? ..not a good idea. Lets just make it to None. self._parentDnaGroup = None self._createFallbackDnaGroup() self.updateDrawingPlane(plane = None) def command_will_exit(self): """ Overrides superclass method. See superclass for documentation. """ _superclass.command_will_exit(self) if isinstance(self.graphicsMode, InsertDna_GraphicsMode): self.mouseClickPoints = [] self.graphicsMode.resetVariables() self._parentDnaGroup = None self._fallbackDnaGroup = None self._segmentList = [] #=== END NEW COMMAND API methods ======================================== def runCommand(self): """ Overrides EditCommand.runCommand """ self.struct = None def keep_empty_group(self, group): """ Returns True if the empty group should not be automatically deleted. otherwise returns False. The default implementation always returns False. Subclasses should override this method if it needs to keep the empty group for some reasons. Note that this method will only get called when a group has a class constant autdelete_when_empty set to True. (and as of 2008-03-06, it is proposed that dna_updater calls this method when needed. @see: Command.keep_empty_group() which is overridden here. """ bool_keep = _superclass.keep_empty_group(self, group) if not bool_keep: #Don't delete any DnaSegements or DnaGroups at all while #in InsertDna_EditCommand. #Reason: See BreakStrand_Command.keep_empty_group. In addition to #this, this command can create multiple DnaSegments Although those #won't be empty, it doesn't hurt in waiting for this temporary #command to exit before deleting any empty groups. if isinstance(group, self.assy.DnaSegment) or \ isinstance(group, self.assy.DnaGroup): bool_keep = True return bool_keep def createStructure(self): """ Overrides superclass method. Creates the structure (DnaSegment) """ assert self.propMgr is not None if self.struct is not None: self.struct = None self.win.assy.part.ensure_toplevel_group() self.propMgr.endPoint1 = self.mouseClickPoints[0] self.propMgr.endPoint2 = self.mouseClickPoints[1] duplexLength = vlen(self.mouseClickPoints[0] - self.mouseClickPoints[1]) numberOfBasePairs = \ getNumberOfBasePairsFromDuplexLength( 'B-DNA', duplexLength, duplexRise = self.duplexRise) self.propMgr.numberOfBasePairsSpinBox.setValue(numberOfBasePairs) self.preview_or_finalize_structure(previewing = True) #Unpick the dna segments (while this command was still #running. ) This is necessary , so that when you strat drawing #rubberband line, it matches the display style of the glpane. #If something was selected, and while in DnaLineMode you changed the #display style, it will be applied only to the selected chunk. #(and the glpane's display style will not change. This , in turn #won't change the display of the rubberband line being drawn. #Another bug: What if something else in the glpane is selected? #complete fix would be to call unpick_all_in_the_glpane. But #that itself is undesirable. Okay for now -- Ninad 2008-02-20 #UPDATE 2008-02-21: The following code is commented out. Don't #change the selection state of the ##if self._fallbackDnaGroup is not None: ##for segment in self._fallbackDnaGroup.members: ##segment.unpick() #Now append this dnaSegment to self._segmentList self._segmentList.append(self.struct) #clear the mouseClickPoints list self.mouseClickPoints = [] self.graphicsMode.resetVariables() self.win.win_update() #fixes bug 2810 def _getStructureType(self): """ Subclasses 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: EditCommand._getStructureType() (overridden here) @see: self.hasValidStructure() """ return self.win.assy.DnaSegment 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. """ #The following can happen in this case: User creates first duplex, #Now clicks inside 3D workspace to define the first point of the #next duplex. Now moves the mouse to draw dna rubberband line. #and then its 'Done' When it does that, it has modified the #'number of base pairs' value in the PM and then it uses that value #to modify self.struct ...which is the first segment user created! #In order to avoid this, either self.struct should be set to None after #its appended to the segment list (in self.createStructure) #Or it should compute the number of base pairs each time instead of #relying on the corresponding value in the PM. The latter is not #advisable if we support modifying the number of base pairs from the #PM (and hitting preview) while in DnaDuplex command. #In the mean time, I think this solution will always work. if len(self.mouseClickPoints) == 1: return else: _superclass._finalizeStructure(self) def _gatherParameters(self): """ Return the parameters from the property manager UI. @return: All the parameters (get those from the property manager): - numberOfBases - dnaForm - basesPerTurn - endPoint1 - endPoint2 @rtype: tuple """ return self.propMgr.getParameters() def _modifyStructure(self, params): """ Modify the structure based on the parameters specified. Overrides EditCommand._modifystructure. This method removes the old structure and creates a new one using self._createStructure. This was needed for the structures like this (Dna, Nanotube etc) . . See more comments in the method. @see: a note in self._createSStructure() about use of dnaSegment.setProps """ #@NOTE: Unlike editcommands such as Plane_EditCommand, this #editCommand actually removes the structure and creates a new one #when its modified. We don't yet know if the DNA object model # will solve this problem. (i.e. reusing the object and just modifying #its attributes. Till that time, we'll continue to use #what the old GeneratorBaseClass use to do ..i.e. remove the item and # create a new one -- Ninad 2007-10-24 self._removeStructure() self.previousParams = params self.struct = self._createStructure() return def cancelStructure(self): """ Overrides Editcommand.cancelStructure ..calls _removeSegments which deletes all the segments created while this command was running @see: B{EditCommand.cancelStructure} """ _superclass.cancelStructure(self) self._removeSegments() def _removeSegments(self): """ Remove the segments created while in this command self._fallbackDnaGroup (if one exists its a bug). This deletes all the segments created while this command was running @see: L{self.cancelStructure} """ segmentList = [] if self._parentDnaGroup is not None: segmentList = self._segmentList elif self._fallbackDnaGroup is not None: segmentList = self._fallbackDnaGroup.get_segments() for segment in segmentList: #can segment be None? Lets add this condition to be on the safer #side. if segment is not None: segment.kill_with_contents() self._revertNumber() if self._fallbackDnaGroup is not None: self._fallbackDnaGroup.kill() self._fallbackDnaGroup = None self._segmentList = [] self.win.win_update() def _createStructure(self): """ Creates and returns the structure (in this case a L{Group} object that contains the DNA strand and axis chunks. @return : group containing that contains the DNA strand and axis chunks. @rtype: L{Group} @note: This needs to return a DNA object once that model is implemented """ params = self._gatherParameters() # No error checking in build_struct, do all your error # checking in gather_parameters numberOfBases, \ dnaForm, \ dnaModel, \ basesPerTurn, \ duplexRise, \ endPoint1, \ endPoint2 = params if numberOfBases < 2: #Don't create a duplex with only one or 0 bases! #Reset a few variables. This should be done by calling a separate #method on command (there is similar code in self.createStructures) #as well. self.mouseClickPoints = [] self.graphicsMode.resetVariables() msg = redmsg("Cannot preview/insert a DNA duplex with less than 2 base pairs.") self.propMgr.updateMessage(msg) self.dna = None # Fixes bug 2530. Mark 2007-09-02 return None else: msg = "Click two more endpoints to insert another DNA duplex." self.propMgr.updateMessage(msg) #If user enters the number of basepairs and hits preview i.e. endPoint1 #and endPoint2 are not entered by the user and thus have default value #of V(0, 0, 0), then enter the endPoint1 as V(0, 0, 0) and compute #endPoint2 using the duplex length. #Do not use '==' equality check on vectors! its a bug. Use same_vals # or Veq instead. if Veq(endPoint1 , endPoint2) and Veq(endPoint1, V(0, 0, 0)): endPoint2 = endPoint1 + \ self.win.glpane.right * \ getDuplexLength('B-DNA', numberOfBases) if dnaForm == 'B-DNA': if dnaModel == 'PAM3': dna = B_Dna_PAM3_Generator() elif dnaModel == 'PAM5': dna = B_Dna_PAM5_Generator() else: print "bug: unknown dnaModel type: ", dnaModel else: raise PluginBug("Unsupported DNA Form: " + dnaForm) self.dna = dna # needed for done msg # 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 # Create the model tree group node. # Make sure that the 'topnode' of this part is a Group (under which the # DNa group will be placed), if the topnode is not a group, make it a # a 'Group' (applicable to Clipboard parts).See part.py # --Part.ensure_toplevel_group method. This is an important line # and it fixes bug 2585 self.win.assy.part.ensure_toplevel_group() if self._parentDnaGroup is None: print_compact_stack("bug: Parent DnaGroup in InsertDna_EditCommand"\ "is None. This means the previous command "\ "was not 'BuildDna_EditCommand' Ignoring for now") if self._fallbackDnaGroup is None: self._createFallbackDnaGroup() dnaGroup = self._fallbackDnaGroup else: dnaGroup = self._parentDnaGroup dnaSegment = DnaSegment(self.name, self.win.assy, dnaGroup, editCommand = self ) try: # Make the DNA duplex. <dnaGroup> will contain three chunks: # - Strand1 # - Strand2 # - Axis dna.make(dnaSegment, numberOfBases, basesPerTurn, duplexRise, endPoint1, endPoint2) #set some properties such as duplexRise and number of bases per turn #This information will be stored on the DnaSegment object so that #it can be retrieved while editing this object. #This works with or without dna_updater. Now the question is #should these props be assigned to the DnaSegment in #dnaDuplex.make() itself ? This needs to be answered while modifying #make() method to fit in the dna data model. --Ninad 2008-03-05 #WARNING 2008-03-05: Since self._modifyStructure calls #self._createStructure() If in the near future, we actually permit #modifying a #structure (such as dna) without actually recreating the whole #structre, then the following properties must be set in #self._modifyStructure as well. Needs more thought. props = (duplexRise, basesPerTurn) dnaSegment.setProps(props) return dnaSegment except (PluginBug, UserError): # Why do we need UserError here? Mark 2007-08-28 dnaSegment.kill_with_contents() raise PluginBug("Internal error while trying to create DNA duplex.") def getCursorText(self, endPoint1, endPoint2): """ This is used as a callback method in DnaLine mode @see: DnaLineMode.setParams, DnaLineMode_GM.Draw """ text = '' textColor = env.prefs[cursorTextColor_prefs_key] if endPoint1 is None or endPoint2 is None: return text, textColor if not env.prefs[dnaDuplexEditCommand_showCursorTextCheckBox_prefs_key]: return text, textColor numberOfBasePairsString = '' numberOfTurnsString = '' duplexLengthString = '' thetaString = '' duplexLength = vlen(endPoint2 - endPoint1) numberOfBasePairs = getNumberOfBasePairsFromDuplexLength( 'B-DNA', duplexLength, duplexRise = self.duplexRise) numberOfBasePairsString = self._getCursorText_numberOfBasePairs( numberOfBasePairs) numberOfTurnsString = self._getCursorText_numberOfTurns( numberOfBasePairs) duplexLengthString = self._getCursorText_length(duplexLength) if env.prefs[dnaDuplexEditCommand_cursorTextCheckBox_angle_prefs_key]: vec = endPoint2 - endPoint1 theta = self.glpane.get_angle_made_with_screen_right(vec) thetaString = "%5.2f deg"%theta commaString = ", " text = numberOfBasePairsString if text and numberOfTurnsString: text += commaString text += numberOfTurnsString if text and duplexLengthString: text += commaString text += duplexLengthString if text and thetaString: text += commaString text += thetaString #@TODO: The following updates the PM as the cursor moves. #Need to rename this method so that you that it also does more things #than just to return a textString -- Ninad 2007-12-20 self.propMgr.numberOfBasePairsSpinBox.setValue(numberOfBasePairs) return text , textColor def _getCursorText_numberOfBasePairs(self, numberOfBasePairs): numberOfBasePairsString = '' if env.prefs[ dnaDuplexEditCommand_cursorTextCheckBox_numberOfBasePairs_prefs_key]: numberOfBasePairsString = "%db"%numberOfBasePairs return numberOfBasePairsString def _getCursorText_numberOfTurns(self, numberOfBasePairs): numberOfTurnsString = '' if env.prefs[dnaDuplexEditCommand_cursorTextCheckBox_numberOfTurns_prefs_key]: numberOfTurns = numberOfBasePairs / self.basesPerTurn numberOfTurnsString = '(%5.3ft)'%numberOfTurns return numberOfTurnsString def _getCursorText_length(self, duplexLength): duplexLengthString = '' if env.prefs[dnaDuplexEditCommand_cursorTextCheckBox_length_prefs_key]: lengthUnitString = 'A' #change the unit of length to nanometers if the length is > 10A #fixes part of bug 2856 if duplexLength > 10.0: lengthUnitString = 'nm' duplexLength = duplexLength * 0.1 duplexLengthString = "%5.3f%s"%(duplexLength, lengthUnitString) return duplexLengthString def _getCursorText_angle(self): pass def listWidgetHasFocus(self): """ Delegates this to self.propMgr. @see: DnaDuplex_PropertyManager.listWidgetHasFocus() """ return self.propMgr.listWidgetHasFocus() def removeListWidgetItems(self): """ Delegates this to self.propMgr. @see: DnaDuplex_PropertyManager.removeListWidgetItems() """ return self.propMgr.removeListWidgetItems() def useSpecifiedDrawingPlane(self): """ Returns True if the drawing plane specified in the Property manager should be used as a placement plane for the Dna duplex. @see: self.isSpecifyPlaneToolActive() @see: Line_GraphicsMode.bareMotion() to see how this is ultimately used. @see: Line_GraphicsMode.leftDown() @see: DnaLine_GM.leftUp() """ if self.propMgr: return self.propMgr.useSpecifiedDrawingPlane() return False def updateDrawingPlane(self, plane = None): """ Delegates this to self.propMgr. @see: InsertDna_GraphicsMode.jigLeftUp @see: DnaDuplex_graphicsMode.setDrawingPlane() """ self.graphicsMode.setDrawingPlane(plane) if self.propMgr: self.propMgr.updateReferencePlaneListWidget(plane) def isSpecifyPlaneToolActive(self): """ Returns True if the Specify reference plane radio button is enabled AND there is no reference plane specified on which the Dna duplex will be drawn. (Delegates this to the propMgr.) @see: DnaDuplex_Graphicsmode.isSpecifyPlaneToolActive() @see: self.useSpecifiedDrawingPlane() """ if self.propMgr: return self.propMgr.isSpecifyPlaneToolActive() return False def isRubberbandLineSnapEnabled(self): """ This returns True or False based on the checkbox state in the PM. This is used as a callback method in DnaLine mode (DnaLine_GM) @see: DnaLine_GM.snapLineEndPoint where the boolean value returned from this method is used @return: Checked state of the linesnapCheckBox in the PM @rtype: boolean """ return self.propMgr.lineSnapCheckBox.isChecked() def getDisplayStyleForRubberbandLine(self): """ This is used as a callback method in DnaLine mode . @return: The current display style for the rubberband line. @rtype: string @see: DnaLineMode.setParams, DnaLineMode_GM.Draw """ return self.propMgr.dnaRubberBandLineDisplayComboBox.currentText() def getDuplexRise(self): """ This is used as a callback method in DnaLine mode . @return: The current duplex rise. @rtype: float @see: DnaLineMode.setParams, DnaLineMode_GM.Draw """ return self.propMgr.duplexRiseDoubleSpinBox.value() #Things needed for DnaLine_GraphicsMode (DnaLine_GM)====================== def _setParamsForDnaLineGraphicsMode(self): """ Needed for DnaLine_GraphicsMode (DnaLine_GM). The method names need to be revised (e.g. callback_xxx. The prefix callback_ was for the earlier implementation of DnaLine mode where it just used to supply some parameters to the previous mode using the callbacks from the previousmode. """ self.mouseClickLimit = None # self.duplexRise = getDuplexRise('B-DNA') self.duplexRise = self.propMgr.duplexRiseDoubleSpinBox.value() self.basesPerTurn = self.propMgr.basesPerTurnDoubleSpinBox.value() self.jigList = self.win.assy.getSelectedJigs() self.callbackMethodForCursorTextString = \ self.getCursorText self.callbackForSnapEnabled = self.isRubberbandLineSnapEnabled self.callback_rubberbandLineDisplay = \ self.getDisplayStyleForRubberbandLine
NanoCAD-master
cad/src/dna/commands/InsertDna/InsertDna_EditCommand.py
NanoCAD-master
cad/src/dna/commands/InsertDna/__init__.py
# Copyright 2004-2008 Nanorex, Inc. See LICENSE file for details. """ InsertDna_PropertyManager.py @author: Mark Sims @version: $Id$ @copyright: 2004-2008 Nanorex, Inc. See LICENSE file for details. Mark 2007-10-18: - Created. Major rewrite of DnaGeneratorPropertyManager.py. Ninad 2007-10-24: - Another major rewrite to a) use EditCommand_PM superclass and b) Implement feature to generate Dna using endpoints of a line. """ import foundation.env as env from dna.model.Dna_Constants import getDuplexBasesPerTurn, getDuplexRise, getDuplexLength from utilities.Log import redmsg ##, greenmsg, orangemsg from PyQt4.Qt import SIGNAL from PyQt4.Qt import Qt from PyQt4.Qt import QAction from PM.PM_ComboBox import PM_ComboBox from PM.PM_DoubleSpinBox import PM_DoubleSpinBox from PM.PM_GroupBox import PM_GroupBox from PM.PM_SpinBox import PM_SpinBox from PM.PM_LineEdit import PM_LineEdit from PM.PM_ToolButton import PM_ToolButton from PM.PM_CoordinateSpinBoxes import PM_CoordinateSpinBoxes from PM.PM_CheckBox import PM_CheckBox from command_support.DnaOrCnt_PropertyManager import DnaOrCnt_PropertyManager from geometry.VQT import V from PM.PM_Constants import PM_DONE_BUTTON from PM.PM_Constants import PM_WHATS_THIS_BUTTON from PM.PM_Constants import PM_CANCEL_BUTTON from ne1_ui.WhatsThisText_for_PropertyManagers import whatsThis_InsertDna_PropertyManager from utilities.prefs_constants import dnaDuplexEditCommand_cursorTextCheckBox_angle_prefs_key from utilities.prefs_constants import dnaDuplexEditCommand_cursorTextCheckBox_length_prefs_key from utilities.prefs_constants import dnaDuplexEditCommand_cursorTextCheckBox_numberOfBasePairs_prefs_key from utilities.prefs_constants import dnaDuplexEditCommand_cursorTextCheckBox_numberOfTurns_prefs_key from utilities.prefs_constants import dnaDuplexEditCommand_showCursorTextCheckBox_prefs_key from widgets.prefs_widgets import connect_checkbox_with_boolean_pref from utilities.prefs_constants import bdnaBasesPerTurn_prefs_key from utilities.prefs_constants import bdnaRise_prefs_key from widgets.prefs_widgets import Preferences_StateRef_double _superclass = DnaOrCnt_PropertyManager class InsertDna_PropertyManager( DnaOrCnt_PropertyManager ): """ The InsertDna_PropertyManager class provides a Property Manager for the B{Insert Dna} command. @ivar title: The title that appears in the property manager header. @type title: str @ivar pmName: The name of this property manager. This is used to set the name of the PM_Dialog object via setObjectName(). @type name: str @ivar iconPath: The relative path to the PNG file that contains a 22 x 22 icon image that appears in the PM header. @type iconPath: str """ title = "Insert DNA" pmName = title iconPath = "ui/actions/Command Toolbar/BuildDna/InsertDna.png" def __init__( self, command ): """ Constructor for the DNA Duplex property manager. """ self.endPoint1 = None self.endPoint2 = None self._conformation = "B-DNA" self._numberOfBases = 0 self._basesPerTurn = getDuplexBasesPerTurn(self._conformation) self._duplexRise = getDuplexRise(self._conformation) self._duplexLength = getDuplexLength(self._conformation, self._numberOfBases) _superclass.__init__( self, command) self.showTopRowButtons( PM_DONE_BUTTON | \ PM_CANCEL_BUTTON | \ PM_WHATS_THIS_BUTTON) 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 change_connect(self._placementOptions.buttonGroup, SIGNAL("buttonClicked(int)"), self.activateSpecifyReferencePlaneTool) change_connect( self.conformationComboBox, SIGNAL("currentIndexChanged(int)"), self.conformationComboBoxChanged ) change_connect( self.numberOfBasePairsSpinBox, SIGNAL("valueChanged(int)"), self.numberOfBasesChanged ) change_connect( self.basesPerTurnDoubleSpinBox, SIGNAL("valueChanged(double)"), self.basesPerTurnChanged ) change_connect( self.duplexRiseDoubleSpinBox, SIGNAL("valueChanged(double)"), self.duplexRiseChanged ) change_connect(self.showCursorTextCheckBox, SIGNAL('stateChanged(int)'), self._update_state_of_cursorTextGroupBox) self.duplexRiseDoubleSpinBox.connectWithState( Preferences_StateRef_double( bdnaRise_prefs_key, env.prefs[bdnaRise_prefs_key] ) ) self.basesPerTurnDoubleSpinBox.connectWithState( Preferences_StateRef_double( bdnaBasesPerTurn_prefs_key, env.prefs[bdnaBasesPerTurn_prefs_key] ) ) def show(self): _superclass.show(self) self.updateMessage("Specify the DNA parameters below, then click "\ "two endpoints in the graphics area to insert a DNA duplex.") def _addGroupBoxes( self ): """ Add the DNA Property Manager group boxes. """ self._pmReferencePlaneGroupBox = PM_GroupBox( self, title = "Placement Options" ) self._loadReferencePlaneGroupBox( self._pmReferencePlaneGroupBox ) self._pmGroupBox1 = PM_GroupBox( self, title = "Endpoints" ) self._loadGroupBox1( self._pmGroupBox1 ) self._pmGroupBox1.hide() self._pmGroupBox2 = PM_GroupBox( self, title = "Parameters" ) self._loadGroupBox2( self._pmGroupBox2 ) self._displayOptionsGroupBox = PM_GroupBox( self, title = "Display Options" ) self._loadDisplayOptionsGroupBox( self._displayOptionsGroupBox ) def _loadGroupBox1(self, pmGroupBox): """ Load widgets in group box 3. """ #Folllowing toolbutton facilitates entering a temporary DnaLineMode #to create a DNA using endpoints of the specified line. self.specifyDnaLineButton = PM_ToolButton( pmGroupBox, text = "Specify Endpoints", iconPath = "ui/actions/Properties Manager/Pencil.png", spanWidth = True ) self.specifyDnaLineButton.setCheckable(True) self.specifyDnaLineButton.setAutoRaise(True) self.specifyDnaLineButton.setToolButtonStyle( Qt.ToolButtonTextBesideIcon) #EndPoint1 and endPoint2 coordinates. These widgets are hidden # as of 2007- 12 - 05 self._endPoint1SpinBoxes = PM_CoordinateSpinBoxes(pmGroupBox, label = "End Point 1") self.x1SpinBox = self._endPoint1SpinBoxes.xSpinBox self.y1SpinBox = self._endPoint1SpinBoxes.ySpinBox self.z1SpinBox = self._endPoint1SpinBoxes.zSpinBox self._endPoint2SpinBoxes = PM_CoordinateSpinBoxes(pmGroupBox, label = "End Point 2") self.x2SpinBox = self._endPoint2SpinBoxes.xSpinBox self.y2SpinBox = self._endPoint2SpinBoxes.ySpinBox self.z2SpinBox = self._endPoint2SpinBoxes.zSpinBox self._endPoint1SpinBoxes.hide() self._endPoint2SpinBoxes.hide() def _loadGroupBox2(self, pmGroupBox): """ Load widgets in group box 4. """ self.conformationComboBox = \ PM_ComboBox( pmGroupBox, label = "Conformation:", choices = ["B-DNA"], setAsDefault = True) dnaModelChoices = ['PAM3', 'PAM5'] self.dnaModelComboBox = \ PM_ComboBox( pmGroupBox, label = "Model:", choices = dnaModelChoices, setAsDefault = True) self.basesPerTurnDoubleSpinBox = \ PM_DoubleSpinBox( pmGroupBox, label = "Bases per turn:", value = env.prefs[bdnaBasesPerTurn_prefs_key], setAsDefault = True, minimum = 8.0, maximum = 20.0, decimals = 2, singleStep = 0.1 ) self.duplexRiseDoubleSpinBox = \ PM_DoubleSpinBox( pmGroupBox, label = "Rise:", value = env.prefs[bdnaRise_prefs_key], setAsDefault = True, minimum = 2.0, maximum = 4.0, decimals = 3, singleStep = 0.01 ) # Strand Length (i.e. the number of bases) self.numberOfBasePairsSpinBox = \ PM_SpinBox( pmGroupBox, label = "Base pairs:", value = self._numberOfBases, setAsDefault = False, minimum = 0, maximum = 10000 ) self.numberOfBasePairsSpinBox.setDisabled(True) # Duplex Length self.duplexLengthLineEdit = \ PM_LineEdit( pmGroupBox, label = "Duplex length: ", text = "0.0 Angstroms", setAsDefault = False) self.duplexLengthLineEdit.setDisabled(True) def _loadDisplayOptionsGroupBox(self, pmGroupBox): """ Load widgets in the Display Options GroupBox @see: DnaOrCnt_PropertyManager. _loadDisplayOptionsGroupBox """ #Call the superclass method that loads the cursor text checkboxes. #Note, as of 2008-05-19, the superclass, DnaOrCnt_PropertyManager #only loads the cursor text groupboxes. Subclasses like this can #call custom methods like self._loadCursorTextCheckBoxes etc if they #don't need all groupboxes that the superclass loads. _superclass._loadDisplayOptionsGroupBox(self, pmGroupBox) self._rubberbandLineGroupBox = PM_GroupBox( pmGroupBox, title = 'Rubber band line:') dnaLineChoices = ['Ribbons', 'Ladder'] self.dnaRubberBandLineDisplayComboBox = \ PM_ComboBox( self._rubberbandLineGroupBox , label = " Display as:", choices = dnaLineChoices, setAsDefault = True) self.lineSnapCheckBox = \ PM_CheckBox(self._rubberbandLineGroupBox , text = 'Enable line snap' , widgetColumn = 1, state = Qt.Checked ) def _connect_showCursorTextCheckBox(self): """ Connect the show cursor text checkbox with user prefs_key. Overrides DnaOrCnt_PropertyManager._connect_showCursorTextCheckBox """ connect_checkbox_with_boolean_pref( self.showCursorTextCheckBox , dnaDuplexEditCommand_showCursorTextCheckBox_prefs_key) def _params_for_creating_cursorTextCheckBoxes(self): """ 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: Superclass method which is overridden here -- DnaOrCnt_PropertyManager._params_for_creating_cursorTextCheckBoxes() """ params = \ [ #Format: (" checkbox text", prefs_key) ("Number of base pairs", dnaDuplexEditCommand_cursorTextCheckBox_numberOfBasePairs_prefs_key), ("Number of turns", dnaDuplexEditCommand_cursorTextCheckBox_numberOfTurns_prefs_key), ("Duplex length", dnaDuplexEditCommand_cursorTextCheckBox_length_prefs_key), ("Angle", dnaDuplexEditCommand_cursorTextCheckBox_angle_prefs_key) ] return params def _addToolTipText(self): """ Tool Tip text for widgets in the DNA Property Manager. """ pass def conformationComboBoxChanged( self, inIndex ): """ Slot for the Conformation combobox. It is called whenever the Conformation choice is changed. @param inIndex: The new index. @type inIndex: int """ conformation = self.conformationComboBox.currentText() if conformation == "B-DNA": self.basesPerTurnDoubleSpinBox.setValue("10.0") elif conformation == "Z-DNA": self.basesPerTurnDoubleSpinBox.setValue("12.0") else: msg = redmsg("conformationComboBoxChanged(): \ Error - unknown DNA conformation. Index = "+ inIndex) env.history.message(msg) self.duplexLengthSpinBox.setSingleStep(getDuplexRise(conformation)) def numberOfBasesChanged( self, numberOfBases ): """ Slot for the B{Number of Bases} spinbox. """ # Update the Duplex Length lineEdit widget. text = str(getDuplexLength(self._conformation, numberOfBases, self._duplexRise)) \ + " Angstroms" self.duplexLengthLineEdit.setText(text) return def basesPerTurnChanged( self, basesPerTurn ): """ Slot for the B{Bases per turn} spinbox. """ self.command.basesPerTurn = basesPerTurn self._basesPerTurn = basesPerTurn return def duplexRiseChanged( self, rise ): """ Slot for the B{Rise} spinbox. """ self.command.duplexRise = rise self._duplexRise = rise return def getParameters(self): """ Return the parameters from this property manager to be used to create the DNA duplex. @return: A tuple containing the parameters @rtype: tuple @see: L{InsertDna_EditCommand._gatherParameters} where this is used """ numberOfBases = self.numberOfBasePairsSpinBox.value() dnaForm = str(self.conformationComboBox.currentText()) basesPerTurn = self.basesPerTurnDoubleSpinBox.value() duplexRise = self.duplexRiseDoubleSpinBox.value() dnaModel = str(self.dnaModelComboBox.currentText()) # First endpoint (origin) of DNA duplex x1 = self.x1SpinBox.value() y1 = self.y1SpinBox.value() z1 = self.z1SpinBox.value() # Second endpoint (direction vector/axis) of DNA duplex. x2 = self.x2SpinBox.value() y2 = self.y2SpinBox.value() z2 = self.z2SpinBox.value() if not self.endPoint1: self.endPoint1 = V(x1, y1, z1) if not self.endPoint2: self.endPoint2 = V(x2, y2, z2) return (numberOfBases, dnaForm, dnaModel, basesPerTurn, duplexRise, self.endPoint1, self.endPoint2) def _addWhatsThisText(self): """ What's This text for widgets in this Property Manager. """ whatsThis_InsertDna_PropertyManager(self)
NanoCAD-master
cad/src/dna/commands/InsertDna/InsertDna_PropertyManager.py
# Copyright 2008 Nanorex, Inc. See LICENSE file for details. """ InsertDna_GraphicsMode.py Graphics mode class for creating a dna duplex by specifying two line end points. The duplex can be created on a specified plane or parallel to screen @author: Ninad @copyright: 2008 Nanorex, Inc. See LICENSE file for details. @version:$Id$ History: Created on 2008-06-24 TODO: - 2008-06-24: See DnaOrCntPropertyManager class for a detailed to do comment regarding the tool that allows user to specify a drawing plane. """ from PyQt4.Qt import Qt from dna.temporary_commands.DnaLineMode import DnaLine_GM from graphics.drawing.drawDnaLabels import draw_dnaBaseNumberLabels _superclass = DnaLine_GM class InsertDna_GraphicsMode(DnaLine_GM): """ Graphics mode class for creating a dna duplex by specifying two line end points. The duplex can be created on a specified plane or parallel to screen @see: Line_GraphicsMode.bareMotion() @see: Line_GraphicsMode.leftDown() @see: DnaLine_GM.leftUp() """ def _drawLabels(self): """ Overrides suoerclass method. @see: GraphicsMode._drawLabels() """ _superclass._drawLabels(self) draw_dnaBaseNumberLabels(self.glpane) def update_cursor_for_no_MB(self): """ Update the cursor for no mouse button pressed """ _superclass.update_cursor_for_no_MB(self) if self.isSpecifyPlaneToolActive(): self.o.setCursor(self.win.specifyPlaneCursor) def keyPressEvent(self, event): """ Handles keyPressEvent. Overrides superclass method. If delete key is pressed while the focus is inside the PM list widget, it deletes that list widget item. @see: ListWidgetItems_PM_Mixing.listWidgetHasFocus() @see: InsertDna_PropertyManager.listWidgetHasFocus() """ if event.key() == Qt.Key_Delete: if self.command.listWidgetHasFocus(): self.command.removeListWidgetItems() return _superclass.keyPressEvent(self, event) def jigLeftUp(self, j, event): """ Overrides superclass method See that method for more details. Additional things it does: If the jig is a Plane and if Specify reference plane tool is enabled (from the Property manager), this method updates the 'drawing plane' on which the dna duplex will be created. @see: Select_graphicsmode_MouseHelpers_preMixin.jigLeftUp() @see: self.self.isSpecifyPlaneToolActive() """ if self.isSpecifyPlaneToolActive() and self.glpane.modkeys is None: if isinstance(j, self.win.assy.Plane): self.command.updateDrawingPlane(j) return _superclass.jigLeftUp(self, j, event) def isSpecifyPlaneToolActive(self): """ Overrides superclass method. Delegates this job to self.command. @see: InsertDna_EditCommand.isSpecifyPlaneToolActive() @see: InsertDna_PropertyManager.isSpecifyPlaneToolActive() @see: self.jigLeftUp() """ if self.command: return self.command.isSpecifyPlaneToolActive() return False def getDrawingPlane(self): """ Overridden in subclasses. Returns the reference plane on which the line will be drawn. The default immplementation returns None. @see: InsertDna_EditCommand.useSpecifiedDrawingPlane() @see: Line_GraphicsMode.bareMotion() @see: Line_GraphicsMode.leftDown() """ if self.command.useSpecifiedDrawingPlane(): return self.plane else: return None
NanoCAD-master
cad/src/dna/commands/InsertDna/InsertDna_GraphicsMode.py
# Copyright 2008 Nanorex, Inc. See LICENSE file for details. """ DnaDisplayStyle_PropertyManager.py The DnaDisplayStyle_PropertyManager class provides a Property Manager for the B{Display Style} command on the flyout toolbar in the Build > Dna mode. @author: Mark, Urmi @version: $Id$ @copyright: 2008 Nanorex, Inc. See LICENSE file for details. To do: - Add "Display Base Orientation Indicators" groupbox and remove from the Preferences dialog. - Add "Base Colors" pref keys/values. """ import os, time, fnmatch, string import foundation.env as env from command_support.Command_PropertyManager import Command_PropertyManager from widgets.prefs_widgets import connect_checkbox_with_boolean_pref from utilities.prefs_constants import getDefaultWorkingDirectory from utilities.prefs_constants import workingDirectory_prefs_key from utilities.Log import greenmsg, redmsg from PyQt4.Qt import SIGNAL from PyQt4.Qt import Qt from PyQt4 import QtGui from PyQt4.Qt import QFileDialog, QString, QMessageBox from PM.PM_GroupBox import PM_GroupBox from PM.PM_ComboBox import PM_ComboBox from PM.PM_StackedWidget import PM_StackedWidget from PM.PM_CheckBox import PM_CheckBox from PM.PM_DoubleSpinBox import PM_DoubleSpinBox from PM.PM_ToolButtonRow import PM_ToolButtonRow from PM.PM_Constants import PM_DONE_BUTTON from PM.PM_Constants import PM_WHATS_THIS_BUTTON from utilities.constants import diDNACYLINDER from utilities.prefs_constants import dnaRendition_prefs_key from utilities.prefs_constants import dnaStyleAxisShape_prefs_key from utilities.prefs_constants import dnaStyleAxisColor_prefs_key from utilities.prefs_constants import dnaStyleAxisScale_prefs_key from utilities.prefs_constants import dnaStyleAxisEndingStyle_prefs_key from utilities.prefs_constants import dnaStyleStrandsShape_prefs_key from utilities.prefs_constants import dnaStyleStrandsColor_prefs_key from utilities.prefs_constants import dnaStyleStrandsScale_prefs_key from utilities.prefs_constants import dnaStyleStrandsArrows_prefs_key from utilities.prefs_constants import dnaStyleStrutsShape_prefs_key from utilities.prefs_constants import dnaStyleStrutsColor_prefs_key from utilities.prefs_constants import dnaStyleStrutsScale_prefs_key from utilities.prefs_constants import dnaStyleBasesShape_prefs_key from utilities.prefs_constants import dnaStyleBasesColor_prefs_key from utilities.prefs_constants import dnaStyleBasesScale_prefs_key from utilities.prefs_constants import dnaStyleBasesDisplayLetters_prefs_key from utilities.prefs_constants import dnaStrandLabelsEnabled_prefs_key from utilities.prefs_constants import dnaStrandLabelsColorMode_prefs_key dnaDisplayStylePrefsList = \ [dnaRendition_prefs_key, dnaStyleAxisShape_prefs_key, dnaStyleAxisScale_prefs_key, dnaStyleAxisColor_prefs_key, dnaStyleAxisEndingStyle_prefs_key, dnaStyleStrandsShape_prefs_key, dnaStyleStrandsScale_prefs_key, dnaStyleStrandsColor_prefs_key, dnaStyleStrandsArrows_prefs_key, dnaStyleStrutsShape_prefs_key, dnaStyleStrutsScale_prefs_key, dnaStyleStrutsColor_prefs_key, dnaStyleBasesShape_prefs_key, dnaStyleBasesScale_prefs_key, dnaStyleBasesColor_prefs_key, dnaStyleBasesDisplayLetters_prefs_key, dnaStrandLabelsEnabled_prefs_key, dnaStrandLabelsColorMode_prefs_key] # = # DNA Display Style Favorite File I/O functions. Talk to Bruce about splitting # these into a separate file and putting them elsewhere. Mark 2008-05-15. def writeDnaDisplayStyleSettingsToFavoritesFile( basename ): """ Writes a "favorite file" (with a .txt extension) to store all the DNA display style settings (pref keys and their current values). @param basename: The filename (without the .fav extension) to write. @type basename: string @note: The favorite file is written to the directory $HOME/Nanorex/Favorites/DnaDisplayStyle. """ if not basename: return 0, "No name given." # Get filename and write the favorite file. favfilepath = getFavoritePathFromBasename(basename) writeDnaFavoriteFile(favfilepath) # msg = "Problem writing file [%s]" % favfilepath return 1, basename def getFavoritePathFromBasename( basename ): """ Returns the full path to the favorite file given a basename. @param basename: The favorite filename (without the .txt extension). @type basename: string @note: The (default) directory for all favorite files is $HOME/Nanorex/Favorites/DnaDisplayStyle. """ _ext = "txt" # Make favorite filename (i.e. ~/Nanorex/Favorites/DnaDisplayStyleFavorites/basename.txt) from platform_dependent.PlatformDependent import find_or_make_Nanorex_subdir _dir = find_or_make_Nanorex_subdir('Favorites/DnaDisplayStyle') return os.path.join(_dir, "%s.%s" % (basename, _ext)) def writeDnaFavoriteFile( filename ): """ Writes a favorite file to I{filename}. """ f = open(filename, 'w') # Write header f.write ('!\n! DNA display style favorite file') f.write ('\n!Created by NanoEngineer-1 on ') timestr = "%s\n!\n" % time.strftime("%Y-%m-%d at %H:%M:%S") f.write(timestr) #write preference list in file without the NE version for pref_key in dnaDisplayStylePrefsList: val = env.prefs[pref_key] pref_keyArray = pref_key.split("/") pref_key = pref_keyArray[1] if isinstance(val, int): f.write("%s = %d\n" % (pref_key, val)) elif isinstance(val, float): f.write("%s = %-6.2f\n" % (pref_key, val)) elif isinstance(val, bool): f.write("%s = %d\n" % (pref_key, val)) else: print "Not sure what pref_key '%s' is." % pref_key f.close() def loadFavoriteFile( filename ): """ Loads a favorite file from anywhere in the disk. @param filename: The full path for the favorite file. @type filename: string """ if os.path.exists(filename): favoriteFile = open(filename, 'r') else: env.history.message("Favorite file to be loaded does not exist.") return 0 # do syntax checking on the file to figure out whether this is a valid # favorite file line = favoriteFile.readline() line = favoriteFile.readline() if line != "! DNA display style favorite file\n": env.history.message(" Not a proper favorite file") favoriteFile.close() return 0 while 1: line = favoriteFile.readline() # marks the end of file if line == "": break # process each line to obtain pref_keys and their corresponding values if line[0] != '!': keyValuePair = line.split('=') pref_keyString = keyValuePair[0].strip() pref_value=keyValuePair[1].strip() # check if pref_value is an integer or float. Booleans currently # stored as integer as well. try: int(pref_value) pref_valueToStore = int(pref_value) except ValueError: pref_valueToStore = float(pref_value) # match pref_keyString with its corresponding variable name in the # preference key list pref_key = findPrefKey( pref_keyString ) #add preference key and its corresponding value to the dictionary if pref_key: env.prefs[pref_key] = pref_valueToStore favoriteFile.close() #check if a copy of this file exists in the favorites directory. If not make # a copy of it in there favName = os.path.basename(str(filename)) name = favName[0:len(favName)-4] favfilepath = getFavoritePathFromBasename(name) if not os.path.exists(favfilepath): saveFavoriteFile(favfilepath, filename) return 1 def findPrefKey( pref_keyString ): """ Matches prefence key in the dnaDisplayStylePrefsList with pref_keyString from the favorte file that we intend to load. @param pref_keyString: preference from the favorite file to be loaded. @type pref_keyString: string @note: very inefficient since worst case time taken is proportional to the size of the list. If original preference strings are in a dictionary, access can be done in constant time """ for keys in dnaDisplayStylePrefsList: #split keys in dnaDisplayStylePrefList into version number and pref_key pref_array= keys.split("/") if pref_array[1] == pref_keyString: return keys return None def saveFavoriteFile( savePath, fromPath ): """ Save favorite file to anywhere in the disk @param savePath: full path for the location where the favorite file is to be saved. @type savePath: string @param savePath: ~/Nanorex/Favorites/DnaDisplayStyle/$FAV_NAME.txt @type fromPath: string """ if savePath: saveFile = open(savePath, 'w') if fromPath: fromFile = open(fromPath, 'r') lines=fromFile.readlines() saveFile.writelines(lines) saveFile.close() fromFile.close() return # = _superclass = Command_PropertyManager class DnaDisplayStyle_PropertyManager( Command_PropertyManager): """ The DnaDisplayStyle_PropertyManager class provides a Property Manager for the B{Display Style} command on the flyout toolbar in the Build > Dna mode. @ivar title: The title that appears in the property manager header. @type title: str @ivar pmName: The name of this property manager. This is used to set the name of the PM_Dialog object via setObjectName(). @type name: str @ivar iconPath: The relative path to the PNG file that contains a 22 x 22 icon image that appears in the PM header. @type iconPath: str """ title = "Edit DNA Display Style" pmName = title iconPath = "ui/actions/Command Toolbar/BuildDna/EditDnaDisplayStyle.png" def __init__( self, command ): """ Constructor for the property manager. """ self.currentWorkingDirectory = env.prefs[workingDirectory_prefs_key] _superclass.__init__(self, command) self.showTopRowButtons( PM_DONE_BUTTON | \ PM_WHATS_THIS_BUTTON) msg = "Modify the DNA display settings below." self.updateMessage(msg) 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 # Favorite buttons signal-slot connections. change_connect( self.applyFavoriteButton, SIGNAL("clicked()"), self.applyFavorite) change_connect( self.addFavoriteButton, SIGNAL("clicked()"), self.addFavorite) change_connect( self.deleteFavoriteButton, SIGNAL("clicked()"), self.deleteFavorite) change_connect( self.saveFavoriteButton, SIGNAL("clicked()"), self.saveFavorite) change_connect( self.loadFavoriteButton, SIGNAL("clicked()"), self.loadFavorite) # Current display settings groupbox. change_connect( self.dnaRenditionComboBox, SIGNAL("currentIndexChanged(int)"), self.change_dnaRendition ) # Axis options. change_connect( self.axisShapeComboBox, SIGNAL("currentIndexChanged(int)"), self.win.userPrefs.change_dnaStyleAxisShape ) change_connect( self.axisScaleDoubleSpinBox, SIGNAL("valueChanged(double)"), self.win.userPrefs.change_dnaStyleAxisScale ) change_connect( self.axisColorComboBox, SIGNAL("currentIndexChanged(int)"), self.win.userPrefs.change_dnaStyleAxisColor ) change_connect( self.axisEndingStyleComboBox, SIGNAL("currentIndexChanged(int)"), self.win.userPrefs.change_dnaStyleAxisEndingStyle ) # Strands options. change_connect( self.strandsShapeComboBox, SIGNAL("currentIndexChanged(int)"), self.win.userPrefs.change_dnaStyleStrandsShape ) change_connect( self.strandsScaleDoubleSpinBox, SIGNAL("valueChanged(double)"), self.win.userPrefs.change_dnaStyleStrandsScale ) change_connect( self.strandsColorComboBox, SIGNAL("currentIndexChanged(int)"), self.win.userPrefs.change_dnaStyleStrandsColor ) change_connect( self.strandsArrowsComboBox, SIGNAL("currentIndexChanged(int)"), self.win.userPrefs.change_dnaStyleStrandsArrows ) # Structs options. change_connect( self.strutsShapeComboBox, SIGNAL("currentIndexChanged(int)"), self.win.userPrefs.change_dnaStyleStrutsShape ) change_connect( self.strutsScaleDoubleSpinBox, SIGNAL("valueChanged(double)"), self.win.userPrefs.change_dnaStyleStrutsScale ) change_connect( self.strutsColorComboBox, SIGNAL("currentIndexChanged(int)"), self.win.userPrefs.change_dnaStyleStrutsColor ) # Nucleotides options. change_connect( self.nucleotidesShapeComboBox, SIGNAL("currentIndexChanged(int)"), self.win.userPrefs.change_dnaStyleBasesShape ) change_connect( self.nucleotidesScaleDoubleSpinBox, SIGNAL("valueChanged(double)"), self.win.userPrefs.change_dnaStyleBasesScale ) change_connect( self.nucleotidesColorComboBox, SIGNAL("currentIndexChanged(int)"), self.win.userPrefs.change_dnaStyleBasesColor ) connect_checkbox_with_boolean_pref( self.dnaStyleBasesDisplayLettersCheckBox, dnaStyleBasesDisplayLetters_prefs_key) # Dna Strand labels option. change_connect( self.standLabelColorComboBox, SIGNAL("currentIndexChanged(int)"), self.change_dnaStrandLabelsDisplay ) def show(self): """ Shows the Property Manager. Extends superclass method """ _superclass.show(self) #@REVIEW: Is it safe to do the follwoing before calling superclass.show()? #-- Ninad 2008-10-02 # Force the Global Display Style to "DNA Cylinder" so the user # can see the display style setting effects on any DNA in the current # model. The current global display style will be restored when leaving # this command (via self.close()). self.originalDisplayStyle = self.o.displayMode # TODO: rename that public attr of GLPane (widely used) # from displayMode to displayStyle. [bruce 080910 comment] self.o.setGlobalDisplayStyle(diDNACYLINDER) # Update all PM widgets, . # note: It is important to update the widgets by blocking the # 'signals'. If done in the reverse order, it will generate signals #when updating the PM widgets (via updateDnaDisplayStyleWidgets()), #causing unneccessary repaints of the model view. self.updateDnaDisplayStyleWidgets(blockSignals = True) def close(self): """ Closes the Property Manager. Extends superclass method. """ _superclass.close(self) # Restore the original global display style. self.o.setGlobalDisplayStyle(self.originalDisplayStyle) def _addGroupBoxes( self ): """ Add the Property Manager group boxes. """ self._pmGroupBox1 = PM_GroupBox( self, title = "Favorites") self._loadGroupBox1( self._pmGroupBox1 ) self._pmGroupBox2 = PM_GroupBox( self, title = "Current Display Settings") self._loadGroupBox2( self._pmGroupBox2 ) def _loadGroupBox1(self, pmGroupBox): """ Load widgets in group box. """ # Other info # Not only loads the factory default settings but also all the favorite # files stored in the ~/Nanorex/Favorites/DnaDisplayStyle directory favoriteChoices = ['Factory default settings'] #look for all the favorite files in the favorite folder and add them to # the list from platform_dependent.PlatformDependent import find_or_make_Nanorex_subdir _dir = find_or_make_Nanorex_subdir('Favorites/DnaDisplayStyle') for file in os.listdir(_dir): fullname = os.path.join( _dir, file) if os.path.isfile(fullname): if fnmatch.fnmatch( file, "*.txt"): # leave the extension out favoriteChoices.append(file[0:len(file)-4]) self.favoritesComboBox = \ PM_ComboBox( pmGroupBox, choices = favoriteChoices, spanWidth = True) self.favoritesComboBox.setWhatsThis( """<b> List of Favorites </b> <p> Creates a list of favorite DNA display styles. Once favorite styles have been added to the list using the Add Favorite button, the list will display the chosen favorites. To change the current favorite, select a current favorite from the list, and push the Apply Favorite button.""") # PM_ToolButtonRow =============== # Button list to create a toolbutton row. # Format: # - QToolButton, buttonId, buttonText, # - iconPath, # - tooltip, shortcut, column BUTTON_LIST = [ ( "QToolButton", 1, "APPLY_FAVORITE", "ui/actions/Properties Manager/ApplyFavorite.png", "Apply Favorite", "", 0), ( "QToolButton", 2, "ADD_FAVORITE", "ui/actions/Properties Manager/AddFavorite.png", "Add Favorite", "", 1), ( "QToolButton", 3, "DELETE_FAVORITE", "ui/actions/Properties Manager/DeleteFavorite.png", "Delete Favorite", "", 2), ( "QToolButton", 4, "SAVE_FAVORITE", "ui/actions/Properties Manager/SaveFavorite.png", "Save Favorite", "", 3), ( "QToolButton", 5, "LOAD_FAVORITE", "ui/actions/Properties Manager/LoadFavorite.png", "Load Favorite", \ "", 4) ] self.favsButtonGroup = \ PM_ToolButtonRow( pmGroupBox, title = "", buttonList = BUTTON_LIST, spanWidth = True, isAutoRaise = False, isCheckable = False, setAsDefault = True, ) self.favsButtonGroup.buttonGroup.setExclusive(False) self.applyFavoriteButton = self.favsButtonGroup.getButtonById(1) self.addFavoriteButton = self.favsButtonGroup.getButtonById(2) self.deleteFavoriteButton = self.favsButtonGroup.getButtonById(3) self.saveFavoriteButton = self.favsButtonGroup.getButtonById(4) self.loadFavoriteButton = self.favsButtonGroup.getButtonById(5) def _loadGroupBox2(self, pmGroupBox): """ Load widgets in group box. """ dnaRenditionChoices = ['3D (default)', '2D with base letters', '2D ball and stick', '2D ladder'] self.dnaRenditionComboBox = \ PM_ComboBox( pmGroupBox, label = "Rendition:", choices = dnaRenditionChoices, setAsDefault = True) dnaComponentChoices = ['Axis', 'Strands', 'Struts', 'Nucleotides'] self.dnaComponentComboBox = \ PM_ComboBox( pmGroupBox, label = "Component:", choices = dnaComponentChoices, setAsDefault = True) self._loadAxisGroupBox() self._loadStrandsGroupBox() self._loadStrutsGroupBox() self._loadNucleotidesGroupBox() widgetList = [self.axisGroupBox, self.strandsGroupBox, self.strutsGroupBox, self.nucleotidesGroupBox] self.dnaComponentStackedWidget = \ PM_StackedWidget( pmGroupBox, self.dnaComponentComboBox, widgetList ) standLabelColorChoices = ['Hide', 'Show (in strand color)', 'Black', 'White', 'Custom color...'] self.standLabelColorComboBox = \ PM_ComboBox( pmGroupBox, label = "Strand labels:", choices = standLabelColorChoices, setAsDefault = True) # This disables "Component" widgets if rendition style is 2D. self.change_dnaRendition(env.prefs[dnaRendition_prefs_key]) def _loadAxisGroupBox(self): """ Load the Axis group box. """ axisGroupBox = PM_GroupBox( None ) self.axisGroupBox = axisGroupBox axisShapeChoices = ['None', 'Wide tube', 'Narrow tube'] self.axisShapeComboBox = \ PM_ComboBox( axisGroupBox , label = "Shape:", choices = axisShapeChoices, setAsDefault = True) self.axisScaleDoubleSpinBox = \ PM_DoubleSpinBox( axisGroupBox, label = "Scale:", value = 1.00, setAsDefault = True, minimum = 0.1, maximum = 2.0, decimals = 2, singleStep = 0.1 ) axisColorChoices = ['Same as chunk', 'Base order', 'Base order (discrete)', 'Base type', 'Strand order'] self.axisColorComboBox = \ PM_ComboBox( axisGroupBox , label = "Color:", choices = axisColorChoices, setAsDefault = True) endingTypeChoices = ['Flat', 'Taper start', 'Taper end', 'Taper both', 'Spherical'] self.axisEndingStyleComboBox = \ PM_ComboBox( axisGroupBox , label = "Ending style:", choices = endingTypeChoices, setAsDefault = True) def _loadStrandsGroupBox(self): """ Load the Strands group box. """ strandsGroupBox = PM_GroupBox( None ) self.strandsGroupBox = strandsGroupBox strandsShapeChoices = ['None', 'Cylinders', 'Tube'] self.strandsShapeComboBox = \ PM_ComboBox( strandsGroupBox , label = "Shape:", choices = strandsShapeChoices, setAsDefault = True) self.strandsScaleDoubleSpinBox = \ PM_DoubleSpinBox( strandsGroupBox, label = "Scale:", value = 1.00, setAsDefault = True, minimum = 0.1, maximum = 5.0, decimals = 2, singleStep = 0.1 ) strandsColorChoices = ['Same as chunk', 'Base order', 'Strand order'] self.strandsColorComboBox = \ PM_ComboBox( strandsGroupBox , label = "Color:", choices = strandsColorChoices, setAsDefault = True) strandsArrowsChoices = ['None', '5\'', '3\'', '5\' and 3\''] self.strandsArrowsComboBox = \ PM_ComboBox( strandsGroupBox , label = "Arrows:", choices = strandsArrowsChoices, setAsDefault = True) def _loadStrutsGroupBox(self): """ Load the Struts group box. """ strutsGroupBox = PM_GroupBox( None ) self.strutsGroupBox = strutsGroupBox strutsShapeChoices = ['None', 'Base-axis-base cylinders', 'Straight cylinders'] self.strutsShapeComboBox = \ PM_ComboBox( strutsGroupBox , label = "Shape:", choices = strutsShapeChoices, setAsDefault = True) self.strutsScaleDoubleSpinBox = \ PM_DoubleSpinBox( strutsGroupBox, label = "Scale:", value = 1.00, setAsDefault = True, minimum = 0.1, maximum = 3.0, decimals = 2, singleStep = 0.1 ) strutsColorChoices = ['Same as strand', 'Base order', 'Strand order', 'Base type'] self.strutsColorComboBox = \ PM_ComboBox( strutsGroupBox , label = "Color:", choices = strutsColorChoices, setAsDefault = True) def _loadNucleotidesGroupBox(self): """ Load the Nucleotides group box. """ nucleotidesGroupBox = PM_GroupBox( None ) self.nucleotidesGroupBox = nucleotidesGroupBox nucleotidesShapeChoices = ['None', 'Sugar spheres', 'Base cartoons'] self.nucleotidesShapeComboBox = \ PM_ComboBox( nucleotidesGroupBox , label = "Shape:", choices = nucleotidesShapeChoices, setAsDefault = True) self.nucleotidesScaleDoubleSpinBox = \ PM_DoubleSpinBox( nucleotidesGroupBox, label = "Scale:", value = 1.00, setAsDefault = True, minimum = 0.1, maximum = 3.0, decimals = 2, singleStep = 0.1 ) nucleotidesColorChoices = ['Same as strand', 'Base order', 'Strand order', 'Base type'] self.nucleotidesColorComboBox = \ PM_ComboBox( nucleotidesGroupBox , label = "Color:", choices = nucleotidesColorChoices, setAsDefault = True) self.dnaStyleBasesDisplayLettersCheckBox = \ PM_CheckBox(nucleotidesGroupBox , text = 'Display base letters', widgetColumn = 1 ) def updateDnaDisplayStyleWidgets( self , blockSignals = False): """ Updates all the DNA Display style widgets based on the current pref keys values. @param blockSignals: If its set to True, the set* methods of the the widgets (currently only PM_ Spinboxes and ComboBoxes) won't emit a signal. @type blockSignals: bool @see: self.show() where this method is called. @see: PM_Spinbox.setValue() @see: PM_ComboBox.setCurrentIndex() @note: This should be called each time the PM is displayed (see show()). """ self.dnaRenditionComboBox.setCurrentIndex( env.prefs[dnaRendition_prefs_key], blockSignals = blockSignals ) self.axisShapeComboBox.setCurrentIndex( env.prefs[dnaStyleAxisShape_prefs_key], blockSignals = blockSignals) self.axisScaleDoubleSpinBox.setValue( env.prefs[dnaStyleAxisScale_prefs_key], blockSignals = blockSignals) self.axisColorComboBox.setCurrentIndex( env.prefs[dnaStyleAxisColor_prefs_key], blockSignals = blockSignals) self.axisEndingStyleComboBox.setCurrentIndex( env.prefs[dnaStyleAxisEndingStyle_prefs_key], blockSignals = blockSignals) self.strandsShapeComboBox.setCurrentIndex( env.prefs[dnaStyleStrandsShape_prefs_key], blockSignals = blockSignals) self.strandsScaleDoubleSpinBox.setValue( env.prefs[dnaStyleStrandsScale_prefs_key], blockSignals = blockSignals) self.strandsColorComboBox.setCurrentIndex( env.prefs[dnaStyleStrandsColor_prefs_key], blockSignals = blockSignals) self.strandsArrowsComboBox.setCurrentIndex( env.prefs[dnaStyleStrandsArrows_prefs_key], blockSignals = blockSignals) self.strutsShapeComboBox.setCurrentIndex( env.prefs[dnaStyleStrutsShape_prefs_key], blockSignals = blockSignals) self.strutsScaleDoubleSpinBox.setValue( env.prefs[dnaStyleStrutsScale_prefs_key], blockSignals = blockSignals) self.strutsColorComboBox.setCurrentIndex( env.prefs[dnaStyleStrutsColor_prefs_key], blockSignals = blockSignals) self.nucleotidesShapeComboBox.setCurrentIndex( env.prefs[dnaStyleBasesShape_prefs_key], blockSignals = blockSignals) self.nucleotidesScaleDoubleSpinBox.setValue( env.prefs[dnaStyleBasesScale_prefs_key], blockSignals = blockSignals) self.nucleotidesColorComboBox.setCurrentIndex( env.prefs[dnaStyleBasesColor_prefs_key], blockSignals = blockSignals) # DNA Strand label combobox. if env.prefs[dnaStrandLabelsEnabled_prefs_key]: _dnaStrandColorItem = env.prefs[dnaStrandLabelsColorMode_prefs_key] + 1 else: _dnaStrandColorItem = 0 self.standLabelColorComboBox.setCurrentIndex( _dnaStrandColorItem, blockSignals = blockSignals) def change_dnaStrandLabelsDisplay(self, mode): """ Changes DNA Strand labels display (and color) mode. @param mode: The display mode: - 0 = hide all labels - 1 = show (same color as chunk) - 2 = show (black) - 3 = show (white) - 4 = show (custom color...) @type mode: int """ if mode == 4: self.win.userPrefs.change_dnaStrandLabelsColor() if mode == 0: #@ Fix this at the same time I (we) remove the DNA display style # prefs options from the Preferences dialog. --Mark 2008-05-13 self.win.userPrefs.toggle_dnaDisplayStrandLabelsGroupBox(False) else: self.win.userPrefs.toggle_dnaDisplayStrandLabelsGroupBox(True) self.win.userPrefs.change_dnaStrandLabelsColorMode(mode - 1) def applyFavorite(self): """ Apply the DNA display style settings stored in the current favorite (selected in the combobox) to the current DNA display style settings. """ # Rules and other info: # The user has to press the button related to this method when he loads # a previously saved favorite file current_favorite = self.favoritesComboBox.currentText() if current_favorite == 'Factory default settings': env.prefs.restore_defaults(dnaDisplayStylePrefsList) else: favfilepath = getFavoritePathFromBasename(current_favorite) loadFavoriteFile(favfilepath) self.updateDnaDisplayStyleWidgets() return def addFavorite(self): """ Adds a new favorite to the user's list of favorites. """ # Rules and other info: # - The new favorite is defined by the current DNA display style # settings. # - The user is prompted to type in a name for the new # favorite. # - The DNA display style settings are written to a file in a special # directory on the disk # (i.e. $HOME/Nanorex/Favorites/DnaDisplayStyle/$FAV_NAME.fav). # - The name of the new favorite is added to the list of favorites in # the combobox, which becomes the current option. # Existence of a favorite with the same name is checked in the above # mentioned location and if a duplicate exists, then the user can either # overwrite and provide a new name. # Prompt user for a favorite name to add. from widgets.simple_dialogs import grab_text_line_using_dialog ok1, name = \ grab_text_line_using_dialog( title = "Add new favorite", label = "favorite name:", iconPath = "ui/actions/Properties Manager/AddFavorite.png", default = "" ) if ok1: # check for duplicate files in the # $HOME/Nanorex/Favorites/DnaDisplayStyle/ directory fname = getFavoritePathFromBasename( name ) if os.path.exists(fname): #favorite file already exists! _ext= ".txt" ret = QMessageBox.warning( self, "Warning!", "The favorite file \"" + name + _ext + "\"already exists.\n" "Do you want to overwrite the existing file?", "&Overwrite", "&Cancel", "", 0, # Enter == button 0 1) # Escape == button 1 if ret == 0: #overwrite favorite file ok2, text = writeDnaDisplayStyleSettingsToFavoritesFile(name) indexOfDuplicateItem = self.favoritesComboBox.findText(name) self.favoritesComboBox.removeItem(indexOfDuplicateItem) print "Add Favorite: removed duplicate favorite item." else: env.history.message("Add Favorite: cancelled overwriting favorite item.") return else: ok2, text = writeDnaDisplayStyleSettingsToFavoritesFile(name) else: # User cancelled. return if ok2: self.favoritesComboBox.addItem(name) _lastItem = self.favoritesComboBox.count() self.favoritesComboBox.setCurrentIndex(_lastItem - 1) msg = "New favorite [%s] added." % (text) else: msg = "Can't add favorite [%s]: %s" % (name, text) # text is reason why not env.history.message(msg) return def deleteFavorite(self): """ Deletes the current favorite from the user's personal list of favorites (and from disk, only in the favorites folder though). @note: Cannot delete "Factory default settings". """ currentIndex = self.favoritesComboBox.currentIndex() currentText = self.favoritesComboBox.currentText() if currentIndex == 0: msg = "Cannot delete '%s'." % currentText else: self.favoritesComboBox.removeItem(currentIndex) # delete file from the disk deleteFile= getFavoritePathFromBasename( currentText ) os.remove(deleteFile) msg = "Deleted favorite named [%s].\n" \ "and the favorite file [%s.txt]." \ % (currentText, currentText) env.history.message(msg) return def saveFavorite(self): """ Writes the current favorite (selected in the combobox) to a file, any where in the disk that can be given to another NE1 user (i.e. as an email attachment). """ cmd = greenmsg("Save Favorite File: ") env.history.message(greenmsg("Save Favorite File:")) current_favorite = self.favoritesComboBox.currentText() favfilepath = getFavoritePathFromBasename(current_favorite) #Check to see if favfilepath exists first if not os.path.exists(favfilepath): msg = "%s does not exist" % favfilepath env.history.message(cmd + msg) return formats = \ "Favorite (*.txt);;"\ "All Files (*.*)" directory = self.currentWorkingDirectory saveLocation = directory + "/" + current_favorite + ".txt" fn = QFileDialog.getSaveFileName( self, "Save Favorite As", # caption saveLocation, #where to save formats, # file format options QString("Favorite (*.txt)") # selectedFilter ) if not fn: env.history.message(cmd + "Cancelled") else: dir, fil = os.path.split(str(fn)) self.setCurrentWorkingDirectory(dir) saveFavoriteFile(str(fn), favfilepath) return def setCurrentWorkingDirectory(self, dir = None): if os.path.isdir(dir): self.currentWorkingDirectory = dir self._setWorkingDirectoryInPrefsDB(dir) else: self.currentWorkingDirectory = getDefaultWorkingDirectory() def _setWorkingDirectoryInPrefsDB(self, workdir = None): """ [private method] Set the working directory in the user preferences database. @param workdir: The fullpath directory to write to the user pref db. If I{workdir} is None (default), there is no change. @type workdir: string """ if not workdir: return workdir = str(workdir) if os.path.isdir(workdir): workdir = os.path.normpath(workdir) env.prefs[workingDirectory_prefs_key] = workdir # Change pref in prefs db. else: msg = "[" + workdir + "] is not a directory. Working directory was not changed." env.history.message( redmsg(msg)) return def loadFavorite(self): """ Prompts the user to choose a "favorite file" (i.e. *.txt) from disk to be added to the personal favorites list. """ # If the file already exists in the favorites folder then the user is # given the option of overwriting it or renaming it env.history.message(greenmsg("Load Favorite File:")) formats = \ "Favorite (*.txt);;"\ "All Files (*.*)" directory = self.currentWorkingDirectory if directory == '': directory= getDefaultWorkingDirectory() fname = QFileDialog.getOpenFileName(self, "Choose a file to load", directory, formats) if not fname: env.history.message("User cancelled loading file.") return else: dir, fil = os.path.split(str(fname)) self.setCurrentWorkingDirectory(dir) canLoadFile=loadFavoriteFile(fname) if canLoadFile == 1: #get just the name of the file for loading into the combobox favName = os.path.basename(str(fname)) name = favName[0:len(favName)-4] indexOfDuplicateItem = self.favoritesComboBox.findText(name) #duplicate exists in combobox if indexOfDuplicateItem != -1: ret = QMessageBox.warning( self, "Warning!", "The favorite file \"" + name + "\"already exists.\n" "Do you want to overwrite the existing file?", "&Overwrite", "&Rename", "&Cancel", 0, # Enter == button 0 1 # button 1 ) if ret == 0: self.favoritesComboBox.removeItem(indexOfDuplicateItem) self.favoritesComboBox.addItem(name) _lastItem = self.favoritesComboBox.count() self.favoritesComboBox.setCurrentIndex(_lastItem - 1) ok2, text = writeDnaDisplayStyleSettingsToFavoritesFile(name) msg = "Overwrote favorite [%s]." % (text) env.history.message(msg) elif ret == 1: # add new item to favorites folder as well as combobox self.addFavorite() else: #reset the display setting values to factory default factoryIndex = self.favoritesComboBox.findText( 'Factory default settings') self.favoritesComboBox.setCurrentIndex(factoryIndex) env.prefs.restore_defaults(dnaDisplayStylePrefsList) env.history.message("Cancelled overwriting favorite file.") return else: self.favoritesComboBox.addItem(name) _lastItem = self.favoritesComboBox.count() self.favoritesComboBox.setCurrentIndex(_lastItem - 1) msg = "Loaded favorite [%s]." % (name) env.history.message(msg) self.updateDnaDisplayStyleWidgets() return def change_dnaRendition(self, rendition): """ Sets the DNA rendition to 3D or one of the optional 2D styles. @param rendition: The rendition mode, where: - 0 = 3D (default) - 1 = 2D with base letters - 2 = 2D ball and stick - 3 = 2D ladder @type rendition: int """ if rendition == 0: _enabled_flag = True else: _enabled_flag = False self.dnaComponentComboBox.setEnabled(_enabled_flag) self.dnaComponentStackedWidget.setEnabled(_enabled_flag) self.standLabelColorComboBox.setEnabled(_enabled_flag) env.prefs[dnaRendition_prefs_key] = rendition self.o.gl_update() # Force redraw return def _addWhatsThisText( self ): """ What's This text for widgets in the DNA Property Manager. """ from ne1_ui.WhatsThisText_for_PropertyManagers import WhatsThis_EditDnaDisplayStyle_PropertyManager WhatsThis_EditDnaDisplayStyle_PropertyManager(self) def _addToolTipText(self): """ Tool Tip text for widgets in the DNA Property Manager. """ from ne1_ui.ToolTipText_for_PropertyManagers import ToolTip_EditDnaDisplayStyle_PropertyManager ToolTip_EditDnaDisplayStyle_PropertyManager(self)
NanoCAD-master
cad/src/dna/commands/DnaDisplayStyle/DnaDisplayStyle_PropertyManager.py
# Copyright 2008 Nanorex, Inc. See LICENSE file for details. """ @author: Mark @version: $Id$ @copyright: 2008 Nanorex, Inc. See LICENSE file for details. """ import foundation.changes as changes from commands.SelectChunks.SelectChunks_GraphicsMode import SelectChunks_GraphicsMode from command_support.EditCommand import EditCommand from utilities.constants import red from dna.commands.DnaDisplayStyle.DnaDisplayStyle_PropertyManager import DnaDisplayStyle_PropertyManager from graphics.drawing.drawDnaLabels import draw_dnaBaseNumberLabels # == GraphicsMode part _superclass_for_GM = SelectChunks_GraphicsMode class DnaDisplayStyle_GraphicsMode( SelectChunks_GraphicsMode ): """ Graphics mode for (DNA) Display Style command. """ def _drawLabels(self): """ Overrides suoerclass method. @see: GraphicsMode._drawLabels() """ _superclass_for_GM._drawLabels(self) draw_dnaBaseNumberLabels(self.glpane) # == Command part class DnaDisplayStyle_Command(EditCommand): """ """ # class constants GraphicsMode_class = DnaDisplayStyle_GraphicsMode PM_class = DnaDisplayStyle_PropertyManager commandName = 'EDIT_DNA_DISPLAY_STYLE' featurename = "DNA Display Style" from utilities.constants import CL_GLOBAL_PROPERTIES command_level = CL_GLOBAL_PROPERTIES command_should_resume_prevMode = True command_has_its_own_PM = True flyoutToolbar = None def _getFlyoutToolBarActionAndParentCommand(self): """ See superclass for documentation. @see: self.command_update_flyout() """ flyoutActionToCheck = 'editDnaDisplayStyleAction' parentCommandName = 'BUILD_DNA' return flyoutActionToCheck, parentCommandName def keep_empty_group(self, group): """ Returns True if the empty group should not be automatically deleted. otherwise returns False. The default implementation always returns False. Subclasses should override this method if it needs to keep the empty group for some reasons. Note that this method will only get called when a group has a class constant autdelete_when_empty set to True. (and as of 2008-03-06, it is proposed that dna_updater calls this method when needed. @see: Command.keep_empty_group() which is overridden here. """ bool_keep = EditCommand.keep_empty_group(self, group) if not bool_keep: #Lets just not delete *ANY* DnaGroup while in DnaDisplayStyle_Command #Although DnaDisplayStyle command can only be accessed through #BuildDna_EditCommand, it could happen (due to a bug) that the #previous command is not BuildDna_Editcommand. So bool_keep #in that case will return False propmting dna updater to even delete #the empty DnaGroup (if it becomes empty for some reasons) of the #BuildDna command. To avoid this ,this method will instruct # to keep all instances of DnaGroup even when they might be empty. if isinstance(group, self.assy.DnaGroup): bool_keep = True #Commented out code that shows what I was planning to implement #earlier. ##previousCommand = self.commandSequencer.prevMode # keep_empty_group: .struct ##if previousCommand.commandName == 'BUILD_DNA': ##if group is previousCommand.struct: ##bool_keep = True return bool_keep
NanoCAD-master
cad/src/dna/commands/DnaDisplayStyle/DnaDisplayStyle_Command.py
NanoCAD-master
cad/src/dna/commands/DnaDisplayStyle/__init__.py
# Copyright 2008-2009 Nanorex, Inc. See LICENSE file for details. """ Graphics mode intended to be used while in DnaSegment_EditCommand. While in this command, user can (a) Highlight and then left drag the resize handles located at the two 'axis endpoints' of thje segment to change its length. (b) Highlight and then left drag any axis atom (except the two end axis atoms) to translate the whole segment along the axis (c) Highlight and then left drag any strand atom to rotate the segment around its axis. Note that implementation b and c may change slightly if we implement special handles to do these oprations. @author: Ninad @version: $Id$ @copyright: 2008-2009 Nanorex, Inc. See LICENSE file for details. History: Created 2008-01-25 TODO: as of 2008-02-01: - This graphics mode uses some duplicated code from Move_GraphicsMode (for rotating or translating about own axis .. its a small portion and simpler to understand) and also from DnaLine_GM (mainly the drawing code). Ideally, it should switch to these graphics modes while remaining in the same command (using command.switchGraphicsModeTo method) But it poses problems. Issues related to use of DnaLine_GM are mentioned in DnaSegment_EditCommand. In future, we may need to incorporate more functionality from these graphics modes so this should be refactored then. - Need to review methods in self.leftDrag and self.leftDown ..there might be some bugs...not sure. """ import foundation.env as env from dna.commands.BuildDna.BuildDna_GraphicsMode import BuildDna_GraphicsMode from graphics.drawing.drawDnaRibbons import drawDnaRibbons from graphics.drawing.CS_draw_primitives import drawcylinder from utilities.constants import darkred, black, orange from model.chem import Atom from utilities.prefs_constants import dnaSegmentResizeHandle_discRadius_prefs_key from utilities.prefs_constants import dnaSegmentResizeHandle_discThickness_prefs_key from geometry.VQT import norm SPHERE_RADIUS = 2.0 SPHERE_DRAWLEVEL = 2 _superclass = BuildDna_GraphicsMode class DnaSegment_GraphicsMode(BuildDna_GraphicsMode): """ Graphics mode for DnaSegment_EditCommand. """ _sphereColor = darkred _sphereOpacity = 0.5 #The flag that decides whether to draw the handles. This flag is #set during left dragging, when no handle is 'grabbed'. This optimizes the #drawing code as it skips handle drawing code and also the computation #of handle positions each time the mouse moves #@see self.Draw_other, and comments in superclass, for more details _handleDrawingRequested = True #Some left drag variables used to drag the whole segment along axis or #rotate the segment around its own axis of for free drag translation _movablesForLeftDrag = [] #The common center is the center about which the list of movables (the segment #contents are rotated. #@see: self.leftADown where this is set. #@see: self.leftDrag where it is used. _commonCenterForRotation = None _axis_for_constrained_motion = None #Flags that decide the type of left drag. #@see: self.leftADown where it is set and self.leftDrag where these are used _translateAlongAxis = False _rotateAboutAxis = False _freeDragWholeStructure = False cursor_over_when_LMB_pressed = '' def Enter_GraphicsMode(self): _superclass.Enter_GraphicsMode(self) #Precaution self.clear_leftA_variables() def bareMotion(self, event): """ @see: self.update_cursor_for_no_MB """ value = _superclass.bareMotion(self, event) #When the cursor is over a specific atom, we need to display #a different icon. (e.g. when over a strand atom, it should display # rotate cursor) self.update_cursor() return value def update_cursor_for_no_MB(self): """ Update the cursor for Select mode (Default implementation). """ _superclass.update_cursor_for_no_MB(self) #minor optimization -- don't go further into the method if #nothing is highlighted i.e. self.o.selobj is None. if self.o.selobj is None: return if self.command and hasattr(self.command.struct, 'isAncestorOf'): if not self.command.struct.isAncestorOf(self.o.selobj): return if self.o.modkeys is None: if isinstance(self.o.selobj, Atom): if self.o.selobj.element.role == 'strand': self.o.setCursor(self.win.rotateAboutCentralAxisCursor) else: self.o.setCursor(self.win.translateAlongCentralAxisCursor) def clear_leftA_variables(self): self._movablesForLeftDrag = [] self._commonCenterForRotation = None self._axis_for_constrained_motion = None _translateAlongAxis = False _rotateAboutAxis = False _freeDragWholeStructure = False def _leftDown_preparation_for_dragging(self, objectUnderMouse, event): """ Handle left down event. Preparation for rotation and/or selection This method is called inside of self.leftDown. @param event: The mouse left down event. @type event: QMouseEvent instance @see: self.leftDown @see: self.leftDragRotation Overrides _superclass._leftDown_preparation_for_dragging """ self.o.SaveMouse(event) self.picking = True self.dragdist = 0.0 farQ_junk, self.movingPoint = self.dragstart_using_GL_DEPTH( event) self.leftADown(objectUnderMouse, event) def Draw_other(self): """ Draw handles (if any) of our DnaSegment. @see:self._drawCursorText() @see:self._drawHandles() """ _superclass.Draw_other(self) if self._handleDrawingRequested: self._drawHandles() def _drawHandles(self): """ Draw the handles for the command.struct @see: DnaSegment_EditCommand.getDnaRibbonParams() @see: self._drawCursorText() @see: self.Draw_other() """ if self.command and self.command.hasValidStructure(): for handle in self.command.handles: if handle.hasValidParamsForDrawing(): handle.draw() self._drawDnaRubberbandLine() def _drawDnaRubberbandLine(self): handleType = '' if self.command.grabbedHandle is not None: if self.command.grabbedHandle in [self.command.rotationHandle1, self.command.rotationHandle2]: handleType = 'ROTATION_HANDLE' else: handleType = 'RESIZE_HANDLE' if handleType and handleType == 'RESIZE_HANDLE': params = self.command.getDnaRibbonParams() if params: end1, end2, basesPerTurn, duplexRise, ribbon1_start_point, \ ribbon2_start_point, ribbon1_direction, ribbon2_direction,\ ribbon1Color, ribbon2Color = params #Note: The displayStyle argument for the rubberband line should #really be obtained from self.command.struct. But the struct #is a DnaSegment (a Group) and doesn't have attr 'display' #Should we then obtain this information from one of its strandChunks? #but what if two strand chunks and axis chunk are rendered #in different display styles? since situation may vary, lets #use self.glpane.displayMode for rubberbandline displayMode drawDnaRibbons(self.glpane, end1, end2, basesPerTurn, duplexRise, self.glpane.scale, self.glpane.lineOfSight, self.glpane.displayMode, ribbonThickness = 4.0, ribbon1_start_point = ribbon1_start_point, ribbon2_start_point = ribbon2_start_point, ribbon1_direction = ribbon1_direction, ribbon2_direction = ribbon2_direction, ribbon1Color = ribbon1Color, ribbon2Color = ribbon2Color, ) #Draw the text next to the cursor that gives info about #number of base pairs etc self._drawCursorText() return pass # end
NanoCAD-master
cad/src/dna/commands/DnaSegment/DnaSegment_GraphicsMode.py
# Copyright 2008-2009 Nanorex, Inc. See LICENSE file for details. """ DnaSegment_EditCommand provides a way to edit an existing DnaSegment. To edit a segment, first enter BuildDna_EditCommand (accessed using Build> Dna) then, select an axis chunk of an existing DnaSegment within the DnaGroup you are editing. When you select the axis chunk, it enters DnaSegment_Editcommand and shows the property manager with its widgets showing the properties of selected segment. While in this command, user can (a) Highlight and then left drag the resize handles located at the two 'axis endpoints' of thje segment to change its length. (b) Highlight and then left drag any axis atom (except the two end axis atoms) to translate the whole segment along the axis (c) Highlight and then left drag any strand atom to rotate the segment around its axis. Note that implementation b and c may change slightly if we implement special handles to do these oprations. See also: DnaSegment_GraphicsMode .. the default graphics mode for this command @author: Ninad @version: $Id$ @copyright: 2008-2009 Nanorex, Inc. See LICENSE file for details. History: Ninad 2008-01-18: Created TODO: - Needs cleanup and REFACTORING. """ import foundation.env as env from command_support.EditCommand import EditCommand from utilities.exception_classes import PluginBug, UserError from geometry.VQT import V, Veq, vlen from geometry.VQT import cross, norm from Numeric import dot from utilities.constants import gensym from utilities.Log import redmsg from exprs.State_preMixin import State_preMixin from exprs.attr_decl_macros import Instance, State from exprs.__Symbols__ import _self from exprs.Exprs import call_Expr from exprs.Exprs import norm_Expr from exprs.ExprsConstants import Width, Point from widgets.prefs_widgets import ObjAttr_StateRef from model.chunk import Chunk from model.chem import Atom from model.bonds import Bond from utilities.constants import noop from utilities.constants import black, applegreen from utilities.Comparison import same_vals from graphics.drawables.RotationHandle import RotationHandle from dna.model.DnaSegment import DnaSegment from dna.model.Dna_Constants import getDuplexRise from dna.model.Dna_Constants import getNumberOfBasePairsFromDuplexLength from dna.model.Dna_Constants import getDuplexLength from dna.generators.B_Dna_PAM3_Generator import B_Dna_PAM3_Generator from dna.generators.B_Dna_PAM5_Generator import B_Dna_PAM5_Generator from dna.commands.DnaSegment.DnaSegment_ResizeHandle import DnaSegment_ResizeHandle from dna.commands.DnaSegment.DnaSegment_GraphicsMode import DnaSegment_GraphicsMode from utilities.prefs_constants import dnaSegmentEditCommand_cursorTextCheckBox_numberOfBasePairs_prefs_key from utilities.prefs_constants import dnaSegmentEditCommand_cursorTextCheckBox_length_prefs_key from utilities.prefs_constants import dnaSegmentEditCommand_showCursorTextCheckBox_prefs_key from utilities.prefs_constants import dnaSegmentEditCommand_cursorTextCheckBox_changedBasePairs_prefs_key from utilities.prefs_constants import dnaSegmentResizeHandle_discRadius_prefs_key from utilities.prefs_constants import dnaSegmentResizeHandle_discThickness_prefs_key from utilities.prefs_constants import cursorTextColor_prefs_key from dna.model.Dna_Constants import getDuplexLength from dna.commands.DnaSegment.DnaSegment_PropertyManager import DnaSegment_PropertyManager CYLINDER_WIDTH_DEFAULT_VALUE = 0.0 HANDLE_RADIUS_DEFAULT_VALUE = 1.2 ORIGIN = V(0,0,0) #Flag that appends rotation handles to the self.handles (thus enabling their #display and computation while in DnaSegment_EditCommand DEBUG_ROTATION_HANDLES = False _superclass = EditCommand class DnaSegment_EditCommand(State_preMixin, EditCommand): """ Command to edit a DnaSegment object. To edit a segment, first enter BuildDna_EditCommand (accessed using Build> Dna) then, select an axis chunk of an existing DnaSegment within the DnaGroup you are editing. When you select the axis chunk, it enters DnaSegment_Editcommand and shows the property manager with its widgets showing the properties of selected segment. """ #Graphics Mode GraphicsMode_class = DnaSegment_GraphicsMode #Property Manager PM_class = DnaSegment_PropertyManager cmd = 'Dna Segment' prefix = 'Segment ' # used for gensym cmdname = "DNA_SEGMENT" commandName = 'DNA_SEGMENT' featurename = "Edit Dna Segment" from utilities.constants import CL_SUBCOMMAND command_level = CL_SUBCOMMAND command_parent = 'BUILD_DNA' command_should_resume_prevMode = True command_has_its_own_PM = True # Generators for DNA, nanotubes and graphene have their MT name # generated (in GeneratorBaseClass) from the prefix. create_name_from_prefix = True call_makeMenus_for_each_event = True #This is set to BuildDna_EditCommand.flyoutToolbar (as of 2008-01-14, #it only uses flyoutToolbar = None handlePoint1 = State( Point, ORIGIN) handlePoint2 = State( Point, ORIGIN) #The minimum 'stopper'length used for resize handles #@see: self._update_resizeHandle_stopper_length for details. _resizeHandle_stopper_length = State(Width, -100000) rotationHandleBasePoint1 = State( Point, ORIGIN) rotationHandleBasePoint2 = State( Point, ORIGIN) #See self._update_resizeHandle_radius where this gets changed. #also see DnaSegment_ResizeHandle to see how its implemented. handleSphereRadius1 = State(Width, HANDLE_RADIUS_DEFAULT_VALUE) handleSphereRadius2 = State(Width, HANDLE_RADIUS_DEFAULT_VALUE) cylinderWidth = State(Width, CYLINDER_WIDTH_DEFAULT_VALUE) cylinderWidth2 = State(Width, CYLINDER_WIDTH_DEFAULT_VALUE) #@TODO: modify the 'State params for rotation_distance rotation_distance1 = State(Width, CYLINDER_WIDTH_DEFAULT_VALUE) rotation_distance2 = State(Width, CYLINDER_WIDTH_DEFAULT_VALUE) duplexRise = getDuplexRise('B-DNA') leftHandle = Instance( DnaSegment_ResizeHandle( command = _self, height_ref = call_Expr( ObjAttr_StateRef, _self, 'cylinderWidth'), origin = handlePoint1, fixedEndOfStructure = handlePoint2, direction = norm_Expr(handlePoint1 - handlePoint2), sphereRadius = handleSphereRadius1, discRadius = env.prefs[dnaSegmentResizeHandle_discRadius_prefs_key], discThickness = env.prefs[dnaSegmentResizeHandle_discThickness_prefs_key], range = (_resizeHandle_stopper_length, 10000) )) rightHandle = Instance( DnaSegment_ResizeHandle( command = _self, height_ref = call_Expr( ObjAttr_StateRef, _self, 'cylinderWidth2'), origin = handlePoint2, fixedEndOfStructure = handlePoint1, direction = norm_Expr(handlePoint2 - handlePoint1), sphereRadius = handleSphereRadius2, discRadius = env.prefs[dnaSegmentResizeHandle_discRadius_prefs_key], discThickness = env.prefs[dnaSegmentResizeHandle_discThickness_prefs_key], range = (_resizeHandle_stopper_length, 10000) )) rotationHandle1 = Instance( RotationHandle( command = _self, rotationDistanceRef = call_Expr( ObjAttr_StateRef, _self, 'rotation_distance1'), center = handlePoint1, axis = norm_Expr(handlePoint1 - handlePoint2), origin = rotationHandleBasePoint1, radiusVector = norm_Expr(rotationHandleBasePoint1 - handlePoint1) )) rotationHandle2 = Instance( RotationHandle( command = _self, rotationDistanceRef = call_Expr( ObjAttr_StateRef, _self, 'rotation_distance2'), center = handlePoint2, axis = norm_Expr(handlePoint2 - handlePoint1), origin = rotationHandleBasePoint2, radiusVector = norm_Expr(rotationHandleBasePoint2 - handlePoint2) )) def __init__(self, commandSequencer): """ Constructor for InsertDna_EditCommand """ #used by self.command_update_internal_state() self._previous_model_change_indicator = None glpane = commandSequencer.assy.glpane State_preMixin.__init__(self, glpane) EditCommand.__init__(self, commandSequencer) #Graphics handles for editing the structure . self.handles = [] self.grabbedHandle = None #New Command API method -- implemented on 2008-08-27 def command_update_internal_state(self): """ Extends the superclass method. @see:baseCommand.command_update_internal_state() for documentation """ #NOTE 2008-09-02: This method is called too often. It should exit early #if , for example , model_change_indicator didn't change. Need to #review and test to see if its okay to do so. [-- Ninad comment] _superclass.command_update_internal_state(self) #This MAY HAVE BUG. WHEN -- #debug pref 'call model_changed only when needed' is ON #See related bug 2729 for details. #The following code that updates te handle positions and the strand #sequence fixes bugs like 2745 and updating the handle positions #updating handle positions in command_update_UI instead of in #self.graphicsMode._draw_handles() is also a minor optimization #This can be further optimized by debug pref #'call command_update_UI only when needed' but its NOT done because of #an issue mentioned in bug 2729 - Ninad 2008-04-07 if self.grabbedHandle is not None: return current_model_change_indicator = self.assy.model_change_indicator() #This should be OK even when a subclass calls this method. #(the model change indicator is updated globally , using self.assy. ) if same_vals(current_model_change_indicator, self._previous_model_change_indicator): return self._previous_model_change_indicator = current_model_change_indicator #PAM5 segment resizing is not supported. #@see: self.hasResizableStructure() if not self.hasValidStructure(): return isStructResizable, why_not = self.hasResizableStructure() if not isStructResizable: self.handles = [] return elif len(self.handles) == 0: self._updateHandleList() self.updateHandlePositions() self._update_previousParams_in_model_changed() def _update_previousParams_in_model_changed(self): #The following fixes bug 2802. The bug comment has details of what #it does. Copying some portion of it below-- #We have fixed similar problem for strand resizing, by updating the #self.previousParams attr in model_changed method (and also updating #the numberOfBasePairs spinbox in the PM. But here, user can even #change the number of basepairs from the PM. When he does that, #the model_changed is called and it resets the number of basepairs #spinbox value with the ones currently on the structure! Thereby #making it impossible to upate structure using spinbox. To fix this #we introduce a new parameter in propMgr.getParameters() which #reports the actual number of bases on the structure. #-- Ninad 2008-04-12 if self.previousParams is not None: new_numberOfBasePairs = self.struct.getNumberOfBasePairs() if new_numberOfBasePairs != self.previousParams[0]: self.propMgr.numberOfBasePairsSpinBox.setValue(new_numberOfBasePairs) self.previousParams = self.propMgr.getParameters() def editStructure(self, struct = None): EditCommand.editStructure(self, struct) if self.hasValidStructure(): self._updatePropMgrParams() #Store the previous parameters. Important to set it after you #set duplexRise and basesPerTurn attrs in the propMgr. #self.previousParams is used in self._previewStructure and #self._finalizeStructure to check if self.struct changed. self.previousParams = self._gatherParameters() #For Rattlesnake, we do not support resizing of PAM5 model. #So don't append the exprs handles to the handle list (and thus #don't draw those handles. See self.model_changed() isStructResizable, why_not = self.hasResizableStructure() if not isStructResizable: self.handles = [] else: self._updateHandleList() self.updateHandlePositions() def _updatePropMgrParams(self): """ Subclasses may override this method. Update some property manager parameters with the parameters of self.struct (which is being edited) @see: self.editStructure() """ #Format in which params need to be provided to the Property manager #(i.e. in propMgr.setParameters(): #numberOfBasePairs, #dnaForm, #dnaModel, #basesPerTurn, #duplexRise, #endPoint1, #endPoint2 basesPerTurn, duplexRise = self.struct.getProps() endPoint1, endPoint2 = self.struct.getAxisEndPoints() numberOfBasePairs = self.struct.getNumberOfBasePairs() color = self.struct.getColor() params_for_propMgr = ( numberOfBasePairs, None, None, basesPerTurn, duplexRise, endPoint1, endPoint2, color ) #TODO 2008-03-25: better to get all parameters from self.struct and #set it in propMgr? This will mostly work except that reverse is #not true. i.e. we can not specify same set of params for #self.struct.setProps ...because endPoint1 and endPoint2 are derived. #by the structure when needed. Commenting out following line of code #UPDATE 2008-05-06 Fixes a bug due to which the parameters in propMGr #of DnaSegment_EditCommand are not same as the original structure #(e.g. bases per turn and duplexrise) self.propMgr.setParameters(params_for_propMgr) def keep_empty_group(self, group): """ Returns True if the empty group should not be automatically deleted. otherwise returns False. The default implementation always returns False. Subclasses should override this method if it needs to keep the empty group for some reasons. Note that this method will only get called when a group has a class constant autdelete_when_empty set to True. (and as of 2008-03-06, it is proposed that dna_updater calls this method when needed. @see: Command.keep_empty_group() which is overridden here. @see: BreakStrands_Command.keep_empty_group @see: Group.autodelete_when_empty.. a class constant used by the dna_updater (the dna updater then decides whether to call this method to see which empty groups need to be deleted) """ bool_keep = EditCommand.keep_empty_group(self, group) if not bool_keep: if self.hasValidStructure(): if group is self.struct: bool_keep = True elif group is self.struct.parent_node_of_class(self.assy.DnaGroup): bool_keep = True #If this command doesn't have a valid structure, as a fall back, #lets instruct it to keep ALL the DnaGroup objects even when empty #Reason? ..see explanation in BreakStrands_Command.keep_empty_group elif isinstance(group, self.assy.DnaGroup): bool_keep = True return bool_keep def hasResizableStructure(self): """ For Rattlesnake release, we dont support segment resizing for PAM5 models. If the structure is not resizable, the handles won't be drawn @see:self.model_changed() @see:DnaSegment_PropertyManager.model_changed() @see: self.editStructure() @see: DnaSegment.is_PAM3_DnaSegment() """ #Note: This method fixes bugs similar to bug 2812 but the changes #didn't made it to Rattlesnake rc2 -- Ninad 2008-04-16 isResizable = True why_not = '' if not self.hasValidStructure(): isResizable = False why_not = 'It is invalid.' return isResizable, why_not isResizable = self.struct.is_PAM3_DnaSegment() if not isResizable: why_not = 'It needs to be converted to PAM3 model' return isResizable, why_not endAtom1, endAtom2 = self.struct.getAxisEndAtoms() if endAtom1 is None or endAtom2 is None: isResizable = False why_not = "Unable to determine one or both end atoms of the segment" return isResizable, why_not if endAtom1 is endAtom2: isResizable = False why_not = "Resizing a segment with single atom is unsupported" return isResizable, why_not return isResizable, why_not def hasValidStructure(self): """ Tells the caller if this edit command has a valid structure. Overrides EditCommand.hasValidStructure() """ #(By Bruce 2008-02-13) isValid = EditCommand.hasValidStructure(self) if not isValid: return isValid # would like to check here whether it's empty of axis chunks; # instead, this will do for now (probably too slow, though): p1, p2 = self.struct.getAxisEndPoints() return (p1 is not None) def _getStructureType(self): """ Subclasses 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: EditCommand._getStructureType() (overridden here) """ return self.win.assy.DnaSegment def _updateHandleList(self): """ Updates the list of handles (self.handles) @see: self.editStructure @see: DnaSegment_GraphicsMode._drawHandles() """ # note: if handlePoint1 and/or handlePoint2 can change more often than this # runs, we'll need to rerun the two assignments above whenever they # change and before the handle is drawn. An easy way would be to rerun # these assignments in the draw method of our GM. [bruce 080128] self.handles = [] # guess, but seems like a good idea [bruce 080128] self.handles.append(self.leftHandle) self.handles.append(self.rightHandle) if DEBUG_ROTATION_HANDLES: self.handles.append(self.rotationHandle1) self.handles.append(self.rotationHandle2) def updateHandlePositions(self): """ Update handle positions and also update the resize handle radii and their 'stopper' lengths. @see: self._update_resizeHandle_radius() @see: self._update_resizeHandle_stopper_length() @see: DnaSegment_GraphicsMode._drawHandles() """ if len(self.handles) == 0: #No handles are appended to self.handles list. #@See self.model_changed() and self._updateHandleList() return #TODO: Call this method less often by implementing model_changed #see bug 2729 for a planned optimization self.cylinderWidth = CYLINDER_WIDTH_DEFAULT_VALUE self.cylinderWidth2 = CYLINDER_WIDTH_DEFAULT_VALUE self._update_resizeHandle_radius() handlePoint1, handlePoint2 = self.struct.getAxisEndPoints() if handlePoint1 is not None and handlePoint2 is not None: # (that condition is bugfix for deleted axis segment, bruce 080213) self.handlePoint1, self.handlePoint2 = handlePoint1, handlePoint2 #Update the 'stopper' length where the resize handle being dragged #should stop. See self._update_resizeHandle_stopper_length() #for more details self._update_resizeHandle_stopper_length() if DEBUG_ROTATION_HANDLES: self.rotation_distance1 = CYLINDER_WIDTH_DEFAULT_VALUE self.rotation_distance2 = CYLINDER_WIDTH_DEFAULT_VALUE #Following computes the base points for rotation handles. #to be revised -- Ninad 2008-02-13 unitVectorAlongAxis = norm(self.handlePoint1 - self.handlePoint2) v = cross(self.glpane.lineOfSight, unitVectorAlongAxis) self.rotationHandleBasePoint1 = self.handlePoint1 + norm(v) * 4.0 self.rotationHandleBasePoint2 = self.handlePoint2 + norm(v) * 4.0 def _update_resizeHandle_radius(self): """ Finds out the sphere radius to use for the resize handles, based on atom /chunk or glpane display (whichever decides the display of the end atoms. @see: self.updateHandlePositions() @see: B{Atom.drawing_radius()} """ atm1 , atm2 = self.struct.getAxisEndAtoms() if atm1 is not None: self.handleSphereRadius1 = max(1.25*atm1.drawing_radius(), 1.25*HANDLE_RADIUS_DEFAULT_VALUE) if atm2 is not None: self.handleSphereRadius2 = max(1.25*atm2.drawing_radius(), 1.25*HANDLE_RADIUS_DEFAULT_VALUE) def _update_resizeHandle_stopper_length(self): """ Update the limiting length at which the resize handle being dragged should 'stop' without proceeding further in the drag direction. The segment resize handle stops when you are dragging it towards the other resizeend and the distance between the two ends reaches two duplexes. The self._resizeHandle_stopper_length computed in this method is used as a lower limit of the 'range' option provided in declaration of resize handle objects (see class definition for the details) @see: self.updateHandlePositions() """ total_length = vlen(self.handlePoint1 - self.handlePoint2) duplexRise = self.struct.getDuplexRise() #Length of the duplex for 2 base pairs two_bases_length = getDuplexLength('B-DNA', 2, duplexRise = duplexRise) self._resizeHandle_stopper_length = - total_length + two_bases_length def _gatherParameters(self): """ Return the parameters from the property manager UI. @return: All the parameters (get those from the property manager): - numberOfBases - dnaForm - basesPerTurn - endPoint1 - endPoint2 @rtype: tuple """ return self.propMgr.getParameters() def _createStructure(self): """ Creates and returns the structure (in this case a L{Group} object that contains the DNA strand and axis chunks. @return : group containing that contains the DNA strand and axis chunks. @rtype: L{Group} @note: This needs to return a DNA object once that model is implemented """ params = self._gatherParameters() # No error checking in build_struct, do all your error # checking in gather_parameters number_of_basePairs_from_struct,\ numberOfBases, \ dnaForm, \ dnaModel, \ basesPerTurn, \ duplexRise, \ endPoint1, \ endPoint2, \ color_junk = params #Note: color_junk is not used. Ideally it should do struct.setColor(color) #but the color combobox in the PM directly sets the color of the #structure to the specified one when the current index in the combobx #changes #If user enters the number of basepairs and hits preview i.e. endPoint1 #and endPoint2 are not entered by the user and thus have default value #of V(0, 0, 0), then enter the endPoint1 as V(0, 0, 0) and compute #endPoint2 using the duplex length. #Do not use '==' equality check on vectors! its a bug. Use same_vals # or Veq instead. if Veq(endPoint1 , endPoint2) and Veq(endPoint1, V(0, 0, 0)): endPoint2 = endPoint1 + \ self.win.glpane.right*getDuplexLength('B-DNA', numberOfBases) if numberOfBases < 1: msg = redmsg("Cannot preview/insert a DNA duplex with 0 bases.") self.propMgr.updateMessage(msg) self.dna = None # Fixes bug 2530. Mark 2007-09-02 return None if dnaForm == 'B-DNA': if dnaModel == 'PAM3': dna = B_Dna_PAM3_Generator() elif dnaModel == 'PAM5': dna = B_Dna_PAM5_Generator() else: print "bug: unknown dnaModel type: ", dnaModel else: raise PluginBug("Unsupported DNA Form: " + dnaForm) self.dna = dna # needed for done msg # 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 # Create the model tree group node. # Make sure that the 'topnode' of this part is a Group (under which the # DNa group will be placed), if the topnode is not a group, make it a # a 'Group' (applicable to Clipboard parts).See part.py # --Part.ensure_toplevel_group method. This is an important line # and it fixes bug 2585 self.win.assy.part.ensure_toplevel_group() dnaSegment = DnaSegment(self.name, self.win.assy, self.win.assy.part.topnode, editCommand = self ) try: # Make the DNA duplex. <dnaGroup> will contain three chunks: # - Strand1 # - Strand2 # - Axis dna.make(dnaSegment, numberOfBases, basesPerTurn, duplexRise, endPoint1, endPoint2) #set some properties such as duplexRise and number of bases per turn #This information will be stored on the DnaSegment object so that #it can be retrieved while editing this object. #This works with or without dna_updater. Now the question is #should these props be assigned to the DnaSegment in #dnaDuplex.make() itself ? This needs to be answered while modifying #make() method to fit in the dna data model. --Ninad 2008-03-05 #WARNING 2008-03-05: Since self._modifyStructure calls #self._createStructure() #If in the near future, we actually permit modifying a #structure (such as dna) without actually recreating the whole #structre, then the following properties must be set in #self._modifyStructure as well. Needs more thought. props = (duplexRise, basesPerTurn) dnaSegment.setProps(props) return dnaSegment except (PluginBug, UserError): # Why do we need UserError here? Mark 2007-08-28 dnaSegment.kill() raise PluginBug("Internal error while trying to create DNA duplex.") def _modifyStructure(self, params): """ Modify the structure based on the parameters specified. Overrides EditCommand._modifystructure. This method removes the old structure and creates a new one using self._createStructure. This was needed for the structures like this (Dna, Nanotube etc) . . See more comments in the method. """ assert self.struct self.dna = B_Dna_PAM3_Generator() number_of_basePairs_from_struct,\ numberOfBases, \ dnaForm, \ dnaModel, \ basesPerTurn, \ duplexRise, \ endPoint1, \ endPoint2 , \ color = params #Delete unused parameters. del endPoint1 del endPoint2 del number_of_basePairs_from_struct numberOfBasePairsToAddOrRemove = self._determine_numberOfBasePairs_to_change() ladderEndAxisAtom = self.get_axisEndAtom_at_resize_end() if numberOfBasePairsToAddOrRemove != 0: resizeEnd_final_position = self._get_resizeEnd_final_position( ladderEndAxisAtom, abs(numberOfBasePairsToAddOrRemove), duplexRise ) self.dna.modify(self.struct, ladderEndAxisAtom, numberOfBasePairsToAddOrRemove, basesPerTurn, duplexRise, ladderEndAxisAtom.posn(), resizeEnd_final_position) #Find new end points of structure parameters after modification #and set these values in the propMgr. new_end1 , new_end2 = self.struct.getAxisEndPoints() params_to_set_in_propMgr = (numberOfBases, dnaForm, dnaModel, basesPerTurn, duplexRise, new_end1, new_end2, color) #TODO: Need to set these params in the PM #and then self.previousParams = params_to_set_in_propMgr self.previousParams = params return def _get_resizeEnd_final_position(self, ladderEndAxisAtom, numberOfBases, duplexRise): final_position = None if self.grabbedHandle: final_position = self.grabbedHandle.currentPosition else: other_axisEndAtom = self.struct.getOtherAxisEndAtom(ladderEndAxisAtom) axis_vector = ladderEndAxisAtom.posn() - other_axisEndAtom.posn() segment_length_to_add = getDuplexLength('B-DNA', numberOfBases, duplexRise = duplexRise) final_position = ladderEndAxisAtom.posn() + norm(axis_vector)*segment_length_to_add return final_position def getStructureName(self): """ Returns the name string of self.struct if there is a valid structure. Otherwise returns None. This information is used by the name edit field of this command's PM when we call self.propMgr.show() @see: DnaSegment_PropertyManager.show() @see: self.setStructureName """ if self.hasValidStructure(): return self.struct.name else: return None def setStructureName(self, name): """ Sets the name of self.struct to param <name> (if there is a valid structure. The PM of this command callss this method while closing itself @param name: name of the structure to be set. @type name: string @see: DnaSegment_PropertyManager.close() @see: self.getStructureName() """ #@BUG: We call this method in self.propMgr.close(). But propMgr.close() #is called even when the command is 'cancelled'. That means the #structure will get changed even when user hits cancel button or #exits the command by clicking on empty space. #This should really be done in self._finalizeStructure but that #method doesn't get called when you click on empty space to exit #the command. See DnaSegment_GraphicsMode.leftUp for a detailed #comment. if self.hasValidStructure(): self.struct.name = name def getCursorText(self): """ This is used as a callback method in DnaLine mode @see: DnaLineMode.setParams, DnaLineMode_GM.Draw """ #@TODO: Refactor this. Similar code exists in #DnaStrand_EditCommand.getCursorText() -- Ninad 2008-04-12 if self.grabbedHandle is None: return currentPosition = self.grabbedHandle.currentPosition fixedEndOfStructure = self.grabbedHandle.fixedEndOfStructure duplexRise = self.struct.getDuplexRise() ############# raw_numberOfBasePairsToAddOrRemove = self._determine_numberOfBasePairs_to_change() #Following fixes bugs like 2904 and 2906 #Note that we are using numberOfBasePairsToAddOrRemove in self._modifyStructure() #if self._determine_numberOfBasePairs_to_change() returns the number of basepairs #to add, it returns 1 more than the actual number of basepairs. Because #while creating the dna, it removes the first base pair of the newly created #dna. So, for cursor text and for PM spinbox, we should make adjustments to the #raw_numberOfBasePairsToAddOrRemove so that it reflects the correct value #in the spinbox and in the PM if raw_numberOfBasePairsToAddOrRemove > 1: numberOfBasePairsToAddOrRemove = raw_numberOfBasePairsToAddOrRemove - 1 else: numberOfBasePairsToAddOrRemove = raw_numberOfBasePairsToAddOrRemove current_numberOfBasePairs = self.struct.getNumberOfBasePairs() numberOfBasePairs = current_numberOfBasePairs + numberOfBasePairsToAddOrRemove if hasattr(self.propMgr, 'numberOfBasePairsSpinBox'): #@TODO: The following updates the PM as the cursor moves. #Need to rename this method so that you that it also does more things #than just to return a textString -- Ninad 2007-12-20 self.propMgr.numberOfBasePairsSpinBox.setValue(numberOfBasePairs) text = "" textColor = env.prefs[cursorTextColor_prefs_key] # Mark 2008-08-28 if not env.prefs[dnaSegmentEditCommand_showCursorTextCheckBox_prefs_key]: return text, textColor #@@TODO: refactor. #this duplex length canculation fixes bug 2906 duplexLength = getDuplexLength('B-DNA', numberOfBasePairs, duplexRise = duplexRise) #Cursor text strings -- duplexLengthString = str(round(duplexLength, 3)) numberOfBasePairsString = self._getCursorText_numberOfBasePairs( numberOfBasePairs) duplexLengthString = self._getCursorText_length(duplexLength) changedBasePairsString = self._getCursorText_changedBasePairs( numberOfBasePairs) #Add commas (to be refactored) commaString = ", " text = numberOfBasePairsString if text and changedBasePairsString: text += " "# commaString not needed here. Mark 2008-07-03 text += changedBasePairsString if text and duplexLengthString: text += commaString text += duplexLengthString return (text, textColor) def _getCursorText_numberOfBasePairs(self, numberOfBasePairs): """ Return the cursor textstring that gives information about the number of basepairs if the corresponding prefs_key returns True. """ numberOfBasePairsString = '' if env.prefs[ dnaSegmentEditCommand_cursorTextCheckBox_numberOfBasePairs_prefs_key]: numberOfBasePairsString = "%db"%numberOfBasePairs return numberOfBasePairsString def _getCursorText_length(self, duplexLength): """ """ duplexLengthString = '' if env.prefs[dnaSegmentEditCommand_cursorTextCheckBox_length_prefs_key]: lengthUnitString = 'A' #change the unit of length to nanometers if the length is > 10A #fixes part of bug 2856 if duplexLength > 10.0: lengthUnitString = 'nm' duplexLength = duplexLength * 0.1 duplexLengthString = "%5.3f%s"%(duplexLength, lengthUnitString) return duplexLengthString def _getCursorText_changedBasePairs(self, numberOfBasePairs): """ """ changedBasePairsString = '' if env.prefs[ dnaSegmentEditCommand_cursorTextCheckBox_changedBasePairs_prefs_key]: original_numberOfBasePairs = self.struct.getNumberOfBasePairs() changed_basePairs = numberOfBasePairs - original_numberOfBasePairs if changed_basePairs > 0: changedBasePairsString = "(" + "+" + str(changed_basePairs) + ")" else: changedBasePairsString = "(" + str(changed_basePairs) + ")" return changedBasePairsString def getDnaRibbonParams(self): """ Returns parameters for drawing the dna ribbon. If the dna rubberband line should NOT be drawn (example when you are removing basepairs from the segment So the caller should check if the method return value is not None. @see: DnaSegment_GraphicsMode._draw_handles() """ if self.grabbedHandle is None: return None if self.grabbedHandle.origin is None: return None direction_of_drag = norm(self.grabbedHandle.currentPosition - \ self.grabbedHandle.origin) #If the segment is being shortened (determined by checking the #direction of drag) , no need to draw the rubberband line. if dot(self.grabbedHandle.direction, direction_of_drag) < 0: return None basesPerTurn = self.struct.getBasesPerTurn() duplexRise = self.struct.getDuplexRise() ladderEndAxisAtom = self.get_axisEndAtom_at_resize_end() ladder = ladderEndAxisAtom.molecule.ladder endBaseAtomList = ladder.get_endBaseAtoms_containing_atom(ladderEndAxisAtom) ribbon1_start_point = None ribbon2_start_point = None ribbon1_direction = None ribbon2_direction = None ribbon1Color = applegreen ribbon2Color = applegreen if endBaseAtomList and len(endBaseAtomList) > 2: strand_atom1 = endBaseAtomList[0] strand_atom2 = endBaseAtomList[2] if strand_atom1: ribbon1_start_point = strand_atom1.posn() for bond_direction, neighbor in strand_atom1.bond_directions_to_neighbors(): if neighbor and neighbor.is_singlet(): ribbon1_direction = bond_direction break ribbon1Color = strand_atom1.molecule.color if not ribbon1Color: ribbon1Color = strand_atom1.element.color if strand_atom2: ribbon2_start_point = strand_atom2.posn() for bond_direction, neighbor in strand_atom2.bond_directions_to_neighbors(): if neighbor and neighbor.is_singlet(): ribbon2_direction = bond_direction break ribbon2Color = strand_atom2.molecule.color if not ribbon2Color: ribbon2Color = strand_atom2.element.color return (self.grabbedHandle.origin, self.grabbedHandle.currentPosition, basesPerTurn, duplexRise, ribbon1_start_point, ribbon2_start_point, ribbon1_direction, ribbon2_direction, ribbon1Color, ribbon2Color ) def modifyStructure(self): """ Called when a resize handle is dragged to change the length of the segment. (Called upon leftUp) . This method assigns the new parameters for the segment after it is resized and calls preview_or_finalize_structure which does the rest of the job. Note that Client should call this public method and should never call the private method self._modifyStructure. self._modifyStructure is called only by self.preview_or_finalize_structure @see: B{DnaSegment_ResizeHandle.on_release} (the caller) @see: B{SelectChunks_GraphicsMode.leftUp} (which calls the the relevent method in DragHandler API. ) @see: B{exprs.DraggableHandle_AlongLine}, B{exprs.DragBehavior} @see: B{self.preview_or_finalize_structure } @see: B{self._modifyStructure} As of 2008-02-01 it recreates the structure @see: a note in self._createStructure() about use of dnaSegment.setProps """ #TODO: need to cleanup this and may be use use something like #self.previousParams = params in the end -- 2008-03-24 (midnight) if self.grabbedHandle is None: return ##self.propMgr.setParameters(params_to_set_in_propMgr) #TODO: Important note: How does NE1 know that structure is modified? #Because number of base pairs parameter in the PropMgr changes as you #drag the handle . This is done in self.getCursorText() ... not the #right place to do it. OR that method needs to be renamed to reflect #this as suggested in that method -- Ninad 2008-03-25 self.preview_or_finalize_structure(previewing = True) ##self.previousParams = params_to_set_in_propMgr self.glpane.gl_update() def get_axisEndAtom_at_resize_end(self): ladderEndAxisAtom = None if self.grabbedHandle is not None: ladderEndAxisAtom = self.struct.getAxisEndAtomAtPosition(self.grabbedHandle.origin) else: endAtom1, endAtom2 = self.struct.getAxisEndAtoms() ladderEndAxisAtom = endAtom2 return ladderEndAxisAtom def _determine_numberOfBasePairs_to_change(self): """ """ duplexRise = self.struct.getDuplexRise() numberOfBasesToAddOrRemove = 0 #Following helps fixing bugs like 2904 and 2906 see also self.getCursorText() #and TODO items in that method. Also note that the grabbed handle case #is similar to the one in MultipleDnaSegmentResize_EditCommand. #needs refactoring and overall cleanup. if self.grabbedHandle is not None: currentPosition = self.grabbedHandle.currentPosition fixedEndOfStructure = self.grabbedHandle.fixedEndOfStructure changedLength = vlen(currentPosition - self.grabbedHandle.origin) direction_of_drag = norm(self.grabbedHandle.currentPosition - \ self.grabbedHandle.origin) #Even when the direction of drag is negative (i.e. the basepairs being #removed), make sure not to remove base pairs for very small movement #of the grabbed handle if changedLength < 0.2*duplexRise: return 0 #This check quickly determines if the grabbed handle moved by a distance #more than the duplexRise and avoids further computations #This condition is applicable only when the direction of drag is #positive..i.e. bases bing added to the segment. if changedLength < duplexRise and \ dot(self.grabbedHandle.direction, direction_of_drag) > 0: return 0 #If the segment is being shortened (determined by checking the #direction of drag) numberOfBasesToAddOrRemove = \ getNumberOfBasePairsFromDuplexLength( 'B-DNA', changedLength, duplexRise = duplexRise) if dot(self.grabbedHandle.direction, direction_of_drag) < 0: numberOfBasesToAddOrRemove = - numberOfBasesToAddOrRemove if numberOfBasesToAddOrRemove > 0: #dna.modify will remove the first base pair it creates #(that basepair will only be used for proper alignment of the #duplex with the existing structure) So we need to compensate for #this basepair by adding 1 to the new number of base pairs. #UPDATE 2008-05-14: The following commented out code #i.e. "##numberOfBasesToAddOrRemove += 1" is not required in this #class , because the way we compute the number of base pairs to #be added is different than than how its done at the moment in the #superclass. In this method, we compute bases to be added from #the resize end and that computation INCLUDES the resize end. #so the number that it returns is already one more than the actual #bases to be added. so commenting out the following line # -- Ninad 2008-05-14 ##numberOfBasesToAddOrRemove += 1 pass else: #The Property manager will be showing the current number #of base pairs (w. May be we can use that number directly here? #The following is safer to do so lets just recompute the #number of base pairs. (if it turns out to be slow, we will consider #using the already computed calue from the property manager new_numberOfBasePairs = self.propMgr.numberOfBasePairsSpinBox.value() endPoint1, endPoint2 = self.struct.getAxisEndPoints() if endPoint1 is None or endPoint2 is None: return 0 original_duplex_length = vlen(endPoint1 - endPoint2) original_numberOfBasePairs = self.struct.getNumberOfBasePairs() numberOfBasesToAddOrRemove = new_numberOfBasePairs - original_numberOfBasePairs if numberOfBasesToAddOrRemove > 0: #dna.modify will remove the first base pair it creates #(that basepair will only be used for proper alignment of the #duplex with the existing structure) So we need to compensate for #this basepair by adding 1 to the new number of base pairs. numberOfBasesToAddOrRemove += 1 return numberOfBasesToAddOrRemove def makeMenus(self): """ Create context menu for this command. """ if not hasattr(self, 'graphicsMode'): return selobj = self.glpane.selobj if selobj is None: return self.Menu_spec = [] highlightedChunk = None if isinstance(selobj, Chunk): highlightedChunk = selobj if isinstance(selobj, Atom): highlightedChunk = selobj.molecule elif isinstance(selobj, Bond): chunk1 = selobj.atom1.molecule chunk2 = selobj.atom2.molecule if chunk1 is chunk2 and chunk1 is not None: highlightedChunk = chunk1 if highlightedChunk is None: return if self.hasValidStructure(): ### REVIEW: these early returns look wrong, since they skip running # the subsequent call of highlightedChunk.make_glpane_cmenu_items # for no obvious reason. [bruce 090114 comment, in two commands] dnaGroup = self.struct.parent_node_of_class(self.assy.DnaGroup) if dnaGroup is None: return #following should be self.struct.getDnaGroup or self.struct.getDnaGroup #need to formalize method name and then make change. if not dnaGroup is highlightedChunk.parent_node_of_class(self.assy.DnaGroup): item = ("Edit unavailable: Member of a different DnaGroup", noop, 'disabled') self.Menu_spec.append(item) return highlightedChunk.make_glpane_cmenu_items(self.Menu_spec, self)
NanoCAD-master
cad/src/dna/commands/DnaSegment/DnaSegment_EditCommand.py
NanoCAD-master
cad/src/dna/commands/DnaSegment/__init__.py
# Copyright 2008 Nanorex, Inc. See LICENSE file for details. """ @author: Ninad @version: $Id$ @copyright: 2007-2008 Nanorex, Inc. See LICENSE file for details. TODO: as of 2008-01-18 See DnaSegment_EditCommand for details. """ from PyQt4.Qt import SIGNAL from PM.PM_GroupBox import PM_GroupBox from command_support.DnaOrCnt_PropertyManager import DnaOrCnt_PropertyManager from PM.PM_Constants import PM_DONE_BUTTON from PM.PM_Constants import PM_WHATS_THIS_BUTTON from PM.PM_Constants import PM_CANCEL_BUTTON from PM.PM_Constants import PM_PREVIEW_BUTTON from PM.PM_SpinBox import PM_SpinBox from PM.PM_DoubleSpinBox import PM_DoubleSpinBox from PM.PM_LineEdit import PM_LineEdit from dna.model.Dna_Constants import getNumberOfBasePairsFromDuplexLength from dna.model.Dna_Constants import getDuplexLength from geometry.VQT import V, vlen from utilities.Log import redmsg from utilities.Comparison import same_vals from utilities.prefs_constants import dnaSegmentEditCommand_cursorTextCheckBox_length_prefs_key from utilities.prefs_constants import dnaSegmentEditCommand_cursorTextCheckBox_numberOfBasePairs_prefs_key from utilities.prefs_constants import dnaSegmentEditCommand_cursorTextCheckBox_changedBasePairs_prefs_key from utilities.prefs_constants import dnaSegmentEditCommand_showCursorTextCheckBox_prefs_key from widgets.prefs_widgets import connect_checkbox_with_boolean_pref _superclass = DnaOrCnt_PropertyManager class DnaSegment_PropertyManager( DnaOrCnt_PropertyManager): """ The DnaSegmenta_PropertyManager class provides a Property Manager for the DnaSegment_EditCommand. @ivar title: The title that appears in the property manager header. @type title: str @ivar pmName: The name of this property manager. This is used to set the name of the PM_Dialog object via setObjectName(). @type name: str @ivar iconPath: The relative path to the PNG file that contains a 22 x 22 icon image that appears in the PM header. @type iconPath: str """ title = "DnaSegment Properties" iconPath = "ui/actions/Tools/Build Structures/DNA.png" def __init__( self, command ): """ Constructor for the Build DNA property manager. """ self.endPoint1 = V(0, 0, 0) self.endPoint2 = V(0, 0, 0) self._numberOfBases = 0 self._conformation = 'B-DNA' self.duplexRise = 3.18 self.basesPerTurn = 10 self.dnaModel = 'PAM3' _superclass.__init__( self, command) self.showTopRowButtons( PM_DONE_BUTTON | \ PM_CANCEL_BUTTON | \ PM_PREVIEW_BUTTON | \ PM_WHATS_THIS_BUTTON) msg = "Use resize handles to resize the segment. Drag any axis or sugar"\ " atom for translation or rotation about axis respectively. Dragging"\ " any bond will freely move the whole segment." self.updateMessage(msg) 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 _superclass.connect_or_disconnect_signals(self, isConnect) change_connect( self.numberOfBasePairsSpinBox, SIGNAL("valueChanged(int)"), self.numberOfBasesChanged ) change_connect( self.basesPerTurnDoubleSpinBox, SIGNAL("valueChanged(double)"), self.basesPerTurnChanged ) change_connect( self.duplexRiseDoubleSpinBox, SIGNAL("valueChanged(double)"), self.duplexRiseChanged ) change_connect(self.showCursorTextCheckBox, SIGNAL('stateChanged(int)'), self._update_state_of_cursorTextGroupBox) def _update_UI_do_updates(self): """ @see: Command_PropertyManager._update_UI_do_updates() @see: DnaSegment_EditCommand.command_update_UI() @see: DnaSegment_EditCommand.hasResizableStructure() @see: self._current_model_changed_params() """ currentParams = self._current_model_changed_params() #Optimization. Return from the model_changed method if the #params are the same. if same_vals(currentParams, self._previous_model_changed_params): return isStructResizable, why_not = currentParams #update the self._previous_model_changed_params with this new param set. self._previous_model_changed_params = currentParams if not isStructResizable: #disable all widgets if self._pmGroupBox1.isEnabled(): self._pmGroupBox1.setEnabled(False) msg = redmsg("DnaSegment is not resizable. Reason: %s"%(why_not)) self.updateMessage(msg) else: if not self._pmGroupBox1.isEnabled(): self._pmGroupBox1.setEnabled(True) msg = "Use resize handles to resize the segment. Drag any axis or sugar"\ " atom for translation or rotation about axis respectively. Dragging"\ " any bond will freely move the whole segment." self.updateMessage(msg) def _current_model_changed_params(self): """ Returns a tuple containing the parameters that will be compared against the previously stored parameters. This provides a quick test to determine whether to do more things in self.model_changed() @see: self.model_changed() which calls this @see: self._previous_model_changed_params attr. """ params = None if self.command: isStructResizable, why_not = self.command.hasResizableStructure() params = (isStructResizable, why_not) return params def show(self): """ Show this property manager. Overrides EditCommand_PM.show() This method also retrives the name information from the command's structure for its name line edit field. @see: DnaSegment_EditCommand.getStructureName() @see: self.close() """ _superclass.show(self) if self.command is not None: name = self.command.getStructureName() if name is not None: self.nameLineEdit.setText(name) def close(self): """ Close this property manager. Also sets the name of the self.command's structure to the one displayed in the line edit field. @see self.show() @see: DnaSegment_EditCommand.setStructureName """ if self.command is not None: name = str(self.nameLineEdit.text()) self.command.setStructureName(name) _superclass.close(self) def setParameters(self, params): """ This is usually called when you are editing an existing structure. Some property manager ui elements then display the information obtained from the object being edited. TODO: - Make this a EditCommand_PM API method? - See also the routines GraphicsMode.setParams or object.setProps ..better to name them all in one style? """ numberOfBasePairs, \ dnaForm, \ dnaModel,\ basesPerTurn, \ duplexRise, \ endPoint1, \ endPoint2 , \ color = params if numberOfBasePairs is not None: self.numberOfBasePairsSpinBox.setValue(numberOfBasePairs) if dnaForm is not None: self._conformation = dnaForm if dnaModel is not None: self.dnaModel = dnaModel if duplexRise is not None: self.duplexRiseDoubleSpinBox.setValue(duplexRise) if basesPerTurn is not None: self.basesPerTurnDoubleSpinBox.setValue(basesPerTurn) if endPoint1 is not None: self.endPoint1 = endPoint1 if endPoint2 is not None: self.endPoint2 = endPoint2 if color is not None: self._colorChooser.setColor(color) def getParameters(self): """ """ #See bug 2802 for details about the parameter #'number_of_basePairs_from_struct'. Basically it is used to check #if the structure got modified (e.g. because of undo) #The numberOfBases parameter obtained from the propMgr is given as a #separate parameter for the reasons mentioned in bug 2802 #-- Ninad 2008-04-12 number_of_basePairs_from_struct = None if self.command.hasValidStructure(): number_of_basePairs_from_struct = self.command.struct.getNumberOfBasePairs() numberOfBases = self.numberOfBasePairsSpinBox.value() dnaForm = self._conformation dnaModel = self.dnaModel basesPerTurn = self.basesPerTurn duplexRise = self.duplexRise color = self._colorChooser.getColor() return ( number_of_basePairs_from_struct, numberOfBases, dnaForm, dnaModel, basesPerTurn, duplexRise, self.endPoint1, self.endPoint2, color ) def numberOfBasesChanged( self, numberOfBases ): """ Slot for the B{Number of Bases} spinbox. """ duplexRise = self.duplexRiseDoubleSpinBox.value() # Update the Duplex Length lineEdit widget. text = str(getDuplexLength(self._conformation, numberOfBases, duplexRise = duplexRise)) \ + " Angstroms" self.duplexLengthLineEdit.setText(text) return def basesPerTurnChanged( self, basesPerTurn ): """ Slot for the B{Bases per turn} spinbox. """ self.basesPerTurn = basesPerTurn def duplexRiseChanged( self, rise ): """ Slot for the B{Rise} spinbox. """ self.duplexRise = rise def _addGroupBoxes( self ): """ Add the DNA Property Manager group boxes. """ self._pmGroupBox1 = PM_GroupBox( self, title = "Parameters" ) self._loadGroupBox1( self._pmGroupBox1 ) self._displayOptionsGroupBox = PM_GroupBox( self, title = "Display Options" ) self._loadDisplayOptionsGroupBox( self._displayOptionsGroupBox ) def _loadGroupBox1(self, pmGroupBox): """ Load widgets in group box 4. """ self.nameLineEdit = PM_LineEdit( pmGroupBox, label = "Segment name:", text = "", setAsDefault = False) # Strand Length (i.e. the number of bases) self.numberOfBasePairsSpinBox = \ PM_SpinBox( pmGroupBox, label = "Base pairs:", value = self._numberOfBases, setAsDefault = False, minimum = 2, maximum = 10000 ) self.basesPerTurnDoubleSpinBox = \ PM_DoubleSpinBox( pmGroupBox, label = "Bases per turn:", value = self.basesPerTurn, setAsDefault = True, minimum = 8.0, maximum = 20.0, decimals = 2, singleStep = 0.1 ) self.basesPerTurnDoubleSpinBox.setDisabled(True) self.duplexRiseDoubleSpinBox = \ PM_DoubleSpinBox( pmGroupBox, label = "Rise:", value = self.duplexRise, setAsDefault = True, minimum = 2.0, maximum = 4.0, decimals = 3, singleStep = 0.01 ) self.duplexRiseDoubleSpinBox.setDisabled(True) # Duplex Length self.duplexLengthLineEdit = \ PM_LineEdit( pmGroupBox, label = "Duplex length: ", text = "0.0 Angstroms", setAsDefault = False) self.duplexLengthLineEdit.setDisabled(True) def _loadDisplayOptionsGroupBox(self, pmGroupBox): """ Overrides superclass method. Also loads the color chooser widget. """ self._loadColorChooser(pmGroupBox) _superclass._loadDisplayOptionsGroupBox(self, pmGroupBox) def _connect_showCursorTextCheckBox(self): """ Connect the show cursor text checkbox with user prefs_key. Overrides DnaOrCnt_PropertyManager._connect_showCursorTextCheckBox """ connect_checkbox_with_boolean_pref( self.showCursorTextCheckBox , dnaSegmentEditCommand_showCursorTextCheckBox_prefs_key) def _params_for_creating_cursorTextCheckBoxes(self): """ 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: Superclass method which is overridden here -- DnaOrCnt_PropertyManager._params_for_creating_cursorTextCheckBoxes() """ params = \ [ #Format: (" checkbox text", prefs_key) ("Number of base pairs", dnaSegmentEditCommand_cursorTextCheckBox_numberOfBasePairs_prefs_key), ("Duplex length", dnaSegmentEditCommand_cursorTextCheckBox_length_prefs_key), ("Number of basepairs to be changed", dnaSegmentEditCommand_cursorTextCheckBox_changedBasePairs_prefs_key) ] return params def _addWhatsThisText(self): """ Add what's this text. """ pass def _addToolTipText(self): """ Add Tooltip text """ pass
NanoCAD-master
cad/src/dna/commands/DnaSegment/DnaSegment_PropertyManager.py
# Copyright 2008-2009 Nanorex, Inc. See LICENSE file for details. """ @author: Ninad @version: $Id$ @copyright: 2008-2009 Nanorex, Inc. See LICENSE file for details. @license: GPL TODO: Attributes such as height_ref need to be renamed. But this should really be done in the superclass exprs.DraggableHandle_AlongLine. """ from geometry.VQT import V from utilities.prefs_constants import hoverHighlightingColor_prefs_key from utilities.prefs_constants import selectionColor_prefs_key from utilities.constants import olive import foundation.env as env from exprs.attr_decl_macros import Option from exprs.attr_decl_macros import State from exprs.Set import Action from exprs.__Symbols__ import _self from exprs.Overlay import Overlay from exprs.ExprsConstants import Drawable from exprs.ExprsConstants import Color from exprs.ExprsConstants import Point from exprs.ExprsConstants import ORIGIN from exprs.ExprsConstants import StateRef from exprs.Rect import Sphere from exprs.Arrow import Arrow from exprs.DraggableHandle import DraggableHandle_AlongLine from exprs.dna_ribbon_view import Cylinder class DnaSegment_ResizeHandle(DraggableHandle_AlongLine): """ Provides a resize handle for editing the length of an existing DnaSegment. """ #Handle color will be changed depending on whether the the handle is grabbed #So this is a 'State variable and its value is used in 'appearance' #(given as an optional argument to 'Sphere') handleColor = State( Color, olive) #The state ref that determines the radius (of the sphere) of this handle. #See DnaSegment_EditCommand._determine_resize_handle_radius() for more #details sphereRadius = Option(StateRef, 1.2) discRadius = Option(StateRef, 1.2) discThickness = Option(StateRef, 1.2) #Stateusbar text. Variable needs to be renamed in superclass. sbar_text = Option(str, "Drag the handle to resize the segment", doc = "Statusbar text on mouseover") #Command object specified as an 'Option' during instantiation of the class #see DnaSegment_EditCommand class definition. command = Option(Action, doc = 'The Command which instantiates this handle') #Current position of the handle. i.e. it is the position of the handle #under the mouse. (its differert than the 'orifinal position) #This variable is used in self.command.graphicsMode to draw a rubberband #line and also to specify the endPoint2 of the structure while modifying #it. See DnaSegment_EditCommand.modifyStructure for details. currentPosition = _self.origin + _self.direction * _self.height_ref.value #Fixed end of the structure (self.command.struct) ..meaning that end won't #move while user grabbs and draggs this handle (attached to a the other #'moving endPoint) . This variable is used to specify endPoint1 of the #structure while modifyin it. See DnaSegment_EditCommand.modifyStructure #and self.on_release for details. fixedEndOfStructure = Option(Point, V(0, 0, 0)) #If this is false, the 'highlightable' object i.e. this handle #won't be drawn. See DraggableHandle.py for the declararion of #the delegate(that defines a Highlightable) We define a If_Exprs to check #whether to draw the highlightable object. should_draw = State(bool, True) pt = _self.direction * _self.discThickness appearance = Overlay( Sphere(_self.sphereRadius, handleColor, center = ORIGIN), Cylinder((ORIGIN + pt, ORIGIN - pt), radius = _self.discRadius, color = handleColor, opacity = 0.5), Arrow( color = handleColor, arrowBasePoint = ORIGIN + _self.direction * 2.0 * _self.sphereRadius, tailPoint = ORIGIN, tailRadius = _self.sphereRadius * 0.3, tailRadiusLimits = (0.36, 3.0), scale = _self.command.glpane.scale, glpane = _self.command.glpane, scale_to_glpane = True ) ) HHColor = env.prefs[hoverHighlightingColor_prefs_key] appearance_highlighted = Option( Drawable, Overlay( Sphere(_self.sphereRadius, HHColor, center = ORIGIN), Cylinder((ORIGIN + pt, ORIGIN - pt), radius = _self.discRadius, color = HHColor), Arrow( color = HHColor, arrowBasePoint = ORIGIN + _self.direction * 2.0 * _self.sphereRadius, tailPoint = ORIGIN, tailRadius = _self.sphereRadius * 0.3, tailRadiusLimits = (0.36, 3.0), scale = _self.command.glpane.scale, glpane = _self.command.glpane, scale_to_glpane = True ) )) def on_press(self): """ Actions when handle is pressed (grabbed, during leftDown event) @see: B{SelectChunks.GraphicsMode.leftDown} @see: B{DnaSegment_EditCommand.grabbedHandle} @see: B{DnaSegment_GraphicsMode.Draw} (which uses some attributes of the current grabbed handle of the command. @see: B{DragHandle_API} """ #Change the handle color when handle is grabbed. See declaration of #self.handleColor in the class definition. self.handleColor = env.prefs[selectionColor_prefs_key] #assign 'self' as the curent grabbed handle of the command. self.command.grabbedHandle = self def on_drag(self): """ Method called while dragging this handle . @see: B{DragHandle_API} """ #Does nothing at the moment. pass def on_release(self): """ This method gets called during leftUp (when the handle is released) @see: B{DnaSegment_EditCommand.modifyStructure} @see: self.on_press @see: B{SelectChunks.GraphicsMode.leftUp} @see: B{DragHandle_API} """ self.handleColor = olive if self.command and hasattr(self.command, 'modifyStructure'): self.command.modifyStructure() #Clear the grabbed handle attribute (the handle is no longer #grabbed) self.command.grabbedHandle = None def hasValidParamsForDrawing(self): """ Returns True if the handles origin and direction are not 'None'. @see: DnaSesgment_GraphicsMode._draw_handles() where the caller uses this to decide whether this handle can be drawn without a problem. """ #NOTE: Better to do it in the drawing code of this class? #But it uses a delegate to draw stuff (see class Highlightable) #May be we should pass this method to that delegate as an optional #argument -- Ninad 2008-04-02 #NOTES: See also: #delegate in class DraggableHandle defined as -- #delegate = If_Exprs(_self.should_draw, Highlightable(....)) if self.origin is None: self.should_draw = False else: self.should_draw = True return self.should_draw
NanoCAD-master
cad/src/dna/commands/DnaSegment/DnaSegment_ResizeHandle.py
# Copyright 2008 Nanorex, Inc. See LICENSE file for details. """ @author: Ninad @version: $Id$ @copyright: 2008 Nanorex, Inc. See LICENSE file for details. @license: GPL History: 2008-10-22: Created to support single click join strand operation Example: while in this command, if user clicks anywhere on a strand, its 3'end is joined to the nearest 5' end on the same dnasegment. TODOs as of 2008-10-26: - Method _bond_two_strandAtoms needs refactoring and to be moved to a dna_helper package. """ import foundation.env as env from dna.commands.JoinStrands.JoinStrands_PropertyManager import JoinStrands_PropertyManager from commands.Select.Select_Command import Select_Command from dna.commands.JoinStrands.ClickToJoinStrands_GraphicsMode import ClickToJoinStrands_GraphicsMode import foundation.env as env from utilities.prefs_constants import joinStrandsCommand_clickToJoinDnaStrands_prefs_key from utilities.debug import print_compact_stack from utilities.constants import CL_SUBCOMMAND from model.bonds import bond_at_singlets from geometry.NeighborhoodGenerator import NeighborhoodGenerator from utilities.prefs_constants import joinStrandsCommand_recursive_clickToJoinDnaStrands_prefs_key from geometry.VQT import vlen # == Command part _superclass = Select_Command class ClickToJoinStrands_Command(Select_Command): """ Command part for joining two strands. @see: superclass B{BreakOrJoinStrands_Command} """ # class constants commandName = 'CLICK_TO_JOIN_STRANDS' featurename = "Click To Join Strands" GraphicsMode_class = ClickToJoinStrands_GraphicsMode FlyoutToolbar_class = None command_should_resume_prevMode = False command_has_its_own_PM = False #class constants for the NEW COMMAND API -- 2008-07-30 command_level = CL_SUBCOMMAND command_parent = 'JOIN_STRANDS' def command_update_state(self): """ See superclass for documentation. Note that this method is called only when self is the currentcommand on the command stack. @see: BuildAtomsFlyout.resetStateOfActions() @see: self.activateAtomsTool() """ _superclass.command_update_state(self) #Make sure that the command Name is JOIN_STRANDS. (because subclasses #of JoinStrands_Command might be using this method). #As of 2008-10-23, if the checkbox 'Click on strand to join' #in the join strands PM is checked, NE1 will enter a command that #implements different mouse behavior in its graphics mode and will stay #there. if self.commandName == 'CLICK_TO_JOIN_STRANDS' and \ not env.prefs[joinStrandsCommand_clickToJoinDnaStrands_prefs_key]: self.command_Done() def joinNeighboringStrands(self, strand, endChoice = 'THREE_PRIME_END'): """ Join the 3 or 5' end of the given strand with a 5' or 3' (respt) end of a neighboring strand, on the SAME DnaSegment. @param strand: The DnaStrand whose 3' or 5' end will be joined with the 5' or 3' end base atom (respectively) on a neighboring strand of the same DnaSegment. @type strand: DnaStrand @see: self._bond_two_strandAtoms() @TODO: implement code when endChoice is 'Five prime end'. At the moment, it works only for the the 3' end atom of <strand>. @see: ClickToJoinStrands_GraphicsMode.chunkLeftUp() """ if not isinstance(strand, self.assy.DnaStrand): print_compact_stack("bug: %s is not a DnaStrand instance"%strand) return bool_recursively_join_strands = env.prefs[joinStrandsCommand_recursive_clickToJoinDnaStrands_prefs_key] if endChoice == 'THREE_PRIME_END': current_strand = strand count = 0 #This implements a NFR by Mark. Recursively join the DnaStrand's #3 prime end with the 5' end of a neighboring strand. #This is SLOW for recursively joining strands. while(True): #If the 'recursivly join DnaStrand option is not checked #return immediately after the first interation (which joins #the two neighboring strands) if count == 1 and not bool_recursively_join_strands: return endAtom = current_strand.get_three_prime_end_base_atom() if endAtom is None: return #Now find the nearest five prime end atom on a strand of the #*same* Dna segment. axis_atom = endAtom.axis_neighbor() if axis_atom is None: return segment = current_strand.get_DnaSegment_with_content_atom(endAtom) if segment is None: return #find all five prime end base atoms contained by this DnaSegment. raw_five_prime_ends = segment.get_all_content_five_prime_ends() def func(atm): """ Returns true if the given atom's strand is not same as the 'strand' which is 'endAoms' parent DnaStrand """ if atm.getDnaStrand() is current_strand: return False return True #Following ensures that the three prime end of <strand> won't be #bonded to the five prime end of the same strand. five_prime_ends = filter(lambda atm: func(atm), raw_five_prime_ends) #Max radius within which to search for the 'neighborhood' atoms #(five prime ends) maxBondLength = 10.0 neighborHood = NeighborhoodGenerator(five_prime_ends, maxBondLength) pos = endAtom.posn() region_atoms = neighborHood.region(pos) #minor optimization if not region_atoms: if not bool_recursively_join_strands: print_compact_stack( "No five prime end atoms found" \ "within %f A radius of the "\ "strand's 3 prime end"%(maxBondLength)) return elif len(region_atoms) == 1: five_prime_end_atom = region_atoms[0] else: lst = [] for atm in region_atoms: length = vlen(pos - atm.posn()) lst.append((length, atm)) lst.sort() #Five prime end atom nearest to the 'endAtom' is the contained #within the first tuple of the sorted list 'tpl' length, five_prime_end_atom = lst[0] self._bond_two_strandAtoms(endAtom, five_prime_end_atom) self.assy.update_parts() current_strand = endAtom.getDnaStrand() count += 1 elif endChoice == 'FIVE_PRIME_END': #NOT IMPLEMENTED AS OF 2008-10-26 endAtom = strand.get_five_prime_end_base_atom() if endAtom is None: return def _bond_two_strandAtoms(self, atm1, atm2): """ Bonds the given strand atoms (sugar atoms) together. To bond these atoms, it always makes sure that a 3' bondpoint on one atom is bonded to 5' bondpoint on the other atom. @param atm1: The first sugar atom of PAM3 (i.e. the strand atom) to be bonded with atm2. @param atm2: Second sugar atom @see: self.joinNeighboringStrands() which calls this TODO 2008-10-26: This method is originally from B_DNA_PAM3_SingleStrand class. It is modified further to account for color change after bonding the two strand atoms. It needs to be refactored and moved to a dna_helper package. [-- Ninad comment] """ #Moved from B_Dna_PAM3_SingleStrand_Generator to here, to fix bugs like #2711 in segment resizing-- Ninad 2008-04-14 assert atm1.element.role == 'strand' and atm2.element.role == 'strand' #Initialize all possible bond points to None five_prime_bondPoint_atm1 = None three_prime_bondPoint_atm1 = None five_prime_bondPoint_atm2 = None three_prime_bondPoint_atm2 = None #Initialize the final bondPoints we will use to create bonds bondPoint1 = None bondPoint2 = None #Find 5' and 3' bondpoints of atm1 (BTW, as of 2008-04-11, atm1 is #the new dna strandend atom See self._fuse_new_dna_with_original_duplex #But it doesn't matter here. for s1 in atm1.singNeighbors(): bnd = s1.bonds[0] if bnd.isFivePrimeOpenBond(): five_prime_bondPoint_atm1 = s1 if bnd.isThreePrimeOpenBond(): three_prime_bondPoint_atm1 = s1 #Find 5' and 3' bondpoints of atm2 for s2 in atm2.singNeighbors(): bnd = s2.bonds[0] if bnd.isFivePrimeOpenBond(): five_prime_bondPoint_atm2 = s2 if bnd.isThreePrimeOpenBond(): three_prime_bondPoint_atm2 = s2 #Determine bondpoint1 and bondPoint2 (the ones we will bond). See method #docstring for details. if five_prime_bondPoint_atm1 and three_prime_bondPoint_atm2: bondPoint1 = five_prime_bondPoint_atm1 bondPoint2 = three_prime_bondPoint_atm2 #Following will overwrite bondpoint1 and bondPoint2, if the condition is #True. Doesn't matter. See method docstring to know why. if three_prime_bondPoint_atm1 and five_prime_bondPoint_atm2: bondPoint1 = three_prime_bondPoint_atm1 bondPoint2 = five_prime_bondPoint_atm2 #Do the actual bonding if bondPoint1 and bondPoint2: bond_at_singlets(bondPoint1, bondPoint2, move = False) else: print_compact_stack("Bug: unable to bond atoms %s and %s: " % (atm1, atm2) ) #The following fixes bug 2770 #Set the color of the whole dna strandGroup to the color of the #strand, whose bondpoint, is dropped over to the bondboint of the #other strandchunk (thus joining the two strands together into #a single dna strand group) - Ninad 2008-04-09 color = atm1.molecule.color if color is None: color = atm1.element.color strandGroup1 = atm1.molecule.parent_node_of_class(self.assy.DnaStrand) #Temporary fix for bug 2829 that Damian reported. #Bruce is planning to fix the underlying bug in the dna updater #code. Once its fixed, The following block of code under #"if DEBUG_BUG_2829" can be deleted -- Ninad 2008-05-01 DEBUG_BUG_2829 = True if DEBUG_BUG_2829: strandGroup2 = atm2.molecule.parent_node_of_class( self.assy.DnaStrand) if strandGroup2 is not None: #set the strand color of strandGroup2 to the one for #strandGroup1. strandGroup2.setStrandColor(color) strandChunkList = strandGroup2.getStrandChunks() for c in strandChunkList: if hasattr(c, 'invalidate_ladder'): c.invalidate_ladder()
NanoCAD-master
cad/src/dna/commands/JoinStrands/ClickToJoinStrands_Command.py
# Copyright 2008 Nanorex, Inc. See LICENSE file for details. """ @author: Ninad @copyright: 2008 Nanorex, Inc. See LICENSE file for details. @version:$Id$ History: TODO: """ from utilities.prefs_constants import arrowsOnThreePrimeEnds_prefs_key from utilities.prefs_constants import arrowsOnFivePrimeEnds_prefs_key from utilities.prefs_constants import useCustomColorForThreePrimeArrowheads_prefs_key from utilities.prefs_constants import dnaStrandThreePrimeArrowheadsCustomColor_prefs_key from utilities.prefs_constants import useCustomColorForFivePrimeArrowheads_prefs_key from utilities.prefs_constants import dnaStrandFivePrimeArrowheadsCustomColor_prefs_key from utilities.prefs_constants import joinStrandsCommand_arrowsOnThreePrimeEnds_prefs_key from utilities.prefs_constants import joinStrandsCommand_arrowsOnFivePrimeEnds_prefs_key from utilities.prefs_constants import joinStrandsCommand_useCustomColorForThreePrimeArrowheads_prefs_key from utilities.prefs_constants import joinStrandsCommand_dnaStrandThreePrimeArrowheadsCustomColor_prefs_key from utilities.prefs_constants import joinStrandsCommand_useCustomColorForFivePrimeArrowheads_prefs_key from utilities.prefs_constants import joinStrandsCommand_dnaStrandFivePrimeArrowheadsCustomColor_prefs_key from dna.command_support.BreakOrJoinStrands_GraphicsMode import BreakOrJoinstrands_GraphicsMode _superclass_for_GM = BreakOrJoinstrands_GraphicsMode class JoinStrands_GraphicsMode( BreakOrJoinstrands_GraphicsMode ): """ Graphics mode for Join strands command """ exit_command_on_leftUp = False #@TODO: This is a flag that may be set externally by previous commands. #Example: In BuildDna_EditCommand (graphicsMode), if you want to join #two strands, upon 'singletLeftDown' of *that command's* graphicsMode, #it enters JoinStrands_Command (i.e. this command and GM), also calling #leftDown method of *this* graphicsmode. Now, when user releases the #left mouse button, it calls leftUp method of this graphics mode, which #in turn exits this command if this flag is set to True #(to go back to the previous command user was in) . This is a bit #confusing but there is no easy way to implement the functionality #we need in the BuildDna command (ability to Join the strands) . #A lot of code that does bondpoint dragging is available in #BuildAtoms_GraphicsMode, but it isn't in BuildDna_GraphicsMode #(as it is a SelectChunks_GraphicsMode superclass for lots of reasons) #So, for some significant amount of time, we may continue to use #this flag to temporarily enter/exit this command. #@see: self.leftUp(), BuildDna_GraphicsMode.singletLeftDown() # [-- Ninad 2008-05-02] def leftDouble(self, event): """ Overrides BuildAtoms_GraphicsMode.leftDouble. In BuildAtoms mode, left double deposits an atom. We don't want that happening here! """ pass def leftUp(self, event): """ Handles mouse leftUp event. @see: BuildDna_GraphicsMode.singletLeftDown() """ _superclass_for_GM.leftUp(self, event) #See a detailed comment about this class variable after #class definition if self.exit_command_on_leftUp: self.exit_command_on_leftUp = False #Exit this GM's command (i.e. the command 'JoinStrands') self.command.command_Done() def deposit_from_MMKit(self, atom_or_pos): """ OVERRIDES superclass method. Returns None as of 2008-05-02 Deposit the library part being previewed into the 3D workspace Calls L{self.deposit_from_Library_page} @param atom_or_pos: If user clicks on a bondpoint in 3D workspace, this is that bondpoint. NE1 will try to bond the part to this bondpoint, by Part's hotspot(if exists) If user double clicks on empty space, this gives the coordinates at that point. This data is then used to deposit the item. @type atom_or_pos: Array (vector) of coordinates or L{Atom} @return: (deposited_stuff, status_msg_text) Object deposited in the 3 D workspace. (Deposits the selected part as a 'Group'. The status message text tells whether the Part got deposited. @rtype: (L{Group} , str) """ #This is a join strands command and we don't want anything to be #deposited from the MMKit. So simply return None. #Fixes bug 2831 return None _GLOBAL_TO_LOCAL_PREFS_KEYS = { arrowsOnThreePrimeEnds_prefs_key: joinStrandsCommand_arrowsOnThreePrimeEnds_prefs_key, arrowsOnFivePrimeEnds_prefs_key: joinStrandsCommand_arrowsOnFivePrimeEnds_prefs_key, useCustomColorForThreePrimeArrowheads_prefs_key: joinStrandsCommand_useCustomColorForThreePrimeArrowheads_prefs_key, useCustomColorForFivePrimeArrowheads_prefs_key: joinStrandsCommand_useCustomColorForFivePrimeArrowheads_prefs_key, dnaStrandThreePrimeArrowheadsCustomColor_prefs_key: joinStrandsCommand_dnaStrandThreePrimeArrowheadsCustomColor_prefs_key, dnaStrandFivePrimeArrowheadsCustomColor_prefs_key: joinStrandsCommand_dnaStrandFivePrimeArrowheadsCustomColor_prefs_key, } def get_prefs_value(self, prefs_key): #bruce 080605 """ [overrides superclass method for certain prefs_keys] """ # map global keys to local ones, when we have them prefs_key = self._GLOBAL_TO_LOCAL_PREFS_KEYS.get( prefs_key, prefs_key) return _superclass_for_GM.get_prefs_value( self, prefs_key)
NanoCAD-master
cad/src/dna/commands/JoinStrands/JoinStrands_GraphicsMode.py
NanoCAD-master
cad/src/dna/commands/JoinStrands/__init__.py
# Copyright 2008 Nanorex, Inc. See LICENSE file for details. """ @author: Ninad @version: $Id$ @copyright: 2008 Nanorex, Inc. See LICENSE file for details. @license: GPL TODOs: Many changes planned in JoinStrands_GraphicsMode . """ from dna.commands.JoinStrands.JoinStrands_PropertyManager import JoinStrands_PropertyManager from dna.command_support.BreakOrJoinStrands_Command import BreakOrJoinStrands_Command from dna.commands.JoinStrands.JoinStrands_GraphicsMode import JoinStrands_GraphicsMode import foundation.env as env from utilities.prefs_constants import joinStrandsCommand_clickToJoinDnaStrands_prefs_key # == Command part _superclass = BreakOrJoinStrands_Command class JoinStrands_Command(BreakOrJoinStrands_Command): """ Command part for joining two strands. @see: superclass B{BreakOrJoinStrands_Command} """ # class constants commandName = 'JOIN_STRANDS' featurename = "Join Strands" GraphicsMode_class = JoinStrands_GraphicsMode PM_class = JoinStrands_PropertyManager def _get_init_gui_flyout_action_string(self): return 'joinStrandsAction' def command_update_state(self): """ See superclass for documentation. Note that this method is called only when self is the currentcommand on the command stack. @see: BuildAtomsFlyout.resetStateOfActions() @see: self.activateAtomsTool() """ _superclass.command_update_state(self) #Make sure that the command Name is JOIN_STRANDS. (because subclasses #of JoinStrands_Command might be using this method). #As of 2008-10-23, if the checkbox 'Click on strand to join' #in the join strands PM is checked, NE1 will enter a command that #implements different mouse behavior in its graphics mode and will stay #there. if self.commandName == 'JOIN_STRANDS' and \ env.prefs[joinStrandsCommand_clickToJoinDnaStrands_prefs_key] \ and not self.graphicsMode.exit_command_on_leftUp: self.commandSequencer.userEnterCommand('CLICK_TO_JOIN_STRANDS')
NanoCAD-master
cad/src/dna/commands/JoinStrands/JoinStrands_Command.py
# Copyright 2008 Nanorex, Inc. See LICENSE file for details. """ JoinStrands_PropertyManager.py The JoinStrands_PropertyManager class provides a Property Manager for the B{Join Strands} command on the flyout toolbar in the Build > Dna mode. @author: Ninad @version: $Id$ @copyright: 2008 Nanorex, Inc. See LICENSE file for details. TODO: as of 2008-02-13: - Remove 'Cancel' button -- This needs to be supported in transient done-cancel button code (confirmation_corner) Ninad 2008-06-04 - 2008-06-05: Revised and refactored arrowhead display code and moved part common to both Break and JoinStrands PMs into new module BreakOrJoinStrands_PropertyManager """ import sys from PM.PM_GroupBox import PM_GroupBox from PM.PM_CheckBox import PM_CheckBox from PyQt4.Qt import SIGNAL import foundation.env as env from utilities.prefs_constants import joinStrandsCommand_arrowsOnThreePrimeEnds_prefs_key from utilities.prefs_constants import joinStrandsCommand_arrowsOnFivePrimeEnds_prefs_key from utilities.prefs_constants import joinStrandsCommand_useCustomColorForThreePrimeArrowheads_prefs_key from utilities.prefs_constants import joinStrandsCommand_dnaStrandThreePrimeArrowheadsCustomColor_prefs_key from utilities.prefs_constants import joinStrandsCommand_useCustomColorForFivePrimeArrowheads_prefs_key from utilities.prefs_constants import joinStrandsCommand_dnaStrandFivePrimeArrowheadsCustomColor_prefs_key from utilities.prefs_constants import joinStrandsCommand_clickToJoinDnaStrands_prefs_key from utilities.prefs_constants import joinStrandsCommand_recursive_clickToJoinDnaStrands_prefs_key from widgets.prefs_widgets import connect_checkbox_with_boolean_pref from dna.command_support.BreakOrJoinStrands_PropertyManager import BreakOrJoinStrands_PropertyManager _superclass = BreakOrJoinStrands_PropertyManager class JoinStrands_PropertyManager( BreakOrJoinStrands_PropertyManager ): """ The JoinStrands_PropertyManager class provides a Property Manager for the B{Join Strands} command on the flyout toolbar in the Build > Dna mode. @ivar title: The title that appears in the property manager header. @type title: str @ivar pmName: The name of this property manager. This is used to set the name of the PM_Dialog object via setObjectName(). @type name: str @ivar iconPath: The relative path to the PNG file that contains a 22 x 22 icon image that appears in the PM header. @type iconPath: str """ title = "Join Strands" pmName = title iconPath = "ui/actions/Command Toolbar/BuildDna/JoinStrands.png" def __init__( self, command ): """ Constructor for the property manager. """ _superclass.__init__(self, command) if sys.platform == 'darwin': leftMouseButtonString = 'mouse button' else: leftMouseButtonString = 'left mouse button' msg = "To <b>join</b> two strands, drag an arrowhead of one strand "\ "and drop it onto the end (arrowhead or pseudo atom) of another "\ "strand." self.updateMessage(msg) return 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 _superclass.connect_or_disconnect_signals(self, isConnect) change_connect(self.clickToJoinDnaStrandsCheckBox, SIGNAL("toggled(bool)"), self.clickToJoinDnaStrandsCheckBox_toggled) def clickToJoinDnaStrandsCheckBox_toggled(self, enable): self.recursive_clickToJoinDnaStrandsCheckBox.setEnabled(enable) def _addGroupBoxes( self ): """ Add the DNA Property Manager group boxes. """ self._joinOptionsGroupBox = PM_GroupBox(self, title = "Join Options") self._loadJoinOptionsGroupbox(self._joinOptionsGroupBox) self._displayOptionsGroupBox = PM_GroupBox( self, title = "Display Options" ) self._loadDisplayOptionsGroupBox( self._displayOptionsGroupBox ) self._baseNumberLabelGroupBox = PM_GroupBox( self, title = "Base Number Labels" ) self._loadBaseNumberLabelGroupBox(self._baseNumberLabelGroupBox) return def _loadJoinOptionsGroupbox(self, pmGroupBox): """ Load widgets in this group box. """ self.clickToJoinDnaStrandsCheckBox = \ PM_CheckBox(pmGroupBox , text = 'Click on strand to join', widgetColumn = 0, spanWidth = True) connect_checkbox_with_boolean_pref( self.clickToJoinDnaStrandsCheckBox, joinStrandsCommand_clickToJoinDnaStrands_prefs_key ) self.recursive_clickToJoinDnaStrandsCheckBox = \ PM_CheckBox(pmGroupBox , text = 'Recursively join strands', widgetColumn = 1, spanWidth = True) connect_checkbox_with_boolean_pref( self.recursive_clickToJoinDnaStrandsCheckBox, joinStrandsCommand_recursive_clickToJoinDnaStrands_prefs_key) if not env.prefs[joinStrandsCommand_clickToJoinDnaStrands_prefs_key]: self.recursive_clickToJoinDnaStrandsCheckBox.setEnabled(False) #Return varius prefs_keys for arrowhead display options ui elements ======= def _prefs_key_arrowsOnThreePrimeEnds(self): """ Return the appropriate KEY of the preference for whether to draw arrows on 3' strand ends of PAM DNA. """ return joinStrandsCommand_arrowsOnThreePrimeEnds_prefs_key def _prefs_key_arrowsOnFivePrimeEnds(self): """ Return the appropriate KEY of the preference for whether to draw arrows on 5' strand ends of PAM DNA. """ return joinStrandsCommand_arrowsOnFivePrimeEnds_prefs_key def _prefs_key_useCustomColorForThreePrimeArrowheads(self): """ Return the appropriate KEY of the preference for whether to use a custom color for 3' arrowheads (if they are drawn) or for 3' strand end atoms (if arrowheads are not drawn) """ return joinStrandsCommand_useCustomColorForThreePrimeArrowheads_prefs_key def _prefs_key_useCustomColorForFivePrimeArrowheads(self): """ Return the appropriate KEY of the preference for whether to use a custom color for 5' arrowheads (if they are drawn) or for 5' strand end atoms (if arrowheads are not drawn). """ return joinStrandsCommand_useCustomColorForFivePrimeArrowheads_prefs_key def _prefs_key_dnaStrandThreePrimeArrowheadsCustomColor(self): """ Return the appropriate KEY of the preference for what custom color to use when drawing 3' arrowheads (if they are drawn) or 3' strand end atoms (if arrowheads are not drawn). """ return joinStrandsCommand_dnaStrandThreePrimeArrowheadsCustomColor_prefs_key def _prefs_key_dnaStrandFivePrimeArrowheadsCustomColor(self): """ Return the appropriate KEY of the preference for what custom color to use when drawing 5' arrowheads (if they are drawn) or 5' strand end atoms (if arrowheads are not drawn). """ return joinStrandsCommand_dnaStrandFivePrimeArrowheadsCustomColor_prefs_key def _addWhatsThisText( self ): """ What's This text for widgets in the DNA Property Manager. """ pass def _addToolTipText(self): """ Tool Tip text for widgets in the DNA Property Manager. """ pass
NanoCAD-master
cad/src/dna/commands/JoinStrands/JoinStrands_PropertyManager.py
# Copyright 2008 Nanorex, Inc. See LICENSE file for details. """ JoinStrands_By_DND_RequestCommand This is a request command called whenever a user wants to join two strands by drag and drop. (DND = Drag and Drop). During singletLeftDown of the current graphicsMode, it calls this request command and then during left up, this request command is exited. @author: Ninad @copyright: 2008 Nanorex, Inc. See LICENSE file for details. @version:$Id$ History: Created to fix this bug reported by Mark: 1. Insert DNA. 2. Nick one of the strands using "Break Strands" 3. Heal nick using "Join Strands" (using drag-and-drop). This causes the premature exit from "Join Strands". TODO: """ from utilities.constants import CL_REQUEST from dna.commands.JoinStrands.JoinStrands_GraphicsMode import JoinStrands_GraphicsMode from dna.commands.JoinStrands.JoinStrands_Command import JoinStrands_Command class JoinStrands_By_DND_RequestCommand(JoinStrands_Command): """ Example: In this BuildDna_EditCommand (graphicsMode), if you want to join two strands, upon 'singletLeftDown' it enters JoinStrands_Command , also calling leftDown method of its graphicsmode. Now, when user releases theLMB, it calls JoinStrands_GraphicsMode.leftUp() which in turn exits that command if the flag 'exit_command_on_leftUp' is set to True(to go back to the previous command user was in) . A lot of code that does bondpoint dragging is available in BuildAtoms_GraphicsMode, but it isn't in BuildDna_GraphicsMode (as it is a SelectChunks_GraphicsMode superclass for lots of reasons) So, for some significant amount of time, we may continue to use this flag to temporarily enter/exit this command. @see: BuildDna_GraphicsMode.singletLeftDown() @see: ClickToJoinStrands_GraphicsMode. """ command_level = CL_REQUEST commandName = 'JoinStrands_By_DND' featurename = 'JoinStrands By DND RequestCommand' GraphicsMode_class = JoinStrands_GraphicsMode command_should_resume_prevMode = True command_has_its_own_PM = False pass
NanoCAD-master
cad/src/dna/commands/JoinStrands/JoinStrands_By_DND_RequestCommand.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-10-21 : Created TODO: """ from utilities.prefs_constants import arrowsOnThreePrimeEnds_prefs_key from utilities.prefs_constants import arrowsOnFivePrimeEnds_prefs_key from utilities.prefs_constants import useCustomColorForThreePrimeArrowheads_prefs_key from utilities.prefs_constants import dnaStrandThreePrimeArrowheadsCustomColor_prefs_key from utilities.prefs_constants import useCustomColorForFivePrimeArrowheads_prefs_key from utilities.prefs_constants import dnaStrandFivePrimeArrowheadsCustomColor_prefs_key from utilities.prefs_constants import joinStrandsCommand_arrowsOnThreePrimeEnds_prefs_key from utilities.prefs_constants import joinStrandsCommand_arrowsOnFivePrimeEnds_prefs_key from utilities.prefs_constants import joinStrandsCommand_useCustomColorForThreePrimeArrowheads_prefs_key from utilities.prefs_constants import joinStrandsCommand_dnaStrandThreePrimeArrowheadsCustomColor_prefs_key from utilities.prefs_constants import joinStrandsCommand_useCustomColorForFivePrimeArrowheads_prefs_key from utilities.prefs_constants import joinStrandsCommand_dnaStrandFivePrimeArrowheadsCustomColor_prefs_key from dna.commands.BuildDna.BuildDna_GraphicsMode import BuildDna_GraphicsMode _superclass = BuildDna_GraphicsMode class ClickToJoinStrands_GraphicsMode(BuildDna_GraphicsMode): def update_cursor_for_no_MB(self): """ Update the cursor for no mouse button pressed """ _superclass.update_cursor_for_no_MB(self) if self.command and self.o.selobj is None: self.o.setCursor(self.win.clickToJoinStrandsCursor) def editObjectOnSingleClick(self): """ Subclasses can override this method. If this method returns True, when you left click on a DnaSegment or a DnaStrand, it becomes editable (i.e. program enters the edit command of that particular object if that object is editable) @see: MakeCrossover_GraphicsMode.editObjectOnSingleClick() """ return False def chunkLeftUp(self, aChunk, event): """ Upon chunkLeftUp, join the 3' end of a strand with a five prime end of a neighboring strand. @see: ClickToJoinStrands_Command.joinNeighboringStrands() which is called here. """ _superclass.chunkLeftUp(self, aChunk, event) if not self.glpane.modkeys is None: return strand = aChunk.getDnaStrand() self.command.joinNeighboringStrands(strand) _GLOBAL_TO_LOCAL_PREFS_KEYS = { arrowsOnThreePrimeEnds_prefs_key: joinStrandsCommand_arrowsOnThreePrimeEnds_prefs_key, arrowsOnFivePrimeEnds_prefs_key: joinStrandsCommand_arrowsOnFivePrimeEnds_prefs_key, useCustomColorForThreePrimeArrowheads_prefs_key: joinStrandsCommand_useCustomColorForThreePrimeArrowheads_prefs_key, useCustomColorForFivePrimeArrowheads_prefs_key: joinStrandsCommand_useCustomColorForFivePrimeArrowheads_prefs_key, dnaStrandThreePrimeArrowheadsCustomColor_prefs_key: joinStrandsCommand_dnaStrandThreePrimeArrowheadsCustomColor_prefs_key, dnaStrandFivePrimeArrowheadsCustomColor_prefs_key: joinStrandsCommand_dnaStrandFivePrimeArrowheadsCustomColor_prefs_key, } def get_prefs_value(self, prefs_key): #bruce 080605 """ [overrides superclass method for certain prefs_keys] """ # map global keys to local ones, when we have them prefs_key = self._GLOBAL_TO_LOCAL_PREFS_KEYS.get( prefs_key, prefs_key) return _superclass.get_prefs_value( self, prefs_key)
NanoCAD-master
cad/src/dna/commands/JoinStrands/ClickToJoinStrands_GraphicsMode.py
# Copyright 2007-2009 Nanorex, Inc. See LICENSE file for details. """ BuildDna_EditCommand.py @author: Ninad @version: $Id$ @copyright: 2007-2009 Nanorex, Inc. See LICENSE file for details. History: Ninad 2008-01-11: Created TODO: as of 2008-01-11 - Needs more documentation and the file is subjected to heavy revision. This is an initial implementation of default Dna edit mode. - Methods such as callback_addSegments might be renamed. BUGS: - Has bugs such as -- Flyout toolbar doesn't get updated when you return to BuildDna_EditCommand from a a temporary command. - Just entering and leaving BuilddDna_EditCommand creates an empty DnaGroup """ from command_support.EditCommand import EditCommand from dna.model.DnaGroup import DnaGroup from utilities.Log import greenmsg from utilities.exception_classes import PluginBug, UserError from utilities.constants import gensym from ne1_ui.toolbars.Ui_DnaFlyout import DnaFlyout from model.chem import Atom from model.chunk import Chunk from model.bonds import Bond from dna.commands.BuildDna.BuildDna_GraphicsMode import BuildDna_GraphicsMode from dna.commands.BuildDna.BuildDna_PropertyManager import BuildDna_PropertyManager from utilities.Comparison import same_vals _superclass = EditCommand class BuildDna_EditCommand(EditCommand): """ BuildDna_EditCommand provides a convenient way to edit or create a DnaGroup object """ #GraphicsMode GraphicsMode_class = BuildDna_GraphicsMode #Property Manager PM_class = BuildDna_PropertyManager #Flyout Toolbar FlyoutToolbar_class = DnaFlyout cmd = greenmsg("Build DNA: ") prefix = 'DnaGroup' # used for gensym cmdname = "Build Dna" commandName = 'BUILD_DNA' featurename = "Build Dna" from utilities.constants import CL_ENVIRONMENT_PROVIDING command_level = CL_ENVIRONMENT_PROVIDING command_should_resume_prevMode = False command_has_its_own_PM = True # Generators for DNA, nanotubes and graphene have their MT name # generated (in GeneratorBaseClass) from the prefix. create_name_from_prefix = True #The following class constant is used in creating dynamic menu items (using self.makeMenus) #if this flag is not defined, the menu doesn't get created #or use of self.graphicsMode in self.makeMenus throws errors. #See also other examples of its use in older Commands such as #BuildAtoms_Command (earlier depositmode) call_makeMenus_for_each_event = True __previous_command_stack_change_indicator = None def command_update_UI(self): """ Extends superclass method. """ _superclass.command_update_UI(self) #Ths following code fixes a bug reported by Mark on 2008-11-10 #the bug is: #1. Insert DNA #2. Enter Break Strands command. Exit command. #3. Do a region selection to select the middle of the DNA duplex. #Notice that atoms are selected, not the strands/segment chunks. #The problem is the selection state is not changed back to the Select Chunks #the code that does this is in Enter_GraphicsMode. #(See SelectChunks_GraphicsMode) but when a command is 'resumed', that #method is not called. The fix for this is to check if the command stack #indicator changed in the command_update_state method, if it is changed #and if currentCommand is BuildDna_EditCommand, call the code that #ensures that chunks will be selected when you draw a selection lasso. #-- Ninad 2008-11-10 indicator = self.assy.command_stack_change_indicator() if same_vals(self.__previous_command_stack_change_indicator, indicator): return self.__previous_command_stack_change_indicator = indicator self.assy.selectChunksWithSelAtoms_noupdate() def runCommand(self): """ Overrides EditCommand.runCommand """ self.struct = None self.existingStructForEditing = False def keep_empty_group(self, group): """ Returns True if the empty group should not be automatically deleted. otherwise returns False. The default implementation always returns False. Subclasses should override this method if it needs to keep the empty group for some reasons. Note that this method will only get called when a group has a class constant autdelete_when_empty set to True. (and as of 2008-03-06, it is proposed that dna_updater calls this method when needed. @see: Command.keep_empty_group() which is overridden here. """ bool_keep = EditCommand.keep_empty_group(self, group) if not bool_keep: if group is self.struct: bool_keep = True return bool_keep def createStructure(self): """ Overrides superclass method. It doesn't do anything for this type of editcommand """ self.preview_or_finalize_structure(previewing = True) def editStructure(self, struct = None): """ Overrides EditCommand.editStructure method. Provides a way to edit an 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} """ if struct is not None: #Should we always unpick the structure while editing it? #Makes sense for editing a Dna. If this is problematic, the #following should be done in the subclasses that need this. if hasattr(struct, 'picked') and struct.picked: struct.unpick() EditCommand.editStructure(self, struct) def _getStructureType(self): """ Subclasses 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: EditCommand._getStructureType() (overridden here) @see: self.hasValidStructure() """ return self.win.assy.DnaGroup def _createStructure(self): """ creates and returns the structure (in this case a L{Group} object that contains the DNA strand and axis chunks. @return : group containing that contains the DNA strand and axis chunks. @rtype: L{Group} @note: This needs to return a DNA object once that model is implemented """ # 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 # Create the model tree group node. # Make sure that the 'topnode' of this part is a Group (under which the # DNa group will be placed), if the topnode is not a group, make it a # a 'Group' (applicable to Clipboard parts).See part.py # --Part.ensure_toplevel_group method. This is an important line # and it fixes bug 2585 self.win.assy.part.ensure_toplevel_group() dnaGroup = DnaGroup(self.name, self.win.assy, self.win.assy.part.topnode, editCommand = self) try: self.win.assy.place_new_geometry(dnaGroup) return dnaGroup except (PluginBug, UserError): # Why do we need UserError here? Mark 2007-08-28 dnaGroup.kill() raise PluginBug("Internal error while trying to create DNA duplex.") def _gatherParameters(self): """ Return the parameters needed to build this structure @return: A list of all DnaSegments present withing the self.struct (which is a dna group) or None if self.structure doesn't exist @rtype: tuple """ #Passing the segmentList as a parameter is not implemented ##if self.struct: ##segmentList = [] ##for segment in self.struct.members: ##if isinstance(segment, DnaSegment): ##segmentList.append(segment) ##if segmentList: ##return (segmentList) return None def _modifyStructure(self, params): """ Modify the structure based on the parameters specified. Overrides EditCommand._modifystructure. This method removes the old structure and creates a new one using self._createStructure. This was needed for the structures like this (Dna, Nanotube etc) . . See more comments in the method. """ assert self.struct # parameters have changed, update existing structure self._revertNumber() # 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 #@NOTE: Unlike editcommands such as Plane_EditCommand, this #editCommand actually removes the structure and creates a new one #when its modified. We don't yet know if the DNA object model # will solve this problem. (i.e. reusing the object and just modifying #its attributes. Till that time, we'll continue to use #what the old GeneratorBaseClass use to do ..i.e. remove the item and # create a new one -- Ninad 2007-10-24 self._removeStructure() self.previousParams = params self.struct = self._createStructure() return def _finalizeStructure(self): """ Overrides EditCommand._finalizeStructure. This method also makes sure that the DnaGroup is not empty ..if its empty it deletes it. @see: dna_model.DnaGroup.isEmpty @see: EditCommand.preview_or_finalize_structure """ if self.struct is not None: if self.struct.isEmpty(): #Don't keep empty DnaGroup Fixes bug 2603. self._removeStructure() self.win.win_update() else: EditCommand._finalizeStructure(self) if self.struct is not None: #Make sure that he DnaGroup in the Model Tree is in collapsed state #after finalizing the structure. #DON'T DO self.struct.open = False in the above conditional #because the EditCommand._finalizeStructure may have assigned #'None' for 'self.struct'! self.struct.open = False def cancelStructure(self): """ Cancel the structure """ EditCommand.cancelStructure(self) if self.struct is not None: if self.struct.isEmpty(): self._removeStructure() def provideParamsForTemporaryMode_in_BuildDna(self, temporaryModeName = None): # REVIEW: this is called directly by our subcommand InsertDna_EditCommand. # I'm not sure if it's ever called by a request command # (but I guess not, due to its old-code check on # temporaryModeName == 'INSERT_DNA'). # If not, it should be removed in favor of direct access to # methods or attrs of interest. See comment near its call in # InsertDna_EditCommand.py. # # For now, I just renamed it and its call, to verify this theory. # Later it should be renamed better and its argument removed. # [bruce 080801 comment] """ ## NOTE: This needs to be a general API method. There are situations when ## user enters a temporary mode , does something there and returns back to ## the previous mode he was in. He also needs to send some data from ## previous mode to the temporary mode . ## @see: B{DnaLineMode} ## @see: self.acceptParamsFromTemporaryMode @see InsertDna_EditCommand._createSegment(), @see: InsertDna_EditCommand.createStructure() """ params = () if temporaryModeName in ('INSERT_DNA', None): #Pass the self.struct to the DnaDuplex_EdiCommand #This deprecates use of self.callback_addSegments (in which #segments created while in DnaDuplex command are added after #returning to BuildDna mode) The new implementation provides the #DnaGroup to the DnaDuplex command and then adds the created #segments directly to it. #See: InsertDna_EditCommand._createSegment(), # InsertDna_EditCommand.createStructure(), and #following condition (hasValidStructure) fixes bug 2815.Earlier #ondition was just checking if self.struct is None. #self.hasValidStructure checks if the structure is killed etc #--Ninad 2008-04-21 if not self.hasValidStructure(): self.struct = self._createStructure() params = (self.struct) return params def makeMenus(self): """ Create context menu for this command. (Build Dna mode) @see: chunk.make_glpane_cmenu_items @see: DnaSegment_EditCommand.makeMenus """ if not hasattr(self, 'graphicsMode'): return selobj = self.glpane.selobj if selobj is None: self._makeEditContextMenus() return self.Menu_spec = [] highlightedChunk = None if isinstance(selobj, Chunk): highlightedChunk = selobj if isinstance(selobj, Atom): highlightedChunk = selobj.molecule elif isinstance(selobj, Bond): chunk1 = selobj.atom1.molecule chunk2 = selobj.atom2.molecule if chunk1 is chunk2 and chunk1 is not None: highlightedChunk = chunk1 if highlightedChunk is not None: highlightedChunk.make_glpane_cmenu_items(self.Menu_spec, self) return
NanoCAD-master
cad/src/dna/commands/BuildDna/BuildDna_EditCommand.py
NanoCAD-master
cad/src/dna/commands/BuildDna/__init__.py
# Copyright 2007-2008 Nanorex, Inc. See LICENSE file for details. """ BuildDna_PropertyManager.py @author: Ninad @version: $Id$ @copyright: 2007-2008 Nanorex, Inc. See LICENSE file for details. History: Ninad 2008-01-11: Created TODO: as of 2008-01-11 - Needs more documentation and the file is subjected to heavy revision. This is an initial implementation of default Dna edit mode. - Methods such as callback_addSegments might be renamed. BUGS: - Has bugs such as -- Flyout toolbar doesn't get updated when you return to BuildDna_EditCommand from a a temporary command. - Just entering and leaving BuilddDna_EditCommand creates an empty DnaGroup """ from utilities import debug_flags from utilities.debug import print_compact_stack from PyQt4.Qt import SIGNAL from PM.PM_GroupBox import PM_GroupBox from PM.PM_PushButton import PM_PushButton from PM.PM_SelectionListWidget import PM_SelectionListWidget from command_support.EditCommand_PM import EditCommand_PM from PM.PM_Constants import PM_DONE_BUTTON from PM.PM_Constants import PM_WHATS_THIS_BUTTON from PM.PM_Constants import PM_CANCEL_BUTTON from PM.PM_Colors import pmReferencesListWidgetColor from utilities.Comparison import same_vals from PM.PM_DnaBaseNumberLabelsGroupBox import PM_DnaBaseNumberLabelsGroupBox DEBUG_CHANGE_COUNTERS = False class BuildDna_PropertyManager(EditCommand_PM): """ The BuildDna_PropertyManager class provides a Property Manager for the B{Build > DNA } command. @ivar title: The title that appears in the property manager header. @type title: str @ivar pmName: The name of this property manager. This is used to set the name of the PM_Dialog object via setObjectName(). @type name: str @ivar iconPath: The relative path to the PNG file that contains a 22 x 22 icon image that appears in the PM header. @type iconPath: str """ title = "Build DNA" pmName = title iconPath = "ui/actions/Tools/Build Structures/DNA.png" sponsor_keyword = None # Nanorex is the sponsor. Change to 'DNA' to the # the NUPACK logo. def __init__( self, command ): """ Constructor for the Build DNA property manager. """ #Attributes for self._update_UI_do_updates() to keep track of changes #in these , since the last call of that method. These are used to #determine whether certain UI updates are needed. self._previousSelectionParams = None self._previousStructureParams = None self._previousCommandStackParams = None #see self.connect_or_disconnect_signals for comment about this flag self.isAlreadyConnected = False self.isAlreadyDisconnected = False EditCommand_PM.__init__( self, command) self.showTopRowButtons( PM_DONE_BUTTON | \ PM_CANCEL_BUTTON | \ PM_WHATS_THIS_BUTTON) 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 """ #TODO: This is a temporary fix for a bug. When you invoke a temporary mode # entering such a temporary mode keeps the signals of #PM from the previous mode connected ( #but while exiting that temporary mode and reentering the #previous mode, it atucally reconnects the signal! This gives rise to #lots of bugs. This needs more general fix in Temporary mode API. # -- Ninad 2008-01-09 (similar comment exists in MovePropertyManager.py if isConnect and self.isAlreadyConnected: if debug_flags.atom_debug: print_compact_stack("warning: attempt to connect widgets"\ "in this PM that are already connected." ) return if not isConnect and self.isAlreadyDisconnected: if debug_flags.atom_debug: print_compact_stack("warning: attempt to disconnect widgets"\ "in this PM that are already disconnected.") return self.isAlreadyConnected = isConnect self.isAlreadyDisconnected = not isConnect if isConnect: change_connect = self.win.connect else: change_connect = self.win.disconnect self.strandListWidget.connect_or_disconnect_signals(isConnect) self.segmentListWidget.connect_or_disconnect_signals(isConnect) change_connect(self.editStrandPropertiesButton, SIGNAL("clicked()"), self._editDnaStrand) change_connect(self.editSegmentPropertiesButton, SIGNAL("clicked()"), self._editDnaSegment) change_connect(self.searchForCrossoversButton, SIGNAL("clicked()"), self._enterMakeCrossoversCommand) self._baseNumberLabelGroupBox.connect_or_disconnect_signals(isConnect) 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. """ #For new command API, we will always show the exit button to check #if Exit button really exits the subcommand and the parent command #(earlier there were bugs) . Regaring 'whether this should be the #default behavior', its a UI design issue and we will worry about it #later -- Ninad 2008-08-27 (based on an email exchanged with Bruce) pass def _update_UI_do_updates(self): """ Overrides superclass method. @see: Command_PropertyManager._update_UI_do_updates() """ newSelectionParams = self._currentSelectionParams() current_struct_params = self._currentStructureParams() selection_params_unchanged = same_vals(newSelectionParams, self._previousSelectionParams) #introducing self._previousStructureParams and #adding structure_params_unchanged check to the 'if' condition below #fixes bug 2910. structure_params_unchanged = same_vals(self._previousStructureParams, current_struct_params) current_command_stack_params = self._currentCommandStackParams() #Check if command stack params changed since last call of this #PM update method. This is used to fix bugs like 2940 command_stack_params_unchanged = same_vals( self._previousCommandStackParams, current_command_stack_params) #No need to proceed if any of the selection/ structure and commandstack #parameters remained unchanged since last call. --- [CONDITION A] if selection_params_unchanged and structure_params_unchanged and command_stack_params_unchanged: #This second condition above fixes bug 2888 return self._previousStructureParams = current_struct_params self._previousSelectionParams = newSelectionParams self._previousCommandStackParams = current_command_stack_params ##if not selection_params_unchanged or not command_stack_params_unchanged and structure_params_unchanged: if structure_params_unchanged: #NOTE: We checked if either of the selection struct or command stack #parameters or both changed. (this was referred as '[CONDITION A]' #above). So, this condition (structure_params_unchanged)also means #either selection or command stack or both parameters were changed. if not command_stack_params_unchanged: #update the list widgets *before* updating the selection if #the command stack changed. This ensures that the selection box #appears around the list widget items that are selected. self.updateListWidgets() selectedStrands, selectedSegments = newSelectionParams self.strandListWidget.updateSelection(selectedStrands) self.segmentListWidget.updateSelection(selectedSegments) if len(selectedStrands) == 1: self.editStrandPropertiesButton.setEnabled(True) else: self.editStrandPropertiesButton.setEnabled(False) if len(selectedSegments) == 1: self.editSegmentPropertiesButton.setText("Edit Properties...") self.editSegmentPropertiesButton.setEnabled(True) elif len(selectedSegments) > 1: resizeString = "Resize Selected Segments (%d)..." % len(selectedSegments) self.editSegmentPropertiesButton.setText(resizeString) self.editSegmentPropertiesButton.setEnabled(True) self.searchForCrossoversButton.setEnabled(True) else: self.editSegmentPropertiesButton.setText("Edit Properties...") self.editSegmentPropertiesButton.setEnabled(False) self.searchForCrossoversButton.setEnabled(False) return # Calling updateListWidgets() here fixes bug 2950 without undoing the # fix to bug 2940. --Mark 2008-12-13. self.updateListWidgets() return def _currentCommandStackParams(self): """ The return value is supposed to be used by BUILD_DNA command PM ONLY and NOT by any subclasses. Returns a tuple containing current scommand stack change indicator and the name of the command 'BUILD_DNA'. These parameters are then used to decide whether updating widgets in this property manager is needed, when self._update_UI_do_updates() is called. @NOTE: - Command_PropertyManager.update_UI() already does a check to see if any of the global change indicators in assembly (command_stack_change, model_change, selection_change) changed since last call and then only calls self._update_UI_do_updates(). - But this method is just used to keep track of the local command stack change counter in order to update the list widgets. - This is used to fix bug 2940 @see: self._update_UI_do_updates() """ commandStackCounter = self.command.assy.command_stack_change_indicator() #Append 'BUILD_DNA to the tuple to be returned. This is just to remind #us that this method is meant for BUIL_DNA command PM only. (and not #by any subclasses) Should we assert this? I think it will slow things #down so this comment is enough -- Ninad 2008-09-30 return (commandStackCounter, 'BUILD_DNA') def _currentSelectionParams(self): """ Returns a tuple containing current selection parameters. These parameters are then used to decide whether updating widgets in this property manager is needed when L{self.model_changed} method is called. @return: A tuple that contains following selection parameters - Total number of selected atoms (int) - Selected Atom if a single atom is selected, else None - Position vector of the single selected atom or None @rtype: tuple @NOTE: This method may be renamed in future. It's possible that there are other groupboxes in the PM that need to be updated when something changes in the glpane. """ selectedStrands = [] selectedSegments = [] if self.command is not None and self.command.hasValidStructure(): selectedStrands = self.command.struct.getSelectedStrands() selectedSegments = self.command.struct.getSelectedSegments() return (selectedStrands, selectedSegments) def _currentStructureParams(self): """ Return current structure parameters of interest to self.model_changed. Right now it only returns the number of strands within the structure (or None). This is a good enough check (and no need to compare each and every strand within the structure with a previously stored set of strands). """ #Can it happen that the total number of strands remains the same even #after some alterations to the strands? Unlikely. (Example: a single #Break strands operation will increase the number of strands by one. #Or Join strands decrease it by 1) params = None if self.command and self.command.hasValidStructure(): strandList = [] strandList = self.command.struct.getStrands() params = len(strandList) return params def close(self): """ Closes the Property Manager. Overrides EditCommand_PM.close() """ #Clear tags, if any, due to the selection in the self.strandListWidget. if self.strandListWidget: self.strandListWidget.clear() if self.segmentListWidget: self.segmentListWidget.clear() EditCommand_PM.close(self) def show(self): """ Show this PM As of 2007-11-20, it also shows the Sequence Editor widget and hides the history widget. This implementation may change in the near future """ EditCommand_PM.show(self) self.updateMessage("Use appropriate command in the command "\ "toolbar to create or modify a DNA Object"\ "<br>" ) def _editDnaStrand(self): """ Enter the DnaStrand_EditCommand to edit the selected strand. """ if not self.command.hasValidStructure(): return selectedStrandList = self.command.struct.getSelectedStrands() if len(selectedStrandList) == 1: strand = selectedStrandList[0] strand.edit() def _editDnaSegment(self): """ """ if self.command is not None and self.command.hasValidStructure(): selectedSegments = self.command.struct.getSelectedSegments() if len(selectedSegments) == 1: selectedSegments[0].edit() elif len(selectedSegments) > 1: self.win.resizeSelectedDnaSegments() def _enterMakeCrossoversCommand(self): """ If more than one segments in the segment list widget are selected, enter make crossovers command @BUG: This enters Make Crossover command which searches for *ALL* of the selected DnaSegments in the model and not just the selected segments of the DnaGroup you are editing in the BuildDna command This is misleading. """ self.win.enterMakeCrossoversCommand() def updateListWidgets(self): """ Update List Widgets (strand list and segment list) in this property manager @see: self.updateSegmentListWidgets, self.updateStrandListWidget """ self.updateStrandListWidget() self.updateSegmentListWidget() def updateStrandListWidget(self): """ Update the list of items inside the strandlist widget Example: Origianally it shows two srands. User now edits an existing dna, and deletes some of the strands, hits done. User then again invokes the Edit command for this dna object -- now the strand list widget must be updated so that it shows only the existing strands. @see: B{Chunk.isStrandChunk} @see: self.updateListWidgets, self.updateSegmentListWidget """ #TODO: #Filter out only the chunks inside the dna group. the DnaDuplex.make #doesn't implement the dna data model yet. Until that's implemented, we #will do an isinstance(node, Chunk) check. Note that it includes both #Strands and Axis chunks -- Ninad 2008-01-09 if self.command.hasValidStructure(): strandChunkList = self.command.struct.getStrands() self.strandListWidget.insertItems( row = 0, items = strandChunkList) else: self.strandListWidget.clear() def updateSegmentListWidget(self): """ Update the list of segments shown in the segments list widget @see: self.updateListWidgets, self.updateStrandListWidget """ segmentList = [] if self.command.isCurrentCommand(): if self.command.hasValidStructure(): def func(node): if isinstance(node, self.win.assy.DnaSegment): segmentList.append(node) self.command.struct.apply2all(func) self.segmentListWidget.insertItems( row = 0, items = segmentList) else: self.segmentListWidget.clear() def _addGroupBoxes( self ): """ Add the DNA Property Manager group boxes. """ #Unused 'References List Box' to be revided. (just commented out for the #time being. ##self._pmGroupBox1 = PM_GroupBox( self, title = "Reference Plane" ) ##self._loadGroupBox1( self._pmGroupBox1 ) self._pmGroupBox2 = PM_GroupBox( self, title = "Strands" ) self._loadGroupBox2( self._pmGroupBox2 ) self._pmGroupBox3 = PM_GroupBox( self, title = "Segments" ) self._loadGroupBox3( self._pmGroupBox3 ) self._loadBaseNumberLabelGroupBox(self) def _loadGroupBox1(self, pmGroupBox): """ load widgets in groupbox1 """ self.referencePlaneListWidget = PM_SelectionListWidget( pmGroupBox, self.win, label = "", color = pmReferencesListWidgetColor, heightByRows = 2) def _loadGroupBox2(self, pmGroupBox): """ load widgets in groupbox2 """ self.strandListWidget = PM_SelectionListWidget(pmGroupBox, self.win, label = "", heightByRows = 9 ) self.strandListWidget.setTagInstruction('PICK_ITEM_IN_GLPANE') self.editStrandPropertiesButton = PM_PushButton( pmGroupBox, label = "", text = "Edit Properties..." ) self.editStrandPropertiesButton.setEnabled(False) def _loadGroupBox3(self, pmGroupBox): """ load widgets in groupbox3 """ self.segmentListWidget = PM_SelectionListWidget(pmGroupBox, self.win, label = "", heightByRows = 4 ) self.segmentListWidget.setObjectName('Segment_list_widget') self.segmentListWidget.setTagInstruction('PICK_ITEM_IN_GLPANE') self.editSegmentPropertiesButton = PM_PushButton( pmGroupBox, label = "", text = "Edit Properties..." ) self.editSegmentPropertiesButton.setEnabled(False) self.searchForCrossoversButton = PM_PushButton( pmGroupBox, label = "", text = "Search For Crossovers..." ) self.searchForCrossoversButton.setEnabled(False) def _loadBaseNumberLabelGroupBox(self, pmGroupBox): """ """ self._baseNumberLabelGroupBox = PM_DnaBaseNumberLabelsGroupBox(pmGroupBox, self.command) def _addWhatsThisText( self ): """ What's This text for widgets in the DNA Property Manager. """ pass def _addToolTipText(self): """ Tool Tip text for widgets in the DNA Property Manager. """ pass
NanoCAD-master
cad/src/dna/commands/BuildDna/BuildDna_PropertyManager.py
# Copyright 2008-2009 Nanorex, Inc. See LICENSE file for details. """ @author: Ninad @version: $Id$ @copyright: 2008-2009 Nanorex, Inc. See LICENSE file for details. History: TODO: """ from commands.SelectChunks.SelectChunks_GraphicsMode import SelectChunks_GraphicsMode from model.chem import Atom from model.bonds import Bond from Numeric import dot from PyQt4.Qt import QMouseEvent from geometry.VQT import V, Q, A, norm, vlen from commands.Select.Select_GraphicsMode import DRAG_STICKINESS_LIMIT from utilities.debug import print_compact_traceback import math import foundation.env as env from utilities.prefs_constants import cursorTextFontSize_prefs_key from graphics.drawing.drawDnaLabels import draw_dnaBaseNumberLabels DEBUG_CLICK_ON_OBJECT_ENTERS_ITS_EDIT_COMMAND = True _superclass = SelectChunks_GraphicsMode class BuildDna_GraphicsMode( SelectChunks_GraphicsMode): """ #doc @note: this has subclasses, including DnaSegment_GraphicsMode. """ #The flag that decides whether to draw the handles. This flag is #set during left dragging, when no handle is 'grabbed'. This optimizes the #drawing code as it skips handle drawing code and also the computation #of handle positions each time the mouse moves. #@see self.leftUp , self.leftDrag, and subclass Draw_other methods # for more details. _handleDrawingRequested = True #Some left drag variables used to drag the whole segment along axis or #rotate the segment around its own axis of for free drag translation _movablesForLeftDrag = [] #Subclasses such as MakeCrossovers_GraphicsMode need this attr. #needs refactoring. See self.leftADown() _movable_dnaSegment_for_leftDrag = None #The common center is the center about which the list of movables (the segment #contents are rotated. #@see: self.leftADown where this is set. #@see: self.leftDrag where it is used. _commonCenterForRotation = None _axis_for_constrained_motion = None #Flags that decide the type of left drag. #@see: self.leftADown where it is set and self.leftDrag where these are used _translateAlongAxis = False _rotateAboutAxis = False _freeDragWholeStructure = False cursor_over_when_LMB_pressed = '' def Enter_GraphicsMode(self): _superclass.Enter_GraphicsMode(self) #Precaution self.clear_leftA_variables() def update_cursor_for_no_MB(self): """ Update the cursor for Select mode (Default implementation). """ _superclass.update_cursor_for_no_MB(self) #minor optimization -- don't go further into the method if #nothing is highlighted i.e. self.o.selobj is None. if self.o.selobj is None: return if self.o.modkeys is None: if isinstance(self.o.selobj, Atom): if self.o.selobj.element.role == 'strand': self.o.setCursor(self.win.rotateAboutCentralAxisCursor) elif self.o.selobj.element.role == 'axis': self.o.setCursor(self.win.translateAlongCentralAxisCursor) def bareMotion(self, event): """ @see: self.update_cursor_for_no_MB """ value = _superclass.bareMotion(self, event) #When the cursor is over a specific atom, we need to display #a different icon. (e.g. when over a strand atom, it should display # rotate cursor) self.update_cursor() return value def leftDown(self, event): """ """ self.reset_drag_vars() self.clear_leftA_variables() _superclass.leftDown(self, event) self.LMB_press_event = QMouseEvent(event) # Make a copy of this event #and save it. # We will need it later if we change our mind and start selecting a 2D # region in leftDrag().Copying the event in this way is necessary #because Qt will overwrite <event> later (in # leftDrag) if we simply set self.LMB_press_event = event. mark 060220 self.LMB_press_pt_xy = (event.pos().x(), event.pos().y()) # <LMB_press_pt_xy> is the position of the mouse in window coordinates #when the LMB was pressed. #Used in mouse_within_stickiness_limit (called by leftDrag() and other #methods). # We don't bother to vertically flip y using self.height #(as mousepoints does), # since this is only used for drag distance within single drags. #Subclasses should override one of the following method if they need #to do additional things to prepare for dragging. ##self._leftDown_preparation_for_dragging(event) def clear_leftA_variables(self): self._movablesForLeftDrag = [] #Subclasses such as MakeCrossovers_GraphicsMode need this attr. #(self._movable_dnaSegment_for_leftDrag) needs refactoring. self._movable_dnaSegment_for_leftDrag = None self._commonCenterForRotation = None self._axis_for_constrained_motion = None self._translateAlongAxis = False self._rotateAboutAxis = False self._freeDragWholeStructure = False def _leftDown_preparation_for_dragging(self, objectUnderMouse, event): """ Handle left down event. Preparation for rotation and/or selection This method is called inside of self.leftDown. @param event: The mouse left down event. @type event: QMouseEvent instance @see: self.leftDown @see: self.leftDragRotation Overrides _superclass._leftDown_preparation_for_dragging """ self.o.SaveMouse(event) self.picking = True self.dragdist = 0.0 farQ_junk, self.movingPoint = self.dragstart_using_GL_DEPTH( event) self.leftADown(objectUnderMouse, event) def singletLeftDown(self, s, event): """ Handles SingletLeftDown (left down on a bond point) event. @see: JoinStrands_GraphicsMode.leftUp() """ #@see: class JoinStrands_GraphicsMode for a detailed explanation. #copying some portion in that comment below -- #Example: In this BuildDna_EditCommand (graphicsMode), if you want to #join two strands, upon 'singletLeftDown' it enters #JoinStrands_By_DND_Command , also calling leftDown method of its graphicsmode. #Now, when user releases theLMB, it calls #JoinStrands_GraphicsMode.leftUp() which in turn exits that command #if the flag 'exit_command_on_leftUp' is set to True(to go back to the #previous command user was in) . #A lot of code that does bondpoint dragging is available in #BuildAtoms_GraphicsMode, but it isn't in BuildDna_GraphicsMode #(as it is a SelectChunks_GraphicsMode superclass for lots of reasons) #So, for some significant amount of time, we may continue to use #this flag to temporarily enter/exit this command. #@see: self.leftUp(), BuildDna_GraphicsMode.singletLeftDown() commandSequencer = self.win.commandSequencer commandSequencer.userEnterCommand('JoinStrands_By_DND') assert commandSequencer.currentCommand.commandName == 'JoinStrands_By_DND' #Make sure that the glpane selobj is set to 's' (this bondpoint) #when we enter a different command, all that information is probably #lost , so its important to set it explicitly here. self.glpane.set_selobj(s) #'gm' is the graphics mode of JoinStrands_Command gm = commandSequencer.currentCommand.graphicsMode #Set the graphics mode flag so that it knows to return to #BuildDna_EditCommand upon leftUp() gm.exit_command_on_leftUp = True gm.leftDown(event) return def chunkLeftDown(self, a_chunk, event): """ Depending on the modifier key(s) pressed, it does various operations on chunk..typically pick or unpick the chunk(s) or do nothing. If an object left down happens, the left down method of that object calls this method (chunkLeftDown) as it is the 'SelectChunks_GraphicsMode' which is supposed to select Chunk of the object clicked @param a_chunk: The chunk of the object clicked (example, if the object is an atom, then it is atom.molecule @type a_chunk: B{Chunk} @param event: MouseLeftDown event @see: self.atomLeftDown @see: self.chunkLeftDown @see:self.objectSetUp() """ strandOrSegment = a_chunk.parent_node_of_class( self.win.assy.DnaStrandOrSegment) if strandOrSegment is not None: #Make sure to call chunkSetUp if you are not calling the #chunkLeftDown method of superclass. This in turn, #calls self.objectSetUp(). Fixes a problem in selecting a #DnaClynder chunk (selobj = Chunk) self.chunkSetUp(a_chunk, event) return _superclass.chunkLeftDown(self, a_chunk, event) def chunkLeftUp(self, aChunk, event): """ Upon chunkLeftUp, it enters the strand or segment edit command This is an alternative implementation. As of 2008-03-03, we have decided to change this implementation. Keeping the related methods alive if, in future, we want to switch to this implementation and/or add a user preference to do this. """ _superclass.chunkLeftUp(self, aChunk, event) if self.glpane.modkeys is not None: #Don't go further if some modkey is pressed. We will call the #edit method of the Dna components only if no modifier key is #pressed return if not self.mouse_within_stickiness_limit(event, DRAG_STICKINESS_LIMIT): return #@TODO: If the object under mouse was double clicked, don't enter the #edit mode, instead do appropriate operation such as expand selection or #contract selection (done in superclass) #Note: when the object is just single clicked, it becomes editable). if self.editObjectOnSingleClick(): if aChunk.picked: if aChunk.isAxisChunk() or aChunk.isStrandChunk(): strandOrSegmentGroup = aChunk.parent_node_of_class( self.win.assy.DnaStrandOrSegment) if strandOrSegmentGroup is not None: strandOrSegmentGroup.edit() strandOrSegmentGroup.pick() def _do_leftShiftCntlUp_delete_operations(self, event, objUnderMouse, parentNodesOfObjUnderMouse = ()): """ Overrides superclass method @param parentNodesOfObjUnderMouse: Tuple containing the parent chunk(s), of which, the object under mouse is a part of, or, some other node such as a DnaStrand Or DnaSegment etc which the user probably wants to operate on. @type: Tuple @see: self.chunkLeftUp() @see: self.leftShiftCntlUp() which calls this method. @see: SelectChunks_GraphicsMode._do_leftShiftCntlUp_delete_operations() """ obj = objUnderMouse if obj is self.o.selobj: if isinstance(obj, Bond): self.bondDelete(event) return _superclass._do_leftShiftCntlUp_delete_operations( self, event, objUnderMouse, parentNodesOfObjUnderMouse = parentNodesOfObjUnderMouse) def leftADown(self, objectUnderMouse, event): """ Method called during mouse left down . It sets some parameters necessary for rotating the structure around its own axis (during a left drag to follow) In graphics modes such as RotateChunks_GraphicsMode, rotating entities around their own axis is acheived by holding down 'A' key and then left dragging , thats why the method is named as 'leftADrag' (A= Axis) """ obj = objectUnderMouse if obj is None: # Cursor over empty space. self.emptySpaceLeftDown(event) #Left A drag is not possible unless the cursor is over a #selected object. So make sure to let self.leftAError method sets #proper flag so that left-A drag won't be done in this case. return ma = V(0, 0, 0) chunk = None if isinstance(obj, Atom): chunk = obj.molecule elif isinstance(obj, self.win.assy.Chunk): chunk = obj elif isinstance(obj, Bond): chunk1 = obj.atom1.molecule chunk2 = obj.atom2.molecule #@@ what should we do if its a interchunk bond?? lets just select #one chunk chunk = chunk1 if chunk is None: return ma, segment = chunk.getAxis_of_self_or_eligible_parent_node() self._axis_for_constrained_motion = ma #@see: DnaSegment.get_all_content_chunks() for details about #what it returns. See also DnaSegment.isAncestorOf() which #is called in self.leftDown to determine whether the DnaSegment #user is editing is an ancestor of the selobj. (it also considers #'logical contents' while determining whether it is an ancestor. #-- Ninad 2008-03-11 if isinstance(segment, self.win.assy.DnaSegment): self._movablesForLeftDrag = segment.get_all_content_chunks() self._movable_dnaSegment_for_leftDrag = segment else: self._movablesForLeftDrag = self.win.assy.getSelectedMovables() ma = norm(V(dot(ma,self.o.right),dot(ma,self.o.up))) self.Zmat = A([ma,[-ma[1],ma[0]]]) if isinstance(obj, Atom) and \ obj.element.role == 'axis': self._translateAlongAxis = True self._rotateAboutAxis = False self._freeDragWholeStructure = False elif isinstance(obj, Atom) and \ obj.element.role == 'strand': self._translateAlongAxis = False self._rotateAboutAxis = True self._freeDragWholeStructure = False #The self._commonCenterForrotation is a point on segment axis #about which the whole segment will be rotated. Specifying this #as a common center for rotation fixes bug 2578. We determine this #by selecting the center of the axis atom that is connected #(bonded) to the strand atom being left dragged. Using this as a #common center instead of the avaraging the center of the segment #axis atoms has an advantage. We compute the rotation offset 'dy' #with reference to the strand atom being dragged, so it seems more #appropriate to use the nearest axis center for segment rotation #about axis. But what happens if the axis is not straigt but is #curved? Should we select the averaged center of all axis atoms? #..that may not be right. Or should we take _average center_ of #a the following axis atoms --strand atoms axis_neighbors and #axis atom centers directly connected to this axis atom. # -- Ninad 2008-03-25 axis_neighbor = obj.axis_neighbor() if axis_neighbor is not None: self._commonCenterForRotation = axis_neighbor.posn() else: self._translateAlongAxis = False self._rotateAboutAxis = False self._freeDragWholeStructure = True self.o.SaveMouse(event) self.dragdist = 0.0 def leftUp(self, event): """ Method called during Left up event. """ _superclass.leftUp(self, event) self.update_selobj(event) self.update_cursor() self.o.gl_update() #Reset the flag that decides whether to draw the handles. This flag is #set during left dragging, when no handle is 'grabbed'. See the #class definition for more details about this flag. if hasattr(self.command, 'handles') and self.command.handles: self.command.updateHandlePositions() if not self._handleDrawingRequested: self._handleDrawingRequested = True #IMPLEMENTATION CHANGE 2008-03-05. #Due to an implementation change, user is not allowed to #exit this command by simply clicking onto empty space. So following #is commented out. (Keeping it for now just in case we change our mind #soon. If you see this code being commented out even after 1 or 2 months #from the original comment date, please just delete it. #--Ninad 2008-03-05 ##if self.cursor_over_when_LMB_pressed == 'Empty Space': ###Exit this command by directly calling command.Done. ###This skips call of command.preview_or_finalize_structure ###Not calling 'preview_or_finialize_structure before calling ###command.command_Done(), has an advantage. As of 2008-02-20, we ###remove the structure (segment) and recreate it upon done. ###This also removes, for instance, any cross overs you created ###earlier. although same thing happens when you hit 'Done button', ###it is likely to happen by accident while you are in segment edit ###mode and just click on empty space, Therefore, we simply call ###Command.command_Done(). See a related bug mentioned in ###DnaSegment_EditCommand.setStructureName ##self.command.command_Done() def leftDrag(self, event): """ Method called during Left drag event. """ if self.mouse_within_stickiness_limit(event, DRAG_STICKINESS_LIMIT): # [let this happen even for drag_handlers -- bruce 060728] return self.current_obj_clicked = False #If there is a drag handler (e.g. a segment resize handle is being #dragged, call its drag method and don't proceed further. #NOTE: #In SelectChunks_GraphicsMode.leftDrag, there is a condition statement #which checks if self.drag_handler is in assy.getSelectedMovables #I don't know why it does that... I think it always assums that the #drag handler is officially a node in the MT? In our case, #the drag handler is a 'Highlightable' object (actually #an instance of 'DnaSegment_ResizeHandle' (has superclass from #exprs module ..which implements API for a highlightable object #So it doesn't get registered in the selectMovables list. Thats why #we are not calling _superclass.leftDrag. The above mentioned #method in the superclass needs to be revised -- Ninad 2008-02-01 if self.drag_handler is not None: self.dragHandlerDrag(self.drag_handler, event) return #Duplicates some code from SelectChunks_GraphicsMode.leftDrag #see a to do comment below in this method if self.cursor_over_when_LMB_pressed == 'Empty Space': self.emptySpaceLeftDrag(event) return if self.o.modkeys is not None: # If a drag event has happened after the cursor was over an atom # and a modkey is pressed, do a 2D region selection as if the # atom were absent. self.emptySpaceLeftDown(self.LMB_press_event) #bruce 060721 question: why don't we also do emptySpaceLeftDrag # at this point? return #TODO: This duplicates some code from SelectChunks_GraphicsMode.leftDrag #Following code will never be called if a handle is grabbed. #Thus, it instructs what to do for other cases (when user is not moving #the draggable handles) #First, don't draw handles (set the flag here so that self.Draw_other knows #not to draw handles). This skips unnecessary computation of new handle #position during left dragging. The flag is reset to True in leftUp if hasattr(self.command, 'handles') and self.command.handles: if self.command.grabbedHandle is None: self._handleDrawingRequested = False #Copies AND modifies some code from Move_GraphicsMode for doing #leftDrag translation or rotation. w = self.o.width + 0.0 h = self.o.height + 0.0 deltaMouse = V(event.pos().x() - self.o.MousePos[0], self.o.MousePos[1] - event.pos().y()) a = dot(self.Zmat, deltaMouse) dx,dy = a * V(self.o.scale/(h*0.5), 2*math.pi/w) if self._translateAlongAxis: for mol in self._movablesForLeftDrag: mol.move(dx*self._axis_for_constrained_motion) if self._rotateAboutAxis: rotation_quat = Q(self._axis_for_constrained_motion, -dy) self.o.assy.rotateSpecifiedMovables( rotation_quat, movables = self._movablesForLeftDrag, commonCenter = self._commonCenterForRotation ) if self._freeDragWholeStructure: try: point = self.dragto( self.movingPoint, event) offset = point - self.movingPoint self.o.assy.translateSpecifiedMovables(offset, movables = self._movablesForLeftDrag) self.movingPoint = point except: #may be self.movingPoint is not defined in leftDown? #(e.g. _superclass.leftDown doesn't get called or as a bug? ) print_compact_traceback("bug:unable to free drag the whole segment") self.dragdist += vlen(deltaMouse) #k needed?? [bruce 070605 comment] self.o.SaveMouse(event) self.o.assy.changed() #ninad060924 fixed bug 2278 self.o.gl_update() return def editObjectOnSingleClick(self): """ Subclasses can override this method. If this method returns True, when you left click on a DnaSegment or a DnaStrand, it becomes editable (i.e. program enters the edit command of that particular object if that object is editable) @see: MakeCrossover_GraphicsMode.editObjectOnSingleClick() """ if DEBUG_CLICK_ON_OBJECT_ENTERS_ITS_EDIT_COMMAND: return True def drawHighlightedChunk(self, glpane, selobj, hicolor, hicolor2): """ Overrides SelectChunks_basicGraphicsMode method. """ chunk = None if isinstance(selobj, self.win.assy.Chunk): chunk = selobj elif isinstance(selobj, Atom):## and not selobj.is_singlet(): chunk = selobj.molecule elif isinstance(selobj, Bond): #@@@ what if its a interchunk bond -- case not supported as of #2008-04-30 chunk = selobj.atom1.molecule if chunk is not None: dnaStrandOrSegment = chunk.parent_node_of_class( self.win.assy.DnaStrandOrSegment) if dnaStrandOrSegment is not None: if self.glpane.modkeys == 'Shift+Control': #Don't highlight the whole chunk if object under cursor #is a bond and user has pressed the Shift+Control key #It means we will allow breaking of that bond upon leftClick if isinstance(selobj, Bond): return False else: #If the object under cursor is not a bond, #AND the modifier key is not "Shift+Control', only highlight #that object (which will most likely be the Atom or a #singlet. This special highlighting will be used to do #various stuff like rotating the Dna duplex around its axis #etc. if isinstance(selobj, Atom): return False #For all other cases , do what superclass does for highlighting # a chunk return _superclass.drawHighlightedChunk(self, glpane, selobj, hicolor, hicolor2) def _drawCursorText(self, position = None): """ Draw the text near the cursor. It gives information about number of basepairs/bases being added or removed, length of the segment (if self.struct is a strand etc. @param position: Optional argument. If position (a vector) is specified, instead of drawing the text at the cursor position, it is drawn at the specified position. @type position: B{V} or None @see: DnaSegment_GraphicsMode, DnaStrand_GraphicsMode (subclasses of this class where this is being used. """ if hasattr(self.command, 'grabbedHandle') and hasattr(self.command, 'getCursorText'): if self.command.grabbedHandle is not None: #Draw the text next to the cursor that gives info about #number of base pairs etc text , textColor = self.command.getCursorText() if position is None: self.glpane.renderTextNearCursor(text, offset = 30, textColor = textColor, fontSize = env.prefs[cursorTextFontSize_prefs_key]) else: self.glpane.renderTextAtPosition(position, text, textColor = textColor, fontSize = env.prefs[cursorTextFontSize_prefs_key]) def _drawLabels(self): """ Overrides superclass method @see: self.Draw_other() @see: drawDnaLabels.py """ _superclass._drawLabels(self) #Draw the Dna base number labels. draw_dnaBaseNumberLabels(self.glpane)
NanoCAD-master
cad/src/dna/commands/BuildDna/BuildDna_GraphicsMode.py
# Copyright 2008 Nanorex, Inc. See LICENSE file for details. """ @author: Ninad @version: $Id$ @copyright:2008 Nanorex, Inc. See LICENSE file for details. History: 2008-05-09 Created TODO: as of 2008-01-18 - See MultipleDnaSegmentResize_EditCommand for details. - need to implement model_changed method """ from PyQt4.Qt import Qt, SIGNAL from PM.PM_GroupBox import PM_GroupBox from PM.PM_Constants import PM_DONE_BUTTON from PM.PM_Constants import PM_WHATS_THIS_BUTTON from PM.PM_ToolButton import PM_ToolButton from PM.PM_WidgetRow import PM_WidgetRow from PM.PM_SelectionListWidget import PM_SelectionListWidget from utilities.constants import lightred_1, lightgreen_2 from geometry.VQT import V from utilities.debug import print_compact_stack from utilities import debug_flags from utilities.Comparison import same_vals from command_support.DnaOrCnt_PropertyManager import DnaOrCnt_PropertyManager from utilities.Log import redmsg from utilities.prefs_constants import dnaSegmentEditCommand_cursorTextCheckBox_length_prefs_key from utilities.prefs_constants import dnaSegmentEditCommand_cursorTextCheckBox_numberOfBasePairs_prefs_key from utilities.prefs_constants import dnaSegmentEditCommand_cursorTextCheckBox_changedBasePairs_prefs_key from utilities.prefs_constants import dnaSegmentEditCommand_showCursorTextCheckBox_prefs_key from widgets.prefs_widgets import connect_checkbox_with_boolean_pref _superclass = DnaOrCnt_PropertyManager class MultipleDnaSegmentResize_PropertyManager( DnaOrCnt_PropertyManager ): title = "Resize Dna Segments" iconPath = "ui/actions/Properties Manager/Resize_Multiple_Segments.png" def __init__( self, command ): """ Constructor for the Build DNA property manager. """ self.endPoint1 = V(0, 0, 0) self.endPoint2 = V(0, 0, 0) self._numberOfBases = 0 self._conformation = 'B-DNA' self.duplexRise = 3.18 self.basesPerTurn = 10 self.dnaModel = 'PAM3' _superclass.__init__( self, command) self.showTopRowButtons( PM_DONE_BUTTON | \ PM_WHATS_THIS_BUTTON) msg = "Use resize handles to resize the segments." self.updateMessage(msg) 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 """ #TODO: This is a temporary fix for a bug. When you invoke a #temporary mode entering such a temporary mode keeps the signals of #PM from the previous mode connected ( #but while exiting that temporary mode and reentering the #previous mode, it atucally reconnects the signal! This gives rise to #lots of bugs. This needs more general fix in Temporary mode API. # -- Ninad 2008-01-09 (similar comment exists in MovePropertyManager.py if isConnect and self.isAlreadyConnected: if debug_flags.atom_debug: print_compact_stack("warning: attempt to connect widgets"\ "in this PM that are already connected." ) return if not isConnect and self.isAlreadyDisconnected: if debug_flags.atom_debug: print_compact_stack("warning: attempt to disconnect widgets"\ "in this PM that are already disconnected.") return self.isAlreadyConnected = isConnect self.isAlreadyDisconnected = not isConnect if isConnect: change_connect = self.win.connect else: change_connect = self.win.disconnect self.segmentListWidget.connect_or_disconnect_signals(isConnect) change_connect(self.addSegmentsToolButton, SIGNAL("toggled(bool)"), self.activateAddSegmentsTool) change_connect(self.removeSegmentsToolButton, SIGNAL("toggled(bool)"), self.activateRemoveSegmentsTool) def _update_UI_do_updates(self): """ @see: Command_PropertyManager._update_UI_do_updates() @see: DnaSegment_EditCommand.model_changed() @see: DnaSegment_EditCommand.hasResizableStructure() @see: self._current_model_changed_params() """ currentParams = self._current_model_changed_params() #Optimization. Return from the model_changed method if the #params are the same. if same_vals(currentParams, self._previous_model_changed_params): return number_of_segments, isStructResizable, why_not = currentParams #update the self._previous_model_changed_params with this new param set. self._previous_model_changed_params = currentParams if not isStructResizable: if not number_of_segments == 0: #disable all widgets self._pmGroupBox1.setEnabled(False) msg = redmsg("DnaSegment is not resizable. Reason: %s"%(why_not)) self.updateMessage(msg) else: if not self._pmGroupBox1.isEnabled(): self._pmGroupBox1.setEnabled(True) msg = "Use resize handles to resize the segments" self.updateMessage(msg) self.updateListWidgets() ##self.command.updateHandlePositions() def _current_model_changed_params(self): """ Returns a tuple containing the parameters that will be compared against the previously stored parameters. This provides a quick test to determine whether to do more things in self.model_changed() @see: self.model_changed() which calls this @see: self._previous_model_changed_params attr. """ params = None if self.command: #update the list first. self.command.updateResizeSegmentList() number_of_segments = len(self.command.getResizeSegmentList()) isStructResizable, why_not = self.command.hasResizableStructure() params = (number_of_segments, isStructResizable, why_not) return params def isAddSegmentsToolActive(self): """ Returns True if the add segments tool (which adds the segments to the list of segments to be resized) is active """ if self.addSegmentsToolButton.isChecked(): #For safety if not self.removeSegmentsToolButton.isChecked(): return True return False def isRemoveSegmentsToolActive(self): """ Returns True if the remove segments tool (which removes the segments from the list of segments to be resized) is active """ if self.removeSegmentsToolButton.isChecked(): if not self.addSegmentsToolButton.isChecked(): #For safety return True return False def activateAddSegmentsTool(self,enable): """ Change the appearance of the list widget (that lists the dna segments to be resized) so as to indicate that the add dna segments tool is active @param enable: If True, changes the appearance of list widget to indicate that the add segments tool is active. @type enable: bool """ if enable: if not self.addSegmentsToolButton.isChecked(): self.addSegmentsToolButton.setChecked(True) if self.removeSegmentsToolButton.isChecked(): self.removeSegmentsToolButton.setChecked(False) self.segmentListWidget.setAlternatingRowColors(False) self.segmentListWidget.setColor(lightgreen_2) else: if self.addSegmentsToolButton.isChecked(): self.addSegmentsToolButton.setChecked(False) self.segmentListWidget.setAlternatingRowColors(True) self.segmentListWidget.resetColor() def activateRemoveSegmentsTool(self,enable): """ Change the appearance of the list widget (that lists the dna segments to be resized) so as to indicate that the REMOVE dna segments tool is active @param enable: If True, changes the appearance of list widget to indicate that the REMOVE segments tool is active. @type enable: bool """ if enable: if not self.removeSegmentsToolButton.isChecked(): self.removeSegmentsToolButton.setChecked(True) if self.addSegmentsToolButton.isChecked(): self.addSegmentsToolButton.setChecked(False) self.segmentListWidget.setAlternatingRowColors(False) self.segmentListWidget.setColor(lightred_1) else: if self.removeSegmentsToolButton.isChecked(): self.removeSegmentsToolButton.setChecked(False) self.segmentListWidget.setAlternatingRowColors(True) self.segmentListWidget.resetColor() def removeListWidgetItems(self): """ Removes selected atoms from the resize dna segment list widget Example: User selects a bunch of items in the list widget and hits delete key to remove the selected items from the list IMPORTANT NOTE: This method does NOT delete the correspoinging model item in the GLPane (i.e. corresponding dnasegment). It just 'removes' the item from the list widget (indicating its no longer being resized) This is intentional. """ self.segmentListWidget.deleteSelection() itemDict = self.segmentListWidget.getItemDictonary() self.command.setResizeStructList(itemDict.values()) self.updateListWidgets() self.win.win_update() def _addGroupBoxes( self ): """ Add the Property Manager group boxes. """ self._pmGroupBox1 = PM_GroupBox( self, title = "Segments for Resizing" ) self._loadGroupBox1( self._pmGroupBox1 ) self._displayOptionsGroupBox = PM_GroupBox( self, title = "Display Options" ) self._loadDisplayOptionsGroupBox( self._displayOptionsGroupBox ) def _loadGroupBox1(self, pmGroupBox): """ load widgets in groupbox1 """ self.segmentListWidget = PM_SelectionListWidget( pmGroupBox, self.win, label = "", heightByRows = 12) self.segmentListWidget.setFocusPolicy(Qt.StrongFocus) self.segmentListWidget.setFocus() self.setFocusPolicy(Qt.StrongFocus) self.addSegmentsToolButton = PM_ToolButton( pmGroupBox, text = "Add segments to the list", iconPath = "ui/actions/Properties Manager"\ "/AddSegment_To_ResizeSegmentList.png", spanWidth = True ) self.addSegmentsToolButton.setCheckable(True) self.addSegmentsToolButton.setAutoRaise(True) self.removeSegmentsToolButton = PM_ToolButton( pmGroupBox, text = "Remove segments from the list", iconPath = "ui/actions/Properties Manager"\ "/RemoveSegment_From_ResizeSegmentList.png", spanWidth = True ) self.removeSegmentsToolButton.setCheckable(True) self.removeSegmentsToolButton.setAutoRaise(True) #Widgets to include in the widget row. widgetList = [ ('QLabel', " Add/Remove Segments:", 0), ('QSpacerItem', 5, 5, 1), ('PM_ToolButton', self.addSegmentsToolButton, 2), ('QSpacerItem', 5, 5, 3), ('PM_ToolButton', self.removeSegmentsToolButton, 4), ('QSpacerItem', 5, 5, 5) ] widgetRow = PM_WidgetRow(pmGroupBox, title = '', widgetList = widgetList, label = "", spanWidth = True ) def _addWhatsThisText(self): """ Add what's this text. Abstract method. """ pass def show(self): """ Overrides the superclass method @see: self._deactivateAddRemoveSegmentsTool """ _superclass.show(self) ##self.updateListWidgets() self._deactivateAddRemoveSegmentsTool() def _deactivateAddRemoveSegmentsTool(self): """ Deactivate tools that allow adding or removing the segments to the segment list in the Property manager. This can be simply done by resetting the state of toolbuttons to False. Example: toolbuttons that add or remove segments to the segment list in the Property manager. When self.show is called these need to be unchecked. @see: self.isAddSegmentsToolActive() @see:self.isRemoveSegmentsToolActive() @see: self.show() """ self.addSegmentsToolButton.setChecked(False) self.removeSegmentsToolButton.setChecked(False) def listWidgetHasFocus(self): """ Checks if the list widget that lists dnasegments to be resized has the Qt focus. This is used to just remove items from the list widget (without actually 'deleting' the corresponding Dnasegment in the GLPane) @see: MultipleDnaSegment_GraphicsMode.keyPressEvent() where it is called """ if self.segmentListWidget.hasFocus(): return True return False def setParameters(self, params): pass def getParameters(self): return () def updateListWidgets(self): self.updateSegmentListWidget() def updateSegmentListWidget(self): """ Update the list of segments shown in the segments list widget @see: self.updateListWidgets, self.updateStrandListWidget """ segmentList = [] segmentList = self.command.getResizeSegmentList() self.segmentListWidget.insertItems( row = 0, items = segmentList) def _connect_showCursorTextCheckBox(self): """ Connect the show cursor text checkbox with user prefs_key. Overrides DnaOrCnt_PropertyManager._connect_showCursorTextCheckBox """ connect_checkbox_with_boolean_pref( self.showCursorTextCheckBox , dnaSegmentEditCommand_showCursorTextCheckBox_prefs_key) def _params_for_creating_cursorTextCheckBoxes(self): """ 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: Superclass method which is overridden here -- DnaOrCnt_PropertyManager._params_for_creating_cursorTextCheckBoxes() """ params = \ [ #Format: (" checkbox text", prefs_key) ("Number of base pairs", dnaSegmentEditCommand_cursorTextCheckBox_numberOfBasePairs_prefs_key), ("Duplex length", dnaSegmentEditCommand_cursorTextCheckBox_length_prefs_key), ("Number of basepairs to be changed", dnaSegmentEditCommand_cursorTextCheckBox_changedBasePairs_prefs_key) ] return params
NanoCAD-master
cad/src/dna/commands/MultipleDnaSegmentResize/MultipleDnaSegmentResize_PropertyManager.py
NanoCAD-master
cad/src/dna/commands/MultipleDnaSegmentResize/__init__.py
# Copyright 2008 Nanorex, Inc. See LICENSE file for details. """ MultipleDnaSegmentResize_EditCommand provides a way to edit (resize) one or more DnaSegments. To resize segments, select the segments you want to resize, highlight the axis of any one (in the default command), right click and select 'Resize DnaSegments' from the context menu to enter this command. Then you can interactively modify the segment list using the Property Manager and use the resize handles to resize all segments at once. @author: Ninad @copyright: 2008 Nanorex, Inc. See LICENSE file for details. @version:$Id$ History: 2008-05-09 - 2008-05-14 Created / modified. """ from Numeric import dot from geometry.VQT import V, norm, vlen from utilities.constants import applegreen from dna.commands.DnaSegment.DnaSegment_EditCommand import DnaSegment_EditCommand from dna.commands.MultipleDnaSegmentResize.MultipleDnaSegmentResize_GraphicsMode import MultipleDnaSegmentResize_GraphicsMode from dna.model.Dna_Constants import getDuplexLength from dna.model.Dna_Constants import getNumberOfBasePairsFromDuplexLength from dna.generators.B_Dna_PAM3_Generator import B_Dna_PAM3_Generator from exprs.attr_decl_macros import Instance, State from exprs.__Symbols__ import _self from exprs.Exprs import call_Expr from exprs.Exprs import norm_Expr from exprs.ExprsConstants import Width, Point from widgets.prefs_widgets import ObjAttr_StateRef from dna.commands.DnaSegment.DnaSegment_ResizeHandle import DnaSegment_ResizeHandle from utilities.debug import print_compact_stack from dna.command_support.DnaSegmentList import DnaSegmentList from dna.commands.MultipleDnaSegmentResize.MultipleDnaSegmentResize_PropertyManager import MultipleDnaSegmentResize_PropertyManager CYLINDER_WIDTH_DEFAULT_VALUE = 0.0 HANDLE_RADIUS_DEFAULT_VALUE = 4.0 ORIGIN = V(0, 0, 0) _superclass = DnaSegment_EditCommand class MultipleDnaSegmentResize_EditCommand(DnaSegment_EditCommand): #Graphics Mode GraphicsMode_class = MultipleDnaSegmentResize_GraphicsMode #Property Manager PM_class = MultipleDnaSegmentResize_PropertyManager cmdname = 'MULTIPLE_DNA_SEGMENT_RESIZE' # REVIEW: needed? correct? commandName = 'MULTIPLE_DNA_SEGMENT_RESIZE' featurename = "Edit Multiple Dna Segments" from utilities.constants import CL_SUBCOMMAND command_level = CL_SUBCOMMAND command_parent = 'BUILD_DNA' #This command operates on (resizes) multiple DnaSegments at once. #It does that by looping through the DnaSegments and resizing them #individually. self.currentStruct is set to the 'current' DnaSegment #in that loop and then it is used in the resizing code. #@see: DnaSegmentList class #@see: self.modifyStructure() currentStruct = None handlePoint1 = State( Point, ORIGIN) handlePoint2 = State( Point, ORIGIN) #The minimum 'stopper'length used for resize handles #@see: self._update_resizeHandle_stopper_length for details. _resizeHandle_stopper_length = State(Width, -100000) rotationHandleBasePoint1 = State( Point, ORIGIN) rotationHandleBasePoint2 = State( Point, ORIGIN) #See self._update_resizeHandle_radius where this gets changed. #also see DnaSegment_ResizeHandle to see how its implemented. handleSphereRadius1 = State(Width, HANDLE_RADIUS_DEFAULT_VALUE) handleSphereRadius2 = State(Width, HANDLE_RADIUS_DEFAULT_VALUE) cylinderWidth = State(Width, CYLINDER_WIDTH_DEFAULT_VALUE) cylinderWidth2 = State(Width, CYLINDER_WIDTH_DEFAULT_VALUE) #@TODO: modify the 'State params for rotation_distance rotation_distance1 = State(Width, CYLINDER_WIDTH_DEFAULT_VALUE) rotation_distance2 = State(Width, CYLINDER_WIDTH_DEFAULT_VALUE) leftHandle = Instance( DnaSegment_ResizeHandle( command = _self, height_ref = call_Expr( ObjAttr_StateRef, _self, 'cylinderWidth'), origin = handlePoint1, fixedEndOfStructure = handlePoint2, direction = norm_Expr(handlePoint1 - handlePoint2), sphereRadius = handleSphereRadius1, range = (_resizeHandle_stopper_length, 10000) )) rightHandle = Instance( DnaSegment_ResizeHandle( command = _self, height_ref = call_Expr( ObjAttr_StateRef, _self, 'cylinderWidth2'), origin = handlePoint2, fixedEndOfStructure = handlePoint1, direction = norm_Expr(handlePoint2 - handlePoint1), sphereRadius = handleSphereRadius2, range = (_resizeHandle_stopper_length, 10000) )) def _update_previousParams_in_model_changed(self): """ Overrides superclass method. Does nothing in this class. @see: self.model_changed() which calls this method. """ pass def isAddSegmentsToolActive(self): """ Returns True if the Add segments tool in the PM, that allows adding dna segments from the resize segment list, is active. @see: MultipleDnaSegmentResize_GraphicsMode.chunkLeftUp() @see: MultipleDnaSegmentResize_GraphicsMode.end_selection_from_GLPane() @see: self.isRemoveSegmentsToolActive() @see: self.addSegmentToResizeSegmentList() """ if self.propMgr is None: return False return self.propMgr.isAddSegmentsToolActive() def isRemoveSegmentsToolActive(self): """ Returns True if the Remove Segments tool in the PM, that allows removing dna segments from the resize segment list, is active. @see: MultipleDnaSegmentResize_GraphicsMode.chunkLeftUp() @see: MultipleDnaSegmentResize_GraphicsMode.end_selection_from_GLPane() @see: self.isAddSegmentsToolActive() @see: self.removeSegmentFromResizeSegmentList() """ if self.propMgr is None: return False return self.propMgr.isRemoveSegmentsToolActive() def addSegmentToResizeSegmentList(self, segment): """ Adds the given segment to the resize segment list @param segment: The DnaSegment to be added to the resize segment list. Also does other things such as updating resize handles etc. @type sement: B{DnaSegment} @see: self.isAddSegmentsToolActive() """ assert isinstance(segment, self.win.assy.DnaSegment) self.struct.addToStructList(segment) def removeSegmentFromResizeSegmentList(self, segment): """ Removes the given segment from the resize segment list @param segment: The DnaSegment to be removed from the resize segment list. Also does other things such as updating resize handles etc. @type sement: B{DnaSegment} @see: self.isRemoveSegmentsToolActive() """ assert isinstance(segment, self.win.assy.DnaSegment) self.struct.removeFromStructList(segment) def setResizeStructList(self, structList): """ Replaces the list of segments to be resized with the given segmentList. Calls the related method of self.struct. @param structList: New list of segments to be resized. @type structList: list @see: DnaSegmentList.setResizeStructList() """ if self.hasValidStructure(): self.struct.setStructList(structList) self.updateHandlePositions() def getResizeSegmentList(self): """ Returns a list of segments to be resized at once. @see: DnaSegmentList.getStructList() """ if self.hasValidStructure(): return self.struct.getStructList() return () def updateResizeSegmentList(self): """ Update the list of resize segments (maintained by self.struct) """ if self.hasValidStructure(): self.struct.updateStructList() def editStructure(self, struct = None): """ Overrides superclass method. It first creates a B{DnaSegmentList} object using the provided list (struct argument) The DnaSegmentList object acts as self.struct. @param struct: The caller of this method should provide a list of containing all the structurs that need to be edited (resized) at once. Caller also needs to make sure that this list contains objects of class DnaSegment. @type struct: list @see: B{DnaSegmentList} """ if isinstance(struct, list): dnaSegmentListObject = DnaSegmentList(self, structList = struct) _superclass.editStructure(self, struct = dnaSegmentListObject) def _updatePropMgrParams(self): """ Subclasses may override this method. Update some property manager parameters with the parameters of self.struct (which is being edited) @see: self.editStructure() @TODO: For multiple Dna segment resizing, this method does nothing as of 2008-05-14. Need to be revised. """ #Commented out code as of 2008-05-14 =========== #endPoint1, endPoint2 = self.struct.getAxisEndPoints() #params_for_propMgr = (None, #endPoint1, #endPoint2) ##TODO 2008-03-25: better to get all parameters from self.struct and ##set it in propMgr? This will mostly work except that reverse is ##not true. i.e. we can not specify same set of params for ##self.struct.setProps ...because endPoint1 and endPoint2 are derived. ##by the structure when needed. Commenting out following line of code ##UPDATE 2008-05-06 Fixes a bug due to which the parameters in propMGr ##of DnaSegment_EditCommand are not same as the original structure ##(e.g. bases per turn and duplexrise) ###self.propMgr.setParameters(params_for_propMgr) pass def _update_resizeHandle_radius(self): """ Finds out the sphere radius to use for the resize handles, based on atom /chunk or glpane display (whichever decides the display of the end atoms. The default value is 1.2. @see: self.updateHandlePositions() @see: B{Atom.drawing_radius()} @TODO: Refactor this. It does essentially same thing as the superclass method. The problem is due to the use of the global constant HANDLE_RADIUS_DEFAULT_VALUE which needs to be different (bigger) in this class. So better to make it a class constant (need similar changes in several commands. To be done in a refactoring project. """ atm1 , atm2 = self.struct.getAxisEndAtoms() if atm1 is not None: self.handleSphereRadius1 = max(1.005*atm1.drawing_radius(), 1.005*HANDLE_RADIUS_DEFAULT_VALUE) if atm2 is not None: self.handleSphereRadius2 = max(1.005*atm2.drawing_radius(), 1.005*HANDLE_RADIUS_DEFAULT_VALUE) def _modifyStructure(self, params): """ Modify the structure based on the parameters specified. Overrides EditCommand._modifystructure. This method removes the old structure and creates a new one using self._createStructure. This was needed for the structures like this (Dna, Nanotube etc) . . See more comments in the method. """ if self.currentStruct is None: print_compact_stack("bug: self.currentStruct doesn't exist"\ "exiting self._modifyStructure") return assert isinstance(self.currentStruct , self.win.assy.DnaSegment) self.dna = B_Dna_PAM3_Generator() duplexRise = self.currentStruct.getDuplexRise() basesPerTurn = self.currentStruct.getBasesPerTurn() numberOfBasePairsToAddOrRemove = self._determine_numberOfBasePairs_to_change() ladderEndAxisAtom = self.get_axisEndAtom_at_resize_end() if ladderEndAxisAtom is None: print_compact_stack("bug: unable to resize the DnaSegment"\ "%r, end axis ato not found"%self.currentStruct) return if numberOfBasePairsToAddOrRemove != 0: resizeEnd_final_position = self._get_resizeEnd_final_position( ladderEndAxisAtom, abs(numberOfBasePairsToAddOrRemove), duplexRise ) self.dna.modify(self.currentStruct, ladderEndAxisAtom, numberOfBasePairsToAddOrRemove, basesPerTurn, duplexRise, ladderEndAxisAtom.posn(), resizeEnd_final_position) self.previousParams = params return def modifyStructure(self): """ Called when a resize handle is dragged to change the length of one or more DnaSegments (to be resized together) Called upon leftUp . To acheive this resizing, it loops through the DnaSegments to be resized and calls self._modifyStructure() for individual DnaSegments. Note that Client should call this public method and should never call the private method self._modifyStructure. @see: B{DnaSegment_ResizeHandle.on_release} (the caller) @see: B{SelectChunks_GraphicsMode.leftUp} (which calls the the relevent method in DragHandler API. ) @see: B{exprs.DraggableHandle_AlongLine}, B{exprs.DragBehavior} @see: B{self._modifyStructure} @see: B{DnaSegmentList.updateAverageEndPoints()} """ if self.grabbedHandle is None: return for segment in self.getResizeSegmentList(): #TODO 2008-05-14: DnaSegmentList class relies on self.currentStruct. #See if there is a better way. Ok for now self.currentStruct = segment #self._modifyStructure needs 'param' argument. As of 2008-05-14 #it is not supported/needed for multiple dna segment resizing. #So just pass an empty tuple. params = () self._modifyStructure(params) #Reset the self.currentStruct after use self.currentStruct = None #Update the average end points of the self.struct so that resize handles #are placed at proper positions. self.struct.updateAverageEndPoints() self.win.assy.changed() self.win.win_update() def _get_resizeEnd_final_position(self, ladderEndAxisAtom, numberOfBases, duplexRise): """ Returns the final position of the resize end. Note that we can not use the grabbedHandle's currentPosition as the final position because resize handle is placed at an 'average' position. So we must compute the correct vector using the 'self.currentStruct' """ final_position = None other_axisEndAtom = self.struct.getOtherAxisEndAtom(ladderEndAxisAtom) if other_axisEndAtom is None: return None axis_vector = ladderEndAxisAtom.posn() - other_axisEndAtom.posn() segment_length_to_add = getDuplexLength('B-DNA', numberOfBases, duplexRise = duplexRise) signFactor = + 1 ##if self.grabbedHandle is not None: ##vec = self.grabbedHandle.currentPosition - \ ## self.grabbedHandle.fixedEndOfStructure ##if dot(vec, axis_vector) < 0: ##signFactor = -1 ##else: ##signFactor = +1 axis_vector = axis_vector * signFactor final_position = ladderEndAxisAtom.posn() + \ norm(axis_vector)*segment_length_to_add return final_position def hasResizableStructure(self): """ """ if len(self.struct.getStructList()) == 0: why_not = 'Segment list is empty' isResizable = False return isResizable, why_not return _superclass.hasResizableStructure(self) def _getStructureType(self): """ Returns the type of the structure this command supports. This is used in isinstance test. @see: EditCommand._getStructureType() """ return DnaSegmentList def getDnaRibbonParams(self): """ Overrides superclass method. @TODO:[2008-05-14] This could SLOW things up! Its called multiple times from the graphics mode (for all the DnaSegments to be resized at once). There is no apparent solution to this, but we could try optimizing the following code. Also needs some refactoring. @see: MultipleDnaSegmentResize_GraphicsMode._drawHandles() @see: self._determine_numberOfBasePairs_to_change() """ #Optimization: First test a few basic things to see if the dna ribbon #should be drawn, before doing more computations -- Ninad 2008-05-14 params_when_adding_bases = None params_when_removing_bases = None if self.grabbedHandle is None: return None, None if self.grabbedHandle.origin is None: return None, None ladderEndAxisAtom = self.get_axisEndAtom_at_resize_end() if ladderEndAxisAtom is None: return None, None numberOfBasePairsToAddOrRemove = self._determine_numberOfBasePairs_to_change() if numberOfBasePairsToAddOrRemove == 0: return None, None direction_of_drag = norm(self.grabbedHandle.currentPosition - \ self.grabbedHandle.origin) #@TODO: BUG: DO NOT use self._get_resizeEnd_final_position to compute #the resizeEnd_final_position. It computes the segment length to add #using the number of base pairs to add ... and it uses #getDuplexLength method which in turn rounds off the length as an integer #multiple of duplexRise. Although this is what we want in self._modify() #the drawDnaRibbon draws the base pair only if step size is > 3.18! #so no basepair is drawn at exact val of 3.18. This is BUG, harder to #fix. for drawing dna ribbon, lets justcompute the resize end final #position using the following code. -- Ninad 2008-05-14 other_axisEndAtom = self.struct.getOtherAxisEndAtom(ladderEndAxisAtom) if other_axisEndAtom is None: return None, None axis_vector = ladderEndAxisAtom.posn() - other_axisEndAtom.posn() currentPosition = self.grabbedHandle.currentPosition changedLength = vlen(currentPosition - self.grabbedHandle.origin) #NOTE: (TODO) we call self._determine_numberOfBasePairs_to_change() at the #beginning of this method which checks various things such as #total distance moved by the handle etc to determine whether to draw #the ribbon. So those checks are not done here. If that call is removed #then we need to do those checks. if dot(self.grabbedHandle.direction, direction_of_drag) < 0: signFactor = -1.0 else: signFactor = 1.0 resizeEnd_final_position = ladderEndAxisAtom.posn() + \ norm(axis_vector)*changedLength*signFactor #If the segment is being shortened (determined by checking the #direction of drag) , no need to draw the rubberband line. if dot(self.grabbedHandle.direction, direction_of_drag) < 0: params_when_adding_bases = None params_when_removing_bases = (resizeEnd_final_position) return params_when_adding_bases, \ params_when_removing_bases basesPerTurn = self.struct.getBasesPerTurn() duplexRise = self.struct.getDuplexRise() ladder = ladderEndAxisAtom.molecule.ladder endBaseAtomList = ladder.get_endBaseAtoms_containing_atom( ladderEndAxisAtom) ribbon1_start_point = None ribbon2_start_point = None ribbon1_direction = None ribbon2_direction = None ribbon1Color = applegreen ribbon2Color = applegreen if endBaseAtomList and len(endBaseAtomList) > 2: strand_atom1 = endBaseAtomList[0] strand_atom2 = endBaseAtomList[2] if strand_atom1: ribbon1_start_point = strand_atom1.posn() for bond_direction, neighbor in strand_atom1.bond_directions_to_neighbors(): if neighbor and neighbor.is_singlet(): ribbon1_direction = bond_direction break ribbon1Color = strand_atom1.molecule.color if not ribbon1Color: ribbon1Color = strand_atom1.element.color if strand_atom2: ribbon2_start_point = strand_atom2.posn() for bond_direction, neighbor in strand_atom2.bond_directions_to_neighbors(): if neighbor and neighbor.is_singlet(): ribbon2_direction = bond_direction break ribbon2Color = strand_atom2.molecule.color if not ribbon2Color: ribbon2Color = strand_atom2.element.color params_when_adding_bases = ( ladderEndAxisAtom.posn(), resizeEnd_final_position, basesPerTurn, duplexRise, ribbon1_start_point, ribbon2_start_point, ribbon1_direction, ribbon2_direction, ribbon1Color, ribbon2Color ) params_when_removing_bases = None return params_when_adding_bases, params_when_removing_bases def _determine_numberOfBasePairs_to_change(self): """ Overrides superclass method @TODO: This is significantly different (and perhaps better) than the superclass method. See how to incorporate changes in this method in superclass. @see: self.getDnaRibbonParams() """ currentPosition = self.grabbedHandle.currentPosition fixedEndOfStructure = self.grabbedHandle.fixedEndOfStructure duplexRise = self.struct.getDuplexRise() changedLength = vlen(currentPosition - self.grabbedHandle.origin) direction_of_drag = norm(self.grabbedHandle.currentPosition - \ self.grabbedHandle.origin) #Even when the direction of drag is negative (i.e. the basepairs being #removed), make sure not to remove base pairs for very small movement #of the grabbed handle if changedLength < 0.2*duplexRise: return 0 #This check quickly determines if the grabbed handle moved by a distance #more than the duplexRise and avoids further computations #This condition is applicable only when the direction of drag is #positive..i.e. bases bing added to the segment. if changedLength < duplexRise and \ dot(self.grabbedHandle.direction, direction_of_drag) > 0: return 0 #If the segment is being shortened (determined by checking the #direction of drag) numberOfBasesToAddOrRemove = \ getNumberOfBasePairsFromDuplexLength( 'B-DNA', changedLength, duplexRise = duplexRise) if dot(self.grabbedHandle.direction, direction_of_drag) < 0: numberOfBasesToAddOrRemove = - numberOfBasesToAddOrRemove if numberOfBasesToAddOrRemove > 0: #dna.modify will remove the first base pair it creates #(that basepair will only be used for proper alignment of the #duplex with the existing structure) So we need to compensate for #this basepair by adding 1 to the new number of base pairs. #UPDATE 2008-05-14: The following commented out code #i.e. "##numberOfBasesToAddOrRemove += 1" is not required in this #class , because the way we compute the number of base pairs to #be added is different than than how its done at the moment in the #superclass. In this method, we compute bases to be added from #the resize end and that computation INCLUDES the resize end. #so the number that it returns is already one more than the actual #bases to be added. so commenting out the following line # -- Ninad 2008-05-14 ##numberOfBasesToAddOrRemove += 1 ##print "*** numberOfBasesToAddOrRemove = ", numberOfBasesToAddOrRemove ##print "**** changedLength =", changedLength pass ###UPDATE 2008-06-26: for some reason, when the number of base pairs ###to be added (i.e. value of numberOfBasesToAddOrRemove) is 1 more ###than the actual number of base pairs to be added. So subtract 1 ###from this number. Cause not debugged. -- Ninad ##if numberOfBasesToAddOrRemove > 1: ##numberOfBasesToAddOrRemove -= 1 #UPDATE 2008-08-20: Note that DnaSegment_EditCommand.getCursorText() #does the job of removing the extra basepair from numberOfBasesToAddOrRemove #It(subtracting 1 basePair) is not done here as #self._modifyStructure() needs it without the subtraction. This is #prone to bugs and need to be cleaned up. -- Ninad return numberOfBasesToAddOrRemove
NanoCAD-master
cad/src/dna/commands/MultipleDnaSegmentResize/MultipleDnaSegmentResize_EditCommand.py
# Copyright 2008 Nanorex, Inc. See LICENSE file for details. """ MultipleDnaSegmentResize_GraphicsMode.py Graphics mode for resizing multiple dna segments at once @author: Ninad @copyright: 2008 Nanorex, Inc. See LICENSE file for details. @version:$Id$ History: TODO: see MultipleDnaSegmentResize_EditCommand """ from dna.commands.DnaSegment.DnaSegment_GraphicsMode import DnaSegment_GraphicsMode from PyQt4.Qt import Qt from graphics.drawing.drawDnaRibbons import drawDnaRibbons import foundation.env as env from utilities.prefs_constants import selectionColor_prefs_key from utilities.prefs_constants import DarkBackgroundContrastColor_prefs_key from utilities.prefs_constants import cursorTextColor_prefs_key from utilities.constants import black, banana, silver, lighterblue, darkred from graphics.drawing.CS_draw_primitives import drawcylinder from graphics.drawing.CS_draw_primitives import drawsphere SPHERE_RADIUS = 6.0 SPHERE_DRAWLEVEL = 2 SPHERE_OPACITY = 0.5 CYL_RADIUS = 13.0 CYL_OPACITY = 0.4 SPHERE_RADIUS_2 = 3.0 _superclass = DnaSegment_GraphicsMode class MultipleDnaSegmentResize_GraphicsMode(DnaSegment_GraphicsMode): """ Graphics mode for resizing multiple dna segments at once """ def Enter_GraphicsMode(self): _superclass.Enter_GraphicsMode(self) #@TODO: Deselect everything. Is it Ok to do?? self.win.assy.unpickall_in_GLPane() def update_cursor_for_no_MB(self): """ Update the cursor for no mouse button pressed """ if self.command: if self.command.isAddSegmentsToolActive(): self.o.setCursor(self.win.addSegmentToResizeSegmentListCursor) return if self.command.isRemoveSegmentsToolActive(): self.o.setCursor(self.win.removeSegmentFromResizeSegmentListCursor) return _superclass.update_cursor_for_no_MB(self) def chunkLeftUp(self, a_chunk, event): """ Overrides superclass method. If add or remove segmets tool is active, upon leftUp , when this method gets called, it modifies the list of segments being resized by self.command. @see: self.update_cursor_for_no_MB() @see: self.end_selection_from_GLPane() """ if self.command.isAddSegmentsToolActive() or \ self.command.isRemoveSegmentsToolActive(): if a_chunk.isAxisChunk(): segmentGroup = a_chunk.parent_node_of_class( self.win.assy.DnaSegment) if segmentGroup is not None: if self.command.isAddSegmentsToolActive(): self.command.addSegmentToResizeSegmentList(segmentGroup) if self.command.isRemoveSegmentsToolActive(): self.command.removeSegmentFromResizeSegmentList(segmentGroup) self.end_selection_from_GLPane() return _superclass.chunkLeftUp(self, a_chunk, event) def end_selection_from_GLPane(self): """ Overrides superclass method. In addition to selecting or deselecting the chunk, if a tool that adds Dna segments to the segment list in the property manager is active, this method also adds the selected dna segments to that list. Example, if user selects 'Add Dna segments' tool and does a lasso selection , then this also method adds the selected segments to the list. Opposite behavior if the 'remove segments from segment list too, is active) """ _superclass.end_selection_from_GLPane(self) selectedSegments = self.win.assy.getSelectedDnaSegments() for segment in selectedSegments: if self.command.isAddSegmentsToolActive(): self.command.addSegmentToResizeSegmentList(segment) if self.command.isRemoveSegmentsToolActive(): self.command.removeSegmentFromResizeSegmentList(segment) def keyPressEvent(self, event): """ Handles keyPressEvent. Overrides superclass method. If delete key is pressed while the focus is inside the PM list widget, it deletes that list widget item. @see: MultipleDnaSegmentResize_PropertyManager.listWidgetHasFocus() @TODO: alls self.command.propMgr object which is better to avoid... """ if event.key() == Qt.Key_Delete: if self.command.propMgr and self.command.propMgr.listWidgetHasFocus(): self.command.propMgr.removeListWidgetItems() return _superclass.keyPressEvent(self, event) def _drawSpecialIndicators(self): """ Overrides superclass method. This draws a transparent cylinder around the segments being resized, to easily distinguish them from other model. @see: basicGraphicsmode._drawSpecialIndicators() """ if self.command: segmentList = self.command.getResizeSegmentList() for segment in segmentList: end1, end2 = segment.getAxisEndPoints() if end1 is not None and end2 is not None: drawcylinder(banana, end1, end2, CYL_RADIUS, capped = True, opacity = CYL_OPACITY ) def _drawTags(self): """ Overrides _superClass._drawTags() for self._tagPositions. @see: self.drawTag() @see: GraphicsMode._drawTags() @see: class PM_SelectionWidget """ if 0: #see method for details. Used for debugging only self._DEBUG_Flag_EndPoint1_ofDnaSegments() if self._tagPositions: for point in self._tagPositions: drawsphere(silver, point, SPHERE_RADIUS, SPHERE_DRAWLEVEL, opacity = SPHERE_OPACITY) def _DEBUG_Flag_EndPoint1_ofDnaSegments(self): """ Temporary method that draws a sphere to indicate the endPoint1 of each segment being resized. Used for debugging a bug in computing average end points for the resize handles. """ if not self.command: return endPoints_1 = [] for segment in self.command.getResizeSegmentList(): e1, e2 = segment.getAxisEndPoints() if e1 is not None: endPoints_1.append(e1) for end1 in endPoints_1: drawsphere(lighterblue, end1, SPHERE_RADIUS, SPHERE_DRAWLEVEL, opacity = 1.0) def _drawDnaRubberbandLine(self): """ Overrides superclass method. It loops through the segments being resized and draws the rubberband lines for all. NOT this could be SLOW @see: MultipleDnaSegmentResize_EditCommand.getDnaRibbonParams() for comments. @TODO: needs more cleanup """ handleType = '' if self.command.grabbedHandle is not None: if self.command.grabbedHandle in [self.command.rotationHandle1, self.command.rotationHandle2]: handleType = 'ROTATION_HANDLE' else: handleType = 'RESIZE_HANDLE' if handleType and handleType == 'RESIZE_HANDLE': # textColor is not used. I'm going to ask Ninad if this should # stay in or should be removed. --Mark #textColor = env.prefs[cursorTextColor_prefs_key] # Mark 2008-08-28 for segment in self.command.getResizeSegmentList(): self.command.currentStruct = segment params_when_adding_bases, params_when_removing_bases = \ self.command.getDnaRibbonParams() if params_when_adding_bases: end1, \ end2, \ basesPerTurn,\ duplexRise, \ ribbon1_start_point, \ ribbon2_start_point, \ ribbon1_direction, \ ribbon2_direction, \ ribbon1Color, \ ribbon2Color = params_when_adding_bases #Note: The displayStyle argument for the rubberband line should #really be obtained from self.command.struct. But the struct #is a DnaSegment (a Group) and doesn't have attr 'display' #Should we then obtain this information from one of its strandChunks? #but what if two strand chunks and axis chunk are rendered #in different display styles? since situation may vary, lets #use self.glpane.displayMode for rubberbandline displayMode drawDnaRibbons(self.glpane, end1, end2, basesPerTurn, duplexRise, self.glpane.scale, self.glpane.lineOfSight, self.glpane.displayMode, ribbonThickness = 4.0, ribbon1_start_point = ribbon1_start_point, ribbon2_start_point = ribbon2_start_point, ribbon1_direction = ribbon1_direction, ribbon2_direction = ribbon2_direction, ribbon1Color = ribbon1Color, ribbon2Color = ribbon2Color, ) #Draw a sphere that indicates the current position of #the resize end of each segment . drawsphere(env.prefs[selectionColor_prefs_key], end2, SPHERE_RADIUS_2, SPHERE_DRAWLEVEL, opacity = SPHERE_OPACITY) #Draw the text next to the cursor that gives info about #number of base pairs etc self._drawCursorText(position = end2) elif params_when_removing_bases: end2 = params_when_removing_bases #Draw a sphere that indicates the current position of #the resize end of each segment. drawsphere(darkred, end2, SPHERE_RADIUS_2, SPHERE_DRAWLEVEL, opacity = SPHERE_OPACITY) #Draw the text next to the cursor that gives info about #number of base pairs etc self._drawCursorText(position = end2) #Reset the command.currentStruct to None. (it is set to 'segment' #at the beginning of the for loop. self.command.currentStruct = None
NanoCAD-master
cad/src/dna/commands/MultipleDnaSegmentResize/MultipleDnaSegmentResize_GraphicsMode.py
# Copyright 2008 Nanorex, Inc. See LICENSE file for details. """ @author: Mark @version: $Id$ @copyright: 2008 Nanorex, Inc. See LICENSE file for details. """ import foundation.changes as changes from commands.SelectChunks.SelectChunks_GraphicsMode import SelectChunks_GraphicsMode from command_support.EditCommand import EditCommand from utilities.constants import red from dna.commands.OrderDna.OrderDna_PropertyManager import OrderDna_PropertyManager from graphics.drawing.drawDnaLabels import draw_dnaBaseNumberLabels # == GraphicsMode part _superclass_for_GM = SelectChunks_GraphicsMode class OrderDna_GraphicsMode( SelectChunks_GraphicsMode ): """ Graphics mode for "Order DNA" command. """ def _drawLabels(self): """ Overrides suoerclass method. @see: GraphicsMode._drawLabels() """ _superclass_for_GM._drawLabels(self) draw_dnaBaseNumberLabels(self.glpane) # == Command part class OrderDna_Command(EditCommand): """ """ # class constants commandName = 'ORDER_DNA' featurename = "Order DNA" from utilities.constants import CL_EXTERNAL_ACTION command_level = CL_EXTERNAL_ACTION GraphicsMode_class = OrderDna_GraphicsMode PM_class = OrderDna_PropertyManager command_should_resume_prevMode = True command_has_its_own_PM = True flyoutToolbar = None def _getFlyoutToolBarActionAndParentCommand(self): """ Overides superclass method. @see: self.command_update_flyout() """ flyoutActionToCheck = 'orderDnaAction' parentCommandName = 'BUILD_DNA' return flyoutActionToCheck, parentCommandName def keep_empty_group(self, group): """ Returns True if the empty group should not be automatically deleted. otherwise returns False. The default implementation always returns False. Subclasses should override this method if it needs to keep the empty group for some reasons. Note that this method will only get called when a group has a class constant autdelete_when_empty set to True. (and as of 2008-03-06, it is proposed that dna_updater calls this method when needed. @see: Command.keep_empty_group() which is overridden here. """ bool_keep = EditCommand.keep_empty_group(self, group) if not bool_keep: #Lets just not delete *ANY* DnaGroup while in OrderDna_Command #Although OrderDna command can only be accessed through #BuildDna_EditCommand, it could happen (due to a bug) that the #previous command is not BuildDna_Editcommand. So bool_keep #in that case will return False propmting dna updater to even delete #the empty DnaGroup (if it becomes empty for some reasons) of the #BuildDna command. To avoid this ,this method will instruct # to keep all instances of DnaGroup even when they might be empty. if isinstance(group, self.assy.DnaGroup): bool_keep = True #Commented out code that shows what I was planning to implement #earlier. ##previousCommand = self.commandSequencer.prevMode # keep_empty_group: .struct ##if previousCommand.commandName == 'BUILD_DNA': ##if group is previousCommand.struct: ##bool_keep = True return bool_keep
NanoCAD-master
cad/src/dna/commands/OrderDna/OrderDna_Command.py
NanoCAD-master
cad/src/dna/commands/OrderDna/__init__.py
# Copyright 2008 Nanorex, Inc. See LICENSE file for details. """ OrderDna_PropertyManager.py The OrderDna_PropertyManager class provides a Property Manager for the B{Order Dna} command on the flyout toolbar in the Build > Dna mode. @author: Mark @version: $Id$ @copyright: 2008 Nanorex, Inc. See LICENSE file for details. """ import os, time from widgets.prefs_widgets import connect_checkbox_with_boolean_pref from PyQt4.Qt import Qt from PyQt4.Qt import SIGNAL from PM.PM_GroupBox import PM_GroupBox from PM.PM_ComboBox import PM_ComboBox from PM.PM_LineEdit import PM_LineEdit from PM.PM_PushButton import PM_PushButton from PM.PM_Constants import PM_DONE_BUTTON from PM.PM_Constants import PM_WHATS_THIS_BUTTON from utilities.prefs_constants import assignColorToBrokenDnaStrands_prefs_key from platform_dependent.PlatformDependent import find_or_make_Nanorex_subdir from platform_dependent.PlatformDependent import open_file_in_editor from dna.model.DnaStrand import DnaStrand from command_support.Command_PropertyManager import Command_PropertyManager from ne1_ui.WhatsThisText_for_PropertyManagers import whatsThis_OrderDna_PropertyManager def writeDnaOrderFile(fileName, assy, numberOfBases, numberOfUnassignedBases, dnaSequence): """ Writes a DNA Order file in comma-separated value (CSV) format. @param fileName: The full path of the DNA order file. @param assy: The assembly. @param numberOfBase: The number of bases. @param numberOfUnassignedBases: The number of unassigned (i.e. X) bases. @param dnaSequence: The dnaSequence string to be written to the file. @see: self.orderDna """ #Create Header date_header = "#NanoEngineer-1 DNA Order Form created on %s\n" \ % time.strftime("%Y-%m-%d at %H:%M:%S") if assy.filename: mmpFileName = "[" + os.path.normpath(assy.filename) + "]" else: mmpFileName = "[" + assy.name + "]" + \ " ( The mmp file was probably not saved when the "\ " sequence was written)" fileNameInfo_header = "#This sequence is created for file '%s'\n" \ % mmpFileName numberOfBases_header = "#Total number of bases: %d\n" % numberOfBases unassignedBases_header = "" if numberOfUnassignedBases: unassignedBases_header = \ "#WARNING: This order includes %d unassigned (i.e. \"X\") bases.\n"\ % numberOfUnassignedBases info_header = "#This file is written in comma-separated value (CSV) format. "\ "Open with Excel or any other program that supports CSV format.\n" column_header = "Name,Length,Sequence,Notes\n" file_header = date_header \ + fileNameInfo_header \ + numberOfBases_header \ + unassignedBases_header \ + info_header \ + "\n" \ + column_header # Write file f = open(fileName,'w') f.write(file_header) f.write(dnaSequence) f.close() return _superclass = Command_PropertyManager class OrderDna_PropertyManager(Command_PropertyManager): """ The OrderDna_PropertyManager class provides a Property Manager for the B{Order Dna} command on the flyout toolbar in the Build > Dna mode. @ivar title: The title that appears in the property manager header. @type title: str @ivar pmName: The name of this property manager. This is used to set the name of the PM_Dialog object via setObjectName(). @type name: str @ivar iconPath: The relative path to the PNG file that contains a 22 x 22 icon image that appears in the PM header. @type iconPath: str """ title = "Order DNA" pmName = title iconPath = "ui/actions/Command Toolbar/BuildDna/OrderDna.png" def __init__( self, command ): """ Constructor for the property manager. """ _superclass.__init__(self, command) self.assy = self.win.assy self.showTopRowButtons( PM_DONE_BUTTON | \ PM_WHATS_THIS_BUTTON) self.update_includeStrands() # Updates the message box. return 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 change_connect( self.viewDnaOrderFileButton, SIGNAL("clicked()"), self.viewDnaOrderFile) change_connect( self.includeStrandsComboBox, SIGNAL("activated(int)"), self.update_includeStrands ) return def _addGroupBoxes( self ): """ Add the Property Manager group boxes. """ self._pmGroupBox1 = PM_GroupBox( self, title = "Options" ) self._loadGroupBox1( self._pmGroupBox1 ) def _loadGroupBox1(self, pmGroupBox): """ Load widgets in group box. """ includeStrandsChoices = ["All strands in model", "Selected strands only"] self.includeStrandsComboBox = \ PM_ComboBox( pmGroupBox, label = "Include strands:", choices = includeStrandsChoices, setAsDefault = True) self.numberOfBasesLineEdit = \ PM_LineEdit( pmGroupBox, label = "Total nucleotides:", text = str(self.getNumberOfBases())) self.numberOfBasesLineEdit.setEnabled(False) self.numberOfXBasesLineEdit = \ PM_LineEdit( pmGroupBox, label = "Unassigned:", text = str(self.getNumberOfBases(unassignedOnly = True))) self.numberOfXBasesLineEdit.setEnabled(False) self.viewDnaOrderFileButton = \ PM_PushButton( pmGroupBox, label = "", text = "View DNA Order File...", spanWidth = True) return def _addWhatsThisText(self): """ What's This text for widgets in this Property Manager. """ whatsThis_OrderDna_PropertyManager(self) return def _addToolTipText(self): """ Tool Tip text for widgets in the DNA Property Manager. """ pass # Ask Bruce where this should live (i.e. class Part?) --Mark def getAllDnaStrands(self, selectedOnly = False): """ Returns a list of all the DNA strands in the current part, or only the selected strands if I{selectedOnly} is True. @param selectedOnly: If True, return only the selected DNA strands. @type selectedOnly: bool """ dnaStrandList = [] def func(node): if isinstance(node, DnaStrand): if selectedOnly: if node.picked: dnaStrandList.append(node) else: dnaStrandList.append(node) self.win.assy.part.topnode.apply2all(func) return dnaStrandList def getNumberOfBases(self, selectedOnly = False, unassignedOnly = False): """ Returns the number of bases count for all the DNA strands in the current part, or only the selected strand if I{selectedOnly} is True. @param selectedOnly: If True, return only the number of bases in the selected DNA strands. @type selectedOnly: bool @param unassignedOnly: If True, return only the number of unassigned bases (i.e. base letters = X). @type unassignedOnly: bool """ dnaSequenceString = '' selectedOnly = self.includeStrandsComboBox.currentIndex() strandList = self.getAllDnaStrands(selectedOnly) for strand in strandList: strandSequenceString = str(strand.getStrandSequence()) dnaSequenceString += strandSequenceString if unassignedOnly: return dnaSequenceString.count("X") return len(dnaSequenceString) def _update_UI_do_updates(self): """ Overrides superclass method. """ self.update_includeStrands() return def getDnaSequence(self, format = 'CSV'): """ Return the complete Dna sequence information string (i.e. all strand sequences) in the specified format. @return: The Dna sequence string @rtype: string """ if format == 'CSV': #comma separated values. separator = ',' dnaSequenceString = '' selectedOnly = self.includeStrandsComboBox.currentIndex() strandList = self.getAllDnaStrands(selectedOnly) for strand in strandList: dnaSequenceString = dnaSequenceString + strand.name + separator strandSequenceString = str(strand.getStrandSequence()) if strandSequenceString: strandSequenceString = strandSequenceString.upper() strandLength = str(len(strandSequenceString)) + separator dnaSequenceString = dnaSequenceString + strandLength + strandSequenceString dnaSequenceString = dnaSequenceString + "\n" return dnaSequenceString def viewDnaOrderFile(self, openFileInEditor = True): """ Writes a DNA Order file in comma-separated values (CSV) format and opens it in a text editor. The user must save the file to a permanent location using the text editor. @see: Ui_DnaFlyout.orderDnaCommand @see: writeDnaOrderFile() @TODO: assy.getAllDnaObjects(). """ dnaSequence = self.getDnaSequence(format = 'CSV') if dnaSequence: tmpdir = find_or_make_Nanorex_subdir('temp') fileBaseName = 'DnaOrder' temporaryFile = os.path.join(tmpdir, "%s.csv" % fileBaseName) writeDnaOrderFile(temporaryFile, self.assy, self.getNumberOfBases(), self.getNumberOfBases(unassignedOnly = True), dnaSequence) if openFileInEditor: open_file_in_editor(temporaryFile) return def update_includeStrands(self, ignoreVal = 0): """ Slot method for "Include (strands)" combobox. """ idx = self.includeStrandsComboBox.currentIndex() includeType = ["model", "selection"] _numberOfBases = self.getNumberOfBases() self.numberOfBasesLineEdit.setText(str(_numberOfBases) + " bases") _numberOfXBases = self.getNumberOfBases(unassignedOnly = True) self.numberOfXBasesLineEdit.setText(str(_numberOfXBases) + " bases") # Make the background color red if there are any unassigned bases. if _numberOfXBases: self.numberOfXBasesLineEdit.setStyleSheet(\ "QLineEdit {"\ "background-color: rgb(255, 0, 0)"\ "}") else: self.numberOfXBasesLineEdit.setStyleSheet(\ "QLineEdit {"\ "background-color: rgb(255, 255, 255)"\ "}") if _numberOfBases > 0: self.viewDnaOrderFileButton.setEnabled(True) msg = "Click on <b>View DNA Order File...</b> to preview a " \ "DNA order for all DNA strands in the current %s." \ % includeType[idx] else: self.viewDnaOrderFileButton.setEnabled(False) msg = "<font color=red>" \ "There are no DNA strands in the current %s." \ % includeType[idx] self.updateMessage(msg) return
NanoCAD-master
cad/src/dna/commands/OrderDna/OrderDna_PropertyManager.py
# Copyright 2007-2008 Nanorex, Inc. See LICENSE file for details. """ BreakStrands_GraphicsMode.py @author: Ninad @version: $Id$ @copyright: 2007-2008 Nanorex, Inc. See LICENSE file for details. @license: GPL History: 2008-07-01: Split this out of BreakStrands_Command.py into its own module. The class was originally created in January 2008 TODO: [ as of 2008-07-01] - bondLeftup deletes any bonds -- it should only break strands.? """ from geometry.VQT import norm from utilities.constants import red from utilities.prefs_constants import arrowsOnThreePrimeEnds_prefs_key from utilities.prefs_constants import arrowsOnFivePrimeEnds_prefs_key from utilities.prefs_constants import useCustomColorForThreePrimeArrowheads_prefs_key from utilities.prefs_constants import dnaStrandThreePrimeArrowheadsCustomColor_prefs_key from utilities.prefs_constants import useCustomColorForFivePrimeArrowheads_prefs_key from utilities.prefs_constants import dnaStrandFivePrimeArrowheadsCustomColor_prefs_key from utilities.prefs_constants import breakStrandsCommand_arrowsOnThreePrimeEnds_prefs_key from utilities.prefs_constants import breakStrandsCommand_arrowsOnFivePrimeEnds_prefs_key from utilities.prefs_constants import breakStrandsCommand_useCustomColorForThreePrimeArrowheads_prefs_key from utilities.prefs_constants import breakStrandsCommand_dnaStrandThreePrimeArrowheadsCustomColor_prefs_key from utilities.prefs_constants import breakStrandsCommand_useCustomColorForFivePrimeArrowheads_prefs_key from utilities.prefs_constants import breakStrandsCommand_dnaStrandFivePrimeArrowheadsCustomColor_prefs_key from utilities.constants import banana, darkgreen, red from graphics.drawing.CS_draw_primitives import drawcylinder from graphics.drawing.CS_draw_primitives import drawsphere, draw3DFlag from dna.commands.BreakStrands.BreakSite_Marker import BreakSite_Marker from dna.commands.BreakStrands.BreakSite_Marker import DEBUG_DRAW_SPHERES_AROUND_ATOMS_AT_BREAK_SITES import time SPHERE_RADIUS = 1.8 SPHERE_DRAWLEVEL = 2 SPHERE_OPACITY = 0.5 CYL_RADIUS = 2.5 CYL_OPACITY = 0.6 SPHERE_RADIUS_2 = 4.0 from dna.command_support.BreakOrJoinStrands_GraphicsMode import BreakOrJoinstrands_GraphicsMode from utilities.GlobalPreferences import DEBUG_BREAK_OPTIONS_FEATURE _superclass = BreakOrJoinstrands_GraphicsMode class BreakStrands_GraphicsMode(BreakOrJoinstrands_GraphicsMode ): """ Graphics mode for Break Strands command. """ _breakSite_marker = None def __init__(self, glpane): """ contructor """ _superclass.__init__(self, glpane) self._create_breakSite_Marker_if_needed() def _create_breakSite_Marker_if_needed(self): if self._breakSite_marker is None: self._breakSite_marker = BreakSite_Marker(self) def updateBreakSites(self): self._breakSite_marker.update() def Enter_GraphicsMode(self): _superclass.Enter_GraphicsMode(self) if DEBUG_BREAK_OPTIONS_FEATURE: self. _create_breakSite_Marker_if_needed() self._breakSite_marker.full_update() def _drawSpecialIndicators(self): """ Overrides superclass method. This draws a transparent cylinder around the segments being resized, to easily distinguish them from other model. @see: basicGraphicsmode._drawSpecialIndicators() """ if self.command: if DEBUG_DRAW_SPHERES_AROUND_ATOMS_AT_BREAK_SITES: breakSitesDict = self._breakSite_marker.getBreakSitesDict() atmList = breakSitesDict.values() for atm in atmList: sphere_radius = max(1.2*atm.drawing_radius(), SPHERE_RADIUS) drawsphere(darkgreen, atm.posn(), sphere_radius, SPHERE_DRAWLEVEL, opacity = SPHERE_OPACITY) breakSites_atomPairs_dict = self._breakSite_marker.getBreakSites_atomPairsDict() for aDict in breakSites_atomPairs_dict.values(): #DEBUG======== for atm1, atm2 in aDict.values(): #Its okay to do this check for only atm1 (for speed reason) #lets assume that atm2 drawing radius will be the same (it won't #be the same in very rare cases....) cyl_radius = max(1.3*atm1.drawing_radius(), CYL_RADIUS) drawcylinder(red, atm1.posn(), atm2.posn(), cyl_radius, capped = True, opacity = CYL_OPACITY ) startAtomsDict = self._breakSite_marker.getStartAtomsDict() for atm in startAtomsDict.values(): sphere_radius = max(1.2*atm.drawing_radius(), SPHERE_RADIUS_2) color = atm.molecule.color if color is None: color = banana atom_radius = atm.drawing_radius() cyl_radius = 0.5*atom_radius cyl_height = 2.5*atom_radius axis_atm = atm.axis_neighbor() direction = None if axis_atm: #Direction will be opposite of direction = norm( atm.posn() - axis_atm.posn()) draw3DFlag(self.glpane, color, atm.posn(), cyl_radius, cyl_height, direction = direction, opacity = 0.8) ##opacity = CYL_OPACITY) ##drawsphere(color, ##atm.posn(), ##sphere_radius, ##SPHERE_DRAWLEVEL, ##opacity = SPHERE_OPACITY) def _drawSpecialIndicators_ORIG(self): """ Overrides superclass method. This draws a transparent cylinder around the segments being resized, to easily distinguish them from other model. @see: basicGraphicsmode._drawSpecialIndicators() """ if self.command: if _DEBUG_DRAW_SPHERES_AROUND_ATOMS_AT_BREAK_SITES: breakSitesDict = self._breakSite_marker.getBreakSitesDict() atmList = breakSitesDict.values() for atm in atmList: sphere_radius = max(1.2*atm.drawing_radius(), SPHERE_RADIUS) drawsphere(darkgreen, atm.posn(), sphere_radius, SPHERE_DRAWLEVEL, opacity = SPHERE_OPACITY) breakSites_atomPairs_dict = self._breakSite_marker.getBreakSites_atomPairsDict() for atm1, atm2 in breakSites_atomPairs_dict.values(): #Its okay to do this check for only atm1 (for speed reason) #lets assume that atm2 drawing radius will be the same (it won't #be the same in very rare cases....) cyl_radius = max(1.3*atm1.drawing_radius(), CYL_RADIUS) drawcylinder(red, atm1.posn(), atm2.posn(), cyl_radius, capped = True, opacity = CYL_OPACITY ) startAtomsDict = self._breakSite_marker.getStartAtomsDict() for atm in startAtomsDict.values(): sphere_radius = max(1.2*atm.drawing_radius(), SPHERE_RADIUS_2) color = atm.molecule.color if color is None: color = banana atom_radius = atm1.drawing_radius() cyl_radius = 0.5*atom_radius cyl_height = 2.5*atom_radius draw3DFlag(self.glpane, color, atm.posn(), cyl_radius, cyl_height, opacity = 0.7) ##opacity = CYL_OPACITY) ##drawsphere(color, ##atm.posn(), ##sphere_radius, ##SPHERE_DRAWLEVEL, ##opacity = SPHERE_OPACITY) def breakStrandBonds_ORIG(self): breakSites_atomPairs_dict = self._breakSite_marker.getBreakSites_atomPairsDict() lst = list(breakSites_atomPairs_dict.keys()) for bond in lst: bond.bust() self._breakSite_marker.update() def breakStrandBonds(self): breakSites_atomPairs_dict = self._breakSite_marker.getBreakSites_atomPairsDict() for aDict in breakSites_atomPairs_dict.values(): lst = list(aDict.keys()) for bond in lst: bond.bust() self._breakSite_marker.full_update() def atomLeftUp(self, a, event): if self.command.isSpecifyEndAtomsToolActive(): self._breakSite_marker.updateEndAtomsDict(a) self.glpane.set_selobj(None) self.glpane.gl_update() ##self.updateBreakSites() return if self.command.isSpecifyStartAtomsToolActive(): self._breakSite_marker.updateStartAtomsDict(a) self.glpane.set_selobj(None) self.glpane.gl_update() ##self.updateBreakSites() return _superclass.atomLeftUp(self, a, event) def bondLeftUp(self, b, event): """ Delete the bond upon left up. """ self.bondDelete(event) def update_cursor_for_no_MB(self): """ Update the cursor for this mode. """ self.glpane.setCursor(self.win.DeleteCursor) def _getBondHighlightColor(self, selobj): """ Return the Bond highlight color . Since its a BreakStrands graphics mode, the color is 'red' by default. @return: Highlight color of the object (Bond) """ return red def leftDouble(self, event): """ Overrides BuildAtoms_GraphicsMode.leftDouble. In BuildAtoms mode, left double deposits an atom. We don't want that happening here! """ pass _GLOBAL_TO_LOCAL_PREFS_KEYS = { arrowsOnThreePrimeEnds_prefs_key: breakStrandsCommand_arrowsOnThreePrimeEnds_prefs_key, arrowsOnFivePrimeEnds_prefs_key: breakStrandsCommand_arrowsOnFivePrimeEnds_prefs_key, useCustomColorForThreePrimeArrowheads_prefs_key: breakStrandsCommand_useCustomColorForThreePrimeArrowheads_prefs_key, useCustomColorForFivePrimeArrowheads_prefs_key: breakStrandsCommand_useCustomColorForFivePrimeArrowheads_prefs_key, dnaStrandThreePrimeArrowheadsCustomColor_prefs_key: breakStrandsCommand_dnaStrandThreePrimeArrowheadsCustomColor_prefs_key, dnaStrandFivePrimeArrowheadsCustomColor_prefs_key: breakStrandsCommand_dnaStrandFivePrimeArrowheadsCustomColor_prefs_key, } def get_prefs_value(self, prefs_key): #bruce 080605 """ [overrides superclass method for certain prefs_keys] """ # map global keys to local ones, when we have them prefs_key = self._GLOBAL_TO_LOCAL_PREFS_KEYS.get( prefs_key, prefs_key) return _superclass.get_prefs_value( self, prefs_key)
NanoCAD-master
cad/src/dna/commands/BreakStrands/BreakStrands_GraphicsMode.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. @license: GPL TODOs: [ as of 2008-01-04] - To be revised heavily . Still a stub, needs documentation. """ from dna.command_support.BreakOrJoinStrands_Command import BreakOrJoinStrands_Command from dna.commands.BreakStrands.BreakStrands_PropertyManager import BreakStrands_PropertyManager from dna.commands.BreakStrands.BreakStrands_GraphicsMode import BreakStrands_GraphicsMode from utilities.prefs_constants import cpkScaleFactor_prefs_key import foundation.env as env #debug flag for experimental code Ninad is #working on (various break strands options) from utilities.GlobalPreferences import DEBUG_BREAK_OPTIONS_FEATURE _superclass = BreakOrJoinStrands_Command class BreakStrands_Command(BreakOrJoinStrands_Command): """ """ # class constants commandName = 'BREAK_STRANDS' featurename = "Break Strands" GraphicsMode_class = BreakStrands_GraphicsMode PM_class = BreakStrands_PropertyManager def _get_init_gui_flyout_action_string(self): return 'breakStrandAction' def command_entered(self): """ Extends superclass method. """ _superclass.command_entered(self) self._modifyCPKScaleFactor() def command_will_exit(self): """ Extends superclass method. """ self._restoreCPKScaleFactor() _superclass.command_will_exit(self) def _modifyCPKScaleFactor(self): """ Modify the global CPK scale factor prefs_key temporarily , while in BreakStrands command. This prefs_key will be restored while exiting this command @see: self._restoreCPKScaleFactor() @see: self.command_entered() """ #Note 2008-11-14: This is implemented based on Mark's NFR. self._original_cpkScaleFactor_prefs_key = env.prefs[cpkScaleFactor_prefs_key] env.prefs[cpkScaleFactor_prefs_key] = 0.5 def _restoreCPKScaleFactor(self): """ @see: self._modifyCPKScaleFactor() @see: self.command_entered() @see: self.command_will_exit() """ env.prefs[cpkScaleFactor_prefs_key] = self._original_cpkScaleFactor_prefs_key #=========================================================================== #Methods used in experimental feature that provide various break options #these are not called but thhe methods do have a safety check to #see id DEBUG_BREAK_OPTIONS_FEATURE is set to True. -- ninad 2008-08-06 def getStrandList(self): part = self.win.assy.part return part.get_topmost_subnodes_of_class(self.win.assy.DnaStrand) def isSpecifyEndAtomsToolActive(self): return False def isSpecifyStartAtomsToolActive(self): if not DEBUG_BREAK_OPTIONS_FEATURE: return False return True def getNumberOfBasesBeforeNextBreak(self): if not DEBUG_BREAK_OPTIONS_FEATURE: return 2 if self.propMgr: return self.propMgr.getNumberOfBasesBeforeNextBreak() return 2 def breakStrandBonds(self): if not DEBUG_BREAK_OPTIONS_FEATURE: return self.graphicsMode.breakStrandBonds() def updateBreakSites(self): if not DEBUG_BREAK_OPTIONS_FEATURE: return self.graphicsMode.updateBreakSites() #===========================================================================
NanoCAD-master
cad/src/dna/commands/BreakStrands/BreakStrands_Command.py
# Copyright 2008 Nanorex, Inc. See LICENSE file for details. """ BreakStrands_PropertyManager.py The BreakStrands_PropertyManager class provides a Property Manager for the B{Break Strands} command on the flyout toolbar in the Build > Dna mode. @author: Ninad @version: $Id$ @copyright: 2008 Nanorex, Inc. See LICENSE file for details. Ninad 2008-06-05: Revised and refactored arrowhead display code and moved part common to both Break and JoinStrands PMs into new module BreakOrJoinStrands_PropertyManager """ from PyQt4.Qt import SIGNAL from widgets.prefs_widgets import connect_checkbox_with_boolean_pref from PM.PM_GroupBox import PM_GroupBox from PM.PM_CheckBox import PM_CheckBox from PM.PM_SpinBox import PM_SpinBox from PM.PM_PushButton import PM_PushButton from utilities.prefs_constants import assignColorToBrokenDnaStrands_prefs_key from utilities.prefs_constants import breakStrandsCommand_arrowsOnThreePrimeEnds_prefs_key from utilities.prefs_constants import breakStrandsCommand_arrowsOnFivePrimeEnds_prefs_key from utilities.prefs_constants import breakStrandsCommand_useCustomColorForThreePrimeArrowheads_prefs_key from utilities.prefs_constants import breakStrandsCommand_dnaStrandThreePrimeArrowheadsCustomColor_prefs_key from utilities.prefs_constants import breakStrandsCommand_useCustomColorForFivePrimeArrowheads_prefs_key from utilities.prefs_constants import breakStrandsCommand_dnaStrandFivePrimeArrowheadsCustomColor_prefs_key from utilities.prefs_constants import breakStrandsCommand_numberOfBasesBeforeNextBreak_prefs_key from utilities.Comparison import same_vals from utilities import debug_flags from utilities.debug import print_compact_stack from dna.command_support.BreakOrJoinStrands_PropertyManager import BreakOrJoinStrands_PropertyManager import foundation.env as env from widgets.prefs_widgets import connect_spinBox_with_pref from utilities.GlobalPreferences import DEBUG_BREAK_OPTIONS_FEATURE from PM.PM_ObjectChooser import PM_ObjectChooser DEBUG_CHANGE_COUNTERS = False _superclass = BreakOrJoinStrands_PropertyManager class BreakStrands_PropertyManager( BreakOrJoinStrands_PropertyManager): """ The BreakStrands_PropertyManager class provides a Property Manager for the B{Break Strands} command on the flyout toolbar in the Build > Dna mode. @ivar title: The title that appears in the property manager header. @type title: str @ivar pmName: The name of this property manager. This is used to set the name of the PM_Dialog object via setObjectName(). @type name: str @ivar iconPath: The relative path to the PNG file that contains a 22 x 22 icon image that appears in the PM header. @type iconPath: str """ title = "Break Strands" pmName = title iconPath = "ui/actions/Command Toolbar/BuildDna/BreakStrand.png" def __init__( self, command ): """ Constructor for the property manager. """ 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) msg = "Click on a strand's backbone bond to break a strand." self.updateMessage(msg) 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 """ #TODO: This is a temporary fix for a bug. When you invoke a temporary mode # entering such a temporary mode keeps the signals of #PM from the previous mode connected ( #but while exiting that temporary mode and reentering the #previous mode, it atucally reconnects the signal! This gives rise to #lots of bugs. This needs more general fix in Temporary mode API. # -- Ninad 2008-01-09 (similar comment exists in MovePropertyManager.py if isConnect and self.isAlreadyConnected: if debug_flags.atom_debug: print_compact_stack("warning: attempt to connect widgets"\ "in this PM that are already connected." ) return if not isConnect and self.isAlreadyDisconnected: if debug_flags.atom_debug: print_compact_stack("warning: attempt to disconnect widgets"\ "in this PM that are already disconnected.") return self.isAlreadyConnected = isConnect self.isAlreadyDisconnected = not isConnect if isConnect: change_connect = self.win.connect else: change_connect = self.win.disconnect _superclass.connect_or_disconnect_signals(self, isConnect = isConnect) if DEBUG_BREAK_OPTIONS_FEATURE: self._dnaStrandChooserGroupBox.connect_or_disconnect_signals(isConnect = isConnect) change_connect(self.breakAllStrandsButton, SIGNAL("clicked()"), self.command.breakStrandBonds) change_connect(self.basesBeforeNextBreakSpinBox, SIGNAL("valueChanged(int)"), self.valueChanged_basesBeforeNextBreak) def _update_UI_do_updates(self): """ Overrides superclass method. @see: Command_PropertyManager._update_UI_do_updates() @see: DnaSegment_EditCommand.hasResizableStructure() @see: self._current_model_changed_params() """ if not DEBUG_BREAK_OPTIONS_FEATURE: return currentParams = self._current_model_changed_params() #Optimization. Return from the model_changed method if the #params are the same. if same_vals(currentParams, self._previous_model_changed_params): return basesBeforeNextBreak = currentParams #update the self._previous_model_changed_params with this new param set. self._previous_model_changed_params = currentParams self.command.updateBreakSites() def _current_model_changed_params(self): """ Returns a tuple containing the parameters that will be compared against the previously stored parameters. This provides a quick test to determine whether to do more things in self.model_changed() @see: self.model_changed() which calls this @see: self._previous_model_changed_params attr. """ params = None if self.command: params = (env.prefs[breakStrandsCommand_numberOfBasesBeforeNextBreak_prefs_key]) return params def valueChanged_basesBeforeNextBreak(self, val): self.win.glpane.gl_update() def getNumberOfBasesBeforeNextBreak(self): return self.basesBeforeNextBreakSpinBox.value() def _addGroupBoxes( self ): """ Add the Property Manager group boxes. """ self._breakOptionsGroupbox = PM_GroupBox( self, title = "Break Options" ) self._loadBreakOptionsGroupbox( self._breakOptionsGroupbox ) self._displayOptionsGroupBox = PM_GroupBox( self, title = "Display Options" ) self._loadDisplayOptionsGroupBox( self._displayOptionsGroupBox ) self._baseNumberLabelGroupBox = PM_GroupBox( self, title = "Base Number Labels" ) self._loadBaseNumberLabelGroupBox(self._baseNumberLabelGroupBox) def _loadBreakOptionsGroupbox(self, pmGroupBox): """ Load widgets in this group box. """ self.assignColorToBrokenDnaStrandsCheckBox = \ PM_CheckBox(pmGroupBox , text = 'Assign new color to broken strands', widgetColumn = 0, spanWidth = True) connect_checkbox_with_boolean_pref( self.assignColorToBrokenDnaStrandsCheckBox, assignColorToBrokenDnaStrands_prefs_key ) self.basesBeforeNextBreakSpinBox = \ PM_SpinBox( pmGroupBox, label = "Break Every:", value = 3, setAsDefault = False, minimum = 1, maximum = 10000, suffix = " bases" ) connect_spinBox_with_pref( self.basesBeforeNextBreakSpinBox, breakStrandsCommand_numberOfBasesBeforeNextBreak_prefs_key) self.breakAllStrandsButton = PM_PushButton( pmGroupBox, label = "", text = "do it" ) self._dnaStrandChooserGroupBox = PM_ObjectChooser( pmGroupBox, self.command, modelObjectType = self.win.assy.DnaStrand, title = "Choose strands " ) if not DEBUG_BREAK_OPTIONS_FEATURE: self._dnaStrandChooserGroupBox.hide() self.breakAllStrandsButton.hide() self.basesBeforeNextBreakSpinBox.hide() #Return varius prefs_keys for arrowhead display options ui elements ======= def _prefs_key_arrowsOnThreePrimeEnds(self): """ Return the appropriate KEY of the preference for whether to draw arrows on 3' strand ends of PAM DNA. """ return breakStrandsCommand_arrowsOnThreePrimeEnds_prefs_key def _prefs_key_arrowsOnFivePrimeEnds(self): """ Return the appropriate KEY of the preference for whether to draw arrows on 5' strand ends of PAM DNA. """ return breakStrandsCommand_arrowsOnFivePrimeEnds_prefs_key def _prefs_key_useCustomColorForThreePrimeArrowheads(self): """ Return the appropriate KEY of the preference for whether to use a custom color for 3' arrowheads (if they are drawn) or for 3' strand end atoms (if arrowheads are not drawn) """ return breakStrandsCommand_useCustomColorForThreePrimeArrowheads_prefs_key def _prefs_key_useCustomColorForFivePrimeArrowheads(self): """ Return the appropriate KEY of the preference for whether to use a custom color for 5' arrowheads (if they are drawn) or for 5' strand end atoms (if arrowheads are not drawn). """ return breakStrandsCommand_useCustomColorForFivePrimeArrowheads_prefs_key def _prefs_key_dnaStrandThreePrimeArrowheadsCustomColor(self): """ Return the appropriate KEY of the preference for what custom color to use when drawing 3' arrowheads (if they are drawn) or 3' strand end atoms (if arrowheads are not drawn). """ return breakStrandsCommand_dnaStrandThreePrimeArrowheadsCustomColor_prefs_key def _prefs_key_dnaStrandFivePrimeArrowheadsCustomColor(self): """ Return the appropriate KEY of the preference for what custom color to use when drawing 5' arrowheads (if they are drawn) or 5' strand end atoms (if arrowheads are not drawn). """ return breakStrandsCommand_dnaStrandFivePrimeArrowheadsCustomColor_prefs_key def _addWhatsThisText( self ): """ What's This text for widgets in the DNA Property Manager. """ pass def _addToolTipText(self): """ Tool Tip text for widgets in the DNA Property Manager. """ pass
NanoCAD-master
cad/src/dna/commands/BreakStrands/BreakStrands_PropertyManager.py
NanoCAD-master
cad/src/dna/commands/BreakStrands/__init__.py
# Copyright 2008-2009 Nanorex, Inc. See LICENSE file for details. """ BreakSite_Marker object wraps the functionality of identifying the potential break sites within a DnaStrand. NOTE: This class has nothing to do with DnaMarker class. @author: Ninad @version: $Id$ @copyright: 2008-2009 Nanorex, Inc. See LICENSE file for details. History: July 2008: created. As of 2008-08-08 a comment here by Ninad said this was not used, but was to be used for new Break options features. As of 2009-01-21 it appears to be used (not fully verified). [--bruce] """ from model.bond_constants import find_bond DEBUG_DRAW_SPHERES_AROUND_ATOMS_AT_BREAK_SITES = False import time class BreakSite_Marker(object): """ BreakSite_Marker object wraps the functionality of identifying the potential break sites within a DnaStrand. @see: BreakStrands_GraphicsMode @NOTE: This class has nothing to do with DnaMarker class. """ def __init__(self, graphicsMode): self.graphicsMode = graphicsMode self.command = self.graphicsMode.command self.win = self.graphicsMode.win self.glpane = self.graphicsMode.glpane self._breakSitesDict = {} self._breakSites_atomPairs_dict = {} self._startAtoms_dict = {} self._endAtoms_dict = {} def getBreakSitesDict(self): return self._breakSitesDict def getStartAtomsDict(self): return self._startAtoms_dict def getEndAtomsDict(self): return self._endAtoms_dict def getBreakSites_atomPairsDict(self): return self._breakSites_atomPairs_dict def full_update(self): self._startAtoms_dict = {} self._endAtoms_dict = {} self.update() def update(self): self.clearDictionaries() self._updateBreakSites() def clearDictionaries(self): self._breakSitesDict = {} self._breakSites_atomPairs_dict = {} ##self._startAtoms_dict = {} ##self._endAtoms_dict = {} def updateStartAtomsDict(self, atm): strand = atm.getDnaStrand() if strand in self.command.getStrandList(): self._startAtoms_dict[strand] = atm self._updateBreakSitesForStrand(strand) def updateEndAtomsDict(self, atm): strand = atm.getStrand() if strand in self.command.getStrandList(): self._endAtoms_dict[strand] = atm self._updateBreakSitesForStrand(strand) def _updateBreakSites(self): ##print "***BEFORE updating the breaksites:", time.clock() strands_to_be_searched = self.command.getStrandList() basesBeforeNextBreak = self.command.getNumberOfBasesBeforeNextBreak() if basesBeforeNextBreak == 0: return #not possible for strand in strands_to_be_searched: self._updateBreakSitesForStrand(strand) ##print "***AFTER updating the breaksites:", time.clock() def _updateBreakSitesForStrand(self, strand): """ """ basesBeforeNextBreak = self.command.getNumberOfBasesBeforeNextBreak() rawStrandAtomList = strand.get_strand_atoms_in_bond_direction() strandAtomList = filter(lambda atm: not atm.is_singlet(), rawStrandAtomList) if len(strandAtomList) < 3: return #skip this strand. It doesn't have enough bases if len(strandAtomList) < basesBeforeNextBreak: return #First create a dict to store the information about the bond #that will be stored in the atom pairs. atomPair_dict = {} # ============================================= #If start and end atoms are specified between which the break sites #need to be computed -- startAtom = None endAtom = None startAtomIndex = 0 endAtomIndex = len(strandAtomList) - 1 if self._startAtoms_dict.has_key(strand): startAtom = self._startAtoms_dict[strand] #@@BUG METHOD NOT FINISHED YET #-- sometimes it gives error x not in list after breaking #a strand etc. CHECK this -- Ninad 2008-07-02 startAtomIndex = strandAtomList.index(startAtom) if self._endAtoms_dict.has_key(strand): endAtom = self._endAtoms_dict.index(endAtom) endAtomIndex = strandAtomList.index(endAtom) if startAtom and endAtom: if startAtomIndex > endAtomIndex: strandAtomList.reverse() startAtomIndex = strandAtomList.index(startAtom) endAtomIndex = strandAtomList.index(endAtom) # ============================================= i = 1 listLength = len(strandAtomList[startAtomIndex: endAtomIndex + 1]) for atm in strandAtomList[startAtomIndex: endAtomIndex + 1]: #Add '1' to the following actual atom index within the list. #This is done because the start atom itself will be counted #as '1st base atom to start with -- INCLUDING THAT ATOM when we #mark the break sites. #Example: User want to create a break after every 1 base. #So, if we start at 5' end, the 5' end atom will be considred #the first base, and a bond between the 5'end atom and the next #strand atom will be a 'break site'. Then the next break site #will be the bond '1 base after that strand atom and like that idx = strandAtomList.index(atm) if (i%basesBeforeNextBreak) == 0 and i < listLength: next_atom = strandAtomList[idx + 1] bond = find_bond(atm, next_atom) if not atomPair_dict.has_key(bond): atomPair_dict[bond] = (atm, next_atom) if DEBUG_DRAW_SPHERES_AROUND_ATOMS_AT_BREAK_SITES: for a in (atm, next_atom): if not self._breakSitesDict.has_key(id(a)): self._breakSitesDict[id(a)] = a i += 1 self._breakSites_atomPairs_dict[strand] = atomPair_dict def _updateBreakSitesForStrand_ORIG(self, strand): """ """ basesBeforeNextBreak = self.command.getNumberOfBasesBeforeNextBreak() rawStrandAtomList = strand.get_strand_atoms_in_bond_direction() strandAtomList = filter(lambda atm: not atm.is_singlet(), rawStrandAtomList) if len(strandAtomList) < 3: return #skip this strand. It doesn't have enough bases if len(strandAtomList) < basesBeforeNextBreak: return # ============================================= #If start and end atoms are specified between which the break sites #need to be computed -- startAtom = None endAtom = None startAtomIndex = 0 endAtomIndex = len(strandAtomList) - 1 if self._startAtoms_dict.has_key(strand): startAtom = self._startAtoms_dict[strand] #@@BUG METHOD NOT FINISHED YET #-- sometimes it gives error x not in list after breaking #a strand etc. CHECK this -- Ninad 2008-07-02 startAtomIndex = strandAtomList.index(startAtom) if self._endAtoms_dict.has_key(strand): endAtom = self._endAtoms_dict.index(endAtom) endAtomIndex = strandAtomList.index(endAtom) if startAtom and endAtom: if startAtomIndex > endAtomIndex: strandAtomList.reverse() startAtomIndex = strandAtomList.index(startAtom) endAtomIndex = strandAtomList.index(endAtom) # ============================================= i = 1 listLength = len(strandAtomList[startAtomIndex: endAtomIndex + 1]) for atm in strandAtomList[startAtomIndex: endAtomIndex + 1]: #Add '1' to the following actual atom index within the list. #This is done because the start atom itself will be counted #as '1st base atom to start with -- INCLUDING THAT ATOM when we #mark the break sites. #Example: User want to create a break after every 1 base. #So, if we start at 5' end, the 5' end atom will be considred #the first base, and a bond between the 5'end atom and the next #strand atom will be a 'break site'. Then the next break site #will be the bond '1 base after that strand atom and like that ##idx = strandAtomList.index(atm) + 1 idx = strandAtomList.index(atm) ##if (idx%basesBeforeNextBreak) == 0 and idx < len(strandAtomList): if (i%basesBeforeNextBreak) == 0 and i < listLength: next_atom = strandAtomList[idx + 1] bond = find_bond(atm, next_atom) if not self._breakSites_atomPairs_dict.has_key(bond): self._breakSites_atomPairs_dict[bond] = (atm, next_atom) for a in (atm, next_atom): if not self._breakSitesDict.has_key(id(a)): self._breakSitesDict[id(a)] = a i += 1
NanoCAD-master
cad/src/dna/commands/BreakStrands/BreakSite_Marker.py
# Copyright 2008 Nanorex, Inc. See LICENSE file for details. """ @author: Ninad @version: $Id$ @copyright: 2008 Nanorex, Inc. See LICENSE file for details. """ from widgets.prefs_widgets import connect_checkbox_with_boolean_pref from PyQt4.Qt import Qt from PyQt4.Qt import SIGNAL from PM.PM_GroupBox import PM_GroupBox from PM.PM_ComboBox import PM_ComboBox from PM.PM_PushButton import PM_PushButton from PM.PM_Constants import PM_DONE_BUTTON from PM.PM_Constants import PM_WHATS_THIS_BUTTON from dna.model.DnaStrand import DnaStrand from command_support.Command_PropertyManager import Command_PropertyManager _superclass = Command_PropertyManager class ConvertDna_PropertyManager(Command_PropertyManager): """ Provides a Property Manager for the B{Convert Dna} command. """ title = "Convert DNA" pmName = title iconPath = "ui/actions/Command Toolbar/BuildDna/ConvertDna.png" def __init__( self, command ): """ Constructor for the property manager. """ _superclass.__init__(self, command) self.assy = self.win.assy self.showTopRowButtons( PM_DONE_BUTTON | \ PM_WHATS_THIS_BUTTON) self.updateMessage() return 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 change_connect(self._convertButton, SIGNAL("clicked()"), self._convertDna) ##change_connect( self.includeStrandsComboBox, ##SIGNAL("activated(int)"), ##self.update_includeStrands ) return # Ask Bruce where this should live (i.e. class Part?) --Mark # This method was copied from OrderDna_PropertyManager.py def _getAllDnaStrands(self, selectedOnly = False): """ Returns a list of all the DNA strands in the current part, or only the selected strands if I{selectedOnly} is True. @param selectedOnly: If True, return only the selected DNA strands. @type selectedOnly: bool """ dnaStrandList = [] def func(node): if isinstance(node, DnaStrand): if selectedOnly: if node.picked: dnaStrandList.append(node) else: dnaStrandList.append(node) self.win.assy.part.topnode.apply2all(func) return dnaStrandList def _convertDna(self): _dnaStrandList = [] _dnaStrandList = self._getAllDnaStrands(selectedOnly = True) if not _dnaStrandList: msg = "<font color=red>" \ "Nothing converted since no DNA strands are currently selected." self.updateMessage(msg) return if self._convertChoiceComboBox.currentIndex() == 0: self._convertPAM3ToPAM5() else: self._convertPAM5ToPAM3() self.updateMessage() return def _convertPAM3ToPAM5(self): self.command.assy.convertPAM3to5Command() return def _convertPAM5ToPAM3(self): self.command.assy.convertPAM5to3Command() return def _addGroupBoxes( self ): """ Add the Property Manager group boxes. """ self._pmGroupBox1 = PM_GroupBox( self, title = "Conversion Options" ) self._loadGroupBox1( self._pmGroupBox1 ) return def _loadGroupBox1(self, pmGroupBox): """ Load widgets in group box. """ convertChoices = ["Convert from PAM3 to PAM5", "Convert from PAM5 to PAM3"] self._convertChoiceComboBox = \ PM_ComboBox( pmGroupBox, label = "", choices = convertChoices, index = 0, setAsDefault = True, spanWidth = True) self._convertButton = \ PM_PushButton( pmGroupBox, label = "", text = "Convert Selection Now", spanWidth = True) return def _addWhatsThisText(self): """ What's This text for widgets in this Property Manager. """ pass def _addToolTipText(self): """ Tool Tip text for widgets in the DNA Property Manager. """ pass def show(self): """ Show this property manager. Overrides EditCommand_PM.show() We need this here to force the message update whenever we show the PM since an old message might still be there. """ _superclass.show(self) self.updateMessage() def updateMessage(self, msg = ''): """ """ if not msg: msg = "Select the DNA you want to convert, then select the appropriate "\ "conversion option and press the <b>Convert Selection Now</b> button." _superclass.updateMessage(self, msg) return
NanoCAD-master
cad/src/dna/commands/ConvertDna/ConvertDna_PropertyManager.py
NanoCAD-master
cad/src/dna/commands/ConvertDna/__init__.py
# Copyright 2008 Nanorex, Inc. See LICENSE file for details. """ @author: Ninad @version: $Id$ @copyright: 2008 Nanorex, Inc. See LICENSE file for details. """ from utilities.constants import CL_EXTERNAL_ACTION from commands.SelectChunks.SelectChunks_Command import SelectChunks_Command from dna.commands.ConvertDna.ConvertDna_GraphicsMode import ConvertDna_GraphicsMode from dna.commands.ConvertDna.ConvertDna_PropertyManager import ConvertDna_PropertyManager _superclass = SelectChunks_Command class ConvertDna_Command(SelectChunks_Command): """ "Convert DNA" command. """ # class constants commandName = 'CONVERT_DNA' featurename = "Convert DNA" command_level = CL_EXTERNAL_ACTION GraphicsMode_class = ConvertDna_GraphicsMode PM_class = ConvertDna_PropertyManager command_should_resume_prevMode = True command_has_its_own_PM = True flyoutToolbar = None
NanoCAD-master
cad/src/dna/commands/ConvertDna/ConvertDna_Command.py
# Copyright 2008 Nanorex, Inc. See LICENSE file for details. """ @author: Ninad @version: $Id$ @copyright: 2008 Nanorex, Inc. See LICENSE file for details. """ from commands.SelectChunks.SelectChunks_GraphicsMode import SelectChunks_GraphicsMode class ConvertDna_GraphicsMode(SelectChunks_GraphicsMode): """ Graphics mode for "Convert DNA" command. """ pass
NanoCAD-master
cad/src/dna/commands/ConvertDna/ConvertDna_GraphicsMode.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-21 - 2008-06-01 Created and further refactored and modified @See: ListWidgetItems_Command_Mixin, ListWidgetItems_GraphicsMode_Mixin ListWidgetItems_PM_Mixin, CrossoverSite_Marker MakeCrossovers_GraphicsMode TODO 2008-06-01 : See class CrossoverSite_Marker for details """ import time import foundation.changes as changes from commands.SelectChunks.SelectChunks_Command import SelectChunks_Command from dna.commands.MakeCrossovers.MakeCrossovers_GraphicsMode import MakeCrossovers_Graphicsmode from dna.commands.MakeCrossovers.MakeCrossovers_PropertyManager import MakeCrossovers_PropertyManager from model.bond_constants import find_bond from model.bonds import bond_at_singlets from utilities.debug import print_compact_traceback, print_compact_stack from utilities.Log import orangemsg from dna.commands.MakeCrossovers.ListWidgetItems_Command_Mixin import ListWidgetItems_Command_Mixin MAXIMUM_ALLOWED_DNA_SEGMENTS_FOR_CROSSOVER = 8 _superclass = SelectChunks_Command class MakeCrossovers_Command(SelectChunks_Command, ListWidgetItems_Command_Mixin ): """ """ GraphicsMode_class = MakeCrossovers_Graphicsmode PM_class = MakeCrossovers_PropertyManager # class constants commandName = 'MAKE_CROSSOVERS' featurename = "Make Crossovers" from utilities.constants import CL_SUBCOMMAND command_level = CL_SUBCOMMAND command_parent = 'BUILD_DNA' command_should_resume_prevMode = True command_has_its_own_PM = True flyoutToolbar = None def _getFlyoutToolBarActionAndParentCommand(self): """ Overides superclass method. @see: self.command_update_flyout() """ flyoutActionToCheck = 'makeCrossoversAction' parentCommandName = None return flyoutActionToCheck, parentCommandName def command_entered(self): #Set the initial segment list. The segments within this segment list #will be searched for the crossovers. ListWidgetItems_Command_Mixin.command_entered(self) _superclass.command_entered(self) selectedSegments = self.win.assy.getSelectedDnaSegments() self.ensureSegmentListItemsWithinLimit(selectedSegments) def logMessage(self, type = 'DEFAULT'): """ Updates the PM message groupbox message with the one specified below. """ msg = '' if type == 'ADD_SEGMENTS_ACTIVATED': msg = """To add new PAM3 DNA segments to the list, click on the segment's axis. Multiple segments can be added at once by doing a rectangular lasso selection in the 3D workspace.""" elif type == 'REMOVE_SEGMENTS_ACTIVATED': msg = """To remove segments from the list, click on the segment's axis. Multiple segments can be removed at once by doing a rectangular lasso selection in the 3D workspace.""" elif type == 'LEFT_DRAG_STARTED': msg = """Transparent green spheres (if present) around the atoms indicate potential crossover sites.""" elif type == 'LEFT_DRAG_FINISHED': msg = self.propMgr.defaultLogMessage elif type == 'WARNING_LIMIT_EXCEEDED': msg = "Only a maximum of <b> %d </b> DNA segments can be searched for "\ "crossover sites. Segments not added to the list"%self.itemLimitForSegmentListWidget() msg = orangemsg(msg) elif type == 'WARNING_PAM5_SEGMENT_FOUND': msg = """Warning: One or more of the PAM5 DNA segments have been removed from the segment list.Make Crossovers command is only availble for PAM3 model.""" msg = orangemsg(msg) else: msg = self.propMgr.defaultLogMessage self.propMgr.updateMessage(msg) def itemLimitForSegmentListWidget(self): """ Maximum number of items allowed in the segment list widet.(For performance reasons) """ return MAXIMUM_ALLOWED_DNA_SEGMENTS_FOR_CROSSOVER def ensureSegmentListItemsWithinLimit(self, segments): """ """ #Following should never happen but added as a safety if len(self._structList) > self.itemLimitForSegmentListWidget(): self.logMessage('WARNING_LIMIT_EXCEEDED') return #Optimization if len(self._structList) == 0 and \ len(segments)<= self.itemLimitForSegmentListWidget(): self.setSegmentList(segments) return raw_number_of_segments = len(self._structList) + len(segments) if raw_number_of_segments <= self.itemLimitForSegmentListWidget(): for segment in segments: self.addSegmentToSegmentList(segment) return #Check how many of the segments are already in self._structList. #Filter the ones that are *NOT* in self._structList. This filtered #segments are the segments to add to the list def func(segment): if segment not in self._structList: return True return False segments_to_add = filter(lambda seg: func(seg), segments) raw_number_of_segments = len(segments_to_add) + len(self._structList) if raw_number_of_segments <= self.itemLimitForSegmentListWidget(): for segment in segments: self.addSegmentToSegmentList(segment) return else: self.logMessage('WARNING_LIMIT_EXCEEDED') def makeAllCrossovers(self): """ Make all possible crossovers @see: self.makeCrossover() """ crossoverPairs = self.graphicsMode.get_final_crossover_pairs() if crossoverPairs: for pairs in crossoverPairs: self.makeCrossover(pairs, suppress_post_crossover_updates = True) self.graphicsMode.clearDictionaries() def makeCrossover(self, crossoverPairs, suppress_post_crossover_updates = False): """ Make the crossover between the atoms of the crossover pairs. @param crossoverPairs: A tuple of 4 atoms between which the crossover will be made. Note: As of 2008-06-03, this method assumes the following form: (atom1, neighbor1, atom2, neighbor2) Where all atoms are PAM3 atoms. pair of atoms atom1 and neighbor1 are sugar atoms bonded to each other (same for pair atom2, neighbor2) The bond between these atoms will be broken first and then the atoms are bonded to the opposite atoms. @type crossoverPair: tuple @param suppress_post_crossover_updates: After making a crossover, this method calls its graphicsMode method to do some more updates (such as updating the atoms dictionaries etc.) But if its a batch process, (e.g. user is calling makeAllCrossovers, this update is not needed after making an individual crossover. The caller then sets this flag to true to tell this method to skip that update. @type suppress_post_crossover_updates: boolean @seE:self.makeAllCrossovers() """ if len(crossoverPairs) != 4: print_compact_stack("Bug in making the crossover.len(crossoverPairs) != 4") return atm1, neighbor1, atm2, neighbor2 = crossoverPairs bond1 = find_bond(atm1, neighbor1) if bond1: bond1.bust() bond2 = find_bond(atm2, neighbor2) if bond2: bond2.bust() #Do we need to check if these pairs are valid (i.e.a 5' end atom is #bonded to a 3' end atom.. I think its not needed as its done in #self._bond_two_strandAtoms. self._bond_two_strandAtoms(atm1, neighbor2) self._bond_two_strandAtoms(atm2, neighbor1) if not suppress_post_crossover_updates: self.graphicsMode.update_after_crossover_creation(crossoverPairs) def _bond_two_strandAtoms(self, atm1, atm2): """ Bonds the given strand atoms (sugar atoms) together. To bond these atoms, it always makes sure that a 3' bondpoint on one atom is bonded to 5' bondpoint on the other atom. @param atm1: The first sugar atom of PAM3 (i.e. the strand atom) to be bonded with atm2. @param atm2: Second sugar atom @Note: This method is copied from DnaDuplex.py """ #Moved from B_Dna_PAM3_SingleStrand_Generator to here, to fix bugs like #2711 in segment resizing-- Ninad 2008-04-14 assert atm1.element.role == 'strand' and atm2.element.role == 'strand' #Initialize all possible bond points to None five_prime_bondPoint_atm1 = None three_prime_bondPoint_atm1 = None five_prime_bondPoint_atm2 = None three_prime_bondPoint_atm2 = None #Initialize the final bondPoints we will use to create bonds bondPoint1 = None bondPoint2 = None #Find 5' and 3' bondpoints of atm1 (BTW, as of 2008-04-11, atm1 is #the new dna strandend atom See self._fuse_new_dna_with_original_duplex #But it doesn't matter here. for s1 in atm1.singNeighbors(): bnd = s1.bonds[0] if bnd.isFivePrimeOpenBond(): five_prime_bondPoint_atm1 = s1 if bnd.isThreePrimeOpenBond(): three_prime_bondPoint_atm1 = s1 #Find 5' and 3' bondpoints of atm2 for s2 in atm2.singNeighbors(): bnd = s2.bonds[0] if bnd.isFivePrimeOpenBond(): five_prime_bondPoint_atm2 = s2 if bnd.isThreePrimeOpenBond(): three_prime_bondPoint_atm2 = s2 #Determine bondpoint1 and bondPoint2 (the ones we will bond). See method #docstring for details. if five_prime_bondPoint_atm1 and three_prime_bondPoint_atm2: bondPoint1 = five_prime_bondPoint_atm1 bondPoint2 = three_prime_bondPoint_atm2 #Following will overwrite bondpoint1 and bondPoint2, if the condition is #True. Doesn't matter. See method docstring to know why. if three_prime_bondPoint_atm1 and five_prime_bondPoint_atm2: bondPoint1 = three_prime_bondPoint_atm1 bondPoint2 = five_prime_bondPoint_atm2 #Copied over from BuildAtoms_GraphicsMode._singletLeftUp_joinStrands() #The following fixes bug 2770 #Set the color of the whole dna strandGroup to the color of the #strand, whose bondpoint, is dropped over to the bondboint of the #other strandchunk (thus joining the two strands together into #a single dna strand group) - Ninad 2008-04-09 color = atm1.molecule.color if color is None: color = atm1.element.color strandGroup1 = atm1.molecule.parent_node_of_class(self.win.assy.DnaStrand) strandGroup2 = atm2.molecule.parent_node_of_class( self.win.assy.DnaStrand) if strandGroup2 is not None: #set the strand color of strandGroup2 to the one for #strandGroup1. strandGroup2.setStrandColor(color) strandChunkList = strandGroup2.getStrandChunks() for c in strandChunkList: if hasattr(c, 'invalidate_ladder'): c.invalidate_ladder() #Do the actual bonding if bondPoint1 and bondPoint2: try: bond_at_singlets(bondPoint1, bondPoint2, move = False) except: print_compact_traceback("Bug: unable to bond atoms %s and %s"%(atm1, atm2)) if strandGroup1 is not None: strandGroup1.setStrandColor(color) def updateCrossoverSites(self): """ Calls the grraphics mode method that does the job of updating all the crossover sites in the 3D workspace. """ self.graphicsMode.updateCrossoverSites() def updateExprsHandleDict(self): self.graphicsMode.updateExprsHandleDict() def ensureValidSegmentList(self): """ Ensures that the segments within the segment list being searched for crossover sites have all valid segments (even empty list is considered as valid as of 2008-06-04) @see: MakeCrossversPropertyManager.model_changed() """ pam5_segment_found = False for segment in self._structList: if not segment.is_PAM3_DnaSegment(): pam5_segment_found = True self._structList.remove(segment) if pam5_segment_found: self.logMessage('WARNING_PAM5_SEGMENT_FOUND') return pam5_segment_found
NanoCAD-master
cad/src/dna/commands/MakeCrossovers/MakeCrossovers_Command.py
# Copyright 2008 Nanorex, Inc. See LICENSE file for details. """ MakeCrossovers_PropertyManager.py @author: Ninad @copyright: 2008 Nanorex, Inc. See LICENSE file for details. @version:$Id$ History: TODO: See MakeCrossovers_Command for details. """ import foundation.env as env from PM.PM_SelectionListWidget import PM_SelectionListWidget from PM.PM_GroupBox import PM_GroupBox from PM.PM_PushButton import PM_PushButton from PM.PM_Constants import PM_DONE_BUTTON from PM.PM_Constants import PM_WHATS_THIS_BUTTON from PM.PM_CheckBox import PM_CheckBox from PyQt4.Qt import SIGNAL, Qt from utilities.prefs_constants import assignColorToBrokenDnaStrands_prefs_key from utilities.prefs_constants import makeCrossoversCommand_crossoverSearch_bet_given_segments_only_prefs_key from dna.commands.MakeCrossovers.ListWidgetItems_PM_Mixin import ListWidgetItems_PM_Mixin from utilities import debug_flags from utilities.debug import print_compact_stack from utilities.Comparison import same_vals from widgets.prefs_widgets import connect_checkbox_with_boolean_pref from ne1_ui.WhatsThisText_for_PropertyManagers import whatsThis_MakeCrossoversPropertyManager from utilities.Log import orangemsg from command_support.Command_PropertyManager import Command_PropertyManager _superclass = Command_PropertyManager class MakeCrossovers_PropertyManager( Command_PropertyManager, ListWidgetItems_PM_Mixin ): """ The MakeCrossovers_PropertyManager class provides a Property Manager for the B{Make Crossovers} command on the flyout toolbar in the Build > Dna mode. @ivar title: The title that appears in the property manager header. @type title: str @ivar pmName: The name of this property manager. This is used to set the name of the PM_Dialog object via setObjectName(). @type name: str @ivar iconPath: The relative path to the PNG file that contains a 22 x 22 icon image that appears in the PM header. @type iconPath: str """ title = "Make Crossovers" pmName = title iconPath = "ui/actions/Command Toolbar/BuildDna/MakeCrossovers.png" def __init__( self, command): """ Constructor for the property manager. """ self.isAlreadyConnected = False self.isAlreadyDisconnected = False self._previous_model_changed_params = None _superclass.__init__(self, command) self.showTopRowButtons( PM_DONE_BUTTON | \ PM_WHATS_THIS_BUTTON) self.defaultLogMessage = """Pairs of white cylinders (if any) in the 3D workspace indicate potential crossover sites. Clicking on such a cylinder pair will make that crossover.""" self.updateMessage(self.defaultLogMessage) 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 """ #TODO: This is a temporary fix for a bug. When you invoke a #temporary mode entering such a temporary mode keeps the signals of #PM from the previous mode connected ( #but while exiting that temporary mode and reentering the #previous mode, it atucally reconnects the signal! This gives rise to #lots of bugs. This needs more general fix in Temporary mode API. # -- Ninad 2008-01-09 (similar comment exists in MovePropertyManager.py if isConnect and self.isAlreadyConnected: if debug_flags.atom_debug: print_compact_stack("warning: attempt to connect widgets"\ "in this PM that are already connected." ) return if not isConnect and self.isAlreadyDisconnected: if debug_flags.atom_debug: print_compact_stack("warning: attempt to disconnect widgets"\ "in this PM that are already disconnected.") return self.isAlreadyConnected = isConnect self.isAlreadyDisconnected = not isConnect if isConnect: change_connect = self.win.connect else: change_connect = self.win.disconnect self.segmentListWidget.connect_or_disconnect_signals(isConnect) change_connect(self.addSegmentsToolButton, SIGNAL("toggled(bool)"), self.activateAddSegmentsTool) change_connect(self.removeSegmentsToolButton, SIGNAL("toggled(bool)"), self.activateRemoveSegmentsTool) change_connect(self.makeCrossoverPushButton, SIGNAL("clicked()"), self._makeAllCrossovers) connect_checkbox_with_boolean_pref( self.crossoversBetGivenSegmentsOnly_checkBox, makeCrossoversCommand_crossoverSearch_bet_given_segments_only_prefs_key) def show(self): """ Overrides the superclass method @see: self._deactivateAddRemoveSegmentsTool """ _superclass.show(self) self._deactivateAddRemoveSegmentsTool() def _makeAllCrossovers(self): self.command.makeAllCrossovers() def _addGroupBoxes( self ): """ Add the Property Manager group boxes. """ self._pmGroupBox1 = PM_GroupBox( self, title = "Segments for Crossover Search" ) self._loadGroupBox1( self._pmGroupBox1 ) def _loadGroupBox1(self, pmGroupBox): """ load widgets in groupbox1 """ self._loadSegmentListWidget(pmGroupBox) self.crossoversBetGivenSegmentsOnly_checkBox = PM_CheckBox( pmGroupBox, text = "Between above segments only", widgetColumn = 0, setAsDefault = True, spanWidth = True, ) #If this preferece value is True, the search algotithm will search for #the potential crossover sites only *between* the segments in the #segment list widget (thus ignoring other segments not in that list) if env.prefs[makeCrossoversCommand_crossoverSearch_bet_given_segments_only_prefs_key]: self.crossoversBetGivenSegmentsOnly_checkBox.setCheckState(Qt.Checked) else: self.crossoversBetGivenSegmentsOnly_checkBox.setCheckState(Qt.Unchecked) self.makeCrossoverPushButton = PM_PushButton( pmGroupBox, label = "", text = "Make All Crossovers", spanWidth = True ) def _update_UI_do_updates(self): """ @see: Command_PropertyManager._update_UI_do_updates() @see: DnaSegment_EditCommand.command_update_UI() @see: DnaSegment_EditCommand.hasResizableStructure() @see: self._current_model_changed_params() """ currentParams = self._current_model_changed_params() #Optimization. Return from the model_changed method if the #params are the same. if same_vals(currentParams, self._previous_model_changed_params): return number_of_segments, \ crossover_search_pref_junk,\ bool_valid_segmentList_junk = currentParams #update the self._previous_model_changed_params with this new param set. self._previous_model_changed_params = currentParams #Ensures that there are only PAM3 DNA segments in the commad's tructure #list (command._structList. Call this before updating the list widgets! self.command.ensureValidSegmentList() self.updateListWidgets() self.command.updateCrossoverSites() def _current_model_changed_params(self): """ Returns a tuple containing the parameters that will be compared against the previously stored parameters. This provides a quick test to determine whether to do more things in self.model_changed() @see: self.model_changed() which calls this @see: self._previous_model_changed_params attr. """ params = None if self.command: #update the list first. self.command.updateSegmentList() bool_valid_segmentList = self.command.ensureValidSegmentList() number_of_segments = len(self.command.getSegmentList()) crossover_search_pref = \ env.prefs[makeCrossoversCommand_crossoverSearch_bet_given_segments_only_prefs_key] params = (number_of_segments, crossover_search_pref, bool_valid_segmentList ) return params def _addWhatsThisText( self ): """ What's This text for widgets in the DNA Property Manager. """ whatsThis_MakeCrossoversPropertyManager(self) def _addToolTipText(self): """ Tool Tip text for widgets in the DNA Property Manager. """ pass
NanoCAD-master
cad/src/dna/commands/MakeCrossovers/MakeCrossovers_PropertyManager.py
NanoCAD-master
cad/src/dna/commands/MakeCrossovers/__init__.py
# Copyright 2008 Nanorex, Inc. See LICENSE file for details. """ ListWidgetItems_Command_Mixin.py @author: Ninad @copyright: 2008 Nanorex, Inc. See LICENSE file for details. @version:$Id$ History: 2008-05-27 -2008-05-29 Created and modified. TODO as of 2008-06-01: - Rename this class and others like ListWidgetItems_*_Mixin to a better name - At the moment used only by MakeCrossOvers_* classes, need refactoring of MultipleDnaSegmentResize classes so that they also implement this API OR refactor these classes so that they are wrap the functionality and are used as an object in the classes such as MakeCrossovers_*. - Move this and other related classes to possibly dna.command_support - These classes refer to MultipleDnaSegmentResize classes because this was originally implemented there (see also dna.command_support.DnaSegmentList) @see: MakeCrossovers_Command ListWidgetItems_GraphicsMode_Mixin ListWidgetItems_PM_Mixin """ class ListWidgetItems_Command_Mixin: #A list of all dnasegments that will be scanned for potential #crossover sites. _structList = [] def command_entered(self): """ @see baseCommand.command_entered() for documentation @see MakeCrossovers_Command.command_entered() """ self._structList = [] def itemLimitForSegmentListWidget(self): """ Maximum number of items allowed in the segment list widet.(For performance reasons) """ return 30 def ensureSegmentListItemsWithinLimit(self, segments): """ Subclasses should override this method. """ pass def logMessage(self, type = ''): """ Subclasses should override this """ pass def activateAddSegmentsTool(self, enableFlag = True): """ """ if self.propMgr is None: return False return self.propMgr.activateAddSegmentsTool(enableFlag) def isAddSegmentsToolActive(self): """ Returns True if the Add segments tool in the PM, that allows adding dna segments from the segment list, is active. @see: MultipleDnaSegmentResize_GraphicsMode.chunkLeftUp() @see: MultipleDnaSegmentResize_GraphicsMode.end_selection_from_GLPane() @see: self.isRemoveSegmentsToolActive() @see: self.addSegmentToResizeSegmentList() """ if self.propMgr is None: return False return self.propMgr.isAddSegmentsToolActive() def activateRemoveSegmentsTool(self, enableFlag = True): if self.propMgr is None: return self.propMgr.activateRemoveSegmentsTool(enableFlag) def isRemoveSegmentsToolActive(self): """ Returns True if the Remove Segments tool in the PM, that allows removing dna segments from the segment list, is active. @see: MultipleDnaSegmentResize_GraphicsMode.chunkLeftUp() @see: MultipleDnaSegmentResize_GraphicsMode.end_selection_from_GLPane() @see: self.isAddSegmentsToolActive() @see: self.removeSegmentFromResizeSegmentList() """ if self.propMgr is None: return False return self.propMgr.isRemoveSegmentsToolActive() def addSegmentToSegmentList(self, segment): """ Adds the given segment to the segment list @param segment: The DnaSegment to be added to the segment list. Also does other things such as updating handles etc. @type sement: B{DnaSegment} @see: self.isAddSegmentsToolActive() @TODO: This allows ONLY PAM3 DNA segments to be added to the segment list. NEEDS REVISION """ if segment.is_PAM3_DnaSegment() and segment not in self._structList: self._structList.append(segment) def removeSegmentFromSegmentList(self, segment): """ Removes the given segment from the segment list @param segment: The DnaSegment to be removed from the segment list. Also does other things such as updating handles etc. @type sement: B{DnaSegment} @see: self.isRemoveSegmentsToolActive() """ if segment in self._structList: self._structList.remove(segment) def getSegmentList(self): return self._structList def updateSegmentList(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 setSegmentList(self, structList): """ Replaces the list of segments with the given segmentList. Calls the related method of self.struct. @param structList: New list of segments. @type structList: list @see: DnaSegmentList.setResizeStructList() """ self._structList = structList
NanoCAD-master
cad/src/dna/commands/MakeCrossovers/ListWidgetItems_Command_Mixin.py