rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
"Completes the current operation and enters Select Chunks mode."\
"Completes the current operation and enters the default mode."\
def createWhatsThis(self): # # File Toolbar # # Open File fileOpenText = "<u><b>Open File</b></u> (Ctrl + O)<br> "\ "<p><img source=\"fileopen\"><br> "\ "Opens a new file."\ "</p>" QMimeSourceFactory.defaultFactory().setPixmap( "fileopen", self.fileOpenAction.iconSet().pixmap() ) self.fileOpenAction.setWhatsThi...
"Cancels the current operation and enters Select Chunks mode."\
"Cancels the current operation and enters the default mode."\
def createWhatsThis(self): # # File Toolbar # # Open File fileOpenText = "<u><b>Open File</b></u> (Ctrl + O)<br> "\ "<p><img source=\"fileopen\"><br> "\ "Opens a new file."\ "</p>" QMimeSourceFactory.defaultFactory().setPixmap( "fileopen", self.fileOpenAction.iconSet().pixmap() ) self.fileOpenAction.setWhatsThi...
NanotubeGeneratorDialog.__init__(self)
NanotubeGeneratorDialog.__init__(self, win)
def __init__(self, win): NanotubeGeneratorDialog.__init__(self) self.win = win self.mol = molecule(win.assy, chem.gensym("Nanotube.")) # Validator for the length linedit widget. self.validator = QDoubleValidator(self) self.validator.setRange(0.0, 1000.0, 2) # Range of nanotube length (0-100, 2 decimal places) self.len...
if basepos and (basepos is not self.curpos):
if basepos != None and (basepos is not self.curpos):
def setatomposn(self, ind, pos, element): #bruce 041108-10 """(private method for our atoms to call:) Set position in self, of the atom with index ind, to pos. Invalidate or incrementally update whatever is required in this molecule (but not bonds or jigs, invalled by the atom); presently [041110] we incrementally upda...
if basepos:
if basepos != None:
def setatomposn(self, ind, pos, element): #bruce 041108-10 """(private method for our atoms to call:) Set position in self, of the atom with index ind, to pos. Invalidate or incrementally update whatever is required in this molecule (but not bonds or jigs, invalled by the atom); presently [041110] we incrementally upda...
if not self.selatoms:
if atomlist is None and not self.selatoms:
def selectConnected(self, atomlist=None): """Select any atom that can be reached from any currently selected atom through a sequence of bonds. If <atomlist> is supplied, use it instead of the currently selected atoms. """ ###@@@ should make sure we don't traverse interspace bonds, until all bugs creating them are fixed...
if not atomlist:
if atomlist is None:
def selectConnected(self, atomlist=None): """Select any atom that can be reached from any currently selected atom through a sequence of bonds. If <atomlist> is supplied, use it instead of the currently selected atoms. """ ###@@@ should make sure we don't traverse interspace bonds, until all bugs creating them are fixed...
from platform import fix_plurals info = fix_plurals( "%d connected atom(s) selected." % totalSelected) env.history.message( cmd + info)
newAtomsSelected = totalSelected - alreadySelected
def selectConnected(self, atomlist=None): """Select any atom that can be reached from any currently selected atom through a sequence of bonds. If <atomlist> is supplied, use it instead of the currently selected atoms. """ ###@@@ should make sure we don't traverse interspace bonds, until all bugs creating them are fixed...
if totalSelected > alreadySelected:
if newAtomsSelected > 0: from platform import fix_plurals info = fix_plurals( "%d connected atom(s) selected." % newAtomsSelected) env.history.message( cmd + info)
def selectConnected(self, atomlist=None): """Select any atom that can be reached from any currently selected atom through a sequence of bonds. If <atomlist> is supplied, use it instead of the currently selected atoms. """ ###@@@ should make sure we don't traverse interspace bonds, until all bugs creating them are fixed...
if os.path.exists(program):
if os.path.exists(program) or os.path.exists(program + '.exe'):
def minimize(self): #bruce 041215 fixed some bugs and changed some error messages # in the case when the simulator executable is not found. # Bugs included uncaught exception (rather than error message) # which could also fail to restore the current working directory. from debug import print_compact_traceback ## bruce ...
s = "simulator not found at %r; installation error?" % program
s = "simulator not found at \"%s\"; installation error?" % program
def minimize(self): #bruce 041215 fixed some bugs and changed some error messages # in the case when the simulator executable is not found. # Bugs included uncaught exception (rather than error message) # which could also fail to restore the current working directory. from debug import print_compact_traceback ## bruce ...
print "note: spawnv args were %r" % (args,) print " in the temporary working directory %r" % (tmpFilePath,)
print "note: spawnv args were %r" % (args,) print " in the temporary working directory \"%s\"" % (tmpFilePath,)
def minimize(self): #bruce 041215 fixed some bugs and changed some error messages # in the case when the simulator executable is not found. # Bugs included uncaught exception (rather than error message) # which could also fail to restore the current working directory. from debug import print_compact_traceback ## bruce ...
elif fn[-3:] in ["pdb","PDB"]: try: insertpdb(self.assy, fn) except: print_compact_traceback( "MWsemantics.py: fileInsert(): error inserting PDB file [%s]: " % fn ) env.history.message( redmsg( "Internal error while inserting PDB file: [ " + fn + " ]") ) else: self.assy.changed() env.history.message( cmd + "PDB file in...
def fileImport(self): # Code copied from fileInsert() slot method. Mark 060731. """Slot method for 'File > Import'. """ cmd = greenmsg("Import File: ") # This format list generated from the Open Babel wiki page: # http://openbabel.sourceforge.net/wiki/Babel#File_Formats formats = \ "All Files (*.*);;"\ "Molecular Mach...
"Animation Master (*.mdl);;"\
def fileExport(self): # Code copied from fileInsert() slot method. Mark 060731. """Slot method for 'File > Export'. """ cmd = greenmsg("Export File: ") # This format list generated from the Open Babel wiki page: # http://openbabel.sourceforge.net/wiki/Babel#File_Formats
elif ext == ".pdb": try: writepdb(self.assy.part, fn) except: print_compact_traceback( "MWsemantics.py: saveFile(): error writing file %r: " % fn ) env.history.message(redmsg( "Problem saving PDB file: [ " + fn + " ]" )) else: self.saved_main_file(fn, fil) env.history.message( "PDB file saved: [ " + os.path.normpath(...
def fileExport(self): # Code copied from fileInsert() slot method. Mark 060731. """Slot method for 'File > Export'. """ cmd = greenmsg("Export File: ") # This format list generated from the Open Babel wiki page: # http://openbabel.sourceforge.net/wiki/Babel#File_Formats
return proc.exitStatus() != 0 and text[0] != "1 molecule converted\n"
return proc.exitStatus() == 0 and text[0] == "1 molecule converted\n"
def blaberr(text=text): text[0] = str(proc.readStderr())
"POV-Ray (*.pov);;"
"POV-Ray (*.pov);;"\ "Animation Master Model (*.mdl);;"
def fileSaveAs_filename(self, images_ok = True): #bruce 050927 split this out of fileSaveAs, added some comments, added images_ok option """Ask user to choose a save-as filename (and file type) based on the current main filename. If file exists, ask them if they want to overwrite that file. If user cancels either dialo...
and that's done so that MmpFiles are easier to clone.
and that's done so that an entry in MmpFile.lines can be a pointer into the MmpFile.atoms list. When a file is cloned, we clone the atoms but keep the same lines.
def str(self): return self._str
other.lines = self.lines[:] other.atoms = [ ]
for x in self.lines: other.lines.append(x.clone(other))
def clone(self): other = MmpFile() other.lines = self.lines[:] other.atoms = [ ] for a in self.atoms: other.atoms.append(a.clone()) return other
QObject.__init__(self, nam)
QObject.__init__(self)
def __init__(self, assembly, nam=None): QObject.__init__(self, nam) self.assy = assembly # name doesn't get used yet, except as a comment # in mmp file output, but could be used to name # separate molecule files if nam: self.name = nam else: self.name = gensym("Part") # atoms in a dictionary, indexed by atom.key self.a...
numol = molecule(self.assy, newname)
numol = molecule(self.assy, "fakename") self.copy_copyable_attrs_to(numol) numol.name = newname
def copy(self, dad=None, offset=V(0,0,0), cauterize = 1): """Public method: Copy the molecule to a new molecule. Offset tells where it will go relative to the original. Unless cauterize = 0, replace bonds out of the molecule with singlets in the copy [though that's not very nice when we're copying a group of mols all a...
self.DepositAtomCursor = QCursor(
import platform if not platform.is_macintosh(): self.DepositAtomCursor = QCursor(
def loadCursors(self):
else: self.DepositAtomCursor = QCursor( QBitmap(filePath + "/../images/DepositAtomCursor.bmp").xForm(QWMatrix(1,0,0,-1, 0,0)), QBitmap(filePath + "/../images/DepositAtomCursor-bm.bmp").xForm(QWMatrix(1,0,0,-1, 0,0)), 0, 0)
def loadCursors(self):
print "MMKit.tabpageChanged: pasteP=False"
def tabpageChanged(self, wg): '''Slot method. Called when user clicked to change the tab page''' pageId = self.tabWidget2.indexOf(wg) if pageId == 1: ## Clipboard page self.w.pasteP = True self.w.depositAtomDashboard.pasteRB.setOn(True) self.elemGLPane.setDisplay(self.displayMode) self._clipboardPageView() else: ## E...
p1 = self.find_singlet(unit1,i1).posn() p2 = self.find_singlet(unit2,i2).posn()
s1 = self.find_singlet(unit1,i1) s2 = self.find_singlet(unit2,i2) p1 = s1.posn() p2 = s2.posn()
def draw_bond_lines(self, unit1, unit2): #bruce 050203 experiment ####@@@@ PROBABLY NEEDS OPTIMIZATION "draw white lines showing the bonds we presently propose to make between the given adjacent units" # works now, but probably needs optim or memo of find_singlets before commit -- # just store a mark->singlet table in ...
('Node', 'Utility'),
('Chunk', 'chunk'), ('Group', 'Utility'),
def _debug_print_object_counts(self): #bruce 060327 for debugging memory leaks: report Atom & Bond refcounts, and objs that might refer to them from HistoryWidget import _graymsg msglater = "" # things to print all in one line for clasname, modulename in ( ('Atom', 'chem'), ('Bond', 'bonds'), ('Node', 'Utility'), ('Par...
filesize = assy.m.totalFrames * ((natoms * 32) + 25)
filesize = assy.m.totalFrames * ((natoms * 28) + 25)
def writemovie(assy, mflag = False): """Creates a moviefile. The name of the moviefile it creates is found in assy.m.filename. The moviefile is either a DPB file or an XYZ trajectory file. DPB = Differential Position Bytes (binary file) XYZ = XYZ trajectory file (text file) mflag: 0 = default, runs a full simulation ...
colorgroup = listview.palette().active() hicolor = QColor (colorgroup.highlight ())
if sys.platform == 'darwin': hicolor = Qt.white textcolor = Qt.black else: colorgroup = listview.palette().active() hicolor = QColor (colorgroup.highlight()) textcolor = QColor (colorgroup.highlightedText())
def get_pixmap_for_dragging_nodes(self, drag_type, nodes): ####@@@@ call this from advise_starting_drag_and_get_dragobj (not from handler ) #e [also put the drag-text-making code in another method near here? or even the dragobj maker? # or even the decision of what to do when the motion is large enough (ie let drag_ha...
textcolor = QColor (colorgroup.highlightedText ())
def get_pixmap_for_dragging_nodes(self, drag_type, nodes): ####@@@@ call this from advise_starting_drag_and_get_dragobj (not from handler ) #e [also put the drag-text-making code in another method near here? or even the dragobj maker? # or even the decision of what to do when the motion is large enough (ie let drag_ha...
w,h = 160,24
item = self.nodeItem(nodes[0]) h = item.height() w = self.get_drag_pixmap_width(nodes)
def paint_nodes(self, p, drag_type, nodes): "paint a dragobject picture of these nodes into the QPainter p; if you give up, raise an exception; return w,h used??" nn = len(nodes) if not nn: print nodes,"no nodes??" # when i try to drag the clipboard?? because unselected. # need to filter it somehow... should be done no...
p.drawText(26,4,w,h,flags,text)
p.drawText(4,4,w,h,flags,text)
def paint_nodes(self, p, drag_type, nodes): "paint a dragobject picture of these nodes into the QPainter p; if you give up, raise an exception; return w,h used??" nn = len(nodes) if not nn: print nodes,"no nodes??" # when i try to drag the clipboard?? because unselected. # need to filter it somehow... should be done no...
painterTemp = QPainter(self, True) fontmetrics = painterTemp.fontMetrics() w = 115 for node in nodes: item = self.nodeItem(node) cw = item.width(fontmetrics, self, 0) if cw > w: w = cw painterTemp.end() return min(164, w + 4)
pt = QPainter(self, True) try: fontmetrics = pt.fontMetrics() w = pt.fontMetrics().width("Moving 99 items") maxw = w * 1.5 for node in nodes: item = self.nodeItem(node) cw = item.width(fontmetrics, self, 0) if cw > w: w = cw pt.end() except: w = 160 print "Exception in get_drag_pixmap_width: w = ", w return min(maxw, ...
def get_drag_pixmap_width(self, nodes): painterTemp = QPainter(self, True) fontmetrics = painterTemp.fontMetrics() w = 115 for node in nodes: item = self.nodeItem(node) cw = item.width(fontmetrics, self, 0) if cw > w: w = cw painterTemp.end() return min(164, w + 4)
if sys.platform == 'darwin': if key == 4099: if _debug_keys: print "fyi: mac bugfix: remapping key %d (actual delete key) to key %d (Qt.Key_Delete)" % (key, Qt.Key_Delete) key = Qt.Key_Delete
from platform import filter_key key = filter_key(key, debug_keys = _debug_keys)
def keyPress(self,key): # bruce 040923: fyi: overridden in depositMode if _debug_keys: print "fyi: basicMode.keyPress(%r)" % (key,) if sys.platform == 'darwin': ###bruce 040924 temp fix, should be revised once we understand relation to other systems (see my email to josh & ninad): if key == 4099: if _debug_keys: print ...
elif self.selmols: dstElm = PeriodicTable.getElement(elem)
if self.selmols: dstElem = PeriodicTable.getElement(elem)
def modifyTransmute(self, elem, force = False, atomType=None): ''' This method was originally a method of class mode and selectMode. Transmute selected atoms into <elem> and with an optional <atomType>. <elem> is an element number that selected atoms will be transmuted to. <force>: boolean variable meaning keeping exis...
self._clipboardPageView()
if self.currentPageOpen(ClipboardPage): self._clipboardPageView() else: self.update_clipboard_page_icon() return
def update_clipboard_items(self): '''Updates the items in the clipboard's listview. ''' self._clipboardPageView()
if sys.platform == 'darwin':
if not self.icon_tabs:
def update_clipboard_page_icon(self): '''Updates the Clipboard page (tab) icon with a full or empty clipboard icon. ''' if sys.platform == 'darwin': # Work around for bug 1659. mark 060310 return if self.w.assy.shelf.get_pastable_chunks(): clipboard_pm = imagename_to_pixmap("clipboard-full.png") else: clipboard_pm = i...
self.prefs_tab.setCurrentPage(0)
self._init_prefs() self.prefs_tab.setCurrentPage(0)
def showDialog(self): '''Display the Preferences dialog''' # This sends a signal to self.setup_current_page(), which will call self._setup_general_page() self.prefs_tab.setCurrentPage(0) self.exec_loop()
prefs = preferences.prefs_context() self.gmspath = prefs.get(gmspath_prefs_key, '') self.gamess_path_linedit.setText(self.gmspath)
self.gamess_path_linedit.setText(self.gmspath)
def _setup_general_page(self): ''' Setup widgets to initial (default or defined) values on the general page. '''
prefs = preferences.prefs_context() self.default_display_btngrp.setButton(prefs.get(defaultDisplayMode_prefs_key, diVDW))
self.default_display_btngrp.setButton(self.default_display_mode)
def _setup_atoms_page(self): ''' Setup widgets to initial (default or defined) values on the display page. ''' # Set colors for atom color swatches self.atom_hilite_color_frame.setPaletteBackgroundColor(RGBf_to_QColor(orange)) self.free_valence_color_frame.setPaletteBackgroundColor(RGBf_to_QColor(red)) # Bug 799 fix. ...
defaultDisplayMode_prefs_key: self.glpane.display,
defaultDisplayMode_prefs_key: self.default_display_mode,
def _update_prefs(self): '''Update user preferences and store them in the shelf. This method has two parts: 1. Update the preference variables stored in various objects (i.e. win, assy, history, etc.) 2. Save the prefences to the shelf. ''' # Do this just in case the user typed in the GAMESS executable path by hand. #...
numol.set_hotspot( hotspot, permit_invalid = True)
self.set_hotspot( hotspot, permit_invalid = True)
def _preserve_implicit_hotspot( self, hotspot): #bruce 050524 #e could also take base-atom arg to use as last resort if len(self.singlets) > 1 and self.hotspot is None: numol.set_hotspot( hotspot, permit_invalid = True) # this checks everything before setting it; if invalid, silent noop
seq = str(self.base_textedit.text()).upper()
seq = self.get_sequence()
def build_dna(self): 'Slot for the OK button' seq = str(self.base_textedit.text()).upper() dnatype = str(self.dna_type_combox.currentText()) double = str(self.endings_combox.currentText()) params = (seq, dnatype, double) if self.previousParams != params: self.remove_dna() self.previousParams = params if self.mol == Non...
def complement_btn_clicked(self):
def get_sequence(self, reverse=False, complement=False, cdict={'C':'G', 'G':'C', 'A':'T', 'T':'A'}):
def complement_btn_clicked(self): seq = '' for ch in str(self.base_textedit.text()).upper(): if ch == 'G': seq += 'C' elif ch == 'C': seq += 'G' elif ch == 'A': seq += 'T' elif ch == 'T': seq += 'A' else: env.history.message(redmsg('Bogus DNA sequence: ' + ch)) return self.base_textedit.setText(seq)
if ch == 'G': seq += 'C' elif ch == 'C': seq += 'G' elif ch == 'A': seq += 'T' elif ch == 'T': seq += 'A'
if ch in 'CGAT': if complement: ch = cdict[ch] seq += ch elif ch in '\ \t\r\n': pass
def complement_btn_clicked(self): seq = '' for ch in str(self.base_textedit.text()).upper(): if ch == 'G': seq += 'C' elif ch == 'C': seq += 'G' elif ch == 'A': seq += 'T' elif ch == 'T': seq += 'A' else: env.history.message(redmsg('Bogus DNA sequence: ' + ch)) return self.base_textedit.setText(seq)
env.history.message(redmsg('Bogus DNA sequence: ' + ch)) return
env.history.message(redmsg('Bogus DNA base: ' + ch + ' (should be C, G, A, or T)')) return '' if reverse: seq = list(seq) seq.reverse() seq = ''.join(seq) return seq def complement_btn_clicked(self): seq = self.get_sequence(complement=True)
def complement_btn_clicked(self): seq = '' for ch in str(self.base_textedit.text()).upper(): if ch == 'G': seq += 'C' elif ch == 'C': seq += 'G' elif ch == 'A': seq += 'T' elif ch == 'T': seq += 'A' else: env.history.message(redmsg('Bogus DNA sequence: ' + ch)) return self.base_textedit.setText(seq)
seq = '' for ch in str(self.base_textedit.text()).upper(): if ch not in 'CGAT': env.history.message(redmsg('Bogus DNA sequence: ' + ch)) return else: seq = ch + seq
seq = self.get_sequence(reverse=True)
def reverse_btn_clicked(self): seq = '' for ch in str(self.base_textedit.text()).upper(): if ch not in 'CGAT': env.history.message(redmsg('Bogus DNA sequence: ' + ch)) return else: seq = ch + seq self.base_textedit.setText(seq)
QDialog.accept(self)
self.cancel_btn_clicked()
def close(self, e=None): """When the user closes dialog by clicking the 'X' button on the dialog title bar, this method is called. """ try: QDialog.accept(self) return True except: return False
for key, val in dict1:
for key, val in dict1.items():
def update(self, dict1): #bruce 050117 # note: unlike repeated setitem, this only opens and closes once. if _shelf: for key, val in dict1: #e (on one KeyError, should we store the rest?) #e (better, should we check all keys before storing anything?) self[key] = val #e could optimize, but at least this leaves it open el...
assy.addmol(mol) mol.moveto(curgrp) mol = None
mol = _addMolecule(mol, assy, curgrp)
def _readmmp(assy, filnam, isInsert = False): """The routine to actually reading a mmp file and save data into data structure """ #bruce 041011: added 'U' to file mode, for universal newline support. l=open(filnam,"rU").readlines() if not isInsert: assy.filename=filnam mol = None ndix={} assy.alist = [] #assy.tree = Gr...
assy.addmol(mol) mol.moveto(opengroup) mol = None
mol = _addMolecule(mol, assy, opengroup)
def _readmmp(assy, filnam, isInsert = False): """The routine to actually reading a mmp file and save data into data structure """ #bruce 041011: added 'U' to file mode, for universal newline support. l=open(filnam,"rU").readlines() if not isInsert: assy.filename=filnam mol = None ndix={} assy.alist = [] #assy.tree = Gr...
elif key == "shaft": list = map(int, re.findall("\d+",card[6:])) list = map((lambda n: ndix[n]), list) prevmotor.setShaft(list)
def _readmmp(assy, filnam, isInsert = False): """The routine to actually reading a mmp file and save data into data structure """ #bruce 041011: added 'U' to file mode, for universal newline support. l=open(filnam,"rU").readlines() if not isInsert: assy.filename=filnam mol = None ndix={} assy.alist = [] #assy.tree = Gr...
if mol: assy.addmol(mol) mol.moveto(opengroup) mol = None
def _readmmp(assy, filnam, isInsert = False): """The routine to actually reading a mmp file and save data into data structure """ #bruce 041011: added 'U' to file mode, for universal newline support. l=open(filnam,"rU").readlines() if not isInsert: assy.filename=filnam mol = None ndix={} assy.alist = [] #assy.tree = Gr...
self.win.assy.root.dumptree()
def dropEvent(self, event): pnt = event.pos() - QPoint(0,24) item = self.itemAt(self.contentsToViewport(pnt)) if item: #print "Moving", self.selectedItem, "to", item.object self.selectedItem.moveto(item.object) self.update() self.win.assy.root.dumptree()
(self.stiffness, self.force,
(self.force, self.stiffness,
def mmp_record_jigspecific_midpart(self): cxyz = self.posn() * 1000 axyz = self.axen() * 1000 dataline = "%.2f %.2f (%d, %d, %d) (%d, %d, %d) %.2f %.2f %.2f" % \ (self.stiffness, self.force, int(cxyz[0]), int(cxyz[1]), int(cxyz[2]), int(axyz[0]), int(axyz[1]), int(axyz[2]), self.length, self.width, self.sradius ) re...
now = time.time() simtime = now - self.__last_3dupdate_time pytime = self.__last_pytime nframes = self.__frame_number - self.__last_3dupdate_frame update_3dview = self.sim_frame_callback_update_check( simtime, pytime, nframes ) if last_frame or debug_all_frames: update_3dview = True if update_3dview: if debug_pyrex_p...
try: now = time.time() simtime = now - self.__last_3dupdate_time pytime = self.__last_pytime nframes = self.__frame_number - self.__last_3dupdate_frame update_3dview = self.sim_frame_callback_update_check( simtime, pytime, nframes ) if last_frame or debug_all_frames: update_3dview = True if update_3dview: if debu...
def sim_frame_callback(self, last_frame): #bruce 060102 "Per-frame callback function for simulator object." # Note: this was called 3550 times for minimizing a small C3 sp3 hydrocarbon... better check the elapsed time quickly. #e Maybe we should make this into a lambda, or even code it in C, to optimize it. if self.PRE...
print 'ok',self.gather_parameters()
if env.debug(): print 'ok' self.gather_parameters()
def ok_btn_clicked(self): 'Slot for OK button.' QDialog.accept(self) print 'ok',self.gather_parameters()### kluge: has side effect on env.prefs (should we pass them?) if platform.atom_debug: print "debug: reloading runSim on each use, for development" import runSim, debug debug.reload_once_per_event(runSim) from runSim...
print 'cancel'
return
def cancel_btn_clicked(self): 'Slot for Cancel button.' QDialog.reject(self) #### should this gather_parameters or restore_defaults? print 'cancel'###
for key,val in zip((endRMS_prefs_key, endMax_prefs_key, cutoverRMS_prefs_key, cutoverMax_prefs_key), self.previousParams): env.prefs[key] = val
env.prefs.restore_defaults([endRMS_prefs_key, endMax_prefs_key, cutoverRMS_prefs_key, cutoverMax_prefs_key])
def restore_defaults_btn_clicked(self): 'Slot for Restore Defaults button.' # p1, p2, p3, ... pn = self.previousParams for key,val in zip((endRMS_prefs_key, endMax_prefs_key, cutoverRMS_prefs_key, cutoverMax_prefs_key), self.previousParams): env.prefs[key] = val self.update_widgets(update_seltype = False)
if b.other(a).key in ndix: numol.bond(na,ndix[b.other(a).key])
a2key = b.other(a).key if a2key in ndix: if a.key < a2key: bond_copied_atoms(na, ndix[a2key], b)
def copy(self, dad=None, offset=V(0,0,0), cauterize = 1): """Public method: Copy the molecule to a new molecule. Offset tells where it will go relative to the original. Unless cauterize = 0, replace bonds out of the molecule with singlets in the copy [though that's not very nice when we're copying a group of mols all a...
numol.bond(na, x)
bond_copied_atoms( na, x, b)
def copy(self, dad=None, offset=V(0,0,0), cauterize = 1): """Public method: Copy the molecule to a new molecule. Offset tells where it will go relative to the original. Unless cauterize = 0, replace bonds out of the molecule with singlets in the copy [though that's not very nice when we're copying a group of mols all a...
def setup_current_page(self, pagename):
def setup_current_page(self, pagename): if pagename != 'General': self._setup_general_page()
def setup_current_page(self, pagename): if pagename == 'General': self._setup_general_page() elif pagename == 'Atoms': self._setup_atoms_page() elif pagename == 'Bonds': self._setup_bonds_page() elif pagename == 'Background': self._setup_background_page() elif pagename == 'History': self._setup_history_page() elif page...
self.mt.setGeometry(0,0,mmk_geometry.width(),560)
self.mt.setGeometry(0,0,200,560)
def _findGoodLocation(self, firstShow): '''Find ideal location for the MMKit. Should only be called after history, and MMKit has been created.''' global MMKitWin if sys.platform == 'linux2': #hist_height = 70 # not needed with new layout. mark 060222. mmk_height = 559 toolbar_height = 25 status_bar_height = 29 else: h...
MMKitWin.dirView.setMinimumSize(QSize(191,150))
MMKitWin.dirView.setMinimumSize(QSize(175,150))
def modifyMMKit(self): '''Open The Molecular Modeling Kit for Build (DEPOSIT) mode. ''' # This should probably be moved elsewhere global MMKitWin if MMKitWin and MMKitWin.isShown(): return MMKitWin
def destroy(self): "forget everything, let all storage be reclaimed; only valid if we have no nodes left"
def destroy(self): "forget enough to prevent memory leaks; only valid if we have no nodes left"
def destroy(self): "forget everything, let all storage be reclaimed; only valid if we have no nodes left" # implem is a guess if debug_parts: print "debug_parts: fyi: destroying part", self assert self.nodecount == 0, "can't destroy a Part which still has nodes" # esp. since it doesn't have a list of them! # actually i...
for attr in self.__dict__.keys(): if not attr.startswith('_'): if 0 and platform.atom_debug: print "atom_debug: destroying part - deleting i mean resetting attr:",attr setattr(self, attr, None)
if "be conservative for now, though memory leaks might result": return
def destroy(self): "forget everything, let all storage be reclaimed; only valid if we have no nodes left" # implem is a guess if debug_parts: print "debug_parts: fyi: destroying part", self assert self.nodecount == 0, "can't destroy a Part which still has nodes" # esp. since it doesn't have a list of them! # actually i...
for mol in self.o.assy.selmols: mol.invalidate_everything()
def invalidate_selection(self): #bruce 041115 (debugging method) "[debugging method] invalidate all aspects of selected atoms or mols" for atm in self.o.assy.selatoms.values(): atm.invalidate_everything() for mol in self.o.assy.selmols: mol.invalidate_everything()
if os.path.exists(rc):
try:
def fileSetWorkDir(self): """ Sets working directory (need dialogue window) """ # Windows Users: .atomrc must be placed in C:\Documents and Settings\[username]\.atomrc # .atomrc contains one line, the Working Directory # Example: C:\Documents and Settings\Mark\My Documents\MMP Parts # Mark [2004-10-13] wd = globalParms...
assert self.kluge_attr2metainfo[attr] == attr_metainfo, "%r == %r fails for %r (2nd class is %s, 1st clas incls %r)" % \ (self.kluge_attr2metainfo[attr], attr_metainfo, attr, class1.__name__, self.kluge_attr2metainfo_from_class[attr])
if self.kluge_attr2metainfo[attr] != attr_metainfo: if self.kluge_attr2metainfo[attr][1] != attr_metainfo[1]: msg = "undo-debug note: attr %r defaultval differs in %s and %s; ok for now but mention in bug 1586 comment" % \ (attr, class1.__name__, self.kluge_attr2metainfo_from_class[attr].class1.__name__) print msg fro...
def classify_instance(self, obj): """Obj is known to be of types.InstanceType. Classify it (memoizing classifications per class when possible). It might be a StateHolder, Data object, or neither. """ class1 = obj.__class__ try: # easy case: we know that __class__ (and it doesn't need to be redone per-object, which anyw...
eleStr = "\nSinglets: " + str(nsinglets) + "\n"
eleStr = "\nOpen Bonds: " + str(nsinglets) + "\n"
def __init__(self, mol): MoleculePropDialog.__init__(self) self.mol = mol self.nameLineEdit.setText(mol.name) self.applyPushButton.setEnabled(False) self.mol.originalColor = self.mol.color # Save original molecule color in case of cancel
a.setDisplay(diDEFAULT)
if a.display == diINVISIBLE: a.setDisplay(diDEFAULT)
def makeAtomsVisible(self): for a in self.mol.atoms.itervalues(): a.setDisplay(diDEFAULT) self.mol.glpane.gl_update()
if platform.atom_debug: linenum() print 'fn', repr(str(fn))
def fileExport(self): # Code copied from fileInsert() slot method. Mark 060731. """Slot method for 'File > Export'. """ cmd = greenmsg("Export File: ") # This format list generated from the Open Babel wiki page: # http://openbabel.sourceforge.net/wiki/Babel#File_Formats
env.history.message(cmd + "Cancelled") return if fn: fn = str(fn) dir, fil, ext = fileparse(fn) if ext == ".mmp": self.save_mmp_file(fn, brag=True)
env.history.message(cmd + "Cancelled") if platform.atom_debug: linenum() print 'fileExport cancelled because fn is no good' return fn = str(fn) dir, fil, ext = fileparse(fn) if ext == ".mmp": self.save_mmp_file(fn, brag=True) else:
def fileExport(self): # Code copied from fileInsert() slot method. Mark 060731. """Slot method for 'File > Export'. """ cmd = greenmsg("Export File: ") # This format list generated from the Open Babel wiki page: # http://openbabel.sourceforge.net/wiki/Babel#File_Formats
import time from qt import QStringList, QProcess dir, fil, ext = fileparse(fn) if platform.atom_debug: linenum() print 'dir, fil, ext', repr(dir), repr(fil), repr(ext) tmpdir = platform.find_or_make_Nanorex_subdir('temp') mmpfile = os.path.join(tmpdir, fil + ".mmp") if platform.atom_debug: linenum() print 'tmpdir, mmpf...
def fileExport(self): # Code copied from fileInsert() slot method. Mark 060731. """Slot method for 'File > Export'. """ cmd = greenmsg("Export File: ") # This format list generated from the Open Babel wiki page: # http://openbabel.sourceforge.net/wiki/Babel#File_Formats
import time from qt import QStringList, QProcess dir, fil, ext = fileparse(fn) tmpdir = platform.find_or_make_Nanorex_subdir('temp') mmpfile = os.path.join(tmpdir, fil + ".mmp") self.saveFile(mmpfile, brag=False) result = self.runBabel(mmpfile, fn) if result and os.path.exists(fn): env.history.message( "File exported: ...
if platform.atom_debug: linenum() print 'file translation failed' print 'Problem:', mmpfile, '->', fn env.history.message(redmsg("File translation failed.")) self.glpane.scale = self.assy.bbox.scale() self.glpane.gl_update() self.mt.mt_update() dir, fil = os.path.split(fn) if platform.atom_debug: linenum() print 'fi...
def fileExport(self): # Code copied from fileInsert() slot method. Mark 060731. """Slot method for 'File > Export'. """ cmd = greenmsg("Export File: ") # This format list generated from the Open Babel wiki page: # http://openbabel.sourceforge.net/wiki/Babel#File_Formats
return proc.exitStatus() == 0 and text[0] == "1 molecule converted\n"
exitStatus = proc.exitStatus() stderr = text[0] if platform.atom_debug: print 'exit status', exitStatus print 'stderr says', repr(stderr) print 'finish runBabel(%s, %s)' % (repr(infile), repr(outfile)) return exitStatus == 0 and stderr == "1 molecule converted\n"
def blaberr(text=text): text[0] = str(proc.readStderr())
import webbrowser
def open_wiki_help_URL(url, whosdoingthis = "Wiki help"): #bruce 051229 split this out of open_wiki_help_page (which is misnamed) """Try to open the given url in the user's browser (unless they've set preferences to prevent this (NIM)), first emitting a history message containing the url (which is described as coming f...
import webbrowser
def data(self, name, context=None): # [obs comment:] You'll always get a warning like this: # QTextBrowser: no mimesource for http://.... # This could be avoided with QApplication.qInstallMsgHandler, # but I don't think that's supported until PyQt 3.15. Also this falls # victim to all the problems swarming around webbr...
self.moviePlayerDashboard.setGeometry(QRect(0,19,1034,29))
self.moviePlayerDashboard.setGeometry(QRect(0,19,1036,29))
def __init__(self,parent = None,name = None,fl = 0): QMainWindow.__init__(self,parent,name,fl) self.statusBar()
self.resize(QSize(1115,1243).expandedTo(self.minimumSizeHint()))
self.resize(QSize(1115,1246).expandedTo(self.minimumSizeHint()))
def __init__(self,parent = None,name = None,fl = 0): QMainWindow.__init__(self,parent,name,fl) self.statusBar()
self.setViewOppositeAction.setMenuText(self.__tr("&Opposite"))
self.setViewOppositeAction.setMenuText(self.__tr("Opposite"))
def languageChange(self): self.setCaption(self.__tr("nanoENGINEER-1")) self.fileOpenAction.setText(self.__tr("Open")) self.fileOpenAction.setMenuText(self.__tr("&Open...")) self.fileOpenAction.setAccel(self.__tr("Ctrl+O")) self.fileSaveAction.setText(self.__tr("Save")) self.fileSaveAction.setMenuText(self.__tr("&Save")...
def changeCCGridColor(self): print "MainWindow.changeCCGridColor(): Not implemented yet"
def setViewOpposite(self): print "MainWindow.setViewOpposite(): Not implemented yet"
def changeCCGridColor(self): print "MainWindow.changeCCGridColor(): Not implemented yet"
assert not hasattr(self, attr), "obsolete menu attr should not be defined: %r.%s" % (self, attr)
assert not hasattr(self, attr), \ "obsolete menu attr should not be defined: %r.%s" % (self, attr)
def setup_menus(self): # rewritten by bruce 041103 mod_attrs = ['Menu_spec_shift', 'Menu_spec_control'] all_attrs = ['Menu_spec'] + mod_attrs + ['debug_Menu_spec'] for attr in all_attrs + ['Menu1','Menu2','Menu3']: if hasattr(self, attr): # probably never happens del self.__dict__[attr] self.makeMenus() # bruce 040923 ...
assert hasattr(self, 'Menu_spec'), "%r.makeMenus() failed to set up self.Menu_spec (to be a menu spec list)" % self
assert hasattr(self, 'Menu_spec'), "%r.makeMenus() failed to set up" \ " self.Menu_spec (to be a menu spec list)" % self
def setup_menus(self): # rewritten by bruce 041103 mod_attrs = ['Menu_spec_shift', 'Menu_spec_control'] all_attrs = ['Menu_spec'] + mod_attrs + ['debug_Menu_spec'] for attr in all_attrs + ['Menu1','Menu2','Menu3']: if hasattr(self, attr): # probably never happens del self.__dict__[attr] self.makeMenus() # bruce 040923 ...
self.Menu1.popup(event.globalPos(),3)
self.Menu1.exec_loop(event.globalPos(),3)
def rightDown(self, event): self.Menu1.popup(event.globalPos(),3)
print "End of tree found"
def _readmmp(assy, filnam, isInsert = False): """The routine to actually reading a mmp file and save data into data structure""" #bruce 041011: added 'U' to file mode, for universal newline support. l=open(filnam,"rU").readlines() if not isInsert: assy.filename=filnam mol = None ndix={} assy.alist = [] AddAtoms = True ...
if self.sellist: self.pickdraw()
def Draw(self): # bruce comment 040922: code is almost identical with selectMode.Draw basicMode.Draw(self) # self.griddraw() if self.sellist: self.pickdraw() if self.o.assy: self.o.assy.draw(self.o)
msg = redmsg("The simulator dynamic library [sim.so on Mac or Linux, in " + self.dylib_path +
msg = redmsg("The simulator dynamic library [sim.so or sim.dll, in " + self.dylib_path +
def set_options_errQ(self): #e maybe split further into several setup methods? #bruce 051115 removed unused 'options' arg """Set movie alist (from simaspect or entire part); debug-msg if it was already set (and always ignore old value). Figure out and set filenames, including sim executable path. All inputs and outputs...
oldposns = map(lambda a: a.posn(), self.part.alist)
def sim_loop_using_dylib(self): #bruce 051231; compare to sim_loop_using_standalone_executable # 051231 6:29pm: works, except no trace file is written so results in history come from prior one (if any) """#doc """ movie = self._movie simopts = self._simopts simobj = self._simobj try: self.remove_old_moviefile(movie.fi...
env.history.message(orangemsg("temp hack for bug 1265: move atoms back to earlier positions")) movie.moveAtoms(oldposns)
def sim_loop_using_dylib(self): #bruce 051231; compare to sim_loop_using_standalone_executable # 051231 6:29pm: works, except no trace file is written so results in history come from prior one (if any) """#doc """ movie = self._movie simopts = self._simopts simobj = self._simobj try: self.remove_old_moviefile(movie.fi...
drawPlane(self.color, self.width, self.height)
hw = self.width/2.0; hh = self.height/2.0 corners_pos = [V(-hw, hh, 0.0), V(-hw, -hh, 0.0), V(hw, -hh, 0.0), V(hw, hh, 0.0)] drawLineLoop(self.color, corners_pos)
def _draw(self, win, dispdef): glPushMatrix()
self.need_process_events = True
def sim_frame_callback(self): #bruce 060102 "Per-frame callback function for simulator object." # Note: this was called 3550 times for minimizing a small C3 sp3 hydrocarbon... better check the elapsed time quickly. #e Maybe we should make this into a lambda, or even code it in C, to optimize it. if self.PREPARE_TO_CLOS...
(due to not enough time passing).
(due to not enough time passing), EXCEPT for Qt-related progress updates other than gl_update -- caller must do those separately in sim_frame_callback_updates, if this method sets self.need_process_events.
def sim_frame_callback_worker(self, frame_number): #bruce 060102 """Do whatever should be done on frame_callbacks that don't return immediately (due to not enough time passing). Might raise exceptions -- caller should protect itself from them until the sim does. + stuff new frame data into atom positions +? fix singlet...
- update progress bar - tell Qt to process events - see if user aborted, if so, set flag in simulator object so it will abort too (but for now, separate code will also terminate the sim run in the usual way, reading redundantly from xyz file)
def sim_frame_callback_worker(self, frame_number): #bruce 060102 """Do whatever should be done on frame_callbacks that don't return immediately (due to not enough time passing). Might raise exceptions -- caller should protect itself from them until the sim does. + stuff new frame data into atom positions +? fix singlet...
if 1:
if not self.aborting:
def sim_frame_callback_worker(self, frame_number): #bruce 060102 """Do whatever should be done on frame_callbacks that don't return immediately (due to not enough time passing). Might raise exceptions -- caller should protect itself from them until the sim does. + stuff new frame data into atom positions +? fix singlet...
self.need_process_events = True return def sim_frame_callback_updates(self): """Do Qt-related updates which are needed after something has updated progress bar displays or done gl_update or printed history messages, if anything has set self.need_process_events to indicate it needs this (and reset that flag): - tell Qt...
def sim_frame_callback_worker(self, frame_number): #bruce 060102 """Do whatever should be done on frame_callbacks that don't return immediately (due to not enough time passing). Might raise exceptions -- caller should protect itself from them until the sim does. + stuff new frame data into atom positions +? fix singlet...
env.call_qApp_processEvents()
self.need_process_events = False env.call_qApp_processEvents() self.need_process_events = False
def sim_frame_callback_worker(self, frame_number): #bruce 060102 """Do whatever should be done on frame_callbacks that don't return immediately (due to not enough time passing). Might raise exceptions -- caller should protect itself from them until the sim does. + stuff new frame data into atom positions +? fix singlet...
env.history.message( redmsg( "aborting sim run: %s" % why ))
if not wasaborting: env.history.message( redmsg( "aborting sim run: %s" % why ))
def abort_sim_run(self, why = "(reason not specified by internal code)" ): #bruce 060102 "#doc" self._simopts.Interrupted = True if not self.errcode: self.errcode = -1 #######@@@@@@@ temporary kluge in case of bugs in RuntimeError from that or its handler; # also needed until we clean up our code to use the new sim.Sim...
import chunk if isinstance(node, chunk.Chunk): dict1 = self.archive._changed_parent_Atoms dict1.update(node.atoms)
return
def node_departing_assy(self, node, assy): #bruce 060315 assert assy is self.assy # has to be true, since we were accessed as assy.undo_manager import chunk # nonmodular, but I think this shouldn't be called too early for that import, since assy will be inited if isinstance(node, chunk.Chunk): dict1 = self.archive._cha...
def draw(self): radius, axis, turn, n, color = self.args
def draw(self, **mods): radius, axis, turn, n, color = self.args color = mods.get('color',color)
def draw(self): radius, axis, turn, n, color = self.args # axis is for x, theta starts 0, at top (y), so y = cos(theta), z = sin(theta) glDisable(GL_LIGHTING) ### not doing this makes it take the color from the prior object glColor3fv(color) glBegin(GL_LINE_STRIP) points = self.points() for p in points: ##glNormal3fv(-...
self.args[-1] = interior_color
def draw(self, **mods): radius, axis, turn, n, color = self.args color0 = mods.get('color',color)##kluge ##e todo: should be more general; maybe should get "state ref" (to show & edit) as arg, too? if color != color0: if debug_color_override: print "color override in %r from %r to %r" % (self, color, color0) # seems to...