python_code
stringlengths
0
992k
repo_name
stringlengths
8
46
file_path
stringlengths
5
162
# Copyright 2004-2008 Nanorex, Inc. See LICENSE file for details. """ writepovfile.py -- write a Part into a POV-Ray file @version: $Id$ @copyright: 2004-2008 Nanorex, Inc. See LICENSE file for details. History: Bruce 080917 split this out of graphics/rendering/fileIO.py. For earlier history see that file's repository log. """ import math import foundation.env as env from geometry.VQT import V, Q, A, vlen from graphics.rendering.povray.povheader import povheader, povpoint from utilities.prefs_constants import PERSPECTIVE from utilities.prefs_constants import material_specular_highlights_prefs_key from utilities.prefs_constants import material_specular_finish_prefs_key # == # Create a POV-Ray file def writepovfile(part, glpane, filename): """ write the given part into a new POV-Ray file with the given name, using glpane for lighting, color, etc """ f = open(filename,"w") # POV-Ray images now look correct when Projection = ORTHOGRAPHIC. Mark 051104. if glpane.ortho == PERSPECTIVE: cdist = 6.0 # Camera distance [see also glpane.cdist] else: # ORTHOGRAPHIC cdist = 1600.0 aspect = (glpane.width + 0.0)/(glpane.height + 0.0) zfactor = 0.4 # zoom factor up = V(0.0, zfactor, 0.0) right = V( aspect * zfactor, 0.0, 0.0) ##1.33 angle = 2.0*math.atan2(aspect, cdist)*180.0/math.pi f.write("// Recommended window size: width=%d, height=%d \n"%(glpane.width, glpane.height)) f.write("// Suggested command line switches: +A +W%d +H%d\n\n"%(glpane.width, glpane.height)) f.write(povheader) # Camera info vdist = cdist if aspect < 1.0: vdist = cdist / aspect eyePos = vdist * glpane.scale*glpane.out-glpane.pov # note: this is probably the same as glpane.eyeball(), # in perspective view, except for the aspect < 1.0 correction. # See comments in def eyeball about whether that correction # is needed there as well. [bruce 080912 comment] f.write("#declare cameraPosition = "+ povpoint(eyePos) + ";\n" + "\ncamera {\n location cameraPosition" + "\n up " + povpoint(up) + "\n right " + povpoint(right) + "\n sky " + povpoint(glpane.up) + "\n angle " + str(angle) + "\n look_at " + povpoint(-glpane.pov) + "\n}\n\n") # Background color. The SkyBlue gradient is supported, but only works correctly when in "Front View". # This is a work in progress (and this implementation is better than nothing). See bug 888 for more info. # Mark 051104. if glpane.backgroundGradient: # SkyBlue. dt = Q(glpane.quat) if not vlen(V(dt.x, dt.y, dt.z)): # This addresses a problem in POV-Ray when dt=0,0,0 for Axis_Rotate_Trans. mark 051111. dt.x = .00001 degY = dt.angle*180.0/math.pi f.write("sky_sphere {\n" + " pigment {\n" + " gradient y\n" + " color_map {\n" + " [(1-cos(radians(" + str(90-angle/2) + ")))/2 color SkyWhite]\n" + " [(1-cos(radians(" + str(90+angle/2) + ")))/2 color SkyBlue]\n" + " }\n" + " scale 2\n" + " translate -1\n" + " }\n" + ' #include "transforms.inc"\n' + " Axis_Rotate_Trans(" + povpoint(V(dt.x, dt.y, dt.z)) + ", " + str(degY) + ")\n" + " }\n") else: # Solid f.write("background {\n color rgb " + povpoint(glpane.backgroundColor*V(1,1,-1)) + "\n}\n") # Lights and Atomic finish. _writepovlighting(f, glpane) # write a union object, which encloses all following objects, so it's # easier to set a global modifier like "Clipped_by" for all objects # Huaicai 1/6/05 f.write("\nunion {\t\n") # Head of the union object # Write atoms and bonds in the part part.writepov(f, glpane.displayMode) #bruce 050421 changed assy.tree to assy.part.topnode to fix an assy/part bug #bruce 050927 changed assy.part -> new part arg #bruce 070928 call part.writepov instead of directly calling part.topnode.writepov, # so the part can prevent external bonds from being drawn twice. # set the near and far clipping plane # removed 050817 josh -- caused crud to appear in the output (and slowed rendering 5x!!) ## farPos = -cdist*glpane.scale*glpane.out*glpane.far + eyePos ## nearPos = -cdist*glpane.scale*glpane.out*glpane.near + eyePos ## pov_out = (glpane.out[0], glpane.out[1], -glpane.out[2]) ## pov_far = (farPos[0], farPos[1], -farPos[2]) ## pov_near = (nearPos[0], nearPos[1], -nearPos[2]) ## pov_in = (-glpane.out[0], -glpane.out[1], glpane.out[2]) ## f.write("clipped_by { plane { " + povpoint(-glpane.out) + ", " + str(dot(pov_in, pov_far)) + " }\n") ## f.write(" plane { " + povpoint(glpane.out) + ", " + str(dot(pov_out, pov_near)) + " } }\n") # [and what was this for? bruce question 071009] ## if glpane.assy.commandSequencer.currentCommand.commandName == 'DEPOSIT': ## dt = -glpane.quat ## degY = dt.angle*180.0/pi ## f.write("plane { \n" + ## " z 0\n" + ## " pigment { color rgbf <0.29, 0.7294, 0.8863, 0.6>}\n" + ## ' #include "transforms.inc"\n' + ## " Axis_Rotate_Trans(" + povpoint(V(dt.x, dt.y, dt.z)) + ", " + str(degY) + ")}\n") f.write("}\n\n") f.close() return # from writepovfile # _writepovlighting() added by Mark. Feel free to ask him if you have questions. 051130. def _writepovlighting(f, glpane): """ Writes a light source record for each light (if enabled) and the 'Atomic' finish record. These records impact the lighting affect. """ # Get the lighting parameters for the 3 lights. (((r0,g0,b0),a0,d0,s0,x0,y0,z0,e0), \ ( (r1,g1,b1),a1,d1,s1,x1,y1,z1,e1), \ ( (r2,g2,b2),a2,d2,s2,x2,y2,z2,e2)) = glpane.getLighting() # For now, we copy the coords of each light here. pos0 = (glpane.right * x0) + (glpane.up *y0) + (glpane.out * z0) pos1 = (glpane.right * x1) + (glpane.up * y1) + (glpane.out * z1) pos2 = (glpane.right * x2) + (glpane.up * y2) + (glpane.out * z2) # The ambient values of only the enabled lights are summed up. # 'ambient' is used in the 'Atomic' finish record. It can have a value # over 1.0 (and makes a difference). ambient = 0.25 # Add 0.25; matches better with NE1 default lighting. # The diffuse values of only the enabled lights are summed up. # 'diffuse' is used in the 'Atomic' finish record. It can have a value # over 1.0 (and makes a difference). diffuse = 0.0 f.write( "\n// Light #0 (Camera Light)" + "\nlight_source {" + "\n cameraPosition" + "\n color <0.3, 0.3, 0.3>" + "\n parallel" + "\n point_at <0.0, 0.0, 0.0>" + "\n}\n") if e0: # Light 1 is On ambient += a0 diffuse += d0 f.write( "\n// Light #1" + "\nlight_source {" + "\n " + povpoint(pos0) + "\n color <" + str(r0*d0) + ", " + str(g0*d0) + ", " + str(b0*d0) + ">" + "\n parallel" + "\n point_at <0.0, 0.0, 0.0>" + "\n}\n") if e1: # Light 2 is On ambient += a1 diffuse += d1 f.write( "\n// Light #2" + "\nlight_source {\n " + povpoint(pos1) + "\n color <" + str(r1*d1) + ", " + str(g1*d1) + ", " + str(b1*d1) + ">" + "\n parallel" + "\n point_at <0.0, 0.0, 0.0>" + "\n}\n") if e2: # Light 3 is On ambient += a2 diffuse += d2 f.write("\n// Light #3" + "\nlight_source {\n " + povpoint(pos2) + "\n color <" + str(r2*d2) + ", " + str(g2*d2) + ", " + str(b2*d2) + ">" + "\n parallel" + "\n point_at <0.0, 0.0, 0.0>" + "\n}\n") # Atomic finish record. # # phong determines the brightness of the highlight, while phong_size determines its size. # # phong: 0.0 (no highlight) to 1.0 (saturated highlight) # # phong_size: 1 (very dull) to 250 (highly polished) # The larger the phong size the tighter, or smaller, the highlight and # the shinier the appearance. The smaller the phong size the looser, # or larger, the highlight and the less glossy the appearance. # # Good values: # brushed metal: phong .25, phong_size 12 # plastic: .7, phong_size 17 # # so phong ranges from .25 - .7 # and phong_size ranges from 12-17 # if env.prefs[material_specular_highlights_prefs_key]: # whiteness: 0.0-1.0, where 0 = metal and 1 = plastic phong = 0.25 + (env.prefs[material_specular_finish_prefs_key] * 0.45) # .25-.7 phong_size = 12.0 + (env.prefs[material_specular_finish_prefs_key] * 5.0) # 12-17 else: phong = 0.0 # No specular highlights phong_size = 0.0 f.write( "\n#declare Atomic =" + "\nfinish {" + "\n ambient 0.1" + # str(ambient) + # Mark 060929 "\n diffuse " + str(diffuse) + "\n phong " + str(phong) + "\n phong_size " + str(phong_size) + "\n}\n") return # from _writepovlighting # end
NanoCAD-master
cad/src/graphics/rendering/povray/writepovfile.py
# Copyright 2004-2007 Nanorex, Inc. See LICENSE file for details. """ povheader.py @author: Josh @version: $Id$ @copyright: 2004-2007 Nanorex, Inc. See LICENSE file for details. """ #bruce 050413: moved povpoint from 4 other modules (identical copies) into this one. # (I'd leave it in fileIO except that would cause a recursive import problem.) def povpoint(p): # note z reversal -- povray is left-handed return "<" + str(p[0]) + "," + str(p[1]) + "," + str(-p[2]) + ">" povheader = """ // COLORS: #declare Red = rgb <1, 0, 0>; #declare Green = rgb <0, 1, 0>; #declare Blue = rgb <0, 0, 1>; #declare Yellow = rgb <1,1,0>; #declare Cyan = rgb <0, 1, 1>; #declare Magenta = rgb <1, 0, 1>; #declare Clear = rgbf 1; #declare White = rgb 1; #declare Black = rgb 0; #declare Gray10 = White * 0.9; #declare Gray25 = White *0.75; #declare Gray40 = White *0.60; #declare Gray50 = White * 0.50; #declare Gray75 = White * 0.25; // SkyBlue Gradient colors. #declare SkyWhite = White * 0.9; #declare SkyBlue = rgb <.33, .73, 1>; // LIGHTBULB: for debugging light sources for POV-Ray images - Mark #declare Lightbulb = union { merge { sphere { <0,0,0>,1 } cylinder { <0,0,1>, <0,0,0>, 1 scale <0.35, 0.35, 1.0> translate 0.5*z } texture { pigment {color rgb <1, 1, 1>} finish {ambient .8 diffuse .6} } } cylinder { <0,0,1>, <0,0,0>, 1 scale <0.4, 0.4, 0.5> translate 1.5*z } rotate -90*x scale .5 } #macro rmotor(p1, p2, rad, col) cylinder { p1, p2, rad pigment { rgb col } finish {Atomic} } #end #macro lmotor(c1, c2, yrot, xrot, trans, col) box { c1, c2 rotate yrot rotate xrot translate trans pigment { rgb col } finish {Atomic} } #end #macro spoke(p1, p2, rad, col) cylinder { p1, p2, rad pigment { rgb col } finish {Atomic} } #end #macro atom(pos, rad, col) sphere { pos, rad pigment { rgb col } finish {Atomic} } #end // macros with hardcoded radii. (since 060622 these might no longer be used) #macro tube1(pos1, col1, cc1, cc2, pos2, col2) cylinder {pos1, cc1, 0.3 pigment { rgb col1 } finish {Atomic} } cylinder {cc1, cc2, 0.3 pigment { Red } finish {Atomic} } cylinder {cc2, pos2, 0.3 pigment { rgb col2 } finish {Atomic} } #end #macro tube2(pos1, col1, cc1, pos2, col2) cylinder {pos1, cc1, 0.3 pigment { rgb col1 } finish {Atomic} } cylinder {cc1, pos2, 0.3 pigment { rgb col2 } finish {Atomic} } #end #macro tube3(pos1, pos2, col) cylinder {pos1, pos2, 0.3 pigment { rgb col } finish {Atomic} } #end #macro bond(pos1, pos2, col) cylinder {pos1, pos2, 0.1 pigment { rgb col } finish {Atomic} } #end // macros with radius arguments. tube3r is equivalent to drawcylinder. (new as of 060622) #macro tube1r(rad, pos1, col1, cc1, cc2, pos2, col2) cylinder {pos1, cc1, rad pigment { rgb col1 } finish {Atomic} } cylinder {cc1, cc2, rad pigment { Red } finish {Atomic} } cylinder {cc2, pos2, rad pigment { rgb col2 } finish {Atomic} } #end #macro tube2r(rad, pos1, col1, cc1, pos2, col2) cylinder {pos1, cc1, rad pigment { rgb col1 } finish {Atomic} } cylinder {cc1, pos2, rad pigment { rgb col2 } finish {Atomic} } #end #macro tube3r(rad, pos1, pos2, col) cylinder {pos1, pos2, rad pigment { rgb col } finish {Atomic} } #end #macro bondr(rad, pos1, pos2, col) cylinder {pos1, pos2, rad pigment { rgb col } finish {Atomic} } #end #macro line(pos1, pos2, col) cylinder {pos1, pos2, 0.05 pigment { rgb col } } #end #macro wirebox(pos, rad, col) #declare c1 = pos - rad; #declare c2 = pos - <-rad,rad,rad>; #declare c3 = pos - <-rad,-rad,rad>; #declare c4 = pos - <rad,-rad,rad>; #declare c5 = pos + <-rad,-rad,rad>; #declare c6 = pos + <rad,-rad,rad>; #declare c7 = pos + rad; #declare c8 = pos + <-rad,rad,rad>; cylinder { c1, c2, 0.05 pigment { rgb col } finish {Atomic} } cylinder { c2, c3, 0.05 pigment { rgb col } finish {Atomic} } cylinder { c3, c4, 0.05 pigment { rgb col } finish {Atomic} } cylinder { c4, c1, 0.05 pigment { rgb col } finish {Atomic} } cylinder { c5, c6, 0.05 pigment { rgb col } finish {Atomic} } cylinder { c6, c7, 0.05 pigment { rgb col } finish {Atomic} } cylinder { c7, c8, 0.05 pigment { rgb col } finish {Atomic} } cylinder { c8, c5, 0.05 pigment { rgb col } finish {Atomic} } cylinder { c1, c5, 0.05 pigment { rgb col } finish {Atomic} } cylinder { c2, c6, 0.05 pigment { rgb col } finish {Atomic} } cylinder { c3, c7, 0.05 pigment { rgb col } finish {Atomic} } cylinder { c4, c8, 0.05 pigment { rgb col } finish {Atomic} } #end #macro anchor(pos, rad, col) wirebox( pos, rad, col ) #end #macro stat(pos, rad, col) wirebox( pos, rad, col ) #end #macro thermo(pos, rad, col) wirebox( pos, rad, col ) #end #macro gamess(pos, rad, col) wirebox( pos, rad, col ) #end #macro esp_plane_texture(p1, p2, p3, p4, imgName) mesh2 { vertex_vectors { 4, p1, p2, p3, p4 } uv_vectors { 4, <0.0, 1.0>, <0.0, 0.0>, <1.0, 0.0>, <1.0, 1.0> } face_indices { 2, <0, 1, 2>, <0, 2, 3> } uv_mapping pigment { image_map {png imgName } } finish {Atomic} } #end #macro esp_plane_color(p1, p2, p3, p4, col4) mesh2 { vertex_vectors { 4, p1, p2, p3, p4 } face_indices { 2, <0, 1, 2>, <0, 2, 3> } pigment {rgbf col4} finish {Atomic} } #end #macro grid_plane(p1, p2, p3, p4, col) cylinder { p1, p2, 0.05 pigment { rgb col } finish {Atomic} } cylinder { p2, p3, 0.05 pigment { rgb col } finish {Atomic} } cylinder { p3, p4, 0.05 pigment { rgb col } finish {Atomic} } cylinder { p4, p1, 0.05 pigment { rgb col } finish {Atomic} } #end #macro Rotate_X(Axis, Angle) #local vX = vaxis_rotate(x,Axis,Angle); #local vY = vaxis_rotate(y,Axis,0); #local vZ = vaxis_rotate(z,Axis,0); transform { matrix < vX.x,vX.y,vX.z, vY.x,vY.y,vY.z, vZ.x,vZ.y,vZ.z, 0,0,0 > } #end """
NanoCAD-master
cad/src/graphics/rendering/povray/povheader.py
NanoCAD-master
cad/src/graphics/rendering/povray/__init__.py
# Copyright 2004-2007 Nanorex, Inc. See LICENSE file for details. """ povray.py - routines to support POV-Ray rendering in nE-1. @author: Mark @version: $Id$ @copyright: 2004-2007 Nanorex, Inc. See LICENSE file for details. History: mark 060529 - Created file to support "View > Raytrace Scene". bruce 060711 major code clean up / bugfixing, in order to support direct include_dir prefs setting for Mac A8 Module classification: has ui and graphics_io code, related to external processes. Not sure what's best, ui or graphics_io. For now, call this "graphics_io". [bruce 071215] """ import os, sys from PyQt4.Qt import QApplication, QCursor, Qt, QStringList, QProcess, QMessageBox import foundation.env as env from utilities.Log import orangemsg ##, redmsg, greenmsg, _graymsg from utilities.debug import print_compact_traceback from processes.Plugins import verifyExecutable from utilities.prefs_constants import megapov_enabled_prefs_key from utilities.prefs_constants import megapov_path_prefs_key from utilities.prefs_constants import povray_enabled_prefs_key from utilities.prefs_constants import povray_path_prefs_key from utilities.prefs_constants import povdir_enabled_prefs_key from utilities.prefs_constants import povdir_path_prefs_key def _dialog_to_offer_prefs_fixup(win, caption, text, macwarning_ok): #bruce 060710 [use Plugin.py instead?] """ Offer the user a chance to fix a problem. Return 0 if they accept (after letting them try), 1 if they decline. """ # modified from (now-removed) activate_plugin() which had similar code macwarning = "" if sys.platform == 'darwin' and macwarning_ok: macwarning = "\n"\ " Warning: Mac GUI versions of POV-Ray or MegaPOV won't work,\n"\ "but the Unix command-line versions can be compiled on the Mac\n"\ "and should work. Contact [email protected] for more info." ret = QMessageBox.warning( win, caption, text + macwarning, "&OK", "Cancel", "", 0, 1 ) if ret == 0: # OK win.userPrefs.show(pagename = 'Plug-ins') # Show Preferences | Plug-ins. return 0 # let caller figure out whether user fixed the problem elif ret == 1: # Cancel return 1 pass def fix_plugin_problem(win, name, errortext, macwarning_ok): caption = "%s Problem" % name text = "Error: %s.\n" % (errortext,) + \ " Select OK to fix this now in the Plugins page of\n" \ "the Preferences dialog and retry rendering, or Cancel." # original code had <b>OK</b> but this was displayed directly (not interpreted), so I removed it [bruce 060711] return _dialog_to_offer_prefs_fixup( win, caption, text, macwarning_ok) # == def decode_povray_prefs(win, ask_for_help, greencmd = None): #bruce 060710 ###@@@ review docstring """ Look at the current state of Plugin Prefs (about POV-Ray and MegaPOV) to determine: - whether the user wants us to launch MegaPOV, POV-Ray, or neither [see below for retval format] - whether we can do what they ask Assume it's an error if we can't launch one of them, and return errorcode, errortext as appropriate. If <ask_for_help> is true, and we can't launch the one the user wants, offer to get them into the prefs dialog to fix the situation; if they fail, return the appropriate error (no second chances, perhaps unless they fixed part of it and we got farther in the setup process). If we can launch one, return the following: 0, (program_nickname, program_path, include_dir), where program_nickname is "POV-Ray" or "MegaPOV", program_path points to an existing file (not necessarily checked for being executable), and include_dir points to an existing directory or (perhaps) is "" (not necessarily checked for including transforms.inc). We might [not yet decided ###k] permit include_dir to not include transforms.inc or be "", with a history warning, since this will sometimes work (as of 060710, I think it works when blue sky background is not used). If we can't launch one, return errorcode, errortext, with errorcode true and errortext an error message string. """ #bruce 060710 created this from parts of write_povray_ini_file and launch_povray_or_megapov if greencmd is None: greencmd = "" # only used as a prefix for history warnings name = "POV-Ray or MegaPOV" ## # If the user didn't enable either POV-Ray or MegaPOV, let them do that now. ## if not (env.prefs[megapov_enabled_prefs_key] or env.prefs[povray_enabled_prefs_key]): ## activate_povray_or_megapov(win, "POV-Ray or MegaPOV") ## if not (env.prefs[megapov_enabled_prefs_key] or env.prefs[povray_enabled_prefs_key]): ## return 1, "neither POV-Ray nor MegaPOV plugins are enabled" # Make sure the other prefs settings are correct; if not, maybe repeat until user fixes them or gives up. macwarning_ok = True # True once, false after that ##e might make it only true for certain warnings, not others while 1: errorcode, errortext_or_info = decode_povray_prefs_0(win, greencmd) if errorcode: if not ask_for_help: return errorcode, errortext_or_info ret = fix_plugin_problem(win, name, errortext_or_info, macwarning_ok) macwarning_ok = False if ret == 0: # Subroutine has shown Preferences | Plug-in. continue # repeat the checks, to figure out whether user fixed the problem elif ret == 1: # User declined to try to fix it now return errorcode, errortext_or_info else: (program_nickname, program_path, include_dir) = errortext_or_info # verify format (since it's in our docstring) return 0, errortext_or_info pass # end of decode_povray_prefs def decode_povray_prefs_0(win, greencmd): #bruce 060710 """ [private helper for decode_povray_prefs] """ # The one they want to use is the first one enabled out of MegaPOV or POV-Ray (in that order). if env.prefs[megapov_enabled_prefs_key]: want = "MegaPOV" wantpath = env.prefs[megapov_path_prefs_key] elif env.prefs[povray_enabled_prefs_key]: want = "POV-Ray" wantpath = env.prefs[povray_path_prefs_key] else: return 1, "neither POV-Ray nor MegaPOV plugins are enabled" if not wantpath: return 1, "%s plug-in executable path is empty" % want if not os.path.exists(wantpath): return 1, "%s executable not found at specified path" % want message = verifyExecutable(wantpath) if (message): return 1, message ##e should check version of plugin, if we know how # Figure out include dir to use. if env.prefs[povdir_enabled_prefs_key] and env.prefs[povdir_path_prefs_key]: include_dir = env.prefs[povdir_path_prefs_key] else: errorcode, include_dir = default_include_dir() # just figure out name, don't check it in any way [can it return ""?] if errorcode: return errorcode, include_dir errorcode, errortext = include_dir_ok(include_dir) # might just print warning if it's not clear whether it's ok if errorcode: return errorcode, errortext return 0, (want, wantpath, include_dir) # (program_nickname, program_path, include_dir) # == def this_platform_can_guess_include_dir_from_povray_path(): return sys.platform != 'darwin' def default_include_dir(): #bruce 060710 split out and revised Mark's & Will's code for this in write_povray_ini_file """ The user did not specify an include dir, so guess one from the POV-Ray path (after verifying it's set). Return 0, include_dir or errorcode, errortext. If not having one is deemed worthy of only a warning, not an error, emit the warning and return 0 [nim]. """ # Motivation: # If MegaPOV is enabled, the Library_Path option must be added and set to the POV-Ray/include # directory in the INI. This is so MegaPOV can find the include file "transforms.inc". Mark 060628. # : Povray also needs transforms.inc - wware 060707 # : : [but when this is povray, it might know where it is on its own (its own include dir)? not sure. bruce 060707] # : : [it looks like it would not know that in the Mac GUI version (which NE1 has no way of supporting, # since external programs can't pass it arguments); I don't know about Unix/Linux or Windows. bruce 060710] if not this_platform_can_guess_include_dir_from_povray_path(): # this runs on Mac return 1, "Can't guess include dir from POV-Ray executable\npath on this platform; please set it explicitly" povray_path = env.prefs[povray_path_prefs_key] if not povray_path: return 1, "Either the POV include directory or the POV-Ray\nexecutable path must be set (even when using MegaPOV)" #e in future, maybe we could use one from POV-Ray, even if it was not enabled, so don't preclude this here try: # try to guess the include directory (include_dir) from povray_path; exception if you fail if sys.platform == 'win32': # Windows povray_bin, povray_exe = os.path.split(povray_path) povray_dir, bin = os.path.split(povray_bin) include_dir = os.path.normpath(os.path.join(povray_dir, "include")) elif sys.platform == 'darwin': # Mac assert 0 else: # Linux povray_bin = povray_path.split(os.path.sep) # list of pathname components assert povray_bin[-2] == 'bin' and povray_bin[-1] == 'povray' # this is the only kind of path we can do this for include_dir = os.path.sep.join(povray_bin[:-2] + ['share', 'povray-3.6', 'include']) return 0, include_dir except: if env.debug() and this_platform_can_guess_include_dir_from_povray_path(): print_compact_traceback("debug fyi: this is the exception inside default_include_dir: ") msg = "Unable to guess POV include directory from\nPOV-Ray executable path; please set it explicitly" return 1, msg pass def include_dir_ok(include_dir): """ Is this include_dir acceptable (or maybe acceptable)? Return (0, "") or (errorcode, errortext). """ if env.debug(): print "debug: include_dir_ok(include_dir = %r)" % (include_dir,) if os.path.isdir(include_dir): # ok, but warn if transforms.inc is not inside it if not os.path.exists(os.path.join(include_dir, "transforms.inc")): msg = "Warning: transforms.inc not present in POV include directory [%s]; rendering might not work" % (include_dir,) env.history.message(orangemsg(msg)) if env.debug(): print "debug: include_dir_ok returns 0 (ok)" return 0, "" # ok else: if env.debug(): print "debug: include_dir_ok returns 1 (Not found or not a directory)" return 1, "POV include directory: Not found or not a directory" #e pathname might be too long for a dialog pass # == def write_povray_ini_file(ini, pov, out, info, width, height, output_type = 'png'): #bruce 060711 revised this extensively for Mac A8 """ Write the povray_ini file, <ini>, containing the commands necessary to render the povray scene file <pov> to produce an image in the output file <out>, using the rendering options width, height, output_type, and the renderer info <info> (as returned fom decode_povray_prefs). All these filenames should be given as absolute pathnames, as if returned from get_povfile_trio() in PovrayScene. (It is currently a requirement that they all be in the same directory -- I'm not sure how necessary that is.) <width>, <height> (ints) are used as the width and height of the rendered image. <output_type> is used as the extension of the output image (currently only 'png' and 'bmp' are supported). [WARNING: bmp may not be correctly supported on Mac.] (I don't know whether the rendering programs require that <output_type> matches the file extension of <out>. As currently called, it supposedly does.) """ # Should this become a method of PovrayScene? I think so, but ask Bruce. Mark 060626. dir_ini, rel_ini = os.path.split(ini) dir_pov, rel_pov = os.path.split(pov) dir_out, rel_out = os.path.split(out) assert dir_ini == dir_pov == dir_out, "current code requires ini, pov, out to be in the same directory" # though I'm not sure why it needs to -- maybe this only matters on Windows? [bruce 060711 comment] (program_nickname, program_path, include_dir) = info #e rename this arg renderer_info? if output_type == 'bmp': output_ext = '.bmp' output_imagetype = 'S' # 'S' = System-specific such as Mac Pict or Windows BMP ####@@@@ that sounds to me like it will fail to write bmp as requested, on Mac OS [bruce 060711 comment] else: # default output_ext = '.png' output_imagetype = 'N' # 'N' = PNG (portable network graphics) format if 1: # output_ext is only needed for this debug warning; remove when works base, ext = os.path.splitext(rel_pov) if rel_out != base + output_ext: print "possible bug introduced in 060711 code cleanup: %r != %r" % (rel_out , base + output_ext) pass f = open(ini,'w') # Open POV-Ray INI file. f.write ('; POV-Ray INI file generated by NanoEngineer-1\n') f.write ('Input_File_Name="%s"\n' % rel_pov) f.write ('Output_File_Name="%s"\n' % rel_out) f.write ('Library_Path="%s"\n' % include_dir) # Library_Path is only needed if MegaPOV is enabled. Doesn't hurt anything always having it. Mark 060628. # According to Will, it's also needed for POV-Ray. Maybe this is only the case on some platforms. [bruce 060710] f.write ('+W%d +H%d\n' % (width, height)) f.write ('+A\n') # Anti-aliasing f.write ('+F%s\n' % output_imagetype) # Output format. f.write ('Pause_When_Done=true\n') # MacOS and Linux only. User hits any key to make image go away. f.write ('; End\n') f.close() return # from write_povray_ini_file def launch_povray_or_megapov(win, info, povray_ini): #bruce 060707/11 revised this extensively for Mac A8 """ Try to launch POV-Ray or MegaPOV, as specified in <info> (as returned from decode_povray_prefs, assumed already checked), on the given <povray_ini> file (which should already exist), and running in the directory of that file (this is required, since it may contain relative pathnames). <win> must be the main window object (used for .glpane.is_animating). Returns (errorcode, errortext), where errorcode is one of the following: ###k 0 = successful 8 = POV-Ray or MegaPOV failed for an unknown reason. """ (program_nickname, program_path, include_dir) = info #e rename this arg renderer_info? exit = '' program = program_path if sys.platform == 'win32': program = "\""+program+"\"" # Double quotes needed by Windows. Mark 060602. if program_nickname == 'POV-Ray': exit = "/EXIT" # Later we'll cd to the POV-Ray's INI file directory and use tmp_ini in the POV-Ray command-line. # This helps us get around POV-Ray's I/O Restrictions. Mark 060529. workdir, tmp_ini = os.path.split(povray_ini) # Render scene. try: args = [tmp_ini] if exit: args += [exit] if env.debug(): ## use env.history.message(_graymsg(msg)) ? print "debug: Launching %s: \n" % program_nickname,\ "working directory=",workdir,"\n program_path=", program_path, "\n args are %r" % (args,) arguments = QStringList() for arg in args: if arg != "": arguments.append(arg) from processes.Process import Process p = Process() #bruce 060707: this doesn't take advantage of anything not in QProcess, # unless it matters that it reads and discards stdout/stderr # (eg so large output would not block -- unlikely that this matters). # It doesn't echo stdout/stderr. See also blabout/blaberr in other files. Maybe fix this? ###@@@ p.setWorkingDirectory(workdir) p.start(program, arguments) # Put up hourglass cursor to indicate we are busy. Restore the cursor below. Mark 060621. QApplication.setOverrideCursor( QCursor(Qt.WaitCursor) ) win.glpane.is_animating = True # This disables selection [do you mean highlighting? #k] while rendering the image. import time msg = "Rendering image" while p.state() == QProcess.Running: # Display a message on the status bar that POV-Ray/MegaPOV is rendering. # I'd much rather display a progressbar and stop button by monitoring the size of the output file. # This would require the output file to be written in PPM or BMP format, but not PNG format, since # I don't believe a PNG's final filesize can be predicted. # Check out monitor_progress_by_file_growth() in runSim.py, which does this. [mark] time.sleep(0.25) env.history.statusbar_msg(msg) env.call_qApp_processEvents() if 1: # Update the statusbar message while rendering. if len(msg) > 40: #bruce changed 100 -> 40 in case of short statusbar msg = "Rendering image" else: #msg = msg + "." msg += "." except: #bruce 060707 moved print_compact_traceback earlier, and its import to toplevel (after Windows A8, before Linux/Mac A8) print_compact_traceback( "exception in launch_povray_or_megapov(): " ) QApplication.restoreOverrideCursor() win.glpane.is_animating = False return 8, "%s failed for an unknown reason." % program_nickname #bruce 060707 moved the following outside the above try clause, and revised it (after Windows A8, before Linux/Mac A8) QApplication.restoreOverrideCursor() # Restore the cursor. Mark 060621. ## env.history.statusbar_msg("Rendering finished!") # this is wrong if it was not a normal exit. [bruce 060707 removed it] win.glpane.is_animating = False if 1: #bruce 060707 added this (after Windows A8, before Linux/Mac A8): # set an appropriate exitcode and msg if p.exitStatus() == QProcess.NormalExit: exitcode = p.exitStatus() if not exitcode: msg = "Rendering finished!" else: msg = "Rendering program had exitcode %r" % exitcode # e.g. 126 for Mac failure; same as shell exitcode, which says "cannot execute binary file"; # but /usr/bin/open helps, so we'll try that above (but not in this commit, which is just to # improve error reporting). ###@@@ # [bruce 060707] else: exitcode = p.exitStatus() exitcode = -1 msg = "Abnormal exit (or failure to launch)" if exitcode or env.debug(): print msg env.history.statusbar_msg(msg) ## if env.debug(): ## env.history.message(_graymsg(msg)) # not needed, caller prints it if exitcode: return 8, "Error: " + msg # this breaks the convention of the other error returns pass # Display image in separate window here. [Actually I think this is done in the caller -- bruce 060707 comment] return 0, "Rendering finished" # from launch_povray_or_megapov def verify_povray_program(): # not yet used, not yet correctly implemented """ Returns 0 if povray_path_prefs_key is the path to the POV-Ray 3.6 executable. Otherwise, returns 1. Always return 0 for now until I figure out a way to verify POV-Ray. Mark 060527. """ vstring = "POV-Ray 3.6" # or somthing like this.os #r = verify_program(env.prefs[povray_path_prefs_key], '-v', vstring) #return r return 0 # == # end
NanoCAD-master
cad/src/graphics/rendering/povray/povray.py
# Copyright 2004-2007 Nanorex, Inc. See LICENSE file for details. """ qutemol.py - provides routines to support QuteMolX as a plug-in. @author: Mark @version: $Id$ @copyright: 2004-2007 Nanorex, Inc. See LICENSE file for details. History: mark 2007-06-02 - Created file. Much of the plug-in checking code was copied from povray.py, written by Bruce. Module classification: [bruce 071215, 080103] Looks like operations and io code. Similar to "simulation" code but is not about simulation -- maybe that category is misconceived and what we want instead is an "external process" category of code. For now, call this "graphics_io" but file it into graphics/rendering/QuteMolX. """ import foundation.env as env import os import sys from PyQt4.Qt import QString, QStringList, QProcess from utilities.prefs_constants import qutemol_enabled_prefs_key, qutemol_path_prefs_key from utilities.debug import print_compact_traceback from utilities.debug_prefs import debug_pref, Choice_boolean_True from utilities.constants import properDisplayNames, TubeRadius, diBALL_SigmaBondRadius from files.pdb.files_pdb import writePDB_Header, writepdb, EXCLUDE_HIDDEN_ATOMS from model.elements import PeriodicTable from utilities.prefs_constants import cpkScaleFactor_prefs_key from utilities.prefs_constants import diBALL_AtomRadius_prefs_key from utilities.prefs_constants import backgroundGradient_prefs_key from utilities.prefs_constants import backgroundColor_prefs_key from utilities.prefs_constants import diBALL_BondCylinderRadius_prefs_key from processes.Plugins import checkPluginPreferences from processes.Process import Process from commands.GroupProperties.GroupProp import Statistics from platform_dependent.PlatformDependent import find_or_make_Nanorex_subdir def launch_qutemol(pdb_file): """ Launch and load QuteMolX with the PDB file I{pdb_file}. @param pdb_file: the PDB filename to load @type pdb_file: string @return: (errorcode, errortext) where errorcode is one of the following: ###k 0 = successful 8 = QuteMolX failed for an unknown reason. @rtype: int, text """ plugin_name = "QuteMolX" plugin_prefs_keys = (qutemol_enabled_prefs_key, qutemol_path_prefs_key) errorcode, errortext_or_path = \ checkPluginPreferences(plugin_name, plugin_prefs_keys, insure_executable = True) if errorcode: return errorcode, errortext_or_path program_path = errortext_or_path workdir, junk_exe = os.path.split(program_path) # This provides a way to tell NE1 which version of QuteMolX is installed. if debug_pref("QuteMol 0.4.1 or later", Choice_boolean_True, prefs_key = True): version = "0.4.1" else: version = "0.4.0" # Start QuteMolX. try: args = [pdb_file] if env.debug(): print "Debug: Launching", plugin_name, \ "\n working directory=", workdir, \ "\n program_path=", program_path, \ "\n args are %r" % (args,) arguments = QStringList() for arg in args: if arg != "": arguments.append(arg) p = Process() # QuteMolX must run from the directory its executable lives. Otherwise, # it has serious problems (but still runs). Mark 2007-06-02. p.setWorkingDirectory(QString(workdir)) # Tried p.startDetached() so that QuteMolX would be its own process and # continue to live even if NE1 exits. Unfortunately, # setWorkingDirectory() doesn't work. Seems like a Qt bug to me. # Mark 2007-06-02 p.start(program_path, arguments) except: print_compact_traceback( "exception in launch_qutemol(): " ) return 8, "%s failed for an unknown reason." % plugin_name # set an appropriate exitcode and msg if p.exitStatus() == QProcess.NormalExit: exitcode = p.exitStatus() if not exitcode: msg = plugin_name + " launched." else: msg = plugin_name + " had exitcode %r" % exitcode else: exitcode = p.exitStatus() exitcode = -1 msg = "Abnormal exit (or failure to launch)" if exitcode: return 8, "Error: " + msg # this breaks the convention of the other error returns return 0, plugin_name + " launched." # from launch_qutemol def write_art_data(fileHandle): """ Writes the Atom Rendering Table (ART) data, which contains all the atom rendering properties needed by QuteMolX, to the file with the given fileHandle. Each atom is on a separate line. Lines starting with '#' are comment lines. """ fileHandle.write("""\ REMARK 8 REMARK 8 ;NanoEngineer-1 Atom Rendering Table (format version 0.1.0) REMARK 8 ;This table specifies the scene rendering scheme as employed by REMARK 8 ;NanoEngineer-1 (NE1) at the time this file was created. REMARK 8 REMARK 8 ;Note: All CPK radii were calculated using a CPK scaling factor that REMARK 8 ;can be modified by the user from "Preferences... | Atoms".\n""") fileHandle.write("REMARK 8 ;This table's CPK Scaling Factor: %2.3f" % env.prefs[cpkScaleFactor_prefs_key]) fileHandle.write(""" REMARK 8 ;To compute the original van der Waals radii, use the formula: REMARK 8 ; vdW Radius = CPK Radius / CPK Scaling Factor REMARK 8 REMARK 8 ;Atom Name NE1 Atom CPK Radius Ball and Stick Color (RGB) REMARK 8 ; Number Radius\n""") elementTable = PeriodicTable.getAllElements() for elementNumber, element in elementTable.items(): color = element.color r = int(color[0] * 255 + 0.5) g = int(color[1] * 255 + 0.5) b = int(color[2] * 255 + 0.5) # The following was distilled from chem.py: Atom.howdraw() # # "Render Radius" cpkRadius = \ element.rvdw * env.prefs[cpkScaleFactor_prefs_key] # "Covalent Radius" ballAndStickRadius = \ element.rvdw * 0.25 * env.prefs[diBALL_AtomRadius_prefs_key] #if element.symbol == 'Ax3': # ballAndStickRadius = 0.1 fileHandle.write \ ("REMARK 8 %-3s %-3d %3.3f %3.3f %3d %3d %3d\n" % (element.symbol, elementNumber, cpkRadius, ballAndStickRadius, r, g, b)) fileHandle.close() return def write_qutemol_pdb_file(part, filename, excludeFlags): """ Writes an NE1-QuteMolX PDB file of I{part} to I{filename}. @param part: the NE1 part. @type part: L{assembly} @param filename: the PDB filename to write @type filename: string @param excludeFlags: used to exclude certain atoms from being written to the QuteMolX PDB file. @type excludeFlags: int @see L{writepdb()} for more information about I{excludeFlags}. """ f = open(filename, "w") skyBlue = env.prefs[ backgroundGradient_prefs_key ] bgcolor = env.prefs[ backgroundColor_prefs_key ] r = int (bgcolor[0] * 255 + 0.5) g = int (bgcolor[1] * 255 + 0.5) b = int (bgcolor[2] * 255 + 0.5) TubBond1Radius = TubeRadius BASBond1Radius = \ diBALL_SigmaBondRadius * \ env.prefs[diBALL_BondCylinderRadius_prefs_key] writePDB_Header(f) # Writes our generic PDB header # Write the QuteMolX REMARKS "header". # See the following wiki page for more information about # the format of all NE1-QuteMolX REMARK records: # http://www.nanoengineer-1.net/mediawiki/index.php?title=NE1_PDB_REMARK_Records_Display_Data_Format # f.write("""\ REMARK 6 - The ";" character is used to denote non-data (explanatory) records REMARK 6 in the REMARK 7 and REMARK 8 blocks. REMARK 6 REMARK 7 REMARK 7 ;Display Data (format version 0.1.0) nanoengineer-1.com/PDB_REMARK_7 REMARK 7\n""") f.write("REMARK 7 ORIENTATION: %1.6f %1.6f %1.6f %1.6f\n" % (part.o.quat.w, part.o.quat.x, part.o.quat.y, part.o.quat.z)) f.write("REMARK 7 SCALE: %4.6f\n" % part.o.scale) f.write("REMARK 7 POINT_OF_VIEW: %6.6f %6.6f %6.6f\n" % (part.o.pov[0], part.o.pov[1], part.o.pov[2])) f.write("REMARK 7 ZOOM=%6.6f\n" % part.o.zoomFactor) if skyBlue: f.write("REMARK 7 BACKGROUND_COLOR: SkyBlue\n") else: f.write("REMARK 7 BACKGROUND_COLOR: %3d %3d %3d\n" % (r, g, b)) f.write("REMARK 7 DISPLAY_STYLE: %s\n" % properDisplayNames[part.o.displayMode]) f.write("REMARK 7 TUBES_BOND_RADIUS: %1.3f\n" % TubBond1Radius) f.write("REMARK 7 BALL_AND_STICK_BOND_RADIUS: %1.3f\n" % BASBond1Radius) # Now write the REMARK records for each chunk (chain) in the part. molNum = 1 for mol in part.molecules: if mol.hidden: # Skip hidden chunks. See docstring in writepdb() for details. # Mark 2008-02-13. continue f.write("REMARK 7 CHAIN: %s " % (molNum)) f.write(" DISPLAY_STYLE: %s " % properDisplayNames[mol.display]) if mol.color: r = int (mol.color[0] * 255 + 0.5) g = int (mol.color[1] * 255 + 0.5) b = int (mol.color[2] * 255 + 0.5) f.write(" COLOR: %3d %3d %3d " % (r, g, b)) f.write(" NAME: \"%s\"\n" % mol.name) molNum+=1 f.write("REMARK 7\n") write_art_data(f) f.close() # Write the "body" of PDB file (appending it to what we just wrote). writepdb(part, filename, mode = 'a', excludeFlags = excludeFlags) def write_qutemol_files(part, excludeFlags = EXCLUDE_HIDDEN_ATOMS): """ Writes a PDB of the current I{part} to the Nanorex temp directory. @param part: the NE1 part. @type part: L{assembly} @param excludeFlags: used to exclude certain atoms from being written to the QuteMolX PDB file, where: WRITE_ALL_ATOMS = 0 (even writes hidden and invisble atoms) EXCLUDE_BONDPOINTS = 1 (excludes bondpoints) EXCLUDE_HIDDEN_ATOMS = 2 (excludes both hidden and invisible atoms) EXCLUDE_DNA_ATOMS = 4 (excludes PAM3 and PAM5 pseudo atoms) EXCLUDE_DNA_AXIS_ATOMS = 8 (excludes PAM3 axis atoms) EXCLUDE_DNA_AXIS_BONDS = 16 (suppresses PAM3 axis bonds) @type excludeFlags: int @return: the name of the temp PDB file, or None if no atoms are in I{part}. @rtype: str """ # Is there a better way to get the number of atoms in <part>.? # Mark 2007-06-02 stats = Statistics(part.tree) if 0: stats.num_atoms = stats.natoms - stats.nsinglets print "write_qutemol_files(): natoms =", stats.natoms, \ "nsinglets =", stats.nsinglets, \ "num_atoms =", stats.num_atoms if not stats.natoms: # There are no atoms in the current part. # writepdb() will create an empty file, which causes # QuteMolX to crash at launch. # Mark 2007-06-02 return None pdb_basename = "QuteMolX.pdb" # Make full pathnames for the PDB file (in ~/Nanorex/temp/) tmpdir = find_or_make_Nanorex_subdir('temp') qutemol_pdb_file = os.path.join(tmpdir, pdb_basename) # Write the PDB file. write_qutemol_pdb_file(part, qutemol_pdb_file, excludeFlags) return qutemol_pdb_file
NanoCAD-master
cad/src/graphics/rendering/qutemol/qutemol.py
NanoCAD-master
cad/src/graphics/rendering/qutemol/__init__.py
# Copyright 2006-2009 Nanorex, Inc. See LICENSE file for details. """ displaymodes.py -- support for new modular display modes. @author: Bruce @version: $Id$ @copyright: 2006-2009 Nanorex, Inc. See LICENSE file for details. Initially this only handles ChunkDisplayModes, which draw entire chunks (even if they are highlighted or selected) without drawing their atoms or bonds in the usual way. (Such a display mode might draw the atoms and bonds in its own custom way, or not at all.) Someday it may also handle AtomDisplayModes, which (like our original hardcoded display modes) draw atoms and bonds in their own way, but draw chunks as not much more than their set of atoms and bonds. These are not yet implemented. To make a new chunk display mode, make a new file which defines and registers a subclass of our class ChunkDisplayMode. For an example, see CylinderChunks.py. """ # USAGE: to make a new display style for whole chunks, # see the instructions in the module docstring above. from utilities.constants import _f_add_display_style_code from utilities.debug import register_debug_menu_command import foundation.env as env # global variables and accessors _display_mode_handlers = {} # maps disp_name, and also its index in constants.dispNames, # to a DisplayMode instance used for drawing def get_display_mode_handler(disp): return _display_mode_handlers.get(disp) # == class DisplayMode: """ abstract class for any sort of display mode (except the 6 original built-in ones defined in constants.py) """ # Note: some subclasses assign a class constant featurename, # but as far as I know, this is not yet used. TODO: add a # get_featurename method like in class Command (or basicCommand) # and add code to use it (not sure where in the UI). # [bruce 071227 comment] featurename = "" chunk_only = False # default value of class constant; some subclasses override this (in fact, not doing so is not yet supported) def __init__(self, ind): self.ind = ind self._icon_name = getattr(self, "icon_name", "modeltree/junk.png") self._hide_icon_name = getattr(self, "hide_icon_name", self._icon_name) def get_icon(self, hidden): from utilities.icon_utilities import imagename_to_pixmap if hidden: return imagename_to_pixmap( self._hide_icon_name) else: return imagename_to_pixmap( self._icon_name) pass def _register_for_readmmp(clas): # staticmethod; name is misleading, but required by other code in this file """ private method called when setting up mmp reading code: register this class as a readmmp-helper, in whatever way differs for different classes of helpers [update, bruce 071017: this docstring is misleading, since so far this has nothing to do with mmp reading; see code comments for details] """ disp_name = clas.mmp_code # we treat this as a unique index; error if not unique, unless classname is the same disp_label = clas.disp_label #bruce 080324 refactored this: allowed_for_atoms = not clas.chunk_only ind = _f_add_display_style_code( disp_name, disp_label, allowed_for_atoms ) inst = clas(ind) _display_mode_handlers[disp_name] = inst _display_mode_handlers[ind] = inst #k are both of these needed?? return _register_for_readmmp = staticmethod( _register_for_readmmp) #e some of ChunkDisplayMode's code probably belongs in this class pass # end of class DisplayMode class ChunkDisplayMode(DisplayMode): """ abstract class for display modes which only work for entire chunks """ chunk_only = True def register_display_mode_class(clas): # staticmethod """ Register the given subclass of ChunkDisplayMode as a new display mode for whole chunks, able to be drawn with, read/written in mmp files, and offered in the UI. @warning: The order in which this is called for different display styles must correspond with the order in which disp index constants (diWhatever) are defined for them in constants.py. (This needs cleanup.) [bruce 080212 comment; related code has comments with same signature] """ # Make sure we can read mmp files which refer to it as clas.mmp_code. # This also covers statusbar display and writemmp. # This works by calling _register_for_readmmp, which also stores clas.disp_label as needed # to show this display mode in the statusbar, when it's in use for the entire GLPane. # (As of 060608 there is no good reason to go through files_mmp to do this, # but in the future it might need to keep its own record of this use of mmp_code.) # (It's probably a kluge that the registering of clas.disp_label goes through files_mmp in any way. # The fault for that lies mainly with the requirement for constants.dispLabel and constants.dispNames # to be lists with corresponding indices. If they were revamped, this could be cleaned up. # But doing so is not trivial, assuming their ordering by bond cylinder radius is required.) # bruce 071017 -- remove register_for_readmmp and replace it with what it did, # since it's more confusing than worthwhile # (but see above comment for the motivation of the old way, which had some legitimacy): ## import files_mmp ## files_mmp.register_for_readmmp( clas) smethod = clas._register_for_readmmp smethod(clas) # The above also made it possible to draw chunks in this display mode, via _display_mode_handlers # and special cases in Chunk draw-related methods. ###e highlighting not yet done # Now add something to the UI so users can change chunks, or the GLPane, to this display mode. # (As a quick hack, just add a debug menu command (always visible) which acts like pressing a toolbutton for this mode.) disp_name = clas.mmp_code inst = _display_mode_handlers[disp_name] register_debug_menu_command("setDisplayStyle_of_selection(%s)" % clas.disp_label, inst.setDisplay_command) ##e should we do something so users can use it as a prefs value for preferred display mode, too? return register_display_mode_class = staticmethod( register_display_mode_class) def setDisplay_command(self, widget): win = env.mainwindow() win.setDisplayStyle_of_selection(self.ind) #bruce 080910 comment, upon renaming that method from setDisplay: # the new name says what it does, but when originally coded # this would set global style if nothing was selected # (since that method used to act that way). if env.debug(): print "setDisplayStyle_of_selection to %r.ind == %r" % (self, self.ind) return def _f_drawchunk(self, glpane, chunk, highlighted = False): """ [private method for use only by Chunk.draw] Call the subclass's drawchunk method, with the supplied arguments (but supplying memo ourselves), in the proper way (whatever is useful for Chunk.draw). In the calling code as it was when this method was written, the chunk has already done its pushMatrix and gotten us inside its OpenGL display list compiling/executing call, but it hasn't done a pushName. [later: chunks now do a pushName, probably (guess) before this call.] @note: possible future revisions: it might do pushName, or it might not put us in the display list unless we say that's ok. """ memo = self.getmemo(chunk) #e exceptions? #e pushname self.drawchunk( glpane, chunk, memo, highlighted = highlighted) return def _f_drawchunk_selection_frame(self, glpane, chunk, selection_frame_color, highlighted = False): """ Call the subclass's drawchunk_selection_frame method, with the supplied arguments (but supplying memo ourselves), in the proper way. """ # note: as of long before now, this is never called. But it should # remain in the API in case we want to revive its use. # [bruce 081001 comment] memo = self.getmemo(chunk) #e exceptions #e pushname #e highlight color for selection frame itself?? self.drawchunk_selection_frame( glpane, chunk, selection_frame_color, memo, highlighted = highlighted) return def _f_drawchunk_realtime(self, glpane, chunk, highlighted = False): """ Call the drawing method that may depend on current view settings, e.g. orientation. """ # piotr 080313 # added the highlighted = False argument - piotr 080521 # assume we don't need memo here ### memo = self.getmemo(chunk) self.drawchunk_realtime(glpane, chunk, highlighted) return def _writepov(self, chunk, file): """ piotr 080314 Render the chunk to a POV-Ray file """ memo = self.getmemo(chunk) self.writepov(chunk, memo, file) def getmemo(self, chunk): # refactored, bruce 090213 """ [needs doc] """ # Note: This is not yet optimized to let the memo be remade less often # than the display list is, but that can still mean we remake it a lot # less often than we're called for drawing the selection frame, # since that is drawn outside the display list and the chunk might get # drawn selected many times without having to remake the display list. our_key_in_chunk = id(self) # safer than using mmp_code, in case a developer reloads the class # at runtime and the memo algorithm changed counter = chunk.changeapp_counter() memo_validity_data = (counter,) # a tuple of everything which has to remain the same, for the memo # data to remain valid; if invalid, the following calls compute_memo memo = chunk.find_or_recompute_memo( our_key_in_chunk, memo_validity_data, self.compute_memo ) return memo pass # end of class ChunkDisplayMode # end
NanoCAD-master
cad/src/graphics/display_styles/displaymodes.py
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. """ CylinderChunks.py -- define a new whole-chunk display mode, which shows a chunk as a single opaque bounding cylinder of the chunk's color. @author: Bruce @version: $Id$ @copyright: 2006-2007 Nanorex, Inc. See LICENSE file for details. This is mainly intended as an example of how to use class ChunkDisplayMode, though it might be useful as a fast-rendering display mode too. """ from Numeric import dot, argmax, argmin, sqrt import foundation.env as env from graphics.drawing.CS_draw_primitives import drawcylinder from graphics.drawing.CS_draw_primitives import drawcylinder_wireframe from geometry.geometryUtilities import matrix_putting_axis_at_z from geometry.VQT import V, norm from utilities.debug import print_compact_traceback from graphics.display_styles.displaymodes import ChunkDisplayMode from utilities.constants import ave_colors from utilities.prefs_constants import atomHighlightColor_prefs_key chunkHighlightColor_prefs_key = atomHighlightColor_prefs_key # initial kluge class CylinderChunks(ChunkDisplayMode): """ example chunk display mode, which draws the chunk as a cylinder, aligned to the chunk's axes, of the chunk's color """ # mmp_code must be a unique 3-letter code, distinct from the values in # constants.dispNames or in other display modes mmp_code = 'cyl' disp_label = 'Cylinder' # label for statusbar fields, menu text, etc. icon_name = "modeltree/displayCylinder.png" hide_icon_name = "modeltree/displayCylinder-hide.png" featurename = "Set Display Cylinder" #mark 060611 ##e also should define icon as an icon object or filename, either in class or in each instance ##e also should define a featurename for wiki help def drawchunk(self, glpane, chunk, memo, highlighted): """ Draw chunk in glpane in the whole-chunk display mode represented by this ChunkDisplayMode subclass. Assume we're already in chunk's local coordinate system (i.e. do all drawing using atom coordinates in chunk.basepos, not chunk.atpos). If highlighted is true, draw it in hover-highlighted form (but note that it may have already been drawn in unhighlighted form in the same frame, so normally the highlighted form should augment or obscure the unhighlighted form). Draw it as unselected, whether or not chunk.picked is true. See also self.drawchunk_selection_frame. (The reason that's a separate method is to permit future drawing optimizations when a chunk is selected or deselected but does not otherwise change in appearance or position.) If this drawing requires info about chunk which it is useful to precompute (as an optimization), that info should be computed by our compute_memo method and will be passed as the memo argument (whose format and content is whatever self.compute_memo returns). That info must not depend on the highlighted variable or on whether the chunk is selected. """ if not chunk.atoms: return end1, end2, radius, color = memo if highlighted: color = ave_colors(0.5, color, env.prefs[chunkHighlightColor_prefs_key]) #e should the caller compute this somehow? drawcylinder(color, end1, end2, radius, capped = True) return def drawchunk_selection_frame(self, glpane, chunk, selection_frame_color, memo, highlighted): """ Given the same arguments as drawchunk, plus selection_frame_color, draw the chunk's selection frame. (Drawing the chunk itself as well would not cause drawing errors but would presumably be a highly undesirable slowdown, especially if redrawing after selection and deselection is optimized to not have to redraw the chunk at all.) Note: in the initial implementation of the code that calls this method, the highlighted argument might be false whether or not we're actually hover-highlighted. And if that's fixed, then just as for drawchunk, we might be called twice when we're highlighted, once with highlighted = False and then later with highlighted = True. """ if not chunk.atoms: return end1, end2, radius, color = memo color = selection_frame_color # make it a little bigger than the cylinder itself axis = norm(end2 - end1) alittle = 0.01 end1 = end1 - alittle * axis end2 = end2 + alittle * axis drawcylinder_wireframe(color, end1, end2, radius + alittle) return def drawchunk_realtime(self, glpane, chunk, highlighted=False): """ Draws the chunk style that may depend on a current view. piotr 080321 """ return def compute_memo(self, chunk): """ If drawing chunk in this display mode can be optimized by precomputing some info from chunk's appearance, compute that info and return it. If this computation requires preference values, access them as env.prefs[key], and that will cause the memo to be removed (invalidated) when that preference value is changed by the user. This computation is assumed to also depend on, and only on, chunk's appearance in ordinary display modes (i.e. it's invalidated whenever havelist is). There is not yet any way to change that, so bugs will occur if any ordinarily invisible chunk info affects this rendering, and potential optimizations will not be done if any ordinarily visible info is not visible in this rendering. These can be fixed if necessary by having the real work done within class Chunk's _recompute_ rules, with this function or drawchunk just accessing the result of that (and sometimes causing its recomputation), and with whatever invalidation is needed being added to appropriate setter methods of class Chunk. If the real work can depend on more than chunk's ordinary appearance can, the access would need to be in drawchunk; otherwise it could be in drawchunk or in this method compute_memo. """ # for this example, we'll turn the chunk axes into a cylinder. # Since chunk.axis is not always one of the vectors chunk.evecs (actually chunk.poly_evals_evecs_axis[2]), # it's best to just use the axis and center, then recompute a bounding cylinder. if not chunk.atoms: return None axis = chunk.axis axis = norm(axis) # needed (unless we're sure it's already unit length, which is likely) center = chunk.center points = chunk.atpos - center # not sure if basepos points are already centered # compare following Numeric Python code to findAtomUnderMouse and its caller matrix = matrix_putting_axis_at_z(axis) v = dot( points, matrix) # compute xy distances-squared between axis line and atom centers r_xy_2 = v[:,0]**2 + v[:,1]**2 ## r_xy = sqrt(r_xy_2) # not needed # to get radius, take maximum -- not sure if max(r_xy_2) would use Numeric code, but this will for sure: i = argmax(r_xy_2) max_xy_2 = r_xy_2[i] radius = sqrt(max_xy_2) # to get limits along axis (since we won't assume center is centered between them), use min/max z: z = v[:,2] min_z = z[argmin(z)] max_z = z[argmax(z)] bcenter = chunk.abs_to_base(center) # return, in chunk-relative coords, end1, end2, and radius of the cylinder, and color. color = chunk.color if color is None: color = V(0.5,0.5,0.5) # make sure it's longer than zero (in case of a single-atom chunk); in fact, add a small margin all around # (note: this is not sufficient to enclose all atoms entirely; that's intentional) margin = 0.2 min_z -= margin max_z += margin radius += margin return (bcenter + min_z * axis, bcenter + max_z * axis, radius, color) pass # end of class CylinderChunks ChunkDisplayMode.register_display_mode_class(CylinderChunks) # end
NanoCAD-master
cad/src/graphics/display_styles/CylinderChunks.py
NanoCAD-master
cad/src/graphics/display_styles/__init__.py
# Copyright 2008-2009 Nanorex, Inc. See LICENSE file for details. """ ProteinChunks.py -- defines I{Reduced Protein} display modes. @author: Piotr @version: $Id$ @copyright: 2008-2009 Nanorex, Inc. See LICENSE file for details. History: piotr 080623: First preliminary version of the protein display style. piotr 080702: Implemented ribbons and cartoons. piotr 080709: Making the file compliant with a Protein class. piotr 080710: Minor fixes. piotr 080723: Improved rotamer rendering speed. piotr 080729: Code cleanup. piotr 080804: Further code cleanup, adding docstrings. piotr 080904: Added missing docstrings, prepared for review. """ import foundation.env as env from geometry.VQT import V, norm, cross from graphics.display_styles.displaymodes import ChunkDisplayMode from graphics.drawing.CS_draw_primitives import drawcylinder from graphics.drawing.CS_draw_primitives import drawpolycone_multicolor from graphics.drawing.CS_draw_primitives import drawsphere from graphics.drawing.CS_draw_primitives import drawline from graphics.drawing.CS_draw_primitives import drawtriangle_strip from Numeric import dot from OpenGL.GL import glMaterialfv from OpenGL.GL import GL_FRONT_AND_BACK from OpenGL.GL import GL_AMBIENT_AND_DIFFUSE from OpenGL.GL import glCallList from OpenGL.GL import glGenLists from OpenGL.GL import glNewList from OpenGL.GL import glEndList from OpenGL.GL import GL_COMPILE import colorsys from utilities.constants import blue, cyan, green, orange, red, white, gray from utilities.constants import yellow ##### TODO: FIX: The *_worker functions are an internal part of the drawing code # and should never be called directly from outside it. Doing so makes it # difficult to modify the drawing code internally. All calls herein to # drawsphere_worker or drawcylinder_worker should be replaced # with equivalent calls to drawsphere or drawcylinder (and then if # that's too much slower, those should be optimized in the drawing # code, not here). [bruce 090304 comment] from graphics.drawing.CS_workers import drawcylinder_worker from graphics.drawing.CS_workers import drawsphere_worker # Protein display style preferences from utilities.prefs_constants import proteinStyle_prefs_key from utilities.prefs_constants import proteinStyleColors_prefs_key from utilities.prefs_constants import proteinStyleQuality_prefs_key from utilities.prefs_constants import proteinStyleScaleFactor_prefs_key from utilities.prefs_constants import proteinStyleScaling_prefs_key from utilities.prefs_constants import proteinStyleHelixColor_prefs_key from utilities.prefs_constants import proteinStyleStrandColor_prefs_key from utilities.prefs_constants import proteinStyleCoilColor_prefs_key from utilities.prefs_constants import proteinStyleSmooth_prefs_key try: from OpenGL.GLE import gleSetJoinStyle from OpenGL.GLE import TUBE_NORM_PATH_EDGE from OpenGL.GLE import TUBE_JN_ANGLE from OpenGL.GLE import TUBE_CONTOUR_CLOSED from OpenGL.GLE import TUBE_JN_CAP except: print "Protein Chunks: GLE module can't be imported. Now trying _GLE" from OpenGL._GLE import gleSetJoinStyle from OpenGL._GLE import TUBE_NORM_PATH_EDGE from OpenGL._GLE import TUBE_JN_ANGLE from OpenGL._GLE import TUBE_CONTOUR_CLOSED from OpenGL._GLE import TUBE_JN_CAP # protein coloring styles PROTEIN_COLOR_SAME = -1 PROTEIN_COLOR_CHUNK = 0 PROTEIN_COLOR_CHAIN = 1 PROTEIN_COLOR_ORDER = 2 PROTEIN_COLOR_HYDROPATHY = 3 PROTEIN_COLOR_POLARITY = 4 PROTEIN_COLOR_ACIDITY = 5 PROTEIN_COLOR_SIZE = 6 PROTEIN_COLOR_CHARACTER = 7 PROTEIN_COLOR_NOC = 8 PROTEIN_COLOR_SECONDARY = 9 PROTEIN_COLOR_SS_ORDER = 10 PROTEIN_COLOR_BFACTOR = 11 PROTEIN_COLOR_OCCUPANCY = 12 PROTEIN_COLOR_ENERGY = 13 PROTEIN_COLOR_CUSTOM = 14 # protein display styles PROTEIN_STYLE_CA_WIRE = 1 PROTEIN_STYLE_CA_CYLINDER = 2 PROTEIN_STYLE_CA_BALL_STICK = 3 PROTEIN_STYLE_TUBE = 4 PROTEIN_STYLE_LADDER = 5 PROTEIN_STYLE_ZIGZAG = 6 PROTEIN_STYLE_FLAT_RIBBON = 7 PROTEIN_STYLE_SOLID_RIBBON = 8 PROTEIN_STYLE_SIMPLE_CARTOONS = 9 PROTEIN_STYLE_FANCY_CARTOONS = 10 PROTEIN_STYLE_PEPTIDE_TILES = 11 # I plan to change the following color schemes so they use less # intrusive colors (maybe just blue-to-white-to-red scale instad # of red-green-blue spectrum). piotr 080902 # coloring according to amino acid hydropathy scale (Kyte-Doolittle) AA_COLORS_HYDROPATHY = { "ALA" : orange, "ARG" : blue, "ASN" : blue, "ASP" : blue, "CYS" : orange, "GLN" : blue, "GLU" : blue, "GLY" : green, "HIS" : blue, "ILE" : red, "LEU" : red, "LYS" : blue, "MET" : orange, "PHE" : orange, "PRO" : cyan, "SER" : green, "THR" : green, "TRP" : green, "TYR" : cyan, "VAL" : red } # coloring according to amino acid polarity AA_COLORS_POLARITY = { "ALA" : red, "ARG" : green, "ASN" : green, "ASP" : green, "CYS" : green, "GLN" : green, "GLU" : green, "GLY" : red, "HIS" : green, "ILE" : red, "LEU" : red, "LYS" : green, "MET" : red, "PHE" : red, "PRO" : red, "SER" : green, "THR" : green, "TRP" : red, "TYR" : red, "VAL" : red } # coloring according to amino acid acidity AA_COLORS_ACIDITY = { "ALA" : green, "ARG" : blue, "ASN" : green, "ASP" : red, "CYS" : green, "GLN" : green, "GLU" : red, "GLY" : green, "HIS" : blue, "ILE" : green, "LEU" : green, "LYS" : blue, "MET" : green, "PHE" : green, "PRO" : green, "SER" : green, "THR" : green, "TRP" : green, "TYR" : green, "VAL" : green } def compute_spline(data, idx, t): """ Implements a Catmull-Rom spline. Interpolates between data[idx] and data[idx+1] using data[idx-1], data[idx], data[idx+1] and data[idx+2] points. @param data: list of data points to interpolate. it needs to have at least data points, otherwise will cause an exception @param idx: index of data points to be interpolated between @type idx: int @param t: interpolation ratio (0.0 <= t <= 1.0) @type t: float @note: this method is basically identical to the one in DnaCylinderChunks, so it should be splitted out from here and moved to another, more general file """ t2 = t*t t3 = t2*t x0 = data[idx-1] x1 = data[idx] x2 = data[idx+1] x3 = data[idx+2] res = 0.5 * ((2.0 * x1) + t * (-x0 + x2) + t2 * (2.0 * x0 - 5.0 * x1 + 4.0 * x2 - x3) + t3 * (-x0 + 3.0 * x1 - 3.0 * x2 + x3)) return res def make_tube(points, colors, radii, dpos, resolution=3): """ Converts a polycylinder tube into a smooth, curved tube using spline interpolation of points, colors and radii. If there is not enough data points, returns the original lists. Thus, it can be used in the following way: pos, col, rad, dpos = make_tube(pos, col, rad, dpos, resolution) Assumes that len(points) == len(colors) == len(radii) @param points: consecutive points to be interpolated @type points: list of V or list of float[3] @param colors: colors corresponding to the points @type colors: list of colors @param radii: radii correspoding to individual points @type radii: list of radii @param dpos: dpos vectors correspoding to individual points @type dpos: list of dpos vectors @param resolution: specifies a number of points intepolated in-between two consecutive input points @type resolution: integer @return: tuple of interpolated (points, colors, radii, dpos) """ n = len(points) if n > 3: new_points = [] new_colors = [] new_radii = [] new_dpos = [] o = 1 ir = 1.0/float(resolution) for p in range (1, n-2): start_spline = 0 end_spline = int(resolution) #@@@ if p == 1: start_spline = int(resolution / 2 - 1) if p == n-3: end_spline = int(resolution / 2 + 1) for m in range (start_spline, end_spline): t = ir * m sp = compute_spline(points, p, t) sc = compute_spline(colors, p, t) sr = compute_spline(radii, p, t) sd = compute_spline(dpos, p, t) new_points.append(sp) new_colors.append(sc) new_radii.append(sr) new_dpos.append(sd) t = ir * (m + 1) sp = compute_spline(points, p, t) sc = compute_spline(colors, p, t) sr = compute_spline(radii, p, t) sd = compute_spline(dpos, p, t) new_points.append(sp) new_colors.append(sc) new_radii.append(sr) new_dpos.append(sd) return (new_points, new_colors, new_radii, new_dpos) else: return (points, colors, radii, dpos) # These two methods are identical to these found in DnaCylinderChunks. def get_rainbow_color(hue, saturation, value): """ Gets a color of a hue range limited to 0 - 0.667 (red - blue) @param hue: color hue (0..1) @type hue: float @param saturation: color saturation (0..1) @type saturation: float @param value: color value (0..1) @type value: float @return: color for given (h,s,v) """ hue = 0.666 * (1.0 - hue) if hue < 0.0: hue = 0.0 if hue > 0.666: hue = 0.666 return colorsys.hsv_to_rgb(hue, saturation, value) def get_rainbow_color_in_range(pos, count, saturation, value): """ Gets a color of a hue range limited to 0 - 0.667 (red - blue color range) correspoding to a "pos" value from (0..count) range. @param pos: position in (0..count range) @type pos: integer @param count: limits the range of allowable values @type count: integer @param saturation: color saturation (0..1) @type saturation: float @param value: color value (0..1) @type value: float @return: color for given (pos, s, v) """ if count > 1: count -= 1 hue = float(pos)/float(count) if hue < 0.0: hue = 0.0 if hue > 1.0: hue = 1.0 return get_rainbow_color(hue, saturation, value) class ProteinChunks(ChunkDisplayMode): """ This class implements drawing of reduced representations of protein structures. General class structure is copied from DnaCylinderChunks.py """ # mmp_code must be a unique 3-letter code, distinct from the values in # constants.dispNames or in other display modes mmp_code = 'pro' disp_label = 'Protein' # label for statusbar fields, menu text, etc. featurename = "Set Display Protein" # Pretty sure Bruce's intention is to define icons for subclasses # of ChunkDisplayMode here, not in mticon_names[] and hideicon_names[] # in chunks.py. Ask him to be sure. Mark 2008-02-12 icon_name = "modeltree/Protein.png" hide_icon_name = "modeltree/Protein-hide.png" def _get_aa_color(self, chunk, pos, n_pos, sec, aa, c_sec, n_sec): """ Returns an amino acid color according to the current color mode. @param chunk: Protein chunk @type chunk: Chunk with protein attribute available @param pos: residue sequence position @type pos: int @param n_pos: length of the protein sequence @type n_pos: int @param sec: secondary structure type (SS_HELIX, SS_STRAND, or SS_COIL) @type sec: int @param aa: amino acid name (3-letter code) @type aa: string @param c_sec: index of secondary structure element @type c_sec: int @param n_sec: number of secondary structure elements @type n_sec: int @return: residue color according to curreny color mode, or gray if wrong parameters were specified """ color = gray if self.proteinStyleColors == PROTEIN_COLOR_ORDER: # Color according to order of amino acids. color = get_rainbow_color_in_range(pos, n_pos, 1.0, 1.0) elif self.proteinStyleColors == PROTEIN_COLOR_CHUNK: # Assign chunk color if chunk.color: color = chunk.color pass elif self.proteinStyleColors == PROTEIN_COLOR_POLARITY: # Color according to amino acid polarity. if aa in AA_COLORS_POLARITY: color = AA_COLORS_POLARITY[aa] elif self.proteinStyleColors == PROTEIN_COLOR_ACIDITY: # Color according to amino acid acidity. if aa in AA_COLORS_ACIDITY: color = AA_COLORS_ACIDITY[aa] elif self.proteinStyleColors == PROTEIN_COLOR_HYDROPATHY: # Color according to amino acid hydropathy index. if aa in AA_COLORS_HYDROPATHY: color = AA_COLORS_HYDROPATHY[aa] elif self.proteinStyleColors == PROTEIN_COLOR_SECONDARY: # Color according to protein secondary structure. if sec == 1: color = self.proteinStyleHelixColor elif sec == 2: color = self.proteinStyleStrandColor else: color = self.proteinStyleCoilColor elif self.proteinStyleColors == PROTEIN_COLOR_SS_ORDER: # Color according to the order of secondary structure elements. if sec > 0: color = get_rainbow_color_in_range(c_sec, n_sec-1, 1.0, 1.0) else: color = self.proteinStyleCoilColor return color def drawchunk(self, glpane, chunk, memo, highlighted): """ Draws a reduced representation of a protein chunk. This method is called per chunk, but in fact it draws individual secondary structure elements, i.e. consecutive part of the protein chain composed of a single type of secondary structure. """ # Note: If the protein model is going to be re-factored in the future # so that every individual chunk corresponds to a single, homogenoeous # secondary structure element, this method could be used without # much changes. # Retrieve parameters from memo structure, total_length, ca_list, n_sec = memo # Get display style settings style = self.proteinStyle scaleFactor = self.proteinStyleScaleFactor resolution = self.proteinStyleQuality scaling = self.proteinStyleScaling smooth = self.proteinStyleSmooth # Set nice joint style for gle Polycone primitives. gleSetJoinStyle(TUBE_JN_ANGLE | TUBE_NORM_PATH_EDGE \ | TUBE_JN_CAP | TUBE_CONTOUR_CLOSED ) # Iterate over consecutive secondary structure elements. current_sec = 0 for sec, secondary in structure: # Number of atoms in SS element including dummy atoms. n_atoms = len(sec) # The length should be at least 3. if n_atoms >= 3: # Alpha carbon trace styles. Simple but fast. # Use either lines or cylinder to connect consecutive alpha carbons. if style == PROTEIN_STYLE_CA_WIRE or \ style == PROTEIN_STYLE_CA_CYLINDER or \ style == PROTEIN_STYLE_CA_BALL_STICK: for n in range( 1, n_atoms-1 ): pos0, ss0, aa0, idx0, dpos0, cbpos0 = sec[n - 1] pos1, ss1, aa1, idx1, dpos1, cbpos1 = sec[n] pos2, ss2, aa2, idx2, dpos2, cbpos2 = sec[n + 1] color = self._get_aa_color(chunk, idx1, total_length, ss1, aa1, current_sec, n_sec) if style == PROTEIN_STYLE_CA_WIRE: # Wire - use line. if pos0: drawline(color, pos1 + 0.5 * (pos0 - pos1), pos1, width=5, isSmooth=True) if pos2: drawline(color, pos1, pos1 + 0.5 * (pos2 - pos1), width=5, isSmooth=True) else: # Cylinder and B&S - use cylinders. if pos0: drawcylinder(color, pos1 + 0.5 * (pos0 - pos1), pos1, 0.25 * scaleFactor, capped=1) if style == PROTEIN_STYLE_CA_BALL_STICK: drawsphere(color, pos1, 0.5 * scaleFactor, 2) else: drawsphere(color, pos1, 0.25 * scaleFactor, 2) if pos2: drawcylinder(color, pos1, pos1 + 0.5 * (pos2 - pos1), 0.25 * scaleFactor, capped=1) elif style == PROTEIN_STYLE_PEPTIDE_TILES: # Peptide tiles: not implemented yet. # piotr 080903: this option should be removed # from Protein Display Style PM. """ for n in range( 1, n_atoms-2 ): pos0, ss0, aa0, idx0, dpos0, cbpos0 = sec[n - 1] pos1, ss1, aa1, idx1, dpos1, cbpos1 = sec[n] color = self._get_aa_color(chunk, idx1, total_length, ss1, aa1, current_sec, n_sec) tri = [] nor = [] col = [] """ elif style == PROTEIN_STYLE_TUBE or \ style == PROTEIN_STYLE_LADDER or \ style == PROTEIN_STYLE_ZIGZAG or \ style == PROTEIN_STYLE_FLAT_RIBBON or \ style == PROTEIN_STYLE_SOLID_RIBBON or \ style == PROTEIN_STYLE_SIMPLE_CARTOONS or \ style == PROTEIN_STYLE_FANCY_CARTOONS: # All of these styles use the same interpolated cubic spline # that connects alpha carbon atoms. # The following lists store positions, colors, radii and # peptide bond vectors for consecutive main chain # positions. tube_pos = [] tube_col = [] tube_rad = [] tube_dpos = [] # Fill-in the position, color, radius and peptide position # lists. for n in range( 2, n_atoms-2 ): pos00, ss00, a00, idx00, dpos00, cbpos00 = sec[n - 2] pos0, ss0, aa0, idx0, dpos0, cbpos0 = sec[n - 1] pos1, ss1, aa1, idx1, dpos1, cbpos1 = sec[n] pos2, ss2, aa2, idx2, dpos2, cbpos2 = sec[n + 1] pos22, ss22, aa22, idx22, dpos22, cbpos22 = sec[n + 2] color = self._get_aa_color(chunk, idx1, total_length, ss1, aa1, current_sec, n_sec) rad = 0.25 * scaleFactor if style == PROTEIN_STYLE_TUBE and \ scaling == 1: if secondary > 0: rad *= 2.0 if n == 2: if pos0: tube_pos.append(pos00) tube_col.append(V(color)) tube_rad.append(rad) tube_dpos.append(dpos1) tube_pos.append(pos0) tube_col.append(V(color)) tube_rad.append(rad) tube_dpos.append(dpos1) if style == PROTEIN_STYLE_LADDER: drawcylinder(color, pos1, cbpos1, rad * 0.75) drawsphere(color, cbpos1, rad * 1.5, 2) if pos1: tube_pos.append(pos1) tube_col.append(V(color)) tube_rad.append(rad) tube_dpos.append(dpos1) if n == n_atoms - 3: if pos2: tube_pos.append(pos2) tube_col.append(V(color)) tube_rad.append(rad) tube_dpos.append(dpos1) tube_pos.append(pos22) tube_col.append(V(color)) tube_rad.append(rad) tube_dpos.append(dpos1) # For smoothed helices we need to add virtual atoms # located approximately at the centers of peptide bonds # but slightly moved away from the helix axis. new_tube_pos = [] new_tube_col = [] new_tube_rad = [] new_tube_dpos = [] if smooth and \ secondary == 1: for p in range(len(tube_pos)): new_tube_pos.append(tube_pos[p]) new_tube_col.append(tube_col[p]) new_tube_rad.append(tube_rad[p]) new_tube_dpos.append(tube_dpos[p]) if p > 1 and p < len(tube_pos) - 3: pv = tube_pos[p-1] - tube_pos[p] nv = tube_pos[p+2] - tube_pos[p+1] mi = 0.5 * (tube_pos[p+1] + tube_pos[p]) # The coefficient below was handpicked to make # the helices approximately round. mi -= 0.75 * norm(nv+pv) new_tube_pos.append(mi) new_tube_col.append(0.5*(tube_col[p]+tube_col[p+1])) new_tube_rad.append(0.5*(tube_rad[p]+tube_rad[p+1])) new_tube_dpos.append(0.5*(tube_dpos[p]+tube_dpos[p+1])) tube_pos = new_tube_pos tube_col = new_tube_col tube_rad = new_tube_rad tube_dpos = new_tube_dpos if secondary != 1 or \ style != PROTEIN_STYLE_SIMPLE_CARTOONS: tube_pos, tube_col, tube_rad, tube_dpos = make_tube( tube_pos, tube_col, tube_rad, tube_dpos, resolution=resolution) if style == PROTEIN_STYLE_ZIGZAG or \ style == PROTEIN_STYLE_FLAT_RIBBON or \ style == PROTEIN_STYLE_SOLID_RIBBON or \ style == PROTEIN_STYLE_SIMPLE_CARTOONS or \ style == PROTEIN_STYLE_FANCY_CARTOONS: last_pos = None last_width = 1.0 reset = False # Find SS element widths and determine width increment. if secondary == 0: # Coils have a constant width. width = scaleFactor * 0.1 dw = 0.0 elif secondary == 1: # Helices expand and shrink at the ends. width = scaleFactor * 0.1 dw = (1.0 * scaleFactor) / (resolution - 3) else: # Strands just shrink at the C-terminal end. width = scaleFactor * 1.0 dw = (1.5 * scaleFactor) / ((1.5 * resolution) - 3) if style == PROTEIN_STYLE_FLAT_RIBBON or \ style == PROTEIN_STYLE_SOLID_RIBBON or \ style == PROTEIN_STYLE_SIMPLE_CARTOONS or \ style == PROTEIN_STYLE_FANCY_CARTOONS: tri_arr0 = [] nor_arr0 = [] col_arr0 = [] if style == PROTEIN_STYLE_SOLID_RIBBON or \ style == PROTEIN_STYLE_SIMPLE_CARTOONS or \ style == PROTEIN_STYLE_FANCY_CARTOONS: tri_arr1 = [] nor_arr1 = [] col_arr1 = [] tri_arr2 = [] nor_arr2 = [] col_arr2 = [] tri_arr3 = [] nor_arr3 = [] col_arr3 = [] # This should be done faster... are individual # copies of the tube positions really necessary? ###from copy import copy ###new_tube_dpos = [dpos for dpos in tube_dpos] # Auxiliary tube positions for FANCY_CARTOON helices. tube_pos_left = [tube_pos[0]] tube_pos_right = [tube_pos[0]] for n in range(1, len(tube_pos)-1): pos = tube_pos[n] col = tube_col[n][0] col2 = tube_col[n+1][0] if last_pos: next_pos = tube_pos[n+1] dpos1 = last_width * tube_dpos[n-1] dpos2 = width * tube_dpos[n] ddpos = dpos1-dpos2 if reset: dpos1 = dpos2 reset = False if self.proteinStyle == PROTEIN_STYLE_ZIGZAG: # The line calls below draw an outline # of ribbon triangles. drawline(col, last_pos-dpos1, pos-dpos2, width=3) drawline(col, last_pos+dpos1, pos+dpos2, width=3) drawline(col, last_pos-dpos1, pos+dpos2, width=1) drawline(col, pos-dpos2, pos+dpos2, width=1) drawline(col, last_pos-dpos1, last_pos+dpos1, width=1) if self.proteinStyle == PROTEIN_STYLE_FLAT_RIBBON: # Flat ribbon only draws a single # layer of triangles. if pos != last_pos: nvec1 = norm(cross(dpos1, pos-last_pos)) if next_pos != pos: nvec2 = norm(cross(dpos2, next_pos-pos)) else: nvec2 = nvec1 nor_arr0.append(nvec1) nor_arr0.append(nvec1) nor_arr0.append(nvec2) nor_arr0.append(nvec2) tri_arr0.append(last_pos-dpos1) tri_arr0.append(last_pos+dpos1) tri_arr0.append(pos-dpos2) tri_arr0.append(pos+dpos2) col_arr0.append(col) col_arr0.append(col) col_arr0.append(col2) col_arr0.append(col2) if self.proteinStyle == PROTEIN_STYLE_SOLID_RIBBON or \ self.proteinStyle == PROTEIN_STYLE_SIMPLE_CARTOONS or \ self.proteinStyle == PROTEIN_STYLE_FANCY_CARTOONS: # These three styles are similar. # The difference between "solid ribbon" # and "fancy cartoons" is that the # cartoons mode uses rounded edges # on helices, while solid ribbon uses # just a flat edge. The difference between # simple cartoons and fancy cartoons or # solid ribbon is that the simple cartoons # mode use simple straight cylinders to # represent alpha helices. if secondary > 0: # Prepare triangle strips positioned # along interpolated curve connecting # consecutive alpha carbon atoms col3 = col4 = V(gray) if pos != last_pos: nvec1 = norm(cross(dpos1, pos-last_pos)) if next_pos != pos: nvec2 = norm(cross(dpos2, next_pos-pos)) else: nvec2 = nvec1 nor_arr0.append(nvec1) nor_arr0.append(nvec1) nor_arr0.append(nvec2) nor_arr0.append(nvec2) if self.proteinStyle == PROTEIN_STYLE_FANCY_CARTOONS: dn1 = 0.15 * nvec1 * scaleFactor dn2 = 0.15 * nvec2 * scaleFactor else: dn1 = 0.15 * nvec1 * scaleFactor dn2 = 0.15 * nvec2 * scaleFactor tri_arr0.append(last_pos - dpos1 - dn1) tri_arr0.append(last_pos + dpos1 - dn1) tri_arr0.append(pos - dpos2 - dn2) tri_arr0.append(pos + dpos2 - dn2) tube_pos_left.append(last_pos - dpos1) tube_pos_right.append(last_pos + dpos1) col_arr0.append(col) col_arr0.append(col) col_arr0.append(col2) col_arr0.append(col2) nor_arr1.append(nvec1) nor_arr1.append(nvec1) nor_arr1.append(nvec2) nor_arr1.append(nvec2) tri_arr1.append(last_pos - dpos1 + dn1) tri_arr1.append(last_pos + dpos1 + dn1) tri_arr1.append(pos - dpos2 + dn2) tri_arr1.append(pos + dpos2 + dn2) if secondary == 1: col_arr1.append( 0.5 * col + 0.5 * V(white)) col_arr1.append( 0.5 * col + 0.5 * V(white)) col_arr1.append( 0.5 * col2 + 0.5 * V(white)) col_arr1.append( 0.5 * col2 + 0.5 * V(white)) else: col_arr1.append(col) col_arr1.append(col) col_arr1.append(col2) col_arr1.append(col2) nor_arr2.append(-dpos1) nor_arr2.append(-dpos1) nor_arr2.append(-dpos2) nor_arr2.append(-dpos2) tri_arr2.append(last_pos - dpos1 - dn1) tri_arr2.append(last_pos - dpos1 + dn1) tri_arr2.append(pos - dpos2 - dn2) tri_arr2.append(pos - dpos2 + dn2) col_arr2.append(col3) col_arr2.append(col3) col_arr2.append(col4) col_arr2.append(col4) nor_arr3.append(-dpos1) nor_arr3.append(-dpos1) nor_arr3.append(-dpos2) nor_arr3.append(-dpos2) tri_arr3.append(last_pos + dpos1 - dn1) tri_arr3.append(last_pos + dpos1 + dn1) tri_arr3.append(pos + dpos2 - dn2) tri_arr3.append(pos + dpos2 + dn2) col_arr3.append(col3) col_arr3.append(col3) col_arr3.append(col4) col_arr3.append(col4) last_pos = pos last_width = width if secondary == 1: if n > len(tube_pos) - resolution: width -= dw elif width < 1.0 * scaleFactor: width += dw if secondary == 2: if n == len(tube_pos) - 1.5 * resolution: width = scaleFactor * 1.6 reset = True if n > len(tube_pos) - 1.5 * resolution: width -= dw ###new_tube_dpos[n] = dpos1 # Append dummy positions at both ends for # GLE polycone rendering. tube_pos_left.append(tube_pos[-2]) tube_pos_right.append(tube_pos[-2]) tube_pos_left.append(tube_pos[-1]) tube_pos_right.append(tube_pos[-1]) if self.proteinStyle == PROTEIN_STYLE_FLAT_RIBBON: # Note: the "-2" opacity component in the color list # tells the ColorSorter that this is a multi color # object and "color material" should be enabled # while rendering it. drawtriangle_strip( [1.0,1.0,0.0,-2.0], tri_arr0, nor_arr0, col_arr0) if self.proteinStyle == PROTEIN_STYLE_SOLID_RIBBON or \ self.proteinStyle == PROTEIN_STYLE_SIMPLE_CARTOONS or \ self.proteinStyle == PROTEIN_STYLE_FANCY_CARTOONS: if secondary == 0: drawpolycone_multicolor( [0,0,0,-2], tube_pos, tube_col, tube_rad) else: if (secondary == 1 and self.proteinStyle == PROTEIN_STYLE_SOLID_RIBBON) or \ secondary == 2: drawtriangle_strip( [1.0,1.0,0.0,-2.0], tri_arr0, nor_arr0, col_arr0) drawtriangle_strip( [1.0,1.0,0.0,-2.0], tri_arr1, nor_arr1, col_arr1) drawtriangle_strip( [1.0,1.0,0.0,-2.0], tri_arr2, nor_arr2, col_arr2) drawtriangle_strip([1.0,1.0,0.0,-2.0], tri_arr3, nor_arr3, col_arr3) # Fill in the strand N-terminal end. quad_tri = [] quad_nor = [] quad_col = [] quad_tri.append(tri_arr2[0]) quad_tri.append(tri_arr3[0]) quad_tri.append(tri_arr2[1]) quad_tri.append(tri_arr3[1]) quad_nor.append(nor_arr2[0]) quad_nor.append(nor_arr3[0]) quad_nor.append(nor_arr2[1]) quad_nor.append(nor_arr3[1]) quad_col.append(col_arr2[0]) quad_col.append(col_arr3[0]) quad_col.append(col_arr2[1]) quad_col.append(col_arr3[1]) drawtriangle_strip( [1.0,1.0,1.0,-2.0], quad_tri, quad_nor,quad_col) if (secondary == 1 and self.proteinStyle == PROTEIN_STYLE_FANCY_CARTOONS): # Draw smooth tubes at the edges of the # helices. drawtriangle_strip( [1.0,1.0,0.0,-2.0], tri_arr0, nor_arr0, col_arr0) drawtriangle_strip([ 1.0,1.0,0.0,-2.0], tri_arr1, nor_arr1, col_arr1) drawpolycone_multicolor( [0,0,0,-2], tube_pos_left, tube_col, tube_rad) drawpolycone_multicolor( [0,0,0,-2], tube_pos_right, tube_col, tube_rad) if (secondary == 1 and style == PROTEIN_STYLE_SIMPLE_CARTOONS): drawcylinder(tube_col[0][0], tube_pos[1], tube_pos[-3], 2.5, capped=1) if style == PROTEIN_STYLE_LADDER or \ style == PROTEIN_STYLE_TUBE: # Draw a smooth tube connecting alpha carbon positions. drawpolycone_multicolor([0,0,0,-2], tube_pos, tube_col, tube_rad) # Increase secondary structure element counter (for coloring # by "secondary structure elements order"). current_sec += 1 def drawchunk_selection_frame(self, glpane, chunk, selection_frame_color, memo, highlighted): """ Given the same arguments as drawchunk, plus selection_frame_color, draw the chunk's selection frame. (Drawing the chunk itself as well would not cause drawing errors but would presumably be a highly undesirable slowdown, especially if redrawing after selection and deselection is optimized to not have to redraw the chunk at all.) @note: in the initial implementation of the code that calls this method, the highlighted argument might be false whether or not we're actually hover-highlighted. And if that's fixed, then just as for drawchunk, we might be called twice when we're highlighted, once with highlighted = False and then later with highlighted = True. This method seems to be obsolete. piotr 080803 """ self.drawchunk(self, glpane, chunk, selection_frame_color, memo, highlighted) return def drawchunk_realtime(self, glpane, chunk, highlighted=False): """ Draws protein rotamers. This is a hack for having atomistic and reduced models displayed simultenaously. This method creates its own display list to store "expanded" rotamers drawn as tubes. Different colors can be assigned to individual rotamers. piotr 080801: Backbone atoms are omitted. """ # Draw rotamers using a display list. Create it if necessary. # Note: the only command that uses this feature is Edit # Rotamers. The purpose of this feature is to have # an atomistic-like display style on top of a reduced # representation. # Note: this implementation may have bugs. The major problem # is that the display list is never explicitly deleted, # so using this feature may introduce memory leaks (I am # not sure about that). # The rotamer is rendered using a style resembling "Tubes". if chunk.protein: if highlighted: # If highlighhting, just draw everything without using # the display list. color = yellow aa_list = chunk.protein.get_amino_acids() glMaterialfv( GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, color[:3]) for aa in aa_list: if chunk.protein.is_expanded(aa): aa_atom_list = aa.get_side_chain_atom_list() for atom in aa_atom_list: pos1 = atom.posn() drawsphere_worker((pos1, 0.2, 1, 1)) for bond in atom.bonds: if atom == bond.atom1: if bond.atom2 in aa_atom_list: pos2 = bond.atom2.posn() drawcylinder_worker(( pos1, pos1 + 0.5*(pos2 - pos1), 0.2, True)) else: if bond.atom1 in aa_atom_list: pos2 = bond.atom1.posn() drawcylinder_worker(( pos1, pos1 + 0.5*(pos2 - pos1), 0.2, True)) else: """ from PyQt4.Qt import QFont, QString, QColor, QFontMetrics labelFont = QFont( QString("Lucida Grande"), 16) fm = QFontMetrics(labelFont) """ if not chunk.protein.residues_dl: # Create a new residues display list if one is not present. chunk.protein.residues_dl = glGenLists(1) glNewList(chunk.protein.residues_dl, GL_COMPILE) aa_list = chunk.protein.get_amino_acids() for aa in aa_list: # Iterate over amino acids and check if any rotamer # is in 'expanded' state. if chunk.protein.is_expanded(aa): aa_atom_list = aa.get_side_chain_atom_list() for atom in aa_atom_list: pos1 = chunk.abs_to_base(atom.posn()) if aa.color: color = aa.color else: color = atom.drawing_color() glMaterialfv( GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, color[:3]) ##### TODO: FIX: The *_worker functions should never be # called directly from outside the drawing code. See longer # comment where they are imported. [bruce 090304 comment] drawsphere_worker((pos1, 0.2, 1, 1)) ### _name = aa.get_atom_name(atom) ### textpos = chunk.abs_to_base(atom.posn()) + 2.0 * glpane.out ### glColor3f(1,1,1) ### chunk.glpane.renderText(textpos[0], textpos[1], textpos[2], _name, labelFont) # Draw bonds for bond in atom.bonds: if bond.atom2 in aa_atom_list: if atom == bond.atom1: if bond.atom2 in aa_atom_list: pos2 = chunk.abs_to_base( bond.atom2.posn()) drawcylinder_worker(( pos1, pos1 + 0.5*(pos2 - pos1), 0.2, True)) else: if bond.atom1 in aa_atom_list: pos2 = chunk.abs_to_base( bond.atom1.posn()) drawcylinder_worker(( pos1, pos1 + 0.5*(pos2 - pos1), 0.2, True)) glEndList() # Call the residues display list glCallList(chunk.protein.residues_dl) return def writepov(self, chunk, memo, file): """ Renders the chunk to a POV-Ray file. Not implemented yet. """ return def compute_memo(self, chunk): """ If drawing chunks in this display mode can be optimized by precomputing some info from chunk's appearance, compute that info and return it. If this computation requires preference values, access them as env.prefs[key], and that will cause the memo to be removed (invalidated) when that preference value is changed by the user. This computation is assumed to also depend on, and only on, chunk's appearance in ordinary display modes (i.e. it's invalidated whenever havelist is). There is not yet any way to change that, so bugs will occur if any ordinarily invisible chunk info affects this rendering, and potential optimizations will not be done if any ordinarily visible info is not visible in this rendering. These can be fixed if necessary by having the real work done within class Chunk's _recompute_ rules, with this function or drawchunk just accessing the result of that (and sometimes causing its recomputation), and with whatever invalidation is needed being added to appropriate setter methods of class Chunk. If the real work can depend on more than chunk's ordinary appearance can, the access would need to be in drawchunk; otherwise it could be in drawchunk or in this method compute_memo(). @param chunk: The chunk. @type chunk: chunk """ def _get_ss(aa): """ Returns secondary structure for a residue, or SS_COIL if aa is None @param aa: amino acid @type aa: Residue """ if aa: return aa.get_secondary_structure() return SS_COIL # BUG: Undefined variable def _get_aa(aa): """ Returns a three-letter amino acid code for a residue, or "UNK" if aa is None. @param aa: amino acid @type aa: Residue """ if aa: return aa.get_three_letter_code() return "UNK" # Return None if the chunk is None if chunk is None: return None # Return None if the chunk is not a protein. if chunk.protein is None: return None # List of secondary structure elements structure = [] # Retrieve protein style properties from user preferences. self.proteinStyle = env.prefs[proteinStyle_prefs_key] + 1 self.proteinStyleSmooth = env.prefs[proteinStyleSmooth_prefs_key] self.proteinStyleQuality = 2 * env.prefs[proteinStyleQuality_prefs_key] self.proteinStyleScaling = env.prefs[proteinStyleScaling_prefs_key] self.proteinStyleScaleFactor = env.prefs[proteinStyleScaleFactor_prefs_key] self.proteinStyleColors = env.prefs[proteinStyleColors_prefs_key] self.proteinStyleAuxColors = 0 self.proteinStyleCustomColor = gray self.proteinStyleAuxCustomColor = gray self.proteinStyleColorsDiscrete = False self.proteinStyleHelixColor = env.prefs[proteinStyleHelixColor_prefs_key] self.proteinStyleStrandColor = env.prefs[proteinStyleStrandColor_prefs_key] self.proteinStyleCoilColor = env.prefs[proteinStyleCoilColor_prefs_key] # Extract secondary structure elements # Every element is a list of consecutive C-alpha atoms of the same # secondary structure conformation. The list also includes # two "dummy" atoms - either preceding and following residues, or # pre-computed dummy atoms extensions. # Empty SS element. sec = [] # Extract a list of alpha carbon atoms and corresponding C-O vectors. # The C-O vectors are rotated to avoid sudden orientation changes. ca_list = [] # "dpos" in the ProteinChunk code corresponds to a vector perpendicular # to Ca-Ca vector and laying in a peptide plane. Roughly, this vector # corresponds to a normalized C=O bond of a peptide carbonyl. # "dpos" vectors can be flipped so the angle between consecutive # "dpos" vectors is less than 90 degree to avoid visual problems. # dictionary of corresponding Ca-Cb atoms for rendering of the # "Ladder" style. ca_cb = {} n_ca = 0 last_c_atom = None last_o_atom = None last_dpos = None last_ca_atom = None # Calculate "dpos" vectors paralles to the peptide planes. for aa in chunk.protein.get_amino_acids(): last_c_atom = aa.get_c_atom() last_o_atom = aa.get_o_atom() last_cb_atom = aa.get_c_beta_atom() ca_atom = aa.get_c_alpha_atom() if ca_atom: dpos = None if last_o_atom and last_c_atom: dpos = norm(last_o_atom.posn() - last_c_atom.posn()) if last_dpos: dca = ca_atom.posn() - last_ca_atom.posn() npep = cross(dca, dpos) # normal to the peptide plane dpos = norm(cross(npep, dca)) n0 = last_dpos n1 = dpos d = dot(n0, n1) # Flip dpos if the angle between consecutive planes # is > 90 deg. if d < 0.0: dpos = -1.0 * dpos last_dpos = dpos ca_list.append((ca_atom, chunk.abs_to_base(ca_atom.posn()), _get_ss(aa), _get_aa(aa), dpos)) last_ca_atom = ca_atom n_ca += 1 if last_cb_atom: ca_cb[ca_atom] = chunk.abs_to_base(last_cb_atom.posn()) elif last_ca_atom: ca_cb[ca_atom] = chunk.abs_to_base(last_ca_atom.posn()) for p in range(len(ca_list)-1): atom, pos, ss, aa, dpos = ca_list[p] if dpos == None: atom2, pos2, ss2, aa2, dpos2 = ca_list[p+1] ca_list[p] = (atom, pos, ss, aa, dpos2) anum = 0 # Smoothing alpha-helices and beta-strands. The consecutive "dpos" # vectors are smoothed using a sliding windows and weighted average. # Beta-strands use longer averaging window than alpha-helices. if self.proteinStyleSmooth and \ (self.proteinStyle == PROTEIN_STYLE_TUBE or self.proteinStyle == PROTEIN_STYLE_LADDER or self.proteinStyle == PROTEIN_STYLE_ZIGZAG or self.proteinStyle == PROTEIN_STYLE_FLAT_RIBBON or self.proteinStyle == PROTEIN_STYLE_SOLID_RIBBON or \ self.proteinStyle == PROTEIN_STYLE_SIMPLE_CARTOONS or \ self.proteinStyle == PROTEIN_STYLE_FANCY_CARTOONS): smooth_list = [] for i in range(len(ca_list)): if i > 0: prev_ca, prev_ca_pos, prev_ss, prev_aa, prev_dpos = ca_list[i - 1] else: prev_ca = None prev_ca_pos = None prev_ss = 0 prev_aa = None prev_dpos = None ca, ca_pos, ss, aa, dpos = ca_list[i] if i < n_ca - 1: next_ca, next_ca_pos, next_ss, next_aa, next_dpos = ca_list[i + 1] else: next_ca = None next_ca_pos = None next_ss = 0 next_aa = None next_dpos = None if (ss == 1 or prev_ss == 1 or next_ss == 1) and prev_ca and next_ca: if prev_dpos and next_dpos: dpos = norm(prev_dpos + dpos + next_dpos) smooth_list.append((ca, ca_pos, ss, aa, dpos, i)) if (ss == 2 or prev_ss == 2 or next_ss == 2) and prev_ca and next_ca: ca_pos = 0.5 * (0.5 * (prev_ca_pos + next_ca_pos) + ca_pos) if next_ss == 2 and prev_ss == 2: dpos = norm(prev_dpos + dpos + next_dpos) smooth_list.append((ca, ca_pos, ss, aa, dpos, i)) for ca, ca_pos, ss, aa, dpos, i in smooth_list: ca_list[i] = (ca, ca_pos, ss, aa, dpos) # Build the list of secondary structure elements. n_sec = 0 for i in range( n_ca ): ca, ca_pos, ss, aa, dpos = ca_list[i] if i > 0: prev_ca, prev_ca_pos, prev_ss, prev_aa, prev_dpos = ca_list[i - 1] else: prev_ca = ca prev_ca_pos = ca_pos prev_ss = ss prev_aa = aa prev_dpos = dpos if i > 1: prev2_ca, prev2_ca_pos, prev2_ss, prev2_aa, prev2_dpos = ca_list[i - 2] else: prev2_ca = prev_ca prev2_ca_pos = prev_ca_pos prev2_ss = prev_ss prev2_aa = prev_aa prev2_dpos = prev_dpos if len(sec) == 0: sec.append((prev2_ca_pos, prev2_ss, prev2_aa, i - 2, prev2_dpos, ca_cb[prev2_ca])) sec.append((prev_ca_pos, prev_ss, prev_aa, i - 1, prev_dpos, ca_cb[prev_ca])) sec.append((ca_pos, ss, aa, i, dpos, ca_cb[ca])) if i < n_ca - 1: next_ca, next_ca_pos, next_ss, next_aa, next_dpos = ca_list[i + 1] else: next_ca = ca next_ca_pos = ca_pos next_ss = ss next_aa = aa next_dpos = dpos if next_ss != ss or i == n_ca-1: if i < n_ca - 2: next2_ca, next2_ca_pos, next2_ss, next2_aa, next2_dpos = ca_list[i + 2] else: next2_ca = next_ca next2_ca_pos = next_ca_pos next2_ss = next_ss next2_aa = next_aa next2_dpos = next_dpos # Preasumably, the sec list includes all atoms # inside a continuous secondary structure chain fragment # (ss element) and FOUR dummy atom positions (two at # each of both terminals). # The dummy atom positions can't be None and therefore # the spline interpolator has to compute fake positions # of the terminal atoms. sec.append((next_ca_pos, next_ss, next_aa, i + 1, dpos, ca_cb[next_ca])) sec.append((next2_ca_pos, next2_ss, next2_aa, i + 2, dpos, ca_cb[next2_ca])) # Fix the endings. pos1, ss1, aa1, idx1, dpos1, cbpos1 = sec[1] pos2, ss2, aa2, idx2, dpos2, cbpos2 = sec[2] pos3, ss3, aa3, idx3, dpos3, cbpos3 = sec[3] ### pos4, ss4, aa4, idx4, dpos4, cbpos4 = sec[4] if pos1 == pos2: pos1 = pos1 - (pos3 - pos2) sec[1] = (pos1, ss1, aa1, idx1, dpos1, cbpos1) pos1, ss1, aa1, idx1, dpos1, cbpos1 = sec[-2] pos2, ss2, aa2, idx2, dpos2, cbpos2 = sec[-3] pos3, ss3, aa3, idx3, dpos3, cbpos3 = sec[-4] ### pos4, ss4, aa4, idx4, dpos4, cbpos4 = sec[-5] if pos1 == pos2: pos1 = pos1 - (pos3 - pos2) sec[-2] = (pos1, ss1, aa1, idx1, dpos1, cbpos1) # Make sure that the interior surface of helices # is properly oriented. This is important for "Fancy Cartoons" # display style. if ss == 1: pos2, ss2, aa2, idx2, dpos2, cbpos2 = sec[2] pos3, ss3, aa3, idx3, dpos3, cbpos3 = sec[3] pos4, ss4, aa4, idx4, dpos4, cbpos4 = sec[4] xvec = cross(pos4-pos3, pos3-pos2) sign = dot(xvec, dpos3) if sign > 0: # Wrong helix face orientation, invert peptide plates for n in range(2, len(sec)-2): (pos1, ss1, aa1, idx1, dpos1, cbpos1) = sec[n] dpos1 *= -1 sec[n] = (pos1, ss1, aa1, idx1, dpos1, cbpos1) pass # Append the secondary structure element. structure.append((sec, ss)) n_sec += 1 sec = [] return (structure, n_ca, ca_list, n_sec) ChunkDisplayMode.register_display_mode_class(ProteinChunks)
NanoCAD-master
cad/src/graphics/display_styles/ProteinChunks.py
# Copyright 2008-2009 Nanorex, Inc. See LICENSE file for details. """ DnaCylinderChunks.py -- defines I{DNA Cylinder} display mode, which draws axis chunks as a cylinder in the chunk's color. @author: Mark, Piotr @version: $Id$ @copyright: 2008-2009 Nanorex, Inc. See LICENSE file for details. History: Mark 2008-02-12: Created by making a copy of CylinderChunks.py piotr 080310: I have rewritten most of the code here from scratch. Most of the code computed within this function has to be moved to "getmemo" for a speed optimization. There are several issues with this rendering code, including lack of highlighting and selection support, and some weird behavior when modeltree is used to select individual strands. The DNA display style requires DNA updater to be enabled. There are four independent structures within the DNA display style: axis, strands, struts and bases. Properties of these parts can be set in the User Preferences dialog. piotr 080317: Added POV-Ray rendering routines. piotr 080318: Moved most of the data generation code to "getmemo" Highlighting and selection now works. Thank you, Ninad!!! ("rainbow" strands still can't be selected nor highlighted, this will be fixed later) piotr 080328: Added several "interactive" features: labels, base orientation indicators, "2D" style. piotr 080509: Code refactoring. piotr 080520: Further code cleanup.. """ import sys import foundation.env as env from graphics.drawing.CS_draw_primitives import drawcylinder from graphics.drawing.CS_draw_primitives import drawpolycone from graphics.drawing.CS_draw_primitives import drawpolycone_multicolor from graphics.drawing.CS_draw_primitives import drawsphere from graphics.drawing.drawers import drawCircle from graphics.drawing.drawers import drawFilledCircle from graphics.drawing.drawers import drawtext from math import sin, cos, pi from Numeric import dot, argmax, argmin, sqrt from graphics.display_styles.displaymodes import ChunkDisplayMode from geometry.VQT import V, Q, norm, cross, angleBetween from utilities.debug import print_compact_traceback from utilities.debug_prefs import debug_pref, Choice, Choice_boolean_True, Choice_boolean_False from utilities.prefs_constants import hoverHighlightingColor_prefs_key from utilities.prefs_constants import selectionColor_prefs_key from utilities.constants import ave_colors, black, red, blue, white from utilities.prefs_constants import atomHighlightColor_prefs_key # 3D and 2D rendition display styles. Mark 2008-05-15 from utilities.prefs_constants import dnaRendition_prefs_key # piotr 080309: user pereferences for DNA style from utilities.prefs_constants import dnaStyleStrandsColor_prefs_key from utilities.prefs_constants import dnaStyleAxisColor_prefs_key from utilities.prefs_constants import dnaStyleStrutsColor_prefs_key from utilities.prefs_constants import dnaStyleBasesColor_prefs_key from utilities.prefs_constants import dnaStyleStrandsShape_prefs_key from utilities.prefs_constants import dnaStyleBasesShape_prefs_key from utilities.prefs_constants import dnaStyleStrandsArrows_prefs_key from utilities.prefs_constants import dnaStyleAxisShape_prefs_key from utilities.prefs_constants import dnaStyleStrutsShape_prefs_key from utilities.prefs_constants import dnaStyleStrandsScale_prefs_key from utilities.prefs_constants import dnaStyleAxisScale_prefs_key from utilities.prefs_constants import dnaStyleBasesScale_prefs_key from utilities.prefs_constants import dnaStyleAxisEndingStyle_prefs_key from utilities.prefs_constants import dnaStyleStrutsScale_prefs_key # piotr 080325 added more user preferences from utilities.prefs_constants import dnaStrandLabelsEnabled_prefs_key from utilities.prefs_constants import dnaStrandLabelsColor_prefs_key from utilities.prefs_constants import dnaStrandLabelsColorMode_prefs_key from utilities.prefs_constants import dnaBaseIndicatorsEnabled_prefs_key from utilities.prefs_constants import dnaBaseIndicatorsColor_prefs_key from utilities.prefs_constants import dnaBaseInvIndicatorsEnabled_prefs_key from utilities.prefs_constants import dnaBaseInvIndicatorsColor_prefs_key from utilities.prefs_constants import dnaBaseIndicatorsPlaneNormal_prefs_key from utilities.prefs_constants import dnaStyleBasesDisplayLetters_prefs_key try: from OpenGL.GLE import glePolyCone from OpenGL.GLE import gleGetNumSides from OpenGL.GLE import gleSetNumSides from OpenGL.GLE import gleExtrusion from OpenGL.GLE import gleTwistExtrusion from OpenGL.GLE import glePolyCylinder from OpenGL.GLE import gleSetJoinStyle from OpenGL.GLE import TUBE_NORM_EDGE from OpenGL.GLE import TUBE_NORM_PATH_EDGE from OpenGL.GLE import TUBE_JN_ROUND from OpenGL.GLE import TUBE_JN_ANGLE from OpenGL.GLE import TUBE_CONTOUR_CLOSED from OpenGL.GLE import TUBE_JN_CAP except: print "DNA Cylinder: GLE module can't be imported. Now trying _GLE" from OpenGL._GLE import glePolyCone from OpenGL._GLE import gleGetNumSides from OpenGL._GLE import gleSetNumSides from OpenGL._GLE import gleExtrusion from OpenGL._GLE import gleTwistExtrusion from OpenGL._GLE import glePolyCylinder from OpenGL._GLE import gleSetJoinStyle from OpenGL._GLE import TUBE_NORM_EDGE from OpenGL._GLE import TUBE_NORM_PATH_EDGE from OpenGL._GLE import TUBE_JN_ROUND from OpenGL._GLE import TUBE_JN_ANGLE from OpenGL._GLE import TUBE_CONTOUR_CLOSED from OpenGL._GLE import TUBE_JN_CAP # OpenGL functions are called by "realtime" draw methods. from OpenGL.GL import glBegin from OpenGL.GL import GL_BLEND from OpenGL.GL import glEnd from OpenGL.GL import glVertex3f from OpenGL.GL import glVertex3fv from OpenGL.GL import glColor3f from OpenGL.GL import glColor3fv from OpenGL.GL import glTranslatef from OpenGL.GL import GL_LINE_STRIP from OpenGL.GL import GL_LINES from OpenGL.GL import GL_POLYGON from OpenGL.GL import glEnable from OpenGL.GL import glDisable from OpenGL.GL import GL_LIGHTING from OpenGL.GL import GL_SMOOTH from OpenGL.GL import glShadeModel from OpenGL.GL import GL_COLOR_MATERIAL from OpenGL.GL import GL_TRIANGLES from OpenGL.GL import GL_FRONT_AND_BACK from OpenGL.GL import GL_AMBIENT_AND_DIFFUSE from OpenGL.GL import glMaterialfv from OpenGL.GL import glPushMatrix from OpenGL.GL import glPopMatrix from OpenGL.GL import glRotatef from OpenGL.GL import glScalef from OpenGL.GL import glLineWidth from OpenGL.GL import GL_QUADS from OpenGL.GL import GL_LINE_SMOOTH import colorsys from OpenGL.GLU import gluUnProject from dna.model.DnaLadderRailChunk import DnaStrandChunk from model.chunk import Chunk chunkHighlightColor_prefs_key = atomHighlightColor_prefs_key # initial kluge # piotr 080519: made this method a global function # it needs to be moved to a more appropriate location def get_dna_base_orientation_indicators(chunk, normal): """ Returns two lists for DNA bases perpendicular and anti-perpendicular to a plane specified by the plane normal vector. @param normal: normal vector defining a plane @type normal: float[3] """ from utilities.prefs_constants import dnaBaseIndicatorsAngle_prefs_key from utilities.prefs_constants import dnaBaseIndicatorsDistance_prefs_key indicators_angle = env.prefs[dnaBaseIndicatorsAngle_prefs_key] indicators_distance = env.prefs[dnaBaseIndicatorsDistance_prefs_key] indicators = [] inv_indicators = [] if chunk.isStrandChunk(): if chunk.ladder.axis_rail: n_bases = chunk.ladder.baselength() if chunk == chunk.ladder.strand_rails[0].baseatoms[0].molecule: chunk_strand = 0 else: chunk_strand = 1 for pos in range(0, n_bases): atom1 = chunk.ladder.strand_rails[chunk_strand].baseatoms[pos] atom2 = chunk.ladder.axis_rail.baseatoms[pos] vz = normal v2 = norm(atom1.posn()-atom2.posn()) # calculate the angle between this vector # and the vector towards the viewer a = angleBetween(vz, v2) if abs(a) < indicators_angle: indicators.append(atom1) if abs(a) > (180.0 - indicators_angle): inv_indicators.append(atom1) return (indicators, inv_indicators) def get_all_available_dna_base_orientation_indicators(chunk, normal, reference_indicator_dict = {}, skip_isStrandChunk_check = False): """ """ # by Ninad #@TODO: Move this and other methods out of this file, into a general #helper pkg and module -- Ninad 2008-06-01 from utilities.prefs_constants import dnaBaseIndicatorsAngle_prefs_key from utilities.prefs_constants import dnaBaseIndicatorsDistance_prefs_key indicators_angle = env.prefs[dnaBaseIndicatorsAngle_prefs_key] indicators_distance = env.prefs[dnaBaseIndicatorsDistance_prefs_key] all_indicators_dict = {} if skip_isStrandChunk_check: pass #caller has already done this check and is explicitely asking to #skip isStrandChunk test (for optimization) else: if chunk.isStrandChunk(): return {}, {} if chunk.ladder.axis_rail: n_bases = chunk.ladder.baselength() if chunk == chunk.ladder.strand_rails[0].baseatoms[0].molecule: chunk_strand = 0 else: chunk_strand = 1 for pos in range(0, n_bases): atom1 = chunk.ladder.strand_rails[chunk_strand].baseatoms[pos] atom2 = chunk.ladder.axis_rail.baseatoms[pos] vz = normal v2 = norm(atom1.posn()-atom2.posn()) # calculate the angle between this vector # and the vector towards the viewer a = angleBetween(vz, v2) if abs(a) < indicators_angle: if not reference_indicator_dict.has_key(id(atom1)): all_indicators_dict[id(atom1)] = atom1 if abs(a) > (180.0 - indicators_angle): if not reference_indicator_dict.has_key(id(atom1)): all_indicators_dict[id(atom1)] = atom1 return all_indicators_dict def get_dna_base_orientation_indicator_dict(chunk, normal, reference_indicator_dict = {}, reference_inv_indicator_dict = {}, skip_isStrandChunk_check = False): """ Returns two dictionaries for DNA bases perpendicular and anti-perpendicular to a plane specified by the plane normal vector. """ # by Ninad #@TODO: Move this and other methods out of this file, into a general #helper pkg and module -- Ninad 2008-06-01 from utilities.prefs_constants import dnaBaseIndicatorsAngle_prefs_key from utilities.prefs_constants import dnaBaseIndicatorsDistance_prefs_key indicators_angle = env.prefs[dnaBaseIndicatorsAngle_prefs_key] indicators_distance = env.prefs[dnaBaseIndicatorsDistance_prefs_key] indicators_dict = {} inv_indicators_dict = {} if skip_isStrandChunk_check: pass #caller has already done this check and is explicitely asking to #skip isStrandChunk test (for optimization) else: if chunk.isStrandChunk(): return {}, {} if chunk.ladder.axis_rail: n_bases = chunk.ladder.baselength() if chunk == chunk.ladder.strand_rails[0].baseatoms[0].molecule: chunk_strand = 0 else: chunk_strand = 1 for pos in range(0, n_bases): atom1 = chunk.ladder.strand_rails[chunk_strand].baseatoms[pos] atom2 = chunk.ladder.axis_rail.baseatoms[pos] vz = normal v2 = norm(atom1.posn()-atom2.posn()) # calculate the angle between this vector # and the vector towards the viewer a = angleBetween(vz, v2) if abs(a) < indicators_angle: if not reference_indicator_dict.has_key(id(atom1)) and \ not reference_inv_indicator_dict.has_key(id(atom1)): indicators_dict[id(atom1)] = atom1 if abs(a) > (180.0 - indicators_angle): if not reference_indicator_dict.has_key(id(atom1)) and \ not reference_inv_indicator_dict.has_key(id(atom1)): inv_indicators_dict[id(atom1)] = atom1 return (indicators_dict, inv_indicators_dict) class DnaCylinderChunks(ChunkDisplayMode): """ Implements DNA Cylinder display mode, which draws PAM-model DNA objects using simplified represenations for individual components. There are four components treated independently: "axis", "strands", "struts" and "nucleotides". Each of these components has its own set of settings. @note: Nothing else is rendered (no atoms, sugar atoms, etc) when set to this display mode. piotr 080316: Some of these features can be displayed as "nucleotides" @attention: This is still considered experimental. """ # OLD limitations/known bugs, mostly fixed # # - Cylinders are always straight. DNA axis chunks with atoms that are not # aligned in a straight line are not displayed correctly (i.e. they don't # follow a curved axis path. -- fixed 080310 piotr # - Hover highlighting does not work. fixed 080318 piotr: thank you, Ninad! # - Selected chunks are not colored in the selection color. fix 080318 piotr # - Cannot drag/move a selected cylinder interactively. fix 080318 piotr # - DNA Cylinders are not written to POV-Ray file. piotr: fixed 080317 # - DNA Cylinders are not written to PDB file and displayed in QuteMolX. # --- this is a more general problem related to limitation of QuteMolX # mmp_code must be a unique 3-letter code, distinct from the values in # constants.dispNames or in other display modes mmp_code = 'dna' disp_label = 'DNA Cylinder' # label for statusbar fields, menu text, etc. featurename = "Set Display DNA Cylinder" icon_name = "modeltree/DnaCylinder.png" hide_icon_name = "modeltree/DnaCylinder-hide.png" ### also should define icon as an icon object or filename, ### either in class or in each instance ### also should define a featurename for wiki help # Several of the methods below should be split into their own files. # piotr 082708 def _compute_spline(self, data, idx, t): """ Implements a Catmull-Rom spline. Interpolates between data[idx] and data[idx+1]. 0.0 <= t <= 1.0. @param data: array with at least four values to be used for interpolation. The following values are used: data[idx-1], data[idx], data[idx+1], data[idx+2] @param t: position (0 <= t <= 1) @type t: float @return: spline value at t """ t2 = t * t t3 = t2 * t x0 = data[idx-1] x1 = data[idx] x2 = data[idx+1] x3 = data[idx+2] res = 0.5 * ((2.0 * x1) + t * (-x0 + x2) + t2 * (2.0 * x0 - 5.0 * x1 + 4.0 * x2 - x3) + t3 * (-x0 + 3.0 * x1 - 3.0 * x2 + x3)) return res def _get_rainbow_color(self, hue, saturation, value): """ Gets a color of a hue range limited to 0 - 0.667 (red - blue color range). @param hue: color hue (0..1) @type hue: float @param saturation: color saturation (0..1) @type saturation: float @param value: color value (0..1) @type value: float @return: color for given (h,s,v) """ hue = 0.666 * (1.0 - hue) if hue < 0.0: hue = 0.0 if hue > 0.666: hue = 0.666 return colorsys.hsv_to_rgb(hue, saturation, value) def _get_full_rainbow_color(self, hue, saturation, value): """ Gets a color from a full hue range (red - red). Can be used for color wrapping (color at hue == 0 is the same as color at hue == 1). @param hue: color hue (0..1) @type hue: float @param saturation: color saturation (0..1) @type saturation: float @param value: color value (0..1) @type value: float @return: color for given (h,s,v) """ if hue < 0.0: hue = 0.0 if hue > 1.0: hue = 1.0 return colorsys.hsv_to_rgb(hue, saturation, value) def _get_nice_rainbow_color(self, hue, saturation, value): """ Gets a color of a hue limited to red-magenta range. @param hue: color hue (0..1) @type hue: float @param saturation: color saturation (0..1) @type saturation: float @param value: color value (0..1) @type value: float @return: color for given (h,s,v) """ hue *= 0.8 if hue < 0.0: hue = 0.0 if hue > 1.0: hue = 1.0 return colorsys.hsv_to_rgb(hue, saturation, value) def _get_base_color(self, base): """ Returns a color according to DNA base type. Two-ring bases (G and A) have darker colors. G = red C = orange A = blue T = cyan @note: there should be a user pref setting for these @param base: DNA base symbol @type base: 1-char string @return: color corresponding to a given base """ if base == "G": color = [1.0, 0.0, 0.0] elif base == "C": color = [1.0, 0.5, 0.0] elif base == "A": color = [0.0, 0.3, 0.9] elif base == "T": color = [0.0, 0.7, 0.8] else: color = [0.5, 0.5, 0.5] return color def _get_rainbow_color_in_range(self, pos, count, saturation, value): """ Gets a color of a hue range limited to 0 - 0.667 (red - blue color range) correspoding to a "pos" value from (0..count) range. @param pos: position in (0..count range) @type pos: integer @param count: limits the range of allowable values @type count: integer @param saturation: color saturation (0..1) @type saturation: float @param value: color value (0..1) @type value: float @return: color for given (pos, s, v) """ if count > 1: count -= 1 hue = float(pos)/float(count) if hue < 0.0: hue = 0.0 if hue > 1.0: hue = 1.0 return self._get_rainbow_color(hue, saturation, value) def _get_full_rainbow_color_in_range(self, pos, count, saturation, value): """ Gets a color from a full hue range (red to red). Can be used for color wrapping (color at hue == 0 is the same as color at hue == 1). The color corresponds to a "pos" value from (0..count) range. @param pos: position in (0..count range) @type pos: integer @param count: limits the range of allowable values @type count: integer @param saturation: color saturation (0..1) @type saturation: float @param value: color value (0..1) @type value: float @return: color for given (pos, s, v) """ if count > 1: count -= 1 hue = float(pos)/float(count) if hue < 0.0: hue = 0.0 if hue > 1.0: hue = 1.0 return self._get_full_rainbow_color(hue, saturation, value) def _get_nice_rainbow_color_in_range(self, pos, count, saturation, value): """ Gets a color of a hue range limited to red-magenta range. The color corresponds to a "pos" value from (0..count) range. @param pos: position in (0..count) range @type pos: integer @param count: limits the range of allowable values @type count: integer @param saturation: color saturation (0..1) @type saturation: float @param value: color value (0..1) @type value: float @return: color for given (pos, s, v) """ if count > 1: count -= 1 hue = float(pos)/float(count) if hue < 0.0: hue = 0.0 if hue > 1.0: hue = 1.0 return self._get_nice_rainbow_color(hue, saturation, value) def _make_curved_strand(self, points, colors, radii): """ Converts a polycylinder tube to a smooth, curved tube by spline interpolating of points, colors and radii. Assumes that len(points) == len(colors) == len(radii) @param points: consecutive points to be interpolated @type points: list of V or list of float[3] @param colors: colors corresponding to the points @type colors: list of colors @param radii: radii correspoding to individual points @type radii: list of radii @return: tuple of interpolated (points, colors, radii) """ n = len(points) if n > 3: # Create lists for the interpolated positions, colors, and radii. new_points = [ None ] * (4*(n-2)-1) new_colors = [ None ] * (4*(n-2)-1) new_radii = [ 0.0 ] * (4*(n-2)-1) for p in range(0, (4*(n-2)-1)): new_points[p] = [ 0.0 ] * 3 new_colors[p] = [ 0.0 ] * 3 o = 1 # Fill-in the lists by computing spline values at consecutive points. # Assume that the spline resolution equals 4. for p in range (1, n-2): for m in range (0, 4): t = 0.25 * m new_points[o] = self._compute_spline(points, p, t) new_colors[o] = self._compute_spline(colors, p, t) new_radii[o] = self._compute_spline(radii, p, t) o += 1 # Fill-in terminal positions. new_points[o] = self._compute_spline(points, p, 1.0) new_colors[o] = self._compute_spline(colors, p, 1.0) new_radii[o] = self._compute_spline(radii, p, 1.0) o += 1 new_points[0] = 3.0 * new_points[1] \ - 3.0 * new_points[2] \ + new_points[3] new_points[o] = 3.0 * new_points[o-1] \ - 3.0 * new_points[o-2] \ + new_points[o-3] new_colors[0] = new_colors[1] new_colors[o] = new_colors[o - 1] new_radii[0] = new_radii[1] new_radii[o] = new_radii[o - 1] return (new_points, new_colors, new_radii) else: # if not enough points, just return the initial lists return (points, colors, radii) def _get_axis_positions(self, chunk, atom_list, color_style): """ From an atom list create a list of positions extended by two dummy positions at both ends. The list looks different depending on the used color style. Uses the chunk to convert atom coordinates to molecule-relative coords. @param chunk: chunk @type chunk: Chunk @param atom_list: list of axis chunk atoms @type atom_list: list of Atoms @param color_style: color style to be used to render the axis @type color_style: int @return: positions of the DNA axis cylinder """ n_atoms = len(atom_list) if color_style == 2 or color_style == 3: # Use discrete colors. Below is an explanation of how the "discrete" # colors work. piotr 080827 # The GLE "polycylinder" (and related methods, e.g. glePolyCone) # interpolates colors between consecutive links. To create a sharp, # "discrete" color transition between two links, a new virtual link # of length 0 has to be introduced. The virtual link will be not # drawn, its purpose is only to make the color transitions sharp. # The virtual links are introduced in-between existing links, # for example: # Original sequence: (P0,C0) - (P1,C1) - (P2,C2) # will be replaced by: # New sequence: (P0,C0) - (P1,C0) - (P1,C1) - (P2,C1) - (P2,C2) # where (Px,Cx) is a (position,color) pair of an individual link. positions = [None] * (2 * n_atoms + 2) pos = 2 for i in range (1, n_atoms): pos1 = chunk.abs_to_base(atom_list[i-1].posn()) pos2 = chunk.abs_to_base(atom_list[i].posn()) positions[pos] = 0.5*(pos1 + pos2) positions[pos + 1] = 0.5*(pos1 + pos2) pos += 2 positions[1] = chunk.abs_to_base(atom_list[0].posn()) positions[0] = 2 * positions[1] - positions[2] positions[pos] = chunk.abs_to_base(atom_list[n_atoms - 1].posn()) positions[pos + 1] = 2 * positions[pos] - positions[pos - 1] else: positions = [None] * (n_atoms + 2) for i in range(1, n_atoms + 1): positions[i] = chunk.abs_to_base(atom_list[i-1].posn()) if n_atoms > 1: positions[0] = 2 * positions[1] - positions[2] else: positions[0] = positions[1] if n_atoms > 1: positions[n_atoms + 1] = 2 * positions[n_atoms] - positions[n_atoms - 1] else: positions[n_atoms + 1] = positions[n_atoms] return positions def _get_axis_atom_color_per_base(self, pos, strand_atoms_lists): """ Gets a color of an axis atom depending on a base type. If the axis cylinder is colored 'per base', it uses two distinct colors: orange for G-C pairs, and teal for A-T pairs. Unknown bases are colored gray. @param pos: atom position in axis chunk @type pos: integer @param strand_atoms_lists: lists of strand atoms (used to find out the name of DNA base). @return: axis atom color """ color = [0.5, 0.5, 0.5] if len(strand_atoms_lists) > 1: if strand_atoms_lists[0] and strand_atoms_lists[1]: len1 = len(strand_atoms_lists[0]) len2 = len(strand_atoms_lists[1]) if pos>=0 and pos < len1 and pos < len2: base_name = strand_atoms_lists[0][pos].getDnaBaseName() if base_name == 'A' or base_name == 'T': color = [0.0, 1.0, 0.5] elif base_name == 'G' or base_name == 'C': color = [1.0, 0.5, 0.0] return color def _get_axis_colors(self, atom_list, strand_atoms_lists, \ color_style, chunk_color, group_color): """ Create a list of colors from an axis atom list, depending on the used color style. @param atom_list: list of axis atoms @param strand_atoms_list: lists of strand atoms @param color_style: color style used to draw the axis chunk @param chunk_color: color of the chunk @param group_color: """ n_atoms = len(atom_list) if color_style == 2 or \ color_style == 3: # Discrete colors. # For discrete color scheme, the number of internal nodes has to be # duplicated in order to deal with (defult) color interpolation # in glePolyCylinder routine (colors are interpolated on links # with zero length, so the interpolation effects are not visible.) # Also, look at comments in _get_axis_positions. colors = [None] * (2 * n_atoms + 2) pos = 2 for i in range (1, n_atoms): if color_style == 2: color1 = self._get_rainbow_color_in_range( i-1, n_atoms, 0.75, 1.0) color2 = self._get_rainbow_color_in_range( i, n_atoms, 0.75, 1.0) elif color_style == 3: color1 = self._get_axis_atom_color_per_base( i-1, strand_atoms_lists) color2 = self._get_axis_atom_color_per_base( i, strand_atoms_lists) colors[pos] = color1 colors[pos + 1] = color2 pos += 2 colors[1] = colors[2] colors[0] = colors[1] colors[pos] = colors[pos - 1] colors[pos + 1] = colors[pos] else: colors = [None] * (n_atoms + 2) if color_style == 1: for i in range(1, n_atoms + 1): colors[i] = self._get_rainbow_color_in_range( i-1, n_atoms, 0.75, 1.0) elif color_style == 4: for i in range(1, n_atoms + 1): colors[i] = group_color else: for i in range(1, n_atoms + 1): colors[i] = chunk_color colors[0] = colors[1] colors[n_atoms + 1] = colors[n_atoms] return colors def _get_axis_radii(self, atom_list, color_style, shape, scale, ending_style): """ Create a list of radii from the axis atom list. @param atom_list: list of axis atoms @param strand_atoms_list: lists of strand atoms @param color_style: color style used to draw the axis chunk @param shape: shape of the axis component @param scale: scale of the axis component @param ending_style: ending style of the axis component (blunt/tapered) """ if shape == 1: rad = 7.0 * scale else: rad = 2.0 * scale n_atoms = len(atom_list) if color_style == 2 or color_style == 3: # Discrete colors. # For discrete colors duplicate a number of nodes. length = 2 * n_atoms + 2 radii = [rad] * (length) # Append radii for the virtual ends. if ending_style == 2 or ending_style == 3: radii[1] = 0.0 radii[2] = 0.5 * rad radii[3] = 0.5 * rad if ending_style == 1 or ending_style == 3: radii[length-4] = 0.5 * rad radii[length-3] = 0.5 * rad radii[length-2] = 0.0 else: length = n_atoms + 2 radii = [rad] * (length) if ending_style == 2 or ending_style == 3: radii[1] = 0.0 radii[2] = 0.66 * rad if ending_style == 1 or ending_style == 3: radii[length-3] = 0.66 * rad radii[length-2] = 0.0 return radii def _get_strand_positions(self, chunk, atom_list): """ From an strand atom list create a list of positions extended by two dummy positions at both ends. @param chunk: current chunk @param atom_list: list of strand atom positions """ n_atoms = len(atom_list) positions = [None] * (n_atoms + 2) for i in range(1, n_atoms + 1): positions[i] = chunk.abs_to_base(atom_list[i-1].posn()) if n_atoms < 3: positions[0] = positions[1] positions[n_atoms + 1] = positions[n_atoms] else: positions[0] = 3.0 * positions[1] \ - 3.0 * positions[2] \ + positions[3] positions[n_atoms + 1] = 3.0 * positions[n_atoms] \ - 3.0 * positions[n_atoms - 1] \ + positions[n_atoms - 2] return positions def _get_atom_rainbow_color(self, idx, n_atoms, start, end, length): """ Calculates a "rainbow" color for a single atom. This code is partially duplicated in get_strand_colors. @param idx: atom index relative to the chunk length @type idx: integer @param n_atoms: number of atoms in the chunk @type n_atoms: integer @param start: index of the first chunk atom relative to the total strand length @type start: integer @param end: index of the last chunk atom relative to the total strand length @type end: integer @param length: total length of the strand @type length: integer """ if n_atoms > 1: step = float(end - start)/float(n_atoms - 1) else: step = 0.0 if length > 1: ilength = 1.0 / float(length - 1) else: ilength = 1.0 q = ilength * (start + step * idx) ### if strand_direction == -1: ### q = 1.0 - q return self._get_rainbow_color(q, 0.75, 1.0) def _get_strand_colors(self, atom_list, color_style, start, end, \ length, chunk_color, group_color): """ From the strand atom list create a list of colors extended by two dummy positions at both ends. @param atom_list: list of the strand atoms @param color_style: color style used to draw the axis chunk @param start: index of the first chunk atom relative to the total strand length @type start: integer @param end: index of the last chunk atom relative to the total strand length @type end: integer @param length: total length of the strand @type length: integer @param chunk_color: color of the chunk @param group_color: color of the group """ n_atoms = len(atom_list) colors = [None] * (n_atoms + 2) pos = 0 if n_atoms > 1: step = float(end - start)/float(n_atoms - 1) else: step = 0.0 if length > 1: ilength = 1.0 / float(length - 1) else: ilength = 1.0 r = start for i in range(0, n_atoms): if color_style == 0: col = chunk_color elif color_style == 1: q = r * ilength #if strand_direction == -1: # q = 1.0 - q col = self._get_rainbow_color(q, 0.75, 1.0) r += step else: col = group_color colors[i + 1] = V(col[0], col[1], col[2]) # Has to convert to array, otherwise spline interpolation # doesn't work (why - I suppose because tuples are immutable ?) colors[0] = colors[1] colors[n_atoms + 1] = colors[n_atoms] return colors def _get_strand_radii(self, atom_list, radius): """ From the atom list create a list of radii extended by two dummy positions at both ends. @param atom_list: list of strand atoms @param radius: scale factor of the strands """ n_atoms = len(atom_list) radii = [None] * (n_atoms + 2) for i in range(1, n_atoms + 1): radii[i] = radius radii[0] = radii[1] radii[n_atoms + 1] = radii[n_atoms] return radii def _make_discrete_polycone(self, positions, colors, radii): """ Converts a polycone_multicolor colors from smoothly interpolated gradient to discrete (sharp edged) color scheme. The number of nodes will be duplicated. @param positions: list of positions @param colors: list of colors @param radii: list of radii @return: (positions, colors, radii) tuple @note: The method is written so it can be called in a following way: pos, col, rad = _make_discrete_polycone(pos, col, rad) """ # See a comment in "_get_axis_positions" n = len(positions) new_positions = [] new_colors = [] new_radii = [] for i in range(0, n - 1): new_positions.append(positions[i]) new_positions.append(positions[i]) new_colors.append(colors[i]) new_colors.append(colors[i+1]) new_radii.append(radii[i]) new_radii.append(radii[i]) return (new_positions, new_colors, new_radii) def drawchunk(self, glpane, chunk, memo, highlighted): """ Draw chunk in glpane in the whole-chunk display mode represented by this ChunkDisplayMode subclass. Assume we're already in chunk's local coordinate system (i.e. do all drawing using atom coordinates in chunk.basepos, not chunk.atpos). If highlighted is true, draw it in hover-highlighted form (but note that it may have already been drawn in unhighlighted form in the same frame, so normally the highlighted form should augment or obscure the unhighlighted form). Draw it as unselected, whether or not chunk.picked is true. See also self.drawchunk_selection_frame. (The reason that's a separate method is to permit future drawing optimizations when a chunk is selected or deselected but does not otherwise change in appearance or position.) If this drawing requires info about chunk which it is useful to precompute (as an optimization), that info should be computed by our compute_memo method and will be passed as the memo argument (whose format and content is whatever self.compute_memo returns). That info must not depend on the highlighted variable or on whether the chunk is selected. """ # --------------------------------------------------------------------- if not memo: # nothing to render return if self.dnaExperimentalMode > 0: # experimental models is drawn in drawchunk_realtime return positions, colors, radii, \ arrows, struts_cylinders, base_cartoons = memo # render the axis cylinder if chunk.isAxisChunk() and \ positions: # fixed bug 2877 (exception when "positions" # is set to None) - piotr 080516 n_points = len(positions) if self.dnaStyleAxisShape > 0: # spherical ends if self.dnaStyleAxisEndingStyle == 4: drawsphere(colors[1], positions[1], radii[1], 2) drawsphere(colors[n_points - 2], positions[n_points - 2], radii[n_points - 2], 2) # set polycone parameters gleSetJoinStyle(TUBE_JN_ANGLE | TUBE_NORM_PATH_EDGE | TUBE_JN_CAP | TUBE_CONTOUR_CLOSED) # draw the polycone if self.dnaStyleAxisColor == 1 \ or self.dnaStyleAxisColor == 2 \ or self.dnaStyleAxisColor == 3: # render discrete colors drawpolycone_multicolor([0, 0, 0, -2], positions, colors, radii) else: drawpolycone(colors[1], positions, radii) elif chunk.isStrandChunk(): # strands, struts and bases gleSetJoinStyle(TUBE_JN_ANGLE | TUBE_NORM_PATH_EDGE | TUBE_JN_CAP | TUBE_CONTOUR_CLOSED) if positions: if self.dnaStyleStrandsColor == 1: # opacity value == -2 is a flag enabling # the "GL_COLOR_MATERIAL" mode, the # color argument is ignored and colors array # is used instead ### positions, colors, radii = self._make_discrete_polycone(positions, colors, radii) drawpolycone_multicolor([0, 0, 0, -2], positions, colors, radii) else: drawpolycone(colors[1], positions, radii) n_points = len(positions) # draw the ending spheres drawsphere( colors[1], positions[1], radii[1], 2) drawsphere( colors[n_points - 2], positions[n_points - 2], radii[n_points - 2], 2) # draw the arrows for color, pos, rad in arrows: drawpolycone(color, pos, rad) # render struts for color, pos1, pos2, rad in struts_cylinders: drawcylinder(color, pos1, pos2, rad, True) # render nucleotides if self.dnaStyleBasesShape > 0: for color, a1pos, a2pos, a3pos, normal, bname in base_cartoons: if a1pos: if self.dnaStyleBasesShape == 1: # sugar spheres drawsphere(color, a1pos, self.dnaStyleBasesScale, 2) elif self.dnaStyleBasesShape == 2: if a2pos: # draw a schematic 'cartoon' shape aposn = a1pos + 0.50 * (a2pos - a1pos) bposn = a1pos + 0.66 * (a2pos - a1pos) cposn = a1pos + 0.75 * (a2pos - a1pos) drawcylinder(color, a1pos, bposn, 0.20 * self.dnaStyleBasesScale, True) if bname == 'G' or \ bname == 'A': # draw two purine rings drawcylinder(color, aposn - 0.25 * self.dnaStyleBasesScale * normal, aposn + 0.25 * self.dnaStyleBasesScale * normal, 0.7 * self.dnaStyleBasesScale, True) drawcylinder(color, cposn - 0.25 * self.dnaStyleBasesScale * normal, cposn + 0.25 * self.dnaStyleBasesScale * normal, 0.9 * self.dnaStyleBasesScale, True) else: drawcylinder(color, bposn - 0.25 * self.dnaStyleBasesScale * normal, bposn + 0.25 * self.dnaStyleBasesScale * normal, 0.9 * self.dnaStyleBasesScale, True) def drawchunk_selection_frame(self, glpane, chunk, selection_frame_color, memo, highlighted): """ Given the same arguments as drawchunk, plus selection_frame_color, draw the chunk's selection frame. (Drawing the chunk itself as well would not cause drawing errors but would presumably be a highly undesirable slowdown, especially if redrawing after selection and deselection is optimized to not have to redraw the chunk at all.) @note: in the initial implementation of the code that calls this method, the highlighted argument might be false whether or not we're actually hover-highlighted. And if that's fixed, then just as for drawchunk, we might be called twice when we're highlighted, once with highlighted = False and then later with highlighted = True. """ drawchunk(self, glpane, chunk, selection_frame_color, memo, highlighted) return def drawchunk_realtime(self, glpane, chunk, highlighted=False): """ Draws the chunk style that may depend on a current view. These are experimental features, work in progress as of 080319. For the DNA style, draws base orientation indicators and strand labels. 080321 piotr: added better label positioning and """ def _realTextSize(text, fm): """ Returns a pair of vectors corresponding to a width and a height vector of a rendered text. Beware, this call is quite expensive. @params: text - text to be measured fm - font metrics created for the text font: fm = QFontMetrics(font) @returns: (v1,v2) - pair of vector covering the text rectangle expressed in world coordinates """ textwidth = fm.width(text) textheight = fm.ascent() x0, y0, z0 = gluUnProject(0, 0, 0) x1, y1, z1 = gluUnProject(textwidth, 0, 0) x2, y2, z2 = gluUnProject(0, textheight, 0) return (V(x1-x0, y1-y0, z1-z0),V(x2-x0, y2-y0, z2-z0)) def _get_screen_position_of_strand_atom(strand_atom): """ For a given strand atom, find its on-screen position. """ axis_atom = strand_atom.axis_neighbor() if axis_atom: mol = axis_atom.molecule axis_atoms = mol.ladder.axis_rail.baseatoms if axis_atoms is None: return None n_bases = len(axis_atoms) pos = axis_atoms.index(axis_atom) atom0 = axis_atom if pos < n_bases - 1: atom1 = axis_atoms[pos + 1] dpos = atom1.posn() - atom0.posn() else: atom1 = axis_atoms[pos - 1] atom2 = axis_atoms[pos] dpos = atom2.posn() - atom1.posn() last_dpos = dpos out = mol.quat.unrot(glpane.out) if flipped: dvec = norm(cross(dpos, -out)) else: dvec = norm(cross(dpos, out)) pos0 = axis_atom.posn() if not highlighted: pos0 = chunk.abs_to_base(pos0) pos1 = pos0 + ssep * dvec pos2 = pos0 - ssep * dvec if mol.ladder.strand_rails[0].baseatoms[pos] == strand_atom: return (pos1, dpos) elif mol.ladder.strand_rails[1].baseatoms[pos] == strand_atom: return (pos2, -dpos) return (None, None) def _draw_arrow(atom): """ Draws a 2-D arrow ending of a DNA strand at 3' atom. @return: True if arrow was drawn, False if this is not a 3' atom. """ if atom: strand = atom.molecule.parent_node_of_class( atom.molecule.assy.DnaStrand) if atom == strand.get_three_prime_end_base_atom(): ax_atom = atom.axis_neighbor() a_neighbors = ax_atom.axis_neighbors() pos0, dvec = _get_screen_position_of_strand_atom(atom) ovec = norm(cross(dvec, chunk.quat.unrot(glpane.out))) pos1 = pos0 + 0.5 * dvec if mode == 1: pos1 += 1.0 * dvec glVertex3fv(pos0) glVertex3fv(pos1) dvec = norm(dvec) avec2 = pos1 - 0.5 * (dvec - ovec) - dvec glVertex3fv(pos1) glVertex3fv(avec2) avec3 = pos1 - 0.5 * (dvec + ovec) - dvec glVertex3fv(pos1) glVertex3fv(avec3) return True return False def _draw_external_bonds(): """ Draws external bonds between different chunks of the same group. """ # note: this is a local function inside 'def drawchunk_realtime'. # it has no direct relation to ChunkDrawer._draw_external_bonds. for bond in chunk.externs: if bond.atom1.molecule.dad == bond.atom2.molecule.dad: # same group if bond.atom1.molecule != bond.atom2.molecule: # but different chunks pos0, dvec = _get_screen_position_of_strand_atom(bond.atom1) pos1, dvec = _get_screen_position_of_strand_atom(bond.atom2) if pos0 and pos1: glVertex3f(pos0[0], pos0[1], pos0[2]) glVertex3f(pos1[0], pos1[1], pos1[2]) def _light_color(color): """ Make a lighter color. """ lcolor = [0.0, 0.0, 0.0] lcolor[0] = 0.5 * (1.0 + color[0]) lcolor[1] = 0.5 * (1.0 + color[1]) lcolor[2] = 0.5 * (1.0 + color[2]) return lcolor # note: this starts the body of def drawchunk_realtime, # after it defines several local functions. from utilities.constants import lightgreen from PyQt4.Qt import QFont, QString, QColor, QFontMetrics from widgets.widget_helpers import RGBf_to_QColor from dna.model.DnaLadderRailChunk import DnaStrandChunk labels_enabled = env.prefs[dnaStrandLabelsEnabled_prefs_key] indicators_enabled = env.prefs[dnaBaseIndicatorsEnabled_prefs_key] if chunk.color: # sometimes the chunk.color is not defined chunk_color = chunk.color else: chunk_color = white hhColor = env.prefs[hoverHighlightingColor_prefs_key] selColor = env.prefs[selectionColor_prefs_key] if self.dnaExperimentalMode == 0: if indicators_enabled: # draw the orientation indicators self.dnaStyleStrandsShape = env.prefs[dnaStyleStrandsShape_prefs_key] self.dnaStyleStrutsShape = env.prefs[dnaStyleStrutsShape_prefs_key] self.dnaStyleBasesShape = env.prefs[dnaStyleBasesShape_prefs_key] indicators_color = env.prefs[dnaBaseIndicatorsColor_prefs_key] inv_indicators_color = env.prefs[dnaBaseInvIndicatorsColor_prefs_key] inv_indicators_enabled = env.prefs[dnaBaseInvIndicatorsEnabled_prefs_key] plane_normal_idx = env.prefs[dnaBaseIndicatorsPlaneNormal_prefs_key] plane_normal = glpane.up if plane_normal_idx == 1: plane_normal = glpane.out elif plane_normal_idx == 2: plane_normal = glpane.right indicators, inv_indicators = get_dna_base_orientation_indicators(chunk, plane_normal) if highlighted: for atom in indicators: drawsphere( indicators_color, atom.posn(), 1.5, 2) if inv_indicators_enabled: for atom in inv_indicators: drawsphere( inv_indicators_color, atom.posn(), 1.5, 2) else: for atom in indicators: drawsphere( indicators_color, chunk.abs_to_base(atom.posn()), 1.5, 2) if inv_indicators_enabled: for atom in inv_indicators: drawsphere( inv_indicators_color, chunk.abs_to_base(atom.posn()), 1.5, 2) if chunk.isStrandChunk(): if hasattr(chunk, "_dnaStyleExternalBonds"): for exbond in chunk._dnaStyleExternalBonds: atom1, atom2, color = exbond pos1 = atom1.posn() pos2 = atom2.posn() if chunk.picked: color = selColor if highlighted: color = hhColor else: pos1 = chunk.abs_to_base(pos1) pos2 = chunk.abs_to_base(pos2) drawsphere(color, pos1, self.dnaStyleStrandsScale, 2) drawsphere(color, pos2, self.dnaStyleStrandsScale, 2) drawcylinder(color, pos1, pos2, self.dnaStyleStrandsScale, True) if self.dnaStyleBasesDisplayLetters: # calculate text size font_scale = int(500.0 / glpane.scale) if sys.platform == "darwin": font_scale *= 2 if font_scale < 9: font_scale = 9 if font_scale > 50: font_scale = 50 # create the label font labelFont = QFont( QString("Lucida Grande"), font_scale) # get font metrics for the current font fm = QFontMetrics(labelFont) glpane.qglColor(RGBf_to_QColor(black)) # get text size in world coordinates label_text = QString("X") dx, dy = _realTextSize(label_text, fm) # disable lighting glDisable(GL_LIGHTING) for atom in chunk.atoms.itervalues(): # pre-compute atom position if not highlighted: textpos = chunk.abs_to_base(atom.posn()) + 3.0 * glpane.out else: textpos = atom.posn() + 3.0 * glpane.out # get atom base name label_text = QString(atom.getDnaBaseName()) # move the text center to the atom position textpos -= 0.5*(dx + dy) # render the text glpane.renderText(textpos[0], textpos[1], textpos[2], label_text, labelFont) # done, enable lighting glEnable(GL_LIGHTING) if labels_enabled: # draw the strand labels self.dnaStyleStrandsShape = env.prefs[dnaStyleStrandsShape_prefs_key] self.dnaStyleStrutsShape = env.prefs[dnaStyleStrutsShape_prefs_key] self.dnaStyleBasesShape = env.prefs[dnaStyleBasesShape_prefs_key] labels_color_mode = env.prefs[dnaStrandLabelsColorMode_prefs_key] if labels_color_mode == 1: labels_color = black elif labels_color_mode == 2: labels_color = white else: labels_color = env.prefs[dnaStrandLabelsColor_prefs_key] # calculate the text size font_scale = int(500.0 / glpane.scale) if sys.platform == "darwin": font_scale *= 2 if font_scale < 9: font_scale = 9 if font_scale > 50: font_scale = 50 if chunk.isStrandChunk(): if self.dnaStyleStrandsShape > 0 or \ self.dnaStyleBasesShape > 0 or \ self.dnaStyleStrutsShape > 0: # REVIEW: Is the following comment still valid? # # Q. the following is copied from DnaStrand.py # I need to find a 5' sugar atom of the strand # is there any more efficient way of doing that? # this is terribly slow... I need something like # "get_strand_chunks_in_bond_direction"... # # A [bruce 081001]: yes, there is an efficient way. # The strand rail atoms are in order, and it's possible # to determine which end is 5'. I forget the details. strandGroup = chunk.parent_node_of_class(chunk.assy.DnaStrand) if strandGroup is None: strand = chunk else: #dna_updater case which uses DnaStrand object for #internal DnaStrandChunks strand = strandGroup # the label is positioned at 5' end of the strand # get the 5' strand atom atom = strand.get_five_prime_end_base_atom() if atom: # and the next atom for extra positioning next_atom = atom.strand_next_baseatom(1) if atom.molecule is chunk and atom and next_atom: # draw labels only for the first chunk # vector to move the label slightly away from the atom center halfbond = 0.5*(atom.posn()-next_atom.posn()) # create the label font labelFont = QFont( QString("Helvetica"), font_scale) # define a color of the label if highlighted: glpane.qglColor(RGBf_to_QColor(hhColor)) elif chunk.picked: glpane.qglColor(RGBf_to_QColor(selColor)) else: if labels_color_mode == 0: glpane.qglColor(RGBf_to_QColor(chunk_color)) else: glpane.qglColor(RGBf_to_QColor(labels_color)) # get font metrics to calculate text extents fm = QFontMetrics(labelFont) label_text = QString(strand.name)+QString(" ") textsize = fm.width(label_text) # calculate the text position # move a bit into viewers direction if not highlighted: textpos = chunk.abs_to_base(atom.posn()) + halfbond + 5.0 * glpane.out else: textpos = atom.posn() + halfbond + 5.0 * glpane.out # calculate shift for right aligned text dx, dy = _realTextSize(label_text, fm) # check if the right alignment is necessary if dot(glpane.right,halfbond)<0.0: textpos -= dx # center the label vertically textpos -= 0.5 * dy # draw the label glDisable(GL_LIGHTING) glpane.renderText(textpos[0], textpos[1], textpos[2], label_text, labelFont) glEnable(GL_LIGHTING) if self.dnaExperimentalMode > 0: # Very exprimental, buggy and undocumented 2D DNA display mode. # The helices are flattened, so sequence ond overall topology # can be visualized in a convenient way. Particularly # useful for short structural motifs and origami structures. # As of 080415, this work is still considered very preliminary # and experimental. # As of 080520, this code is less buggy, but still quite slow. # REVIEW: Suggestions for speedup? # suggestion added by piotr 080910: # The 2D representation is drawn in intermediate mode. # This code uses multiple individual OpenGL calls (glVertex, # glColor). These calls should be replaced by single OpenGL # array call. # The structure will follow a 2D projection of the central axis. # Note: this mode doesn't work well for PAM5 models. axis = chunk.ladder.axis_rail flipped = False mode = self.dnaExperimentalMode - 1 no_axis = False if axis is None: axis = chunk.ladder.strand_rails[0] no_axis = True if axis: # Calculate the font scale. if mode == 0: font_scale = int(500.0 / glpane.scale) else: font_scale = int(300.0 / glpane.scale) # Rescale font scale for OSX. if sys.platform == "darwin": font_scale *= 2 # Limit the font scale. if font_scale < 9: font_scale = 9 if font_scale > 100: font_scale = 100 # Number of bases n_bases = len(axis) # Disable lighting, we are drawing only text and lines. glDisable(GL_LIGHTING) # Calculate the line width. if mode == 0 \ or mode == 2: lw = 1.0 + 100.0 / glpane.scale if mode == 1: lw = 2.0 + 200.0 / glpane.scale labelFont = QFont( QString("Lucida Grande"), font_scale) fm = QFontMetrics(labelFont) # Calculate the font extents dx, dy = _realTextSize("X", fm) # Get the axis atoms axis_atoms = axis.baseatoms # Get the strand atoms strand_atoms = [None, None] for i in range(0, len(chunk.ladder.strand_rails)): strand_atoms[i] = chunk.ladder.strand_rails[i].baseatoms base_list = [] if mode == 0: ssep = 7.0 elif mode == 1 \ or mode == 2: ssep = 7.0 # Prepare a list of bases to render and their positions. for pos in range(0, n_bases): atom0 = axis_atoms[pos] if pos < n_bases - 1: atom1 = axis_atoms[pos + 1] dpos = atom1.posn() - atom0.posn() else: atom1 = axis_atoms[pos - 1] atom2 = axis_atoms[pos] dpos = atom2.posn() - atom1.posn() last_dpos = dpos # Project the axis atom position onto a current view plane out = chunk.quat.unrot(glpane.out) if flipped: dvec = norm(cross(dpos, -out)) else: dvec = norm(cross(dpos, out)) pos0 = atom0.posn() if not highlighted: pos0 = chunk.abs_to_base(pos0) s_atom0 = s_atom1 = None if strand_atoms[0]: if pos < len(strand_atoms[0]): s_atom0 = strand_atoms[0][pos] if strand_atoms[1]: if pos < len(strand_atoms[1]): s_atom1 = strand_atoms[1][pos] s_atom0_pos = pos0 + ssep * dvec s_atom1_pos = pos0 - ssep * dvec str_atoms = [s_atom0, s_atom1] str_pos = [s_atom0_pos, s_atom1_pos] base_list.append((atom0, pos0, str_atoms, str_pos)) if chunk.isStrandChunk(): glLineWidth(lw) for str in [0, 1]: # Draw the strand atom = None for base in base_list: ax_atom, ax_atom_pos, str_atoms, str_atoms_pos = base if str_atoms[str] != None: atom = str_atoms[str] break if atom and \ chunk == atom.molecule: if atom.molecule.color: strand_color = atom.molecule.color else: strand_color = lightgreen if chunk.picked: strand_color = selColor if highlighted: strand_color = hhColor glColor3fv(strand_color) glBegin(GL_LINES) last_str_atom_pos = None for base in base_list: ax_atom, ax_atom_pos, str_atoms, str_atoms_pos = base if str_atoms[str]: if last_str_atom_pos: glVertex3fv(last_str_atom_pos) glVertex3fv(str_atoms_pos[str]) last_str_atom_pos = str_atoms_pos[str] else: last_str_atom_pos = None glEnd() if mode == 0 \ or mode == 2: glLineWidth(lw) elif mode == 1: glLineWidth(0.5 * lw) glBegin(GL_LINES) # Draw an arrow on 3' atom if not _draw_arrow(atom): # Check out the other end atom = None for base in base_list: ax_atom, ax_atom_pos, str_atoms, str_atoms_pos = base if str_atoms[str] != None: atom = str_atoms[str] # Draw an arrow on 3' atom _draw_arrow(atom) glEnd() glLineWidth(lw) glBegin(GL_LINES) # draw the external bonds _draw_external_bonds() # note: this calls a local function defined # earlier (not a method, thus the lack of self), # which has no direct relation to # ChunkDrawer._draw_external_bonds. # Line drawing done glEnd() # Draw the base letters if mode == 0: for base in base_list: ax_atom, ax_atom_pos, str_atoms, str_atoms_pos = base if str_atoms[str]: textpos = ax_atom_pos + 0.5 * (str_atoms_pos[str] - ax_atom_pos) base_name = str_atoms[str].getDnaBaseName() label_text = QString(base_name) textpos -= 0.5 * (dx + dy) color = black if chunk.picked: glColor3fv(selColor) color = selColor else: base_color = self._get_base_color(base_name) glColor3fv(base_color) color = base_color if highlighted: glColor3fv(hhColor) color = hhColor ### drawtext(label_text, color, textpos, font_scale, glpane) glpane.renderText(textpos[0], textpos[1], textpos[2], label_text, labelFont) elif mode == 1 \ or mode == 2: if no_axis == False: glLineWidth(lw) glBegin(GL_LINES) if chunk.picked: glColor3fv(selColor) elif highlighted: glColor3fv(hhColor) for base in base_list: ax_atom, ax_atom_pos, str_atoms, str_atoms_pos = base if str_atoms[str]: if not chunk.picked and \ not highlighted: base_color = self._get_base_color( str_atoms[str].getDnaBaseName()) glColor3fv(base_color) glVertex3fv(str_atoms_pos[str]) glVertex3fv(ax_atom_pos) glEnd() if mode == 1: # draw circles interior for base in base_list: if chunk.picked: lcolor = _light_color(selColor) elif highlighted: lcolor = hhColor else: lcolor = _light_color(strand_color) ax_atom, ax_atom_pos, str_atoms, str_atoms_pos = base if str_atoms[str]: drawFilledCircle( lcolor, str_atoms_pos[str] + 3.0 * chunk.quat.unrot(glpane.out), 1.5, chunk.quat.unrot(glpane.out)) # draw circles border glLineWidth(3.0) #glColor3fv(strand_color) for base in base_list: ax_atom, ax_atom_pos, str_atoms, str_atoms_pos = base if str_atoms[str]: drawCircle( strand_color, str_atoms_pos[str] + 3.1 * chunk.quat.unrot(glpane.out), 1.5, chunk.quat.unrot(glpane.out)) glLineWidth(1.0) if chunk.isAxisChunk(): if mode == 0: # Draw filled circles in the center of the axis rail. if chunk.picked: color = selColor elif highlighted: color = hhColor else: color = black for base in base_list: ax_atom, ax_atom_pos, str_atoms, str_atoms_pos = base if str_atoms[0] and str_atoms[1]: drawFilledCircle(color, ax_atom_pos, 0.5, chunk.quat.unrot(glpane.out)) else: drawFilledCircle(color, ax_atom_pos, 0.15, chunk.quat.unrot(glpane.out)) glEnable(GL_LIGHTING) glLineWidth(1.0) # line width should be restored to initial value # but I think 1.0 is maintained within the program def writepov(self, chunk, memo, file): """ Renders the chunk to a POV-Ray file. This is an experimental feature as of 080319. @param chunk: chunk to be rendered @type chunk: Chunk @param memo: a tuple describing the reduced representation @type memo: a tuple """ from graphics.rendering.povray.povheader import povpoint from geometry.VQT import vlen def writetube(points, colors, radii, rainbow, smooth): """ Writes a smooth tube in a POV-Ray format. @param points: list of tube points @param colors: list of tube colors @param radii: list of tube radii @param rainbow: use rainbow gradient to color the tube @param smooth: if True, use smooth tube, otherwise draw it as connected cylinders @type smooth: boolean """ file.write("sphere_sweep {\n") if smooth == True: file.write(" linear_spline\n") else: # REVIEW: What should the non-smooth version be? # The non-smooth version should just draw straight # cylinders with spherical joints. This is not implemented. file.write(" linear_spline\n") file.write(" %d,\n" % (len(points))) n = len(points) for i in range(0,n): file.write(" " + povpoint(chunk.base_to_abs(points[i])) +", %g\n" % radii[i]); file.write(" pigment {\n") vec = points[n-1]-points[0] nvec = radii[0] * norm(vec) vec += 2.0 * nvec file.write(" gradient <%g,%g,%g> scale %g translate " % (vec[0], vec[1], vec[2], vlen(vec))) file.write(povpoint(chunk.base_to_abs(points[0] - nvec)) + "\n") file.write(" color_map { RainbowMap }\n") file.write(" }\n") file.write("}\n") def writecylinder(start, end, rad, color): """ Write a POV-Ray cylinder starting at start and ending at end, of radius rad, using given color. """ file.write("cylinder {\n") file.write(" " + povpoint(chunk.base_to_abs(start)) + ", " + povpoint(chunk.base_to_abs(end))) file.write(", %g\n" % (rad)) file.write(" pigment {color <%g %g %g>}\n" % (color[0], color[1], color[2])) file.write("}\n") def writesphere(color, pos, rad): """ Write a POV-Ray sphere at position pos of radius rad using given color. """ file.write("sphere {\n") file.write(" " + povpoint(chunk.base_to_abs(pos))) file.write(", %g\n" % rad) file.write(" pigment {color <%g %g %g>}\n" % (color[0], color[1], color[2])) file.write("}\n") def writecone(color, pos1, pos2, rad1, rad2): """ Write a POV-Ray cone starting at pos1 ending at pos2 using radii rad1 and rad2 in given color. """ file.write("cone {\n") file.write(" " + povpoint(chunk.base_to_abs(pos1))) file.write(", %g\n" % rad1) file.write(" " + povpoint(chunk.base_to_abs(pos2))) file.write(", %g\n" % rad2) file.write(" pigment {color <%g %g %g>}\n" % (color[0], color[1], color[2])) file.write("}\n") # Write a POV-Ray file. # Make sure memo is precomputed. if memo is None: return positions, colors, radii, \ arrows, struts_cylinders, base_cartoons = memo if positions is None: return # Render the axis cylinder n_points = len(positions) if self.dnaStyleAxisShape > 0: # spherical ends if self.dnaStyleAxisEndingStyle == 4: writesphere(colors[1], positions[1], radii[1]) writesphere(colors[n_points - 2], positions[n_points - 2], radii[n_points - 2]) # draw the polycone writetube(positions, colors, radii, False, True) elif chunk.isStrandChunk(): # strands, struts and bases writetube(positions, colors, radii, False, True) # draw the arrows for color, pos, rad in arrows: writecone(color, pos[1], pos[2], rad[1], rad[2]) # render struts for color, pos1, pos2, rad in struts_cylinders: writecylinder(pos1, pos2, rad, color) # render nucleotides if self.dnaStyleBasesShape > 0: for color, a1pos, a2pos, a3pos, normal, bname in base_cartoons: if a1pos: if self.dnaStyleBasesShape == 1: # sugar spheres writesphere(color, a1pos, self.dnaStyleBasesScale) elif self.dnaStyleBasesShape == 2: if a2pos: # draw a schematic 'cartoon' shape aposn = a1pos + 0.50 * (a2pos - a1pos) bposn = a1pos + 0.66 * (a2pos - a1pos) cposn = a1pos + 0.75 * (a2pos - a1pos) writecylinder( a1pos, bposn, 0.20 * self.dnaStyleBasesScale, color) if bname == 'G' \ or bname == 'A': # draw two purine rings writecylinder( aposn - 0.25 * self.dnaStyleBasesScale * normal, aposn + 0.25 * self.dnaStyleBasesScale * normal, 0.7 * self.dnaStyleBasesScale, color) writecylinder( cposn - 0.25 * self.dnaStyleBasesScale * normal, cposn + 0.25 * self.dnaStyleBasesScale * normal, 0.9 * self.dnaStyleBasesScale, color) else: writecylinder( bposn - 0.25 * self.dnaStyleBasesScale * normal, bposn + 0.25 * self.dnaStyleBasesScale * normal, 0.9 * self.dnaStyleBasesScale, color) def compute_memo(self, chunk): """ If drawing chunks in this display mode can be optimized by precomputing some info from chunk's appearance, compute that info and return it. If this computation requires preference values, access them as env.prefs[key], and that will cause the memo to be removed (invalidated) when that preference value is changed by the user. This computation is assumed to also depend on, and only on, chunk's appearance in ordinary display modes (i.e. it's invalidated whenever havelist is). There is not yet any way to change that, so bugs will occur if any ordinarily invisible chunk info affects this rendering, and potential optimizations will not be done if any ordinarily visible info is not visible in this rendering. These can be fixed if necessary by having the real work done within class Chunk's _recompute_ rules, with this function or drawchunk just accessing the result of that (and sometimes causing its recomputation), and with whatever invalidation is needed being added to appropriate setter methods of class Chunk. If the real work can depend on more than chunk's ordinary appearance can, the access would need to be in drawchunk; otherwise it could be in drawchunk or in this method compute_memo(). @param chunk: The chunk @type chunk: Chunk """ # REVIEW: Does this take into account curved strand shapes? # # for this example, we'll turn the chunk axes into a cylinder. # Since chunk.axis is not always one of the vectors chunk.evecs # (actually chunk.poly_evals_evecs_axis[2]), # it's best to just use the axis and center, then recompute # a bounding cylinder. # piotr 080910 comment: yes, it is not a straight cylinder representing # the chunk axis anymore. It is a glePolyCone object # drawn along a path of DNA axis chunk. Similarly, the strand chunks # are represented by curved polycone objects. # import the style preferences from User Preferences self.dnaStyleStrandsShape = env.prefs[dnaStyleStrandsShape_prefs_key] self.dnaStyleStrandsColor = env.prefs[dnaStyleStrandsColor_prefs_key] self.dnaStyleStrandsScale = env.prefs[dnaStyleStrandsScale_prefs_key] self.dnaStyleStrandsArrows = env.prefs[dnaStyleStrandsArrows_prefs_key] self.dnaStyleAxisShape = env.prefs[dnaStyleAxisShape_prefs_key] self.dnaStyleAxisColor = env.prefs[dnaStyleAxisColor_prefs_key] self.dnaStyleAxisScale = env.prefs[dnaStyleAxisScale_prefs_key] self.dnaStyleAxisEndingStyle = env.prefs[dnaStyleAxisEndingStyle_prefs_key] self.dnaStyleStrutsShape = env.prefs[dnaStyleStrutsShape_prefs_key] self.dnaStyleStrutsColor = env.prefs[dnaStyleStrutsColor_prefs_key] self.dnaStyleStrutsScale = env.prefs[dnaStyleStrutsScale_prefs_key] self.dnaStyleBasesShape = env.prefs[dnaStyleBasesShape_prefs_key] self.dnaStyleBasesColor = env.prefs[dnaStyleBasesColor_prefs_key] self.dnaStyleBasesScale = env.prefs[dnaStyleBasesScale_prefs_key] self.dnaStyleBasesDisplayLetters = env.prefs[dnaStyleBasesDisplayLetters_prefs_key] self.dnaExperimentalMode = env.prefs[dnaRendition_prefs_key] # Four components of the reduced DNA style can be created and # controlled independently: central axis, strands, structs, and bases. if not hasattr(chunk, 'ladder'): # DNA updater is off? Don't render # (should display a warning message?) return None if not chunk.atoms or not chunk.ladder: # nothing to display - return return None n_bases = chunk.ladder.baselength() if n_bases < 1: # no bases - return return None # make sure there is a chunk color if chunk.color: chunk_color = chunk.color else: # sometimes the chunk.color is not defined, use white color # in this case. this may happen when a strand or segment # are being interactively edited. chunk_color = white # atom positions in strand and axis strand_positions = axis_positions = None # number of strand in the ladder num_strands = chunk.ladder.num_strands() # current strand current_strand = 0 # get both lists of strand atoms strand_atoms = [None] * num_strands for i in range(0, num_strands): strand_atoms[i] = chunk.ladder.strand_rails[i].baseatoms if chunk.ladder.strand_rails[i].baseatoms[0].molecule is chunk: current_strand = i # empty list for strand colors strand_colors = [None] * num_strands # list of axis atoms axis_atoms = None if chunk.ladder.axis_rail: axis_atoms = chunk.ladder.axis_rail.baseatoms # group color (white by default) group_color = white # 5' and 3' end atoms of current strand (used for drawing arrowheads) five_prime_atom = three_prime_atom = None # current strand chunk direction strand_direction = 0 # start and end positions of the current strand chunk (or corresponding # axis segment chunk) relative to the length of the entire strand start_index = end_index = 0 total_strand_length = 1 # positions, colors and radii to be used for model drawing positions = None colors = None radii = None # pre-calculate polycylinder positions (main drawing primitive # for strands and/or central axis) arrows = [] struts_cylinders = [] base_cartoons = [] if chunk.isAxisChunk() \ and axis_atoms \ and num_strands > 1: if self.dnaStyleAxisColor == 4: # color according to position along the longest strand. longest_rail = None longest_wholechain = None longest_length = 0 # Find a longest rail and wholechain strand_rails = chunk.ladder.strand_rails for rail in strand_rails: length = len(rail.baseatoms[0].molecule.wholechain) if length > longest_length: longest_length = length longest_rail = rail longest_wholechain = rail.baseatoms[0].molecule.wholechain wholechain = longest_wholechain # Get first and last positions of the wholechain pos0, pos1 = wholechain.wholechain_baseindex_range() # index of the first wholechain base in the longest rail idx = wholechain.wholechain_baseindex(longest_rail, 0) # The "group_color" is a uniform color used for entire chunk # Calculate the group color according to relative position # of the wholechain using the "nice rainbow" coloring scheme. # For circular structures, the exact starting position # is unpredictable, but the whole color range is still # properly displayed. group_color = self._get_nice_rainbow_color_in_range( idx - pos0, pos1 - pos0, 0.75, 1.0) # Make sure there are two strands present in the rail # piotr 080430 (fixed post-FNANO Top 20 bugs - exception in # DNA cylinder chunks) positions = self._get_axis_positions( chunk, axis_atoms, self.dnaStyleAxisColor) colors = self._get_axis_colors( axis_atoms, strand_atoms, self.dnaStyleAxisColor, chunk_color, group_color) radii = self._get_axis_radii(axis_atoms, self.dnaStyleAxisColor, self.dnaStyleAxisShape, self.dnaStyleAxisScale, self.dnaStyleAxisEndingStyle) elif chunk.isStrandChunk() and \ (strand_atoms[0] or strand(atoms[1])): n_atoms = len(strand_atoms[current_strand]) strand_group = chunk.getDnaGroup() if strand_group: strands = strand_group.getStrands() # find out strand color group_color = self._get_rainbow_color_in_range( strands.index(chunk.dad), len(strands), 0.75, 1.0) strand = chunk.parent_node_of_class(chunk.assy.DnaStrand) if strand: # determine 5' and 3' end atoms of the strand the chunk # belongs to, and find out the strand direction five_prime_atom = strand.get_five_prime_end_base_atom() three_prime_atom = strand.get_three_prime_end_base_atom() strand_direction = chunk.idealized_strand_direction() wholechain = chunk.wholechain # determine strand and end atom indices # within the entire strand. all_atoms = strand.get_strand_atoms_in_bond_direction() start_atom = strand_atoms[current_strand][0] end_atom = strand_atoms[current_strand][len(strand_atoms[0])-1] # find out first and last strand chunk atom positions relative # to the length of the entire strand if start_atom in all_atoms and \ end_atom in all_atoms: start_index = all_atoms.index(start_atom) - 1 end_index = all_atoms.index(end_atom) - 1 total_strand_length = len(all_atoms) - 2 if self.dnaStyleStrandsShape > 0: # Get positions, colors and radii for current strand chunk positions = self._get_strand_positions( chunk, strand_atoms[current_strand]) colors = self._get_strand_colors( strand_atoms[current_strand], self.dnaStyleStrandsColor, start_index, end_index, total_strand_length, chunk_color, group_color) radii = self._get_strand_radii( strand_atoms[current_strand], self.dnaStyleStrandsScale) if self.dnaStyleStrandsShape == 2: # strand shape is a tube positions, \ colors, \ radii = self._make_curved_strand( positions, colors, radii ) # Create a list of external bonds. # Moved drawing to draw_realtime, otherwise the struts are not # updated. piotr 080411 # These bonds need to be drawn in draw_realtime # to reflect position changes of the individual chunks. chunk._dnaStyleExternalBonds = [] for bond in chunk.externs: if bond.atom1.molecule.dad == bond.atom2.molecule.dad: # same group if bond.atom1.molecule != bond.atom2.molecule: # but different chunks if bond.atom1.molecule is chunk: idx = strand_atoms[current_strand].index(bond.atom1) if self.dnaStyleStrandsColor == 0: color = chunk.color elif self.dnaStyleStrandsColor == 1: color = self._get_atom_rainbow_color( idx, n_atoms, start_index, end_index, total_strand_length) else: color = group_color chunk._dnaStyleExternalBonds.append( (bond.atom1, bond.atom2, color)) # Make the strand arrows. # Possibly, this code is too complicated... make sure that # the conditions below are not redundant. arrlen = 5.0 n = len(positions) if strand_direction == 1: draw_5p = (strand_atoms[current_strand][0] == five_prime_atom) draw_3p = (strand_atoms[current_strand][n_atoms - 1] == three_prime_atom) if draw_5p and (self.dnaStyleStrandsArrows == 1 or self.dnaStyleStrandsArrows == 3): arrvec = arrlen * norm(positions[2] - positions[1]) arrows.append((colors[1], [positions[1] + arrvec, positions[1] + arrvec, positions[1] - arrvec, positions[1] - arrvec], [0.0, 0.0, radii[1]*2.0, radii[1]*2.0])) if draw_3p and (self.dnaStyleStrandsArrows == 2 or self.dnaStyleStrandsArrows == 3): arrvec = arrlen * norm(positions[n-3] - positions[n-2]) arrows.append((colors[n-2], [positions[n-2], positions[n-2], positions[n-2] - arrvec, positions[n-2] - arrvec], [radii[n-2]*2.0, radii[n-2]*2.0, 0.0, 0.0])) else: draw_5p = (strand_atoms[current_strand][n_atoms - 1] == five_prime_atom) draw_3p = (strand_atoms[current_strand][0] == three_prime_atom) if draw_3p and (self.dnaStyleStrandsArrows == 2 or self.dnaStyleStrandsArrows == 3): arrvec = arrlen * norm(positions[2] - positions[1]) arrows.append((colors[1], [positions[1], positions[1], positions[1] - arrvec, positions[1] - arrvec], [radii[1]*2.0, radii[1]*2.0, 0.0, 0.0])) if draw_5p and (self.dnaStyleStrandsArrows == 1 or self.dnaStyleStrandsArrows == 3): arrvec = arrlen * norm(positions[n-3] - positions[n-2]) arrows.append((colors[n-2], [positions[n-2] + arrvec, positions[n-2] + arrvec, positions[n-2] - arrvec, positions[n-2] - arrvec], [0.0, 0.0, radii[n-2]*2.0, radii[n-2]*2.0])) # Make struts. if self.dnaStyleStrutsShape > 0: if num_strands > 1: for pos in range(0, n_atoms): atom1 = strand_atoms[current_strand][pos] atom3 = strand_atoms[1 - current_strand][pos] if self.dnaStyleStrutsShape == 1: # strand-axis-strand type atom2_pos = chunk.abs_to_base(axis_atoms[pos].posn()) elif self.dnaStyleStrutsShape == 2: # strand-strand type atom2_pos = chunk.abs_to_base(0.5 * (atom1.posn() + atom3.posn())) if self.dnaStyleStrutsColor == 0: # color by chunk color color = chunk_color elif self.dnaStyleStrutsColor == 1: # color by base order color = self._get_rainbow_color_in_range( pos, n_atoms, 0.75, 1.0) else: # color by base type color = self._get_base_color(atom1.getDnaBaseName()) struts_cylinders.append( (color, chunk.abs_to_base(atom1.posn()), atom2_pos, 0.5 * self.dnaStyleStrutsScale)) # Make nucleotides. if self.dnaStyleBasesShape > 0: atom1_pos = None atom2_pos = None atom3_pos = None normal = None for pos in range(0, n_atoms): atom = strand_atoms[current_strand][pos] bname = atom.getDnaBaseName() if self.dnaStyleBasesColor == 0: # color by chunk color color = chunk_color elif self.dnaStyleBasesColor == 1: # color by base order color = self._get_rainbow_color_in_range(pos, n_atoms, 0.75, 1.0) elif self.dnaStyleBasesColor == 2: # color by group color color = group_color else: # color by base type color = self._get_base_color(atom.getDnaBaseName()) if self.dnaStyleBasesShape == 1: # draw spheres atom1_pos = chunk.abs_to_base(atom.posn()) elif self.dnaStyleBasesShape == 2 and \ num_strands > 1: # draw a schematic 'cartoon' shape atom1_pos = chunk.abs_to_base(strand_atoms[current_strand][pos].posn()) atom3_pos = chunk.abs_to_base(strand_atoms[1 - current_strand][pos].posn()) atom2_pos = chunk.abs_to_base(axis_atoms[pos].posn()) # figure out a normal to the bases plane v1 = atom1_pos - atom2_pos v2 = atom1_pos - atom3_pos normal = norm(cross(v1, v2)) base_cartoons.append(( color, atom1_pos, atom2_pos, atom3_pos, normal, bname)) # For current chunk, returns: list of positions, colors, radii, arrows, # strut cylinders and base cartoons return (positions, colors, radii, arrows, struts_cylinders, base_cartoons) pass # end of class DnaCylinderChunks ChunkDisplayMode.register_display_mode_class(DnaCylinderChunks) # end
NanoCAD-master
cad/src/graphics/display_styles/DnaCylinderChunks.py
# Copyright 2006-2009 Nanorex, Inc. See LICENSE file for details. """ SurfaceChunks.py -- define a new whole-chunk display mode, which uses Oleksandr's new code to display a chunk as a surface in the chunk's color. @version: $Id$ @copyright: 2006-2009 Nanorex, Inc. See LICENSE file for details. See also CylinderChunks.py for comparison. See renderSurface and drawsurface* in drawer.py for rendering code. How to demo the pyrex/C code for SurfaceChunks (which only computes the mesh -- it doesn't draw it): see cad/src/experimental/oleksandr/README.txt. """ from Numeric import sqrt, pi, sin, cos import types from PyQt4.Qt import QApplication, Qt, QCursor import foundation.env as env from graphics.drawing.CS_draw_primitives import drawsurface from graphics.drawing.CS_draw_primitives import drawsurface_wireframe from graphics.drawing.shape_vertices import getSphereTriangles from geometry.VQT import V, cross from utilities.Log import greenmsg from graphics.display_styles.displaymodes import ChunkDisplayMode from utilities.constants import ave_colors from utilities.constants import diTrueCPK from utilities.prefs_constants import atomHighlightColor_prefs_key _psurface_import_worked = False #Flag that suppresses the console print that reports failed psurface import. #The psurface feature (surface chunks display) is not a part of NE1 anymore #by default (as of before 2008-02-15) _VERBOSE_IMPORT_ERROR = False _psurface_import_status_has_been_reported = False def _report_psurface_import_status(): #bruce 080223; only run if feature is used, by default """ Print whether import psurface succeeded, but only the first time this is called per session. """ global _psurface_import_status_has_been_reported if not _psurface_import_status_has_been_reported: _psurface_import_status_has_been_reported = True if not _psurface_import_worked: print "psurface not imported, check if it has been built" print " (will use slow python version instead)" else: print "fyi: psurface import succeeded:", psurface return try: import psurface _psurface_import_worked = True except ImportError: if _VERBOSE_IMPORT_ERROR: _report_psurface_import_status() chunkHighlightColor_prefs_key = atomHighlightColor_prefs_key # initial kluge class Interval: def __init__(self, *args): """interval constructor""" self.min = 0 self.max = 0 if len(args) == 0: pass if len(args) == 2: self.min, self.max = args def __str__(self): """returns the interval in a textual form""" s = "" s += "%s " % self.min s += "%s " % self.max return s def Empty(self): """clear interval""" self.min = 1000000 self.max = -1000000 def Center(self): """calculate center""" return (self.max + self.min) / 2 def Extent(self): """calculate extent""" return (self.max - self.min) / 2 def Point(self, u): """calculate point""" return (1 - u) * self.min + u * self.max def Normalize(self, u): """normalization""" return (u - self.min) / (self.max - self.min) def Contains(self, p): """interval contains point""" return p >= self.min and p <= self.max def Enclose(self, p): """adjust interval""" if (p < self.min): self.min = p; if (p > self.max): self.max = p; class Box: def __init__(self, *args): """box constructor""" self.x = Interval() self.y = Interval() self.z = Interval() if len(args) == 0: pass if len(args) == 3: self.x, self.y, self.z = args def __str__(self): """returns the box in a textual form""" s = "" s += "%s " % self.x s += "%s " % self.y s += "%s " % self.z return s def Empty(self): """clear box""" self.x.Empty() self.y.Empty() self.z.Empty() def Center(self): """calculate center""" return Triple(self.x.Center(),self.y.Center(),self.z.Center()) def Min(self): """calculate min""" return Triple(self.x.min,self.y.min,self.z.min) def Max(self): """calculate max""" return Triple(self.x.max,self.y.max,self.z.max) def Extent(self): """calculate extent""" return Triple(self.x.Extent(),self.y.Extent(),self.z.Extent()) def Contains(self, p): """box contains point""" return self.x.Contains(p.x) and self.y.Contains(p.y) and self.z.Contains(p.z) def Enclose(self, p): """adjust box""" self.x.Enclose(p.x) self.y.Enclose(p.y) self.z.Enclose(p.z) class Triple: def __init__(self, *args): """vector constructor""" self.x = 0 self.y = 0 self.z = 0 if len(args) == 0: pass if len(args) == 1: if isinstance(args[0], types.InstanceType): self.x = args[0].x self.y = args[0].y self.z = args[0].z elif isinstance(args[0], types.ListType): self.x = args[0][0] self.y = args[0][1] self.z = args[0][2] else: self.x = args[0] self.y = args[0] self.z = args[0] if len(args) == 2: self.x = args[1][0] - args[0][0] self.y = args[1][1] - args[0][1] self.z = args[1][2] - args[0][2] if len(args) == 3: self.x, self.y, self.z = args def __str__(self): """returns the triple in a textual form""" s = "" s += "%s " % self.x s += "%s " % self.y s += "%s " % self.z return s def Len2(self): """square of vector length""" return self.x * self.x + self.y * self.y + self.z * self.z def Len(self): """vector length""" return sqrt(self.Len2()) def Normalize(self): """normalizes vector to unit length""" length = self.Len(); self.x /= length self.y /= length self.z /= length return self def Greatest(self): """calculate greatest value""" if self.x > self.y: if self.x > self.z: return self.x else: return self.z else: if self.y > self.z: return self.y else: return self.z def __add__( self, rhs ): """operator a + b""" t = Triple(rhs) return Triple(self.x + t.x, self.y + t.y, self.z + t.z) def __radd__( self, lhs ): """operator b + a""" t = Triple(lhs) t.x += self.x t.y += self.y t.z += self.z return t def __sub__( self, rhs ): """operator a - b""" t = Triple(rhs) return Triple(self.x - t.x, self.y - t.y, self.z - t.z) def __rsub__( self, lhs ): """operator b - a""" t = Triple(lhs) t.x -= self.x t.y -= self.y t.z -= self.z return t def __mul__( self, rhs ): """operator a * b""" t = Triple(rhs) return Triple(self.x * t.x, self.y * t.y, self.z * t.z) def __rmul__( self, lhs ): """operator b * a""" t = Triple(lhs) t.x *= self.x t.y *= self.y t.z *= self.z return t def __div__( self, rhs ): """operator a / b""" t = Triple(rhs) return Triple(self.x / t.x, self.y / t.y, self.z / t.z) def __rdiv__( self, lhs ): """operator b / a""" t = Triple(lhs) t.x /= self.x t.y /= self.y t.z /= self.z return t def __mod__( self, rhs ): """operator a % b (scalar product)""" r = self.x * rhs.x + self.y * rhs.y + self.z * rhs.z return r def __neg__( self): """operator -a""" return Triple(-self.x, -self.y, -self.z) class Surface: def __init__(self): """surface constructor""" self.spheres = [] self.radiuses = [] def Predicate(self, p): """calculate omega function: positive inside molecula, equal to zero on the boundary, negative outside""" om = 0.0 # calculate omega for all moleculas for i in range(len(self.spheres)): t = p - self.spheres[i] r = self.radiuses[i] s = (r * r - t.x * t.x - t.y * t.y - t.z * t.z) / (r + r) if i == 0: om = s else: if om < s: om = s return om def SurfaceTriangles(self, trias): """make projection all points onto molecula""" self.colors = [] self.points = [] self.trias = [] self.Duplicate(trias) self.SurfaceNormals() np = len(self.points) for j in range(np): p = self.points[j] pt = Triple(p[0],p[1],p[2]) n = self.normals[j] nt = -Triple(n[0],n[1],n[2]) nt.Normalize() om = self.Predicate(pt) if om < -2.0 : om = -2.0 pn = pt - 0.5 * om * nt self.points[j] = (pn.x, pn.y, pn.z) return (self.trias, self.points, self.colors) def Duplicate(self, trias): """delete duplicate points""" eps = 0.0000001 n = len(trias) n3 = 3 * n ia = [] for i in range(n3): ia.append(i + 1) #find and mark duplicate points points = [] for i in range(n): t = trias[i] points.append(Triple(t[0][0],t[0][1],t[0][2])) points.append(Triple(t[1][0],t[1][1],t[1][2])) points.append(Triple(t[2][0],t[2][1],t[2][2])) nb = 17 #use bucket for increase speed bucket = Bucket(nb,points) for i in range(n3): p = points[i] v = bucket.Array(p) for jv in range(len(v)): j = v[jv] if i == j : continue if ia[j] > 0 : pj = points[j] if (p - pj).Len2() < eps : ia[j] = - ia[i] #change array for points & normals #change index for i in range(n3): if ia[i] > 0 : self.points.append((points[i].x,points[i].y,points[i].z)) ia[i] = len(self.points) else: ir = ia[i] if ir < 0 : ir = -ir ia[i] = ia[ir - 1] for i in range(n): self.trias.append((ia[3*i]-1,ia[3*i+1]-1,ia[3*i+2]-1)) def SurfaceNormals(self): """calculate surface normals for all points""" normals = [] for i in range(len(self.points)): normals.append(V(0.0,0.0,0.0)) for i in range(len(self.trias)): t = self.trias[i] p0 = self.points[t[0]] p1 = self.points[t[1]] p2 = self.points[t[2]] v0 = V(p1[0] - p0[0], p1[1] - p0[1], p1[2] - p0[2]) v1 = V(p2[0] - p0[0], p2[1] - p0[1], p2[2] - p0[2]) n = cross(v0, v1) normals[t[0]] += n normals[t[1]] += n normals[t[2]] += n self.normals = [] for n in normals: self.normals.append((n[0],n[1],n[2])) return self.normals def CalculateTorus(self, a, b, u, v): """calculate point on torus""" pi2 = 2 * pi #transformation function - torus cf = cos(pi2*u) sf = sin(pi2*u) ct = cos(pi2*v) st = sin(pi2*v) #point on torus return Triple((a+b*ct)*cf, (a+b*ct)*sf, b*st) def TorusTriangles(self, a, b, n): """generate triangles on torus""" n6 = int(6*a*n) if (n6 == 0): n6 = 6 n2 = int(6*b*n) if (n2 == 0): n2 = 6 trias = [] for i in range(n6): u0 = i / float(n6) u1 = (i +1) / float(n6) for j in range(n2): v0 = j / float(n2); v1 = (j + 1) / float(n2) p0 = self.CalculateTorus(a,b,u0,v0) p1 = self.CalculateTorus(a,b,u1,v0) p2 = self.CalculateTorus(a,b,u1,v1) p3 = self.CalculateTorus(a,b,u0,v1) t1 = ((p0.x,p0.y,p0.z),(p1.x,p1.y,p1.z),(p2.x,p2.y,p2.z)) t2 = ((p0.x,p0.y,p0.z),(p2.x,p2.y,p2.z),(p3.x,p3.y,p3.z)) trias.append(t1) trias.append(t2) return trias class Bucket: def __init__(self, n, points): """bucket constructor""" self.n = n self.nn = n * n self.nnn = self.nn * n self.a = [] for i in range(self.nnn): self.a.append([]) count = 0 for p in points: self.a[self.Index(p)].append(count) count += 1 def Index(self, p): """calculate index in bucket for point p""" i = (int)(self.n * (p.x + 1) / 2) if i >= self.n : i = self.n - 1 j = (int)(self.n * (p.y + 1) / 2) if j >= self.n : j = self.n - 1 k = (int)(self.n * (p.z + 1) / 2) if k >= self.n : k = self.n - 1 return i * self.nn + j * self.n + k def Array(self, p): """get array from bucket for point p""" return self.a[self.Index(p)] class SurfaceChunks(ChunkDisplayMode): """ example chunk display mode, which draws the chunk as a surface, aligned to the chunk's axes, of the chunk's color """ # mmp_code must be a unique 3-letter code, distinct from the values in # constants.dispNames or in other display modes mmp_code = 'srf' disp_label = 'SurfaceChunks' # label for statusbar fields, menu text, etc icon_name = "modeltree/displaySurface.png" hide_icon_name = "modeltree/displaySurface-hide.png" featurename = "Set Display Surface" #mark 060611 cmdname = greenmsg("Set Display Surface: ") # Mark 060621. ##e also should define icon as an icon object or filename, either in class or in each instance ##e also should define a featurename for wiki help def drawchunk(self, glpane, chunk, memo, highlighted): """Draw chunk in glpane in the whole-chunk display mode represented by this ChunkDisplayMode subclass. Assume we're already in chunk's local coordinate system (i.e. do all drawing using atom coordinates in chunk.basepos, not chunk.atpos). If highlighted is true, draw it in hover-highlighted form (but note that it may have already been drawn in unhighlighted form in the same frame, so normally the highlighted form should augment or obscure the unhighlighted form). Draw it as unselected, whether or not chunk.picked is true. See also self.drawchunk_selection_frame. (The reason that's a separate method is to permit future drawing optimizations when a chunk is selected or deselected but does not otherwise change in appearance or position.) If this drawing requires info about chunk which it is useful to precompute (as an optimization), that info should be computed by our compute_memo method and will be passed as the memo argument (whose format and content is whatever self.compute_memo returns). That info must not depend on the highlighted variable or on whether the chunk is selected. """ if not chunk.atoms: return pos, radius, color, tm, nm = memo if highlighted: color = ave_colors(0.5, color, env.prefs[chunkHighlightColor_prefs_key]) #e should the caller compute this somehow? # THIS IS WHERE OLEKSANDR SHOULD CALL HIS NEW CODE TO RENDER THE SURFACE (NOT CYLINDER). # But if this requires time-consuming computations which depend on atom positions (etc) but not on point of view, # those should be done in compute_memo, not here, and their results will be passed here in the memo argument. # (This method drawchunk will not be called on every frame, but it will usually be called much more often than compute_memo.) # For example, memo might contain a Pyrex object pointer to a C object representing some sort of mesh, # which can be rendered quickly by calling a Pyrex method on it. drawsurface(color, pos, radius, tm, nm) return def drawchunk_selection_frame(self, glpane, chunk, selection_frame_color, memo, highlighted): """Given the same arguments as drawchunk, plus selection_frame_color, draw the chunk's selection frame. (Drawing the chunk itself as well would not cause drawing errors but would presumably be a highly undesirable slowdown, especially if redrawing after selection and deselection is optimized to not have to redraw the chunk at all.) Note: in the initial implementation of the code that calls this method, the highlighted argument might be false whether or not we're actually hover-highlighted. And if that's fixed, then just as for drawchunk, we might be called twice when we're highlighted, once with highlighted = False and then later with highlighted = True. """ if not chunk.atoms: return pos, radius, color, tm, nm = memo color = selection_frame_color # make it a little bigger than the sphere itself alittle = 0.01 # THIS IS WHERE OLEKSANDR SHOULD RENDER A "SELECTED" SURFACE, OR (PREFERABLY) A SELECTION WIREFRAME # around an already-rendered surface. # (For a selected chunk, both this and drawchunk will be called -- not necessarily in that order.) drawsurface_wireframe(color, pos, radius + alittle, tm, nm) return def drawchunk_realtime(self, glpane, chunk, highlighted=False): """ Draws the chunk style that may depend on a current view. piotr 080320 """ return def compute_memo(self, chunk): """If drawing chunk in this display mode can be optimized by precomputing some info from chunk's appearance, compute that info and return it. If this computation requires preference values, access them as env.prefs[key], and that will cause the memo to be removed (invalidated) when that preference value is changed by the user. This computation is assumed to also depend on, and only on, chunk's appearance in ordinary display modes (i.e. it's invalidated whenever havelist is). There is not yet any way to change that, so bugs will occur if any ordinarily invisible chunk info affects this rendering, and potential optimizations will not be done if any ordinarily visible info is not visible in this rendering. These can be fixed if necessary by having the real work done within class Chunk's _recompute_ rules, with this function or drawchunk just accessing the result of that (and sometimes causing its recomputation), and with whatever invalidation is needed being added to appropriate setter methods of class Chunk. If the real work can depend on more than chunk's ordinary appearance can, the access would need to be in drawchunk; otherwise it could be in drawchunk or in this method compute_memo. """ # for this example, we'll turn the chunk axes into a cylinder. # Since chunk.axis is not always one of the vectors chunk.evecs (actually chunk.poly_evals_evecs_axis[2]), # it's best to just use the axis and center, then recompute a bounding cylinder. if not chunk.atoms: return None # Put up hourglass cursor to indicate we are busy. Restore the cursor below. Mark 060621. QApplication.setOverrideCursor( QCursor(Qt.WaitCursor) ) env.history.message(self.cmdname + "Computing surface. Please wait...") # Mark 060621. env.history.h_update() # Update history widget with last message. # Mark 060623. _report_psurface_import_status() # prints only once per session if _psurface_import_worked: # cpp surface stuff center = chunk.center bcenter = chunk.abs_to_base(center) rad = 0.0 margin = 0 radiuses = [] spheres = [] atoms = [] coltypes = [] for a in chunk.atoms.values(): col = a.drawing_color() ii = 0 for ic in range(len(coltypes)): ct = coltypes[ic] if ct == col: break; ii += 1 if ii >= len(coltypes): coltypes.append(col); atoms.append(ii) dispjunk, ra = a.howdraw(diTrueCPK) if ra > margin : margin = ra radiuses.append(ra) p = a.posn() - center spheres.append(p) r = p[0]**2+p[1]**2+p[2]**2 if r > rad: rad = r rad = sqrt(rad) radius = rad + margin cspheres = [] from utilities.debug_prefs import debug_pref, Choice_boolean_True use_colors = debug_pref("surface: use colors?", Choice_boolean_True) #bruce 060927 (old code had 0 for use_colors) for i in range(len(spheres)): st = spheres[i] / radius rt = radiuses[i] / radius # cspheres.append((st[0],st[1],st[2],rt,use_colors)) cspheres.append((st[0],st[1],st[2],rt,atoms[i])) #cspheres.append((-0.3,0,0,0.3,1)) #cspheres.append((0.3,0,0,0.3,2)) color = chunk.drawing_color() if color is None: color = V(0.5,0.5,0.5) # create surface level = 3 if rad > 6 : level = 4 ps = psurface # 0 - sphere triangles # 1 - torus rectangles # 2 - omega rectangles method = 2 ((em,pm,am), nm) = ps.CreateSurface(cspheres, level, method) cm = [] if True: # True for color for i in range(len(am)): cm.append(coltypes[am[i]]) else: for i in range(len(am)): cm.append((0.5,0.5,0.5)) tm = (em,pm,cm) else : # python surface stuff center = chunk.center bcenter = chunk.abs_to_base(center) rad = 0.0 s = Surface() margin = 0 for a in chunk.atoms.values(): dispjunk, ra = a.howdraw(diTrueCPK) if ra > margin : margin = ra s.radiuses.append(ra) p = a.posn() - center s.spheres.append(Triple(p[0], p[1], p[2])) r = p[0]**2+p[1]**2+p[2]**2 if r > rad: rad = r rad = sqrt(rad) radius = rad + margin for i in range(len(s.spheres)): s.spheres[i] /= radius s.radiuses[i] /= radius color = chunk.drawing_color() if color is None: color = V(0.5,0.5,0.5) # create surface level = 3 if rad > 6 : level = 4 ts = getSphereTriangles(level) #ts = s.TorusTriangles(0.7, 0.3, 20) tm = s.SurfaceTriangles(ts) nm = s.SurfaceNormals() QApplication.restoreOverrideCursor() # Restore the cursor. Mark 060621. env.history.message(self.cmdname + "Done.") # Mark 060621. return (bcenter, radius, color, tm, nm) pass # end of class SurfaceChunks ChunkDisplayMode.register_display_mode_class(SurfaceChunks) # end
NanoCAD-master
cad/src/graphics/display_styles/SurfaceChunks.py
# Copyright 2009 Nanorex, Inc. See LICENSE file for details. """ GLPane_drawingset_methods.py -- DrawingSet/CSDL helpers for GLPane_minimal @author: Bruce @version: $Id$ @copyright: 2009 Nanorex, Inc. See LICENSE file for details. History: Bruce 090219 refactored this out of yesterday's additions to Part.after_drawing_model. """ from utilities.debug_prefs import debug_pref from utilities.debug_prefs import Choice_boolean_False, Choice_boolean_True from utilities.debug import print_compact_traceback import foundation.env as env from graphics.drawing.DrawingSetCache import DrawingSetCache from graphics.widgets.GLPane_csdl_collector import GLPane_csdl_collector from graphics.widgets.GLPane_csdl_collector import fake_GLPane_csdl_collector _DEBUG_DSETS = False # == class GLPane_drawingset_methods(object): """ DrawingSet/CSDL helpers for GLPane_minimal, as a mixin class """ # todo, someday: split our intended mixin-target, GLPane_minimal, # into a base class GLPane_minimal_base which doesn't inherit us, # which we can inherit to explain to pylint that we *do* have a # drawing_phase attribute, and the rest. These need to be in # separate modules to avoid an import cycle. We can't inherit # GLPane_minimal itself -- that is not only an import cycle # but a superclass-cycle! [bruce 090227 comment] _csdl_collector = None # allocated on demand _csdl_collector_class = fake_GLPane_csdl_collector # Note: this attribute is modified dynamically. # This default value is appropriate for drawing which does not # occur between matched calls of _before/_after_drawing_csdls, since # drawing then is deprecated but needs to work, # so this class will work, but warn when created. # Its "normal" value is used between matched calls # of _before/_after_drawing_csdls. _always_remake_during_movies = False # True in some subclasses _remake_display_lists = True # might change at start and end of each frame def __get_csdl_collector(self): """ get method for self.csdl_collector property: Initialize self._csdl_collector if necessary, and return it. """ try: ## print "__get_csdl_collector", self if not self._csdl_collector: ## print "alloc in __get_csdl_collector", self self._csdl_collector = self._csdl_collector_class( self) # note: self._csdl_collector_class changes dynamically return self._csdl_collector except: # without this try/except, python will report any exception in here # (or at least any AttributeError) as if it was an AttributeError # on self.csdl_collector, discarding all info about the nature # and code location of the actual error! [bruce 090220] ### TODO: flush all output streams in print_compact_traceback; # in current code, the following prints before we finish printing # whatever print statement had the exception partway through, if one did print_compact_traceback("\nfollowing exception is *really* this one, inside __get_csdl_collector: ") print raise pass def __set_csdl_collector(self): """ set method for self.csdl_collector property; should never be called """ assert 0 def __del_csdl_collector(self): """ del method for self.csdl_collector property """ ## print "\ndel csdl_collector", self self._csdl_collector = None csdl_collector = property(__get_csdl_collector, __set_csdl_collector, __del_csdl_collector) # accessed only in this class (as of 090317) def _has_csdl_collector(self): # not used as of 090317 """ @return: whether we presently have an allocated csdl_collector (which would be returned by self.csdl_collector). @rtype: boolean """ return self._csdl_collector is not None _current_drawingset_cache_policy = None # or a tuple of (temporary, cachename) def _before_drawing_csdls(self, bare_primitives = False, dset_change_indicator = None ): """ [private submethod of _call_func_that_draws_model] Whenever some CSDLs are going to be drawn (or more precisely, collected for drawing, since they might be redrawn again later due to reuse_cached_drawingsets) by self.draw_csdl, call this first, draw them (I mean pass them to self.draw_csdl), and then call self._after_drawing_csdls. @param bare_primitives: when True, also open up a new CSDL and collect all "bare primitives" (not drawn into other CSDLs) into it, and draw it at the end. The new CSDL will be marked to permit reentrancy of ColorSorter.start, and will not be allowed to open up a "catchall display list" (an nfr for CSDL) since that might lead to nested display list compiles, not allowed by OpenGL. @param dset_change_indicator: if provided and not false, and if a certain debug_pref is enabled, then if _after_drawing_csdls would use a drawingset_cache and one already exists and has the same value of dset_change_indicator saved from our last use of that cache, we assume there is no need for the caller to remake the drawingsets in that cache, which we tell it (the caller) by returning True. (This is never fully correct -- for details see caller docstring. Soon [090313] we intend to add usage_tracking to make it much closer to being correct.) @return: usually False; True in special cases explained in the docstring for our dset_change_indicator parameter. WARNING: when we return true, our caller is REQUIRED (not just permitted) to immediately call _after_drawing_csdls (with certain options, see current calling code) without doing anything to its cached drawingsets/csdls -- i.e. to skip its usual "drawing". """ # as of 090317, defined and used only in this class; will be refactored; # some other files have comments about it which will need revision then # someday we might take other args, e.g. an "intent map" del self.csdl_collector self._csdl_collector_class = GLPane_csdl_collector # instantiated the first time self.csdl_collector is accessed # (which might be just below, depending on prefs and options) self._remake_display_lists = self._compute_remake_display_lists_now() # note: this affects how we use both debug_prefs, below. res = False # return value, modified below cache = None # set to actual DrawingSetCache if we find or make one cache_began_usage_tracking = False # modified if it did that # [not yet fully implemented or used as of 090317, but should cause no harm] if debug_pref("GLPane: use DrawingSets to draw model?", Choice_boolean_True, #bruce 090225 revised non_debug = True, prefs_key = "v1.2/GLPane: use DrawingSets?" ): if self._remake_display_lists: self.csdl_collector.setup_for_drawingsets() # sets self.csdl_collector.use_drawingsets, and more # (note: this is independent of self.permit_shaders, # since DrawingSets can be used even if shaders are not) self._current_drawingset_cache_policy = self._choose_drawingset_cache_policy() if debug_pref("GLPane: reuse cached DrawingSets? (has bugs)", Choice_boolean_False, non_debug = True, prefs_key = True ): if dset_change_indicator: policy = self._current_drawingset_cache_policy # policy is None or a tuple of (temporary, cachename) [misnamed?] cache = self._find_or_make_dset_cache_to_use(policy, make = False) if cache: if cache.saved_change_indicator == dset_change_indicator: res = True # NOTE: the following debug_pref is not yet implemented, # and this method plus a few others will be heavily refactored # before it is, since keeping track of (planned) usage tracking # is getting too messy without that. # So I if 0'd it (sort of) but left it in for illustration. # [bruce 090317 comment] if 0 and debug_pref("GLPane: usage-track cached DrawingSets?", #bruce 090313 Choice_boolean_False, #####True, non_debug = True, # for now -- remove when works prefs_key = True ): if not res: # if we're reusing dset_cache, i.e. not remaking it, # then no need to track usage "while remaking it"; # this must be synchronized with _after_drawing_csdls # calling end_tracking_usage -- thus the requirements # (new as of 090313) about caller honoring return value res # (see our docstring); for robustness (since _after can't # deduce this perfectly, at least not clearly) we also # set a flag about whether we're doing this in the cache. cache = self._find_or_make_dset_cache_to_use(policy, make = True) # (note make = True, different than earlier call) cache.begin_tracking_usage() #### args? #} cache_began_usage_tracking = True #} # fix word order (or just refactor this mess) cache.track_use() ###### WRONG, do this when we draw it! (in _after I think) #} pass pass pass pass pass pass # following will be done in a better way when we refactor [bruce 090317 comment]: ## if cache: ## cache.is_usage_tracking = cache_began_usage_tracking ####### how do we know it's false if it's not? ## #} ## pass if debug_pref("GLPane: highlight atoms in CSDLs?", Choice_boolean_True, #bruce 090225 revised # maybe: scrap the pref or make it not non_debug non_debug = True, prefs_key = "v1.2/GLPane: highlight atoms in CSDLs?" ): if bare_primitives and self._remake_display_lists: self.csdl_collector.setup_for_bare_primitives() return res def _compute_remake_display_lists_now(self): #bruce 090224 """ [can be overridden in subclasses, but isn't so far] """ # as of 090317, defined and used only in this class remake_during_movies = debug_pref( "GLPane: remake display lists during movies?", Choice_boolean_True, # Historically this was hardcoded to False; # but I don't know whether it's still a speedup # to avoid remaking them (on modern graphics cards), # or perhaps a slowdown, so I'm making it optional. # Also, when active it will disable shader primitives, # forcing use of polygonal primitives instead; #### REVIEW whether it makes sense at all in that case. # [bruce 090224] # update: I'll make it default True, since that's more reliable, # and we might not have time to test it. # [bruce 090225] non_debug = True, prefs_key = "v1.2/GLPane: remake display lists during movies?" ) # whether to actually remake is more complicated -- it depends on self # (thumbviews always remake) and on movie_is_playing flag (external). remake_during_movies = remake_during_movies or \ self._always_remake_during_movies remake_now = remake_during_movies or not self._movie_is_playing() if remake_now != self._remake_display_lists: # (kluge: knows how calling code uses value) # leave this in until we've tested the performance of movie playing # for both prefs values; it's not verbose print "fyi: setting _remake_display_lists = %r" % remake_now return remake_now def _movie_is_playing(self): #bruce 090224 split this out of ChunkDrawer """ [can be overridden in subclasses, but isn't so far] """ # as of 090317, defined and used only in this class return env.mainwindow().movie_is_playing #bruce 051209 # warning: use of env.mainwindow is a KLUGE; # could probably be fixed, but needs review for thumbviews def draw_csdl(self, csdl, selected = False, highlight_color = None): """ Depending on prefs, either draw csdl now (with the given draw options), or make sure it will be in a DrawingSet which will be drawn later with those options. """ # as of 090317, called in many drawing methods elsewhere (and one here), # defined only here; calls and API won't change in planned upcoming # refactoring, but implem might. # future: to optimize rigid drag, options (aka "drawing intent") # will also include which dynamic transform (if any) to draw it inside. csdl_collector = self.csdl_collector intent = (bool(selected), highlight_color) # note: intent must match the "inverse code" in # self._draw_options(), and must be a suitable # dict key. # someday: include symbolic "dynamic transform" in intent, # to optimize rigid drag. (see scratch/TransformNode.py) if csdl_collector.use_drawingsets: csdl_collector.collect_csdl(csdl, intent) else: options = self._draw_options(intent) csdl.draw(**options) return def _draw_options(self, intent): #bruce 090226 """ Given a drawing intent (as created inside self.draw_csdl), return suitable options (as a dict) to be passed to either CSDL.draw or DrawingSet.draw. """ # as of 090317, defined and used only in this class, # but logically, could be overridden in subclasses; # will probably not be changed during planned upcoming refactoring selected, highlight_color = intent # must match the code in draw_csdl if highlight_color is None: return dict(selected = selected) else: return dict(selected = selected, highlighted = True, highlight_color = highlight_color ) pass def _after_drawing_csdls(self, error = False, reuse_cached_dsets_unchanged = False, dset_change_indicator = None ): """ [private submethod of _call_func_that_draws_model] @see: _before_drawing_csdls @param error: if the caller knows, it can pass an error flag to indicate whether drawing succeeded or failed. If it's known to have failed, we might not do some things we normally do. Default value is False since most calls don't pass anything. (#REVIEW: good? true?) @param reuse_cached_dsets_unchanged: whether to do what it says. Typically equal to the return value of the preceding call of _before_drawing_csdls. @param dset_change_indicator: if true, store in the dset cache (whether found or made, modified or not) as .saved_change_indicator. """ # as of 090317, defined and used only in this class; will be refactored self._remake_display_lists = self._compute_remake_display_lists_now() if not error: if self.csdl_collector.bare_primitives: # this must come before the _draw_drawingsets below csdl = self.csdl_collector.finish_bare_primitives() self.draw_csdl(csdl) pass if self.csdl_collector.use_drawingsets: self._draw_drawingsets( reuse_cached_dsets_unchanged = reuse_cached_dsets_unchanged, dset_change_indicator = dset_change_indicator ) # note, the DrawingSets themselves last between draw calls, # and are stored elsewhere in self. self.csdl_collector has # attributes used to collect necessary info during a # draw call for updating the DrawingSets before drawing them. pass pass del self.csdl_collector del self._csdl_collector_class # expose class default value return def _whole_model_drawingset_change_indicator(self): """ [should be overridden in subclasses which want to cache drawingsets] """ # as of 090317, overridden in one subclass, called only in this class # (in _call_func_that_draws_model); might remain unchanged after # planned upcoming refactoring return None # disable this optim by default def _call_func_that_draws_model(self, func, prefunc = None, postfunc = None, bare_primitives = None, drawing_phase = None, whole_model = True ): """ If whole_model is False (*not* the default): Call func() between calls of self._before_drawing_csdls(**kws) and self._after_drawing_csdls(). Return whatever func() returns (or raise whatever exception it raises, but call _after_drawing_csdls even when raising an exception). func should usually be something which calls before/after_drawing_model inside it, e.g. one of the standard functions for drawing the entire model (e.g. part.draw or graphicsMode.Draw), or self._call_func_that_draws_objects which draws a portion of the model between those methods. If whole_model is True (default): Sometimes act as above, but other times do the same drawing that func would have done, without actually calling it, by reusing cached DrawingSets whenever nothing changed to make them out of date. Either way, always call prefunc (if provided) before, and postfunc (if provided) after, calling or not calling func. Those calls participate in the effect of our exception-protection and drawing_phase behaviors, but they stay out of the whole_model- related optimizations (so they are called even if func is not). @warning: prefunc and postfunc are not called between _before_drawing_csdls and _after_drawing_csdls, so they should not use csdls for drawing. (If we need to revise this, we might want to pass a list of funcs rather than a single func, with each one optimized separately for sometimes not being called; or more likely, refactor this entirely to make each func and its redraw-vs-reuse conditions a GraphicsRule object.) @param bare_primitives: passed to _before_drawing_csdls. @param drawing_phase: if provided, drawing_phase must be '?' on entry; we'll set it as specified only during this call. If not provided, we don't check it or change it (typically, in that case, caller ought to do something to set it properly itself). The value of drawing_phase matters and needs to correspond to what's drawn by func, because it determines the "drawingset_cache" (see that term in the code for details). @param whole_model: whether func draws the whole model. Default True. Permits optimizations when the model appearance doesn't change since it was last drawn. """ # as of 090317, defined only here, called here and elsewhere # (in many places); likely to remain unchanged in our API for other # methods and client objects, even after planned upcoming refactoring, # though we may replace *some* of its calls with something modified, # as if inlining the refactored form. # todo: convert some older callers to pass drawing_phase # rather than implementing their own similar behavior. if drawing_phase is not None: assert self.drawing_phase == '?' self.set_drawing_phase(drawing_phase) if prefunc: try: prefunc() except: msg = "bug: exception in %r calling prefunc %r: skipping it" % (self, prefunc) print_compact_traceback(msg + ": ") pass pass if whole_model: dset_change_indicator = self._whole_model_drawingset_change_indicator() # note: if this is not false, then if a certain debug_pref is enabled, # then if we'd use a drawingset_cache and one already # exists and has the same value of dset_change_indicator # saved from our last use of that cache, we assume there # is no need to remake the drawingsets and therefore # no need to call func at all; instead we just redraw # the saved drawingsets. This is never correct -- in practice # some faster but nonnull alternative to func would need # to be called -- but is useful for testing the maximum # speedup possible from an "incremental remake of drawing" # optimization, and is a prototype for correct versions # of similar optimizations. [bruce 090309] else: dset_change_indicator = None skip_dset_remake = self._before_drawing_csdls( bare_primitives = bare_primitives, dset_change_indicator = dset_change_indicator ) # WARNING: if skip_dset_remake, we are REQUIRED (as of 090313) # (not just permitted, as before) # [or at least we would have been if I had finished implementing # usage tracking -- see comment elsewhere for status -- bruce 090317] # to do nothing to any of our cached dsets or csdl collectors # (i.e. to do no drawing) before calling _after_drawing_csdls. # Fortunately we call it just below, so it's easy to verify # this requirement -- just don't forget to think about this # if you modify the following code. (### Todo: refactor this to # make it more failsafe, e.g. pass func to a single method # which encapsulates _before_drawing_csdls and _after_drawing_csdls... # but wait, isn't *this* method that single method? Ok, just make # them private [done] and document them as only for use by this # method [done]. Or maybe a smaller part of this really *should* be # a single method.... [yes, or worse -- 090317]) error = True res = None try: if not skip_dset_remake: res = func() error = False finally: # (note: this is usually what does much of the actual drawing # requested by func()) self._after_drawing_csdls( error, reuse_cached_dsets_unchanged = skip_dset_remake, dset_change_indicator = dset_change_indicator ) if postfunc: try: postfunc() except: msg = "bug: exception in %r calling postfunc %r: skipping it" % (self, postfunc) print_compact_traceback(msg + ": ") pass pass if drawing_phase is not None: self.set_drawing_phase('?') return res def set_drawing_phase(self, drawing_phase): """ [overridden in subclasses of the class we mix into; see those for doc] """ # as of 090317, called in many places, overridden in some; # this will remain true after planned upcoming refactoring return def _call_func_that_draws_objects(self, func, part, bare_primitives = None): """ Like _call_func_that_draws_model, but also wraps func with the part methods before/after_drawing_model, necessary when drawing some portion of a Part (or when drawing all of it, but typical methods to draw all of it already do this themselves, e.g. part.draw or graphicsMode.Draw). This method's name is meant to indicate that you can pass us a func which draws one or more model objects, or even all of them, as long as it doesn't already bracket its individual object .draw calls with the Part methods before/after_drawing_model, like the standard functions for drawing the entire model do. """ # as of 090317, defined only here, called only elsewhere; # likely to remain unchanged in our API for other methods, # even after planned upcoming refactoring def func2(): part.before_drawing_model() error = True try: func() error = False finally: part.after_drawing_model(error) return self._call_func_that_draws_model( func2, bare_primitives = bare_primitives, whole_model = False ) return _dset_caches = None # or map from cachename to persistent DrawingSetCache ### review: make _dset_caches per-Part? Probably not -- might be a big # user of memory or VRAM, and the CSDLs persist so it might not matter # too much. OTOH, Part-switching will be slower without doing this. # Consider doing it only for the last two Parts, or so. # Be sure to delete it for destroyed Parts. # # todo: delete this when deleting an assy, or next using a new one # (not very important -- could reduce VRAM in some cases, # but won't matter after loading a new similar file) def _draw_drawingsets(self, reuse_cached_dsets_unchanged = False, dset_change_indicator = None ): """ Using info collected in self.csdl_collector, update our cached DrawingSets for this frame (unless reuse_cached_dsets_unchanged is true), then draw them. """ ### REVIEW: move inside csdl_collector? # or into some new cooperating object, which keeps the DrawingSets? # as of 090317, defined and used only in this class (in _after_drawing_csdls) incremental = debug_pref("GLPane: use incremental DrawingSets?", Choice_boolean_True, #bruce 090226, since it works non_debug = True, prefs_key = "v1.2/GLPane: incremental DrawingSets?" ) csdl_collector = self.csdl_collector intent_to_csdls = \ csdl_collector.grab_intent_to_csdls_dict() # grab (and reset) the current value of the # dict from intent (about how a csdl's drawingset should be drawn) # to a set of csdls (as a dict from their csdl_id's), # which includes exactly the CSDLs which should be drawn in this # frame (whether or not they were drawn in the last frame). # We own this dict, and can destructively modify it as convenient # (though ownership is needed only in our incremental case below). if reuse_cached_dsets_unchanged: # note: we assume reuse_cached_dsets_unchanged is never true # unless caller verified that the cached dsets in question # actually exist, so we don't need to check this assert incremental # simple sanity check of caller behavior intent_to_csdls.clear() # [no longer needed as of 090313] # set dset_cache to the DrawingSetCache we should use; # if it's temporary, make sure not to store it in any dict if incremental: # figure out (temporary, cachename) cache_before = self._current_drawingset_cache_policy # chosen during _before_drawing_csdls cache_after = self._choose_drawingset_cache_policy() # chosen now ## assert cache_after == cache_before if not (cache_after == cache_before): print "bug: _choose_drawingset_cache_policy differs: before %r vs after %r" % \ (cache_before, cache_after) dset_cache = self._find_or_make_dset_cache_to_use( cache_before) else: # not incremental: # destroy all old caches (matters after runtime prefs change) if self._dset_caches: for cachename, cache in self._dset_caches.items(): cache.destroy() self._dset_caches = None pass # make a new DrawingSetCache to use temporary, cachename = True, None dset_cache = DrawingSetCache(cachename, temporary) del temporary, cachename pass ##### REVIEW: do this inside some method of dset_cache? # This might relate to its upcoming usage_tracking features. [090313] if dset_change_indicator: dset_cache.saved_change_indicator = dset_change_indicator ##### REVIEW: if not, save None? if not reuse_cached_dsets_unchanged: # (note: if not incremental, then dset_cache is empty, so the # following method just fills it non-incrementally in that case, # so we don't need to pass an incremental flag to the method) dset_cache.incrementally_set_contents_to( intent_to_csdls, ## dset_change_indicator = dset_change_indicator ) del intent_to_csdls # draw all current DrawingSets dset_cache.draw( self, self._draw_options, debug = _DEBUG_DSETS, destroy_as_drawn = dset_cache.temporary or not incremental # review (not urgent): can this value be simplified # due to relations between # dset_cache.temporary and incremental? ) if dset_cache.temporary: #### REVIEW: do this in dset_cache.draw when destroy_as_drawn is true, # or when some other option is passed? # note: dset_cache is guaranteed not to be in any dict we have dset_cache.destroy() return def _find_or_make_dset_cache_to_use(self, policy, make = True): """ Find, or make (if option permits), the DrawingSetCache to use, based on policy, which can be None if not make, or can be (temporary, cachename). @return: existing or new DrawingSetCache, or None if not make and no existing one is found. """ # as of 090317, called only in this class, in _before_drawing_csdls and # (during _after_drawing_csdls) in _draw_drawingsets; # defined only in this class if not make and not policy: return None temporary, cachename = policy if not make: return not temporary and \ self._dset_caches and \ self._dset_caches.get(cachename) else: if temporary: dset_cache = DrawingSetCache(cachename, temporary) else: if self._dset_caches is None: self._dset_caches = {} dset_cache = self._dset_caches.get(cachename) if not dset_cache: dset_cache = DrawingSetCache(cachename, temporary) self._dset_caches[cachename] = dset_cache pass pass return dset_cache pass def _choose_drawingset_cache_policy(self): #bruce 090227 """ Based on self.drawing_phase, decide which cache to keep DrawingSets in and whether it should be temporary. @return: (temporary, cachename) @rtype: (bool, string) [overridden in subclasses of the class we mix into; for calling, private to this mixin class] """ # as of 090317, called only in this class, in _before_drawing_csdls and # (during _after_drawing_csdls) in _draw_drawingsets; # defined here and overridden in one other class return False, None pass # end of mixin class GLPane_drawingset_methods # end
NanoCAD-master
cad/src/graphics/widgets/GLPane_drawingset_methods.py
# Copyright 2007-2008 Nanorex, Inc. See LICENSE file for details. """ GLPane_image_methods.py @author: Bruce @version: $Id$ @copyright: 2007-2008 Nanorex, Inc. See LICENSE file for details. History: bruce 070626 wrote some of these in GLPane.py bruce 080919 split this into its own file, added new methods & calling code """ from OpenGL.GL import GL_CURRENT_RASTER_POSITION_VALID from OpenGL.GL import GL_CURRENT_RASTER_POSITION from OpenGL.GL import GL_DEPTH_TEST from OpenGL.GL import GL_FALSE, GL_TRUE from OpenGL.GL import GL_LIGHTING, GL_TEXTURE_2D from OpenGL.GL import GL_RGB, GL_RED, GL_RGBA from OpenGL.GL import GL_DEPTH_COMPONENT from OpenGL.GL import GL_UNSIGNED_BYTE from OpenGL.GL import GL_UNSIGNED_INT, GL_FLOAT from OpenGL.GL import glColorMask from OpenGL.GL import glDisable from OpenGL.GL import glDrawPixels, glDrawPixelsub, glDrawPixelsf from OpenGL.GL import glEnable from OpenGL.GL import glGetBooleanv, glGetFloatv from OpenGL.GL import glRasterPos3f from OpenGL.GL import glReadPixels, glReadPixelsf from OpenGL.GL import GL_DEPTH_BUFFER_BIT from OpenGL.GL import glClear from OpenGL.GLU import gluUnProject from PyQt4.QtOpenGL import QGLWidget import foundation.env as env from utilities.debug_prefs import debug_pref from utilities.debug_prefs import Choice_boolean_False from utilities.Comparison import same_vals import sys # == ##_GL_TYPE_FOR_DEPTH = GL_UNSIGNED_INT _GL_TYPE_FOR_DEPTH = GL_FLOAT # makes no difference - HL still fails ## _GL_FORMAT_FOR_COLOR = GL_RGB _GL_FORMAT_FOR_COLOR = GL_RGBA # this probably removes the crashes & visual errors for most width values # == def _trim(width): """ Reduce a width or height (in pixels) to a safe value (e.g. 0 mod 16). (This would not be needed if GL functions for images were used properly and had no bugs.) """ return width # this seems to work when _GL_FORMAT_FOR_COLOR = GL_RGBA, # whereas this was needed when it was GL_RGB: ## # this fixed the C crash on resizing the main window ## # (which happened from increasing width, then redraw) ## return width - width % 16 # == class GLPane_image_methods(object): """ Private mixin superclass to provide image capture/redraw support (and to use it in specific ways) for class GLPane_rendering_methods. """ _conf_corner_bg_image_data = None def _draw_cc_test_images(self): """ draw some test images related to the confirmation corner (if desired) """ ccdp1 = debug_pref("Conf corner test: redraw at lower left", Choice_boolean_False, prefs_key = True) ccdp2 = debug_pref("Conf corner test: redraw in-place", Choice_boolean_False, prefs_key = True) if ccdp1 or ccdp2: self.grab_conf_corner_bg_image() #bruce 070626 (needs to be done before draw_overlay in caller) if ccdp1: self.draw_conf_corner_bg_image((0, 0)) if ccdp2: self.draw_conf_corner_bg_image() def grab_conf_corner_bg_image(self): #bruce 070626 """ Grab an image of the top right corner, for use in confirmation corner optimizations which redraw it without redrawing everything. """ width = self.width height = self.height subwidth = min(width, 100) subheight = min(height, 100) gl_format, gl_type = _GL_FORMAT_FOR_COLOR, GL_UNSIGNED_BYTE # these (but with GL_RGB) seem to be enough; # GL_RGBA, GL_FLOAT also work but look the same image = glReadPixels( width - subwidth, height - subheight, subwidth, subheight, gl_format, gl_type ) self._conf_corner_bg_image_data = (subwidth, subheight, width, height, gl_format, gl_type, image) # Note: the following alternative form probably grabs a Numeric array, but I'm not sure # our current PyOpenGL (in release builds) supports those, so for now I'll stick with strings, as above. ## image2 = glReadPixelsf( width - subwidth, height - subheight, subwidth, subheight, GL_RGB) ## print "grabbed image2 (type %r):" % ( type(image2), ) # <type 'array'> return def draw_conf_corner_bg_image(self, pos = None): #bruce 070626 (pos argument is just for development & debugging) """ Redraw the previously grabbed conf_corner_bg_image, in the same place from which it was grabbed, or in the specified place (lower left corner of pos, in OpenGL window coords). Note: this modifies the OpenGL raster position. """ if not self._conf_corner_bg_image_data: print "self._conf_corner_bg_image_data not yet assigned" else: subwidth, subheight, width, height, gl_format, gl_type, image = self._conf_corner_bg_image_data if width != self.width or height != self.height: # I don't know if this can ever happen; if it can, caller might need # to detect this itself and do a full redraw. # (Or we might make this method return a boolean to indicate it.) print "can't draw self._conf_corner_bg_image_data -- glpane got resized" ### else: if pos is None: pos = (width - subwidth, height - subheight) x, y = pos self._set_raster_pos(x, y) glDisable(GL_DEPTH_TEST) # otherwise it can be obscured by prior drawing into depth buffer # Note: doing more disables would speed up glDrawPixels, # but that doesn't matter unless we do it many times per frame. glDrawPixels(subwidth, subheight, gl_format, gl_type, image) glEnable(GL_DEPTH_TEST) pass return def _set_raster_pos(x, y): # staticmethod """ """ # If x or y is exactly 0, then numerical roundoff errors can make the raster position invalid. # Using 0.1 instead apparently fixes it, and causes no noticable image quality effect. # (Presumably they get rounded to integer window positions after the view volume clipping, # though some effects I saw implied that they don't get rounded, so maybe 0.1 is close enough to 0.0.) # This only matters when GLPane size is 100x100 or less, # or when drawing this in lower left corner for debugging, # so we don't have to worry about whether it's perfect. # (The known perfect fix is to initialize both matrices, but we don't want to bother, # or to worry about exceeding the projection matrix stack depth.) x1 = max(x, 0.1) y1 = max(y, 0.1) depth = 0.1 # this should not matter, as long as it's within the viewing volume x1, y1, z1 = gluUnProject(x1, y1, depth) glRasterPos3f(x1, y1, z1) # z1 does matter (when in perspective view), since this is a 3d position # Note: using glWindowPos would be simpler and better, but it's not defined # by the PyOpenGL I'm using. [bruce iMac G5 070626] ### UPDATE [bruce 081203]: glWindowPos2i *is* defined, at least on my newer Mac. # There are lots of variants, all suffix-typed with [23][dfis]{,v}. # I need to check whether it's defined on the older Macs too, then use it here. ####FIX if not glGetBooleanv(GL_CURRENT_RASTER_POSITION_VALID): # This was happening when we used x, y = exact 0, # and was causing the image to not get drawn sometimes (when mousewheel zoom was used). # It can still happen for extreme values of mousewheel zoom (close to the ones # which cause OpenGL exceptions), mostly only when pos = (0, 0) but not entirely. # Sometimes the actual drawing positions can get messed up then, too. # This doesn't matter much, but indicates that re-initing the matrices would be # a better solution if we could be sure the projection stack depth was sufficient # (or if we reset the standard projection when done, rather than using push/pop). print "bug: not glGetBooleanv(GL_CURRENT_RASTER_POSITION_VALID); pos =", x, y # if this happens, the subsequent effect is that glDrawPixels draws nothing else: # verify correct raster position px, py, pz, pw = glGetFloatv(GL_CURRENT_RASTER_POSITION) if not (0 <= px - x < 0.4) and (0 <= py - y < 0.4): # change to -0.4 < px - x ?? print "LIKELY BUG: glGetFloatv(GL_CURRENT_RASTER_POSITION) = %s" % [px, py, pz, pw] # seems to be in window coord space, but with float values, # roughly [0.1, 0.1, 0.1, 1.0] but depends on viewpoint, error about 10**-5 pass return _set_raster_pos = staticmethod(_set_raster_pos) # == # known bugs with cached bg image [as of 080922 morn]: # - some update bugs listed below # - drawaxes (origin axes) end up as dotted line; fix: exclude them from bg image (in basicGM.draw()) # - other special drawing in basicGM.draw # - Build Atoms region sel rubberband is not visible # - preventing crashes or visual image format errors required various kluges, incl _trim # - highlight is not working def _get_bg_image_comparison_data(self): """ """ data = ( self.graphicsMode, # often too conservative, but not always # bug: some graphicsModes use prefs or PM settings to decide # how much of the model to display; this ignores those # bug: some GMs do extra drawing in .Draw; this ignores prefs etc that affect that self._fog_test_enable, self.displayMode, # display style self.part, self.part.assy.all_change_indicators(), # TODO: fix view change indicator for this to work fully # note: that's too conservative, since it notices changes in other parts (e.g. from Copy Selection) # KLUGE until view change indicator is fixed -- include view data # directly; should be ok indefinitely + self.quat, # this hit a bug in same_vals (C version), fixed by Eric M 080922 in samevalshelp.c rev 14311 ## + self.quat.vec, # workaround for that bug (works) + self.pov, self.scale, self.zoomFactor, self.width, self.height, QGLWidget.width(self), # in case it disagrees with self.width QGLWidget.height(self), self._resize_counter, # redundant way to force new grab after resize # (tho it might be safer to completely disable the feature # for a frame, after resize ### TRYIT) self.ortho, ) return data _cached_bg_color_image = None _cached_bg_depth_image = None def _print_data(self): return "%d; %d %d == %#x %#x" % \ (env.redraw_counter, self.width, self.height, self.width, self.height,) def _capture_saved_bg_image(self): """ """ # TODO: investigate better ways to do this, which don't involve the CPU. # For example, frame buffer objects, or "render to texture": # - by glCopyTexImage2D, # http://nehe.gamedev.net/data/lessons/lesson.asp?lesson=36 # (which can do color -- I don't know about depth), # - or by more platform-specific ways, e.g. pbuffer. # [bruce 081002] print "_capture_saved_bg_image", self._print_data() sys.stdout.flush() if 1: from OpenGL.GL import glFlush, glFinish glFlush() # might well be needed, based on other code in NE1; not enough by itself glFinish() # try this too if needed w = _trim(self.width) h = _trim(self.height) # grab the color image part image = glReadPixels( 0, 0, w, h, _GL_FORMAT_FOR_COLOR, GL_UNSIGNED_BYTE ) self._cached_bg_color_image = image # grab the depth part ## image = glReadPixels( 0, 0, w, h, GL_DEPTH_COMPONENT, _GL_TYPE_FOR_DEPTH ) image = glReadPixelsf(0, 0, w, h, GL_DEPTH_COMPONENT) ##### self._cached_bg_depth_image = image print "grabbed depth at 0,0:", image[0][0]###### return def _draw_saved_bg_image(self): """ """ print "_draw_saved_bg_image", self._print_data() sys.stdout.flush() assert self._cached_bg_color_image is not None w = _trim(self.width) h = _trim(self.height) glDisable(GL_DEPTH_TEST) # probably a speedup glDisable(GL_LIGHTING) glDisable(GL_TEXTURE_2D) # probably already the NE1 default (if so, doesn't matter here) # Note: doing more disables might well speed up glDrawPixels; # don't know whether that matters. color_image = self._cached_bg_color_image depth_image = self._cached_bg_depth_image # draw the color image part (review: does this also modify the depth buffer?) self._set_raster_pos(0, 0) if 0 and 'kluge - draw depth as color': glDrawPixels(w, h, GL_RED, _GL_TYPE_FOR_DEPTH, depth_image) else: glDrawPixels(w, h, _GL_FORMAT_FOR_COLOR, GL_UNSIGNED_BYTE, color_image) # draw the depth image part; ###BUG: this seems to replace all colors with blue... fixed below self._set_raster_pos(0, 0) # adding this makes the all-gray bug slightly less bad glClear(GL_DEPTH_BUFFER_BIT) # should not matter, but see whether it does ##### glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE) # don't draw color pixels - # fixes bug where this glDrawPixels replaced all colors with blue # (reference doc for glDrawPixels explains why - it makes fragments # using current color and depths from image, draws them normally) print "depth_image[0][0] being written now:", depth_image[0][0] ##### ## depth_image[0][0] being written now: 0.0632854178548 ## glDrawPixels(w, h, GL_DEPTH_COMPONENT, _GL_TYPE_FOR_DEPTH, depth_image) # see if this works any better -- not sure which type to try: # types listed at http://pyopengl.sourceforge.net/documentation/ref/gl/drawpixels.html ## print glDrawPixels.__class__ #### glDrawPixelsf(GL_DEPTH_COMPONENT, depth_image) ## if it was PIL, could say .tostring("raw","R",0,-1))###### glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE) if 1:#### from OpenGL.GL import glFlush glFlush()###### self._set_raster_pos(0, 0) # precaution (untested) if 1: # confirm if possible print "readback of depth at 0,0:", glReadPixels( 0, 0, 1, 1, GL_DEPTH_COMPONENT, _GL_TYPE_FOR_DEPTH )[0][0] ###### ## BUG: readback of depth at 0,0: 1.0 ## import Numeric ## print "min depth:" , Numeric.minimum( glReadPixels( 0, 0, w, h, GL_DEPTH_COMPONENT, _GL_TYPE_FOR_DEPTH ) ) #### 6 args required ## ## ValueError: invalid number of arguments print glEnable(GL_LIGHTING) glEnable(GL_DEPTH_TEST) # (but leave GL_TEXTURE_2D disabled) return pass # end
NanoCAD-master
cad/src/graphics/widgets/GLPane_image_methods.py
# Copyright 2004-2008 Nanorex, Inc. See LICENSE file for details. """ GLPane_mixin_for_DisplayListChunk.py @version: $Id$ @copyright: 2004-2008 Nanorex, Inc. See LICENSE file for details. bruce 080910 split this out of class GLPane """ from OpenGL.GL import glGenLists from OpenGL.GL import glNewList from OpenGL.GL import glEndList from OpenGL.GL import glCallList from utilities.debug_prefs import debug_pref from utilities.debug_prefs import Choice_boolean_False from foundation.state_utils import transclose class GLPane_mixin_for_DisplayListChunk(object): #bruce 070110 moved this here from exprs/DisplayListChunk.py and made GLPane inherit it #bruce 080215 renamed this #bruce 080910 moved this into its own file """ Private mixin class for GLPane. Attr and method names must not interfere with GLPane. Likely to be merged into class GLPane in future (as directly included methods rather than a mixin superclass). """ compiling_displist = 0 #e rename to be private? probably not. compiling_displist_owned_by = None def glGenLists(self, *args): return glGenLists(*args) def glNewList(self, listname, mode, owner = None): """ Execute glNewList, after verifying args are ok and we don't think we're compiling a display list now. (The OpenGL call is illegal if we're *actually* compiling one now. Even if it detects that error (as is likely), it's not a redundant check, since our internal flag about whether we're compiling one could be wrong.) If owner is provided, record it privately (until glEndList) as the owner of the display list being compiled. This allows information to be tracked in owner or using it, like the set of sublists directly called by owner's list. Any initialization of tracking info in owner is up to our caller.###k doit """ #e make our GL context current? no need -- callers already had to know that to safely call the original form of glNewList #e assert it's current? yes -- might catch old bugs -- but not yet practical to do. assert self.compiling_displist == 0 assert self.compiling_displist_owned_by is None assert listname glNewList(listname, mode) self.compiling_displist = listname self.compiling_displist_owned_by = owner # optional arg in general, but required for the tracking done in this module return def glEndList(self, listname = None): assert self.compiling_displist != 0 if listname is not None: # optional arg assert listname == self.compiling_displist glEndList() # no arg is permitted self.compiling_displist = 0 self.compiling_displist_owned_by = None return def glCallList(self, listname): """ Compile a call to the given display list. Note: most error checking and any extra tracking is responsibility of caller. """ ##e in future, could merge successive calls into one call of multiple lists ## assert not self.compiling_displist # redundant with OpenGL only if we have no bugs in maintaining it, so worth checking # above was WRONG -- what was I thinking? This is permitted, and we'll need it whenever one displist can call another. # (And I'm surprised I didn't encounter it before -- did I still never try an MT with displists?) # (Did I mean to put this into some other method? or into only certain uses of this method?? # For now, do an info print, in case sometimes this does indicate an error, and since it's useful # for analyzing whether nested displists are behaving as expected. [bruce 070203] if self.compiling_displist and \ debug_pref("GLPane: print nested displist compiles?", Choice_boolean_False, prefs_key = True): print "debug: fyi: displist %r is compiling a call to displist %r" % \ (self.compiling_displist, listname) assert listname # redundant with following? glCallList(listname) return def ensure_dlist_ready_to_call( self, dlist_owner_1 ): #e rename the local vars, revise term "owner" in it [070102 cmt] """ [private helper method for use by DisplayListChunk] This implements the recursive algorithm described in DisplayListChunk.__doc__. dlist_owner_1 should be a DisplistOwner ###term; we use private attrs and/or methods of that class, including _key, _recompile_if_needed_and_return_sublists_dict(). What we do: make sure that dlist_owner_1's display list can be safely called (executed) right after we return, with all displists that will call (directly or indirectly) up to date (in their content). Note that, in general, we won't know which displists will be called by a given one until after we've updated its content (and thereby compiled calls to those displists as part of its content). Assume we are only called when our GL context is current and we're not presently compiling a displist in it. """ ###e verify our GL context is current, or make it so; not needed now since only called during some widget's draw call assert self.compiling_displist == 0 toscan = { dlist_owner_1._key : dlist_owner_1 } def collector( obj1, dict1): dlist_owner = obj1 direct_sublists_dict = dlist_owner._recompile_if_needed_and_return_sublists_dict() # [renamed from _ensure_self_updated] # This says to dlist_owner: if your list is invalid, recompile it (and set your flag saying it's valid); # then you know your direct sublists, so we can ask you to return them. # Note: it only has to include sublists whose drawing effects might be invalid. # This means, if its own effects are valid, it can optim by just returning {}. # [#e Someday it might maintain a dict of invalid sublists and return that. Right now it returns none or all of them.] # Note: during that call, the glpane (self) is modified to know which dlist_owner's list is being compiled. dict1.update( direct_sublists_dict ) seen = transclose( toscan, collector ) # now, for each dlist_owner we saw, tell it its drawing effects are valid. for dlist_owner in seen.itervalues(): dlist_owner._your_drawing_effects_are_valid() # Q: this resets flags which cause inval propogation... does it retain consistency? # A: it does it in reverse logic dir and reverse arrow dir (due to transclose) as inval prop, so it's ok. # Note: that comment won't be understandable in a month [from 070102]. Need to explain it better. ###doc return pass # end of class GLPane_mixin_for_DisplayListChunk # end
NanoCAD-master
cad/src/graphics/widgets/GLPane_mixin_for_DisplayListChunk.py
# Copyright 2008 Nanorex, Inc. See LICENSE file for details. """ GLPane_stereo_methods.py @author: Piotr @version: $Id$ @copyright: 2008 Nanorex, Inc. See LICENSE file for details. History: piotr 080515 and 080529 wrote these in GLPane.py bruce 080912 split this into its own file """ import foundation.env as env from utilities.prefs_constants import stereoViewMode_prefs_key from utilities.prefs_constants import stereoViewSeparation_prefs_key from utilities.prefs_constants import stereoViewAngle_prefs_key from OpenGL.GL import GL_CLIP_PLANE5 from OpenGL.GL import GL_DEPTH_BUFFER_BIT from OpenGL.GL import GL_FALSE from OpenGL.GL import GL_MODELVIEW from OpenGL.GL import GL_TRANSFORM_BIT from OpenGL.GL import GL_TRUE from OpenGL.GL import glClear from OpenGL.GL import glClipPlane from OpenGL.GL import glColorMask from OpenGL.GL import glDisable from OpenGL.GL import glEnable from OpenGL.GL import glLoadIdentity from OpenGL.GL import glMatrixMode from OpenGL.GL import glPopAttrib from OpenGL.GL import glPopMatrix from OpenGL.GL import glPushAttrib from OpenGL.GL import glPushMatrix from OpenGL.GL import glRotatef from OpenGL.GL import glTranslatef class GLPane_stereo_methods(object): """ Private mixin superclass to provide stereo rendering support to class GLPane. The main class needs to call these methods at appropriate times and use some attributes we maintain in appropriate ways. For documentation see the method docstrings and code comments. All our attribute names and method names contain the string 'stereo', making them easy to find by text-searching the main class source code. """ # note: instance variable default values are class assignments # in the main class, of stereo_enabled and a few other attrs. def set_stereo_enabled(self, enabled): #bruce 080911 """ Set whether stereo will be enabled during the next draw (and subsequent draws until this is set again). @note: this should only be called between draws. If it's called by Qt event handlers, that should guarantee this, since they are atomic with respect to paintGL and paintGL never does recursive event processing. """ # future: if this could be called during paintGL, then we'd # need to reimplement it so that instead of setting self.stereo_enabled # directly, we'd set another attr which would be copied into it when # we call _update_stereo_settings at the start of the next paintGL. self.stereo_enabled = enabled if self.stereo_enabled: # have two images for the stereo rendering. # In some stereo_modes these are clipped left and right images; # in others they are drawn overlapping with different colormasks. # This is set up as needed by passing these values (as stereo_image) # to self._enable_stereo. self.stereo_images_to_draw = (-1, 1) else: # draw only once if stereo is disabled self.stereo_images_to_draw = (0,) return def stereo_image_hit_by_event(self, event): #bruce 080912 split this out """ return a value for caller to store into self.current_stereo_image to indicate which stereo image the mouse press event was in: 0 means stereo is disabled, or the two stereo images overlap (as opposed to being a left/right pair -- this is determined by self.stereo_mode) -1 means the left image (of a left/right pair) was clicked on +1 means the right image was clicked on """ # piotr 080529 wrote this in GLPane current_stereo_image = 0 if self.stereo_enabled: # if in side-by-side stereo if self.stereo_mode == 1 or \ self.stereo_mode == 2: # find out which stereo image was clicked in if event.x() < self.width / 2: current_stereo_image = -1 else: current_stereo_image = 1 return current_stereo_image # stereo rendering methods [piotr 080515 added these, and their calling code] def _enable_stereo(self, stereo_image, preserve_colors = False, no_clipping = False): """ Enables stereo rendering. This should be called before entering a drawing phase and should be accompanied by a self._disable_stereo call after the drawing for that phase. These methods push a modelview matrix on the matrix stack and modify the matrix. @param stereo_image: Indicates which stereo image is being drawn (-1 == left, 1 == right, 0 == stereo is disabled) @param preserve_colors: Disable color mask manipulations, which normally occur in anaglyph mode. (Also disable depth buffer clearing for 2nd image, which occurs then.) @param no_clipping: Disable clipping, which normally occurs in side-by-side mode. """ if not self.stereo_enabled: return glPushAttrib(GL_TRANSFORM_BIT) stereo_mode = self.stereo_mode stereo_separation = self.stereo_separation stereo_angle = self.stereo_angle # push the modelview matrix on the stack glMatrixMode(GL_MODELVIEW) glPushMatrix() separation = stereo_separation * self.scale angle = stereo_angle # might be modified below if stereo_mode <= 2: # side-by-side stereo mode # clip left or right image # reset the modelview matrix if not no_clipping: glPushMatrix() # Note: this might look redundant with the # glPushMatrix above, but removing it (and its glPopMatrix # 10 lines below) causes a bug (no image visible). # Guess: it's needed so the glLoadIdentity needed to set up # the clipping plane just below has only a temporary effect. # [bruce 080911 comment] glLoadIdentity() if stereo_image == -1: clip_eq = (-1.0, 0.0, 0.0, 0.0) else: clip_eq = ( 1.0, 0.0, 0.0, 0.0) # using GL_CLIP_PLANE5 for stereo clipping glClipPlane(GL_CLIP_PLANE5, clip_eq) glEnable(GL_CLIP_PLANE5) glPopMatrix() # for cross-eyed mode, exchange left and right views if stereo_mode == 2: angle *= -1 # translate images for side-by-side stereo glTranslatef(separation * stereo_image * self.right[0], separation * stereo_image * self.right[1], separation * stereo_image * self.right[2]) # rotate the stereo image ("toe-in" method) glRotatef(angle * stereo_image, self.up[0], self.up[1], self.up[2]) else: # Anaglyphs stereo mode - Red plus Blue, Cyan, or Green image. angle *= 0.5 if not preserve_colors: if stereo_image == -1: # red image glColorMask(GL_TRUE, GL_FALSE, GL_FALSE, GL_TRUE) else: # clear depth buffer to combine red/blue images # REVIEW: this would cause bugs in the predraw_glselectdict code # used for depth-testing selobj candidates. Maybe it does # not happen then? The name of the flag 'preserve_colors' # does not say anything about preserving depths. # Anyway, it *does* happen then, so I think there is a bug. # Also, remind me, what's the 4th arg to glColorMask? # [bruce 080911 comment] # # piotr 080911 response: You are right. This technically # causes a bug: the red image is not highlightable, # but actually when using anaglyph glasses, the bug is not # noticeable, as both red and blue images converge. # The bug becomes noticeable if user tries to highlight an # object without wearing the anaglyph glasses. # At this point, I think we can either leave it as it is, # or consider implementing anaglyph stereo by using # OpenGL alpha blending. # Also, I am not sure if highlighting problem is the only bug # that is caused by clearing the GL_DEPTH_BUFFER_BIT. glClear(GL_DEPTH_BUFFER_BIT) if stereo_mode == 3: # blue image glColorMask(GL_FALSE, GL_FALSE, GL_TRUE, GL_TRUE) elif stereo_mode == 4: # cyan image glColorMask(GL_FALSE, GL_TRUE, GL_TRUE, GL_TRUE) elif stereo_mode == 5: # green image glColorMask(GL_FALSE, GL_TRUE, GL_FALSE, GL_TRUE) # rotate the stereo image ("toe-in" method) glRotatef(angle * stereo_image, self.up[0], self.up[1], self.up[2]) return def _disable_stereo(self): """ Disables stereo rendering. This method pops a modelview matrix from the matrix stack. """ if not self.stereo_enabled: return if self.stereo_mode <= 2: # side-by-side stereo mode # make sure that the clipping plane is disabled glDisable(GL_CLIP_PLANE5) else: # anaglyphs stereo mode # enable all colors glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE) # restore the matrix glMatrixMode(GL_MODELVIEW) glPopMatrix() glPopAttrib() return def _update_stereo_settings(self): #bruce 080911 (bugfix, see docstring) """ set self.stereo_* attributes (mode, separation, angle) based on current user prefs values @note: this should be called just once per draw event, before anything might use these attributes, to make sure these settings remain constant throughout that event (perhaps not an issue since event handlers are atomic), and to ensure they remain correct relative to what was drawn in subsequent calls of mousePressEvent or mousepoints (necessary in case intervening user events modified the prefs values) """ if self.stereo_enabled: # this code (by Piotr) must be kept in synch with the code # which sets the values of these prefs (in another module) self.stereo_mode = env.prefs[stereoViewMode_prefs_key] self.stereo_separation = 0.01 * env.prefs[stereoViewSeparation_prefs_key] self.stereo_angle = -0.1 * (env.prefs[stereoViewAngle_prefs_key] - 25) return pass # end
NanoCAD-master
cad/src/graphics/widgets/GLPane_stereo_methods.py
# Copyright 2004-2009 Nanorex, Inc. See LICENSE file for details. """ GLPane_lighting_methods.py @version: $Id$ @copyright: 2004-2009 Nanorex, Inc. See LICENSE file for details. bruce 080910 split this out of class GLPane """ from graphics.drawing.gl_lighting import glprefs_data_used_by_setup_standard_lights from graphics.drawing.gl_lighting import _default_lights # REVIEW: rename as a constant? # note: pylint claims incorrectly that this import of _default_lights is unused. # In fact, it's used, then locally overridden. # (So the code is confusing but does use it. TODO: clean it up. [bruce 080918 comment]) from graphics.drawing.gl_lighting import setup_standard_lights from utilities.prefs_constants import glpane_lights_prefs_key from utilities.prefs_constants import light1Color_prefs_key from utilities.prefs_constants import light2Color_prefs_key from utilities.prefs_constants import light3Color_prefs_key import foundation.preferences as preferences import foundation.env as env from OpenGL.GL import glMatrixMode from OpenGL.GL import GL_MODELVIEW from OpenGL.GL import GL_PROJECTION from OpenGL.GL import glLoadIdentity from OpenGL.GL import glEnable from OpenGL.GL import GL_NORMALIZE from utilities.debug import print_compact_traceback from utilities.debug_prefs import debug_pref from utilities.debug_prefs import Choice_boolean_False _DEBUG_LIGHTING = False #bruce 050418 class GLPane_lighting_methods(object): """ private mixin for providing lighting methods to class GLPane """ #bruce 050311 wrote these in class GLPane (rush order for Alpha4) #bruce 080910 split them into a separate file # default values of instance variables # [bruce 051212 comment: not sure if this needs to be in sync with any other values; # also not sure if this is used anymore, since __init__ sets _lights from prefs db via loadLighting.] _lights = _default_lights _default_lights = _lights # this copy will never be changed need_setup_lighting = True # whether the next paintGL needs to call _setup_lighting (in our method setup_lighting_if_needed) _last_glprefs_data_used_by_lights = None #bruce 051212, replaces/generalizes _last_override_light_specular def setup_lighting_if_needed(self): #bruce 080910 un-inlined this if self.need_setup_lighting \ or (self._last_glprefs_data_used_by_lights != glprefs_data_used_by_setup_standard_lights( self.glprefs)) \ or debug_pref("always setup_lighting?", Choice_boolean_False): #bruce 060415 added debug_pref("always setup_lighting?"), # in GLPane and ThumbView [KEEP DFLTS THE SAME!!]; # using it makes specularity work on my iMac G4, # except for brief periods as you move mouse around to change selobj # (also observed on G5, but less frequently I think). # BTW using this (on G4) has no effect on whether "new wirespheres" # is needed to make wirespheres visible. # # (bruce 051126 added override_light_specular part of condition) # I don't know if it matters to avoid calling this every time... # in case it's slow, we'll only do it when it might have changed. self.need_setup_lighting = False # set to true again if setLighting is called self._setup_lighting() return def setLighting(self, lights, _guard_ = 6574833, gl_update = True): """ Set current lighting parameters as specified (using the format as described in the getLighting method docstring). This does not save them in the preferences file; for that see the saveLighting method. If option gl_update is False, then don't do a gl_update, let caller do that if they want to. """ assert _guard_ == 6574833 # don't permit optional args to be specified positionally!! try: # check, standardize, and copy what the caller gave us for lights res = [] lights = list(lights) assert len(lights) == 3 for c,a,d,s,x,y,z,e in lights: # check values, give them standard types r = float(c[0]) g = float(c[1]) b = float(c[2]) a = float(a) d = float(d) s = float(s) x = float(x) y = float(y) z = float(z) assert 0.0 <= r <= 1.0 assert 0.0 <= g <= 1.0 assert 0.0 <= b <= 1.0 assert 0.0 <= a <= 1.0 assert 0.0 <= d <= 1.0 assert 0.0 <= s <= 1.0 assert e in [0,1,True,False] e = not not e res.append( ((r,g,b),a,d,s,x,y,z,e) ) lights = res except: print_compact_traceback("erroneous lights %r (ignored): " % lights) return self._lights = lights # set a flag so we'll set up the new lighting in the next paintGL call self.need_setup_lighting = True #e maybe arrange to later save the lighting in prefs... don't know if this belongs here # update GLPane unless caller wanted to do that itself if gl_update: self.gl_update() return def getLighting(self): """ Return the current lighting parameters. [For now, these are a list of 3 tuples, one per light, each giving several floats and booleans (specific format is only documented in other methods or in their code).] """ return list(self._lights) def _setup_lighting(self): """ [private method] Set up lighting in the model (according to self._lights). [Called from both initializeGL and paintGL.] """ # note: there is some duplicated code in this method # in GLPane_lighting_methods (has more comments) and ThumbView, # but also significant differences. Should refactor sometime. # [bruce 060415/080912 comment] glEnable(GL_NORMALIZE) # bruce comment 050311: I don't know if this relates to lighting or not # grantham 20051121: Yes, if NORMALIZE is not enabled (and normals # aren't unit length or the modelview matrix isn't just rotation) # then the lighting equation can produce unexpected results. #bruce 050413 try to fix bug 507 in direction of lighting: ##k might be partly redundant now; not sure whether projection matrix needs to be modified here [bruce 051212] glMatrixMode(GL_PROJECTION) glLoadIdentity() glMatrixMode(GL_MODELVIEW) glLoadIdentity() #bruce 051212 moved most code from this method into new function, setup_standard_lights setup_standard_lights( self._lights, self.glprefs) # record what glprefs data was used by that, for comparison to see when we need to call it again # (not needed for _lights since another system tells us when that changes) self._last_glprefs_data_used_by_lights = glprefs_data_used_by_setup_standard_lights( self.glprefs) return def saveLighting(self): """ save the current lighting values in the standard preferences database """ try: prefs = preferences.prefs_context() key = glpane_lights_prefs_key # we'll store everything in a single value at this key, # making it a dict of dicts so it's easy to add more lighting attrs (or lights) later # in an upward-compatible way. # [update, bruce 051206: it turned out that when we added lots of info it became # not upward compatible, causing bug 1181 and making the only practical fix of that bug # a change in this prefs key. In successive commits I moved this key to prefs_constants, # then renamed it (variable and key string) to try to fix bug 1181. I would also like to find out # what's up with our two redundant storings of light color in prefs db, ###@@@ # but I think bug 1181 can be fixed safely this way without my understanding that.] (((r0,g0,b0),a0,d0,s0,x0,y0,z0,e0), \ ( (r1,g1,b1),a1,d1,s1,x1,y1,z1,e1), \ ( (r2,g2,b2),a2,d2,s2,x2,y2,z2,e2)) = self._lights # now process it in a cleaner way val = {} for (i, (c,a,d,s,x,y,z,e)) in zip(range(3), self._lights): name = "light%d" % i params = dict( color = c, \ ambient_intensity = a, \ diffuse_intensity = d, \ specular_intensity = s, \ xpos = x, ypos = y, zpos = z, \ enabled = e ) val[name] = params # save the prefs to the database file prefs[key] = val # This was printing many redundant messages since this method is called # many times while changing lighting parameters in the Preferences | Lighting dialog. # Mark 051125. #env.history.message( greenmsg( "Lighting preferences saved" )) except: print_compact_traceback("bug: exception in saveLighting (pref changes not saved): ") #e redmsg? return def loadLighting(self, gl_update = True): """ load new lighting values from the standard preferences database, if possible; if correct values were loaded, start using them, and do gl_update unless option for that is False; return True if you loaded new values, False if that failed """ try: prefs = preferences.prefs_context() key = glpane_lights_prefs_key try: val = prefs[key] except KeyError: # none were saved; not an error and not even worthy of a message # since this is called on startup and it's common for nothing to be saved. # Return with no changes. return False # At this point, you have a saved prefs val, and if this is wrong it's an error. # val format is described (partly implicitly) in saveLighting method. res = [] # will become new argument to pass to self.setLighting method, if we succeed for name in ['light0','light1','light2']: params = val[name] # a dict of ambient, diffuse, specular, x, y, z, enabled color = params['color'] # light color (r,g,b) a = params['ambient_intensity'] # ambient intensity d = params['diffuse_intensity'] # diffuse intensity s = params['specular_intensity'] # specular intensity x = params['xpos'] # X position y = params['ypos'] # Y position z = params['zpos'] # Z position e = params['enabled'] # boolean res.append( (color,a,d,s,x,y,z,e) ) self.setLighting( res, gl_update = gl_update) if _DEBUG_LIGHTING: print "_DEBUG_LIGHTING: fyi: Lighting preferences loaded" return True except: print_compact_traceback("bug: exception in loadLighting (current prefs not altered): ") #e redmsg? return False pass def restoreDefaultLighting(self, gl_update = True): """ restore the default (built-in) lighting preferences (but don't save them). """ # Restore light color prefs keys. env.prefs.restore_defaults([ light1Color_prefs_key, light2Color_prefs_key, light3Color_prefs_key, ]) self.setLighting( self._default_lights, gl_update = gl_update ) return True pass # end
NanoCAD-master
cad/src/graphics/widgets/GLPane_lighting_methods.py
# Copyright 2009 Nanorex, Inc. See LICENSE file for details. """ GLPane_csdl_collector.py -- classes for use as a GLPane's csdl_collector @author: Bruce @version: $Id$ @copyright: 2009 Nanorex, Inc. See LICENSE file for details. History: Bruce 090218 wrote this as part of Part_drawing_frame, then realized it belonged elsewhere and split it into a separate object on 090219 """ from utilities.debug import print_compact_stack from graphics.drawing.ColorSortedDisplayList import ColorSortedDisplayList from graphics.drawing.ColorSorter import ColorSorter # == class _GLPane_csdl_collector_superclass: """ """ use_drawingsets = False # whether to draw CSDLs using DrawingSets bare_primitives = None # None, or a CSDL for collecting bare primitives pass # == class GLPane_csdl_collector(_GLPane_csdl_collector_superclass): """ One of these is created whenever drawing a model, provided GLPane._before_drawing_csdls is called. It holds attributes needed for GLPane.draw_csdl to work (and helper methods for that as well). See superclass code comments for documentation of attributes. For more info, see docstring of GLPane._before_drawing_csdls. """ def __init__(self, glpane): ## print "\ninit GLPane_csdl_collector", glpane, glpane.drawing_phase self._glpane = glpane # note: this won't be a ref cycle once we're done with, # since glpane won't refer to us anymore then return def setup_for_drawingsets(self): # review: needed in fake_GLPane_csdl_collector too?? """ """ self.use_drawingsets = True self._drawingset_contents = {} def setup_for_bare_primitives(self): #bruce 090220 """ """ self.bare_primitives = ColorSortedDisplayList(reentrant = True) ColorSorter.start(self._glpane, self.bare_primitives) return def collect_csdl(self, csdl, intent): """ When self.use_drawingsets is set, model component drawing code which wants to draw a CSDL should pass it to this method rather than drawing it directly. This method just collects it into a dict based on intent. At the end of the current drawing frame, all csdls passed to this method will be added to (or maintained in) an appropriate DrawingSet, and all DrawingSets will be drawn, by external code which calls grab_intent_to_csdls_dict. @param csdl: a CSDL to draw later @type csdl: ColorSortedDisplayList @param intent: specifies how the DrawingSet which csdl ends up in should be drawn (transform, other GL state, draw options) @type intent: not defined here, but must be useable as a dict key @return: None This API requires that every csdl to be drawn must be passed here in every frame (though the DrawingSets themselves can be persistent and incrementally updated, depending on how the data accumulated here is used). A more incremental API would probably perform better but would be much more complex, having to deal with chunks which move in and out of self, get killed, or don't get drawn for any other reason, and also requiring chunks to "diff" their own drawing intents and do incremental update themselves. """ try: csdl_dict = self._drawingset_contents[intent] except KeyError: csdl_dict = self._drawingset_contents[intent] = {} csdl_dict[csdl.csdl_id] = csdl return def finish_bare_primitives(self): assert self.bare_primitives csdl = self.bare_primitives self.bare_primitives = None # precaution assert ColorSorter._parent_csdl is csdl ColorSorter.finish( draw_now = False) return csdl def grab_intent_to_csdls_dict(self): """ Return (with ownership) to the caller (and reset in self) a dict from intent (about how a csdl's drawingset should be drawn) to a set of csdls (as a dict from their csdl_id's), which includes exactly the CSDLs which should be drawn in this frame (whether or not they were drawn in the last frame). The intent and csdl pairs in what we return are just the ones which were passed to collect_csdl during this frame. """ res = self._drawingset_contents self._drawingset_contents = {} return res pass # == class fake_GLPane_csdl_collector(_GLPane_csdl_collector_superclass): """ Use one of these "between draws" to avoid or mitigate bugs. """ def __init__(self, glpane): print_compact_stack( "warning: fake_GLPane_csdl_collector is being instantiated: " ) return pass # end
NanoCAD-master
cad/src/graphics/widgets/GLPane_csdl_collector.py
NanoCAD-master
cad/src/graphics/widgets/__init__.py
# Copyright 2004-2008 Nanorex, Inc. See LICENSE file for details. """ GLPane_view_change_methods.py @author: Mark @version: $Id$ @copyright: 2004-2008 Nanorex, Inc. See LICENSE file for details. I think Mark wrote most or all of these, in GLPane.py. bruce 080912 split this out of class GLPane """ import time import math from Numeric import dot from geometry.VQT import V, Q, norm, vlen import foundation.env as env from utilities.Log import orangemsg from utilities.debug import print_compact_traceback from utilities.prefs_constants import animateStandardViews_prefs_key from utilities.prefs_constants import animateMaximumTime_prefs_key MIN_REPAINT_TIME = 0.01 # minimum time to repaint (in seconds) # == def typecheckViewArgs(q2, s2, p2, z2): #mark 060128 """ Typecheck the view arguments quat q2, scale s2, pov p2, and zoom factor z2 used by GLPane.snapToView() and GLPane.animateToView(). """ assert isinstance(q2, Q) assert isinstance(s2, float) assert len(p2) == 3 assert isinstance(p2[0], float) assert isinstance(p2[1], float) assert isinstance(p2[2], float) assert isinstance(z2, float) return # == class GLPane_view_change_methods(object): """ Private mixin superclass to provide view change methods to class GLPane, including view change animation methods, and some slot methods or direct submethods of those. @see: ops_view.py, which has UI slot methods that call some of these methods """ # note: is_animating is visible as a public attr of the main class is_animating = False # mark 060404 # Set to True while animating between views in animateToView() # so that update_selobj() in SelectAtoms_GraphicsMode will not # hover highlight objects under the cursor during that time. _repaint_duration = MIN_REPAINT_TIME # == view toolbar helper methods # [bruce 050418 made these from corresponding methods in MWsemantics.py, # which still exist but call these, perhaps after printing a history message. # Also revised them for assembly/part split, i.e. per-part namedView attributes.] def setViewHome(self): """ Change view to our model's home view (for glpane's current part). """ self.animateToNamedView( self.part.homeView) def setViewFitToWindow(self, fast = False): """ Change view so that the visible part of the entire model fits in the glpane. If <fast> is True, then snap to the view (i.e. don't animate). """ # Recalculate center and bounding box for all the visible chunks in the current part. # The way a 3d bounding box is used to calculate the fit is not adequate. I consider this a bug, but I'm not sure # how to best use the BBox object to compute the proper fit. Should ask Bruce. This will do for now. Mark 060713. # BUG: only chunks are considered. See comment in bbox_for_viewing_model. # [bruce 070919 comment] bbox = self.assy.bbox_for_viewing_model() center, scale = self.center_and_scale_from_bbox( bbox, klugefactor = 0.75 ) pov = V(-center[0], -center[1], -center[2]) if fast: self.snapToView(self.quat, scale, pov, 1.0) else: self.animateToView(self.quat, scale, pov, 1.0) def setViewZoomToSelection(self, fast = False): #Ninad 60903 """ Change the view so that only selected atoms, chunks and Jigs fit in the GLPane. (i.e. Zoom to the selection) If <fast> is True, then snap to the view """ #ninad060905: #This considers only selected atoms, movable jigs and chunks while doing fit to window. #Zoom to selection ignores other immovable jigs. (it clearly tells this in a history msg) # For future: Should work when a non movable jig is selected #Bugs due to use of Bbox remain as in fit to window. bbox = self.assy.bbox_for_viewing_selection() if bbox is None: env.history.message( orangemsg( " Zoom To Selection: No visible atoms , chunks or movable jigs selected" \ " [Acceptable Jigs: Motors, Grid Plane and ESP Image]" )) # KLUGE: the proper content of this message depends on the behavior # of bbox_for_viewing_selection, which should be extended to cover more # kinds of objects. return center, scale = self.center_and_scale_from_bbox( bbox, klugefactor = 0.85 ) #ninad060905 experimenting with the scale factor # [which was renamed to klugefactor after this comment was written]. # I see no change with various values! pov = V(-center[0], -center[1], -center[2]) if fast: self.snapToView(self.quat, scale, pov, 1.0) else: self.animateToView(self.quat, scale, pov, 1.0) return def setViewHomeToCurrent(self): """ Set the Home view to the current view. """ self.part.homeView.setToCurrentView(self) self.part.changed() # Mark [041215] def setViewRecenter(self, fast = False): """ Recenter the current view around the origin of modeling space. """ print "**in setViewRecenter" part = self.part part.computeBoundingBox() scale = (part.bbox.scale() * 0.75) + (vlen(part.center) * .5) # regarding the 0.75, it has the same role as the klugefactor # option of self.center_and_scale_from_bbox(). [bruce comment 070919] aspect = self.aspect if aspect < 1.0: scale /= aspect pov = V(0, 0, 0) if fast: self.snapToView(self.quat, scale, pov, 1.0) else: self.animateToView(self.quat, scale, pov, 1.0) def setViewProjection(self, projection): # Added by Mark 050918. """ Set projection, where 0 = Perspective and 1 = Orthographic. It does not set the prefs db value itself, since we don't want all user changes to projection to be stored in the prefs db, only the ones done from the Preferences dialog. """ # Set the checkmark for the Ortho/Perspective menu item in the View menu. # This needs to be done before comparing the value of self.ortho to projection # because self.ortho and the toggle state of the corresponding action may # not be in sync at startup time. This fixes bug #996. # Mark 050924. if projection: self.win.setViewOrthoAction.setChecked(1) else: self.win.setViewPerspecAction.setChecked(1) if self.ortho == projection: return self.ortho = projection # note: ortho is defined in GLPane_minimal. self.gl_update() def snapToNamedView(self, namedView): """ Snap to the destination view L{namedView}. @param namedView: The view to snap to. @type namedView: L{NamedView} """ self.snapToView(namedView.quat, namedView.scale, namedView.pov, namedView.zoomFactor) def animateToNamedView(self, namedView, animate = True): """ Animate to the destination view I{namedView}. @param namedView: The view to snap to. @type namedView: L{NamedView} @param animate: If True, animate between views. If False, snap to I{namedView}. If the user pref "Animate between views" is unchecked, then this argument is ignored. @type animate: boolean """ # Determine whether to snap (don't animate) to the destination view. if not animate or not env.prefs[animateStandardViews_prefs_key]: self.snapToNamedView(namedView) return self.animateToView(namedView.quat, namedView.scale, namedView.pov, namedView.zoomFactor, animate) return def snapToView(self, q2, s2, p2, z2, update_duration = False): """ Snap to the destination view defined by quat q2, scale s2, pov p2, and zoom factor z2. """ # Caller could easily pass these args in the wrong order. Let's typecheck them. typecheckViewArgs(q2, s2, p2, z2) self.quat = Q(q2) self.pov = V(p2[0], p2[1], p2[2]) self.zoomFactor = z2 self.scale = s2 if update_duration: self.gl_update_duration() else: self.gl_update() def rotateView(self, q2): """ Rotate current view to quat (viewpoint) q2 """ self.animateToView(q2, self.scale, self.pov, self.zoomFactor, animate = True) return # animateToView() uses "Normalized Linear Interpolation" # and not "Spherical Linear Interpolation" (AKA slerp), # which traces the same path as slerp but works much faster. # The advantages to this approach are explained in detail here: # http://number-none.com/product/Hacking%20Quaternions/ def animateToView(self, q2, s2, p2, z2, animate = True): """ Animate from the current view to the destination view defined by quat q2, scale s2, pov p2, and zoom factor z2. If animate is False *or* the user pref "Animate between views" is not selected, then do not animate; just snap to the destination view. """ # Caller could easily pass these args in the wrong order. Let's typecheck them. typecheckViewArgs(q2, s2, p2, z2) # Precaution. Don't animate if we're currently animating. if self.is_animating: return # Determine whether to snap (don't animate) to the destination view. if not animate or not env.prefs[animateStandardViews_prefs_key]: self.snapToView(q2, s2, p2, z2) return # Make copies of the current view parameters. q1 = Q(self.quat) s1 = self.scale p1 = V(self.pov[0], self.pov[1], self.pov[2]) z1 = self.zoomFactor # Compute the normal vector for current and destination view rotation. wxyz1 = V(q1.w, q1.x, q1.y, q1.z) wxyz2 = V(q2.w, q2.x, q2.y, q2.z) # The rotation path may turn either the "short way" (less than 180) or the "long way" (more than 180). # Long paths can be prevented by negating one end (if the dot product is negative). if dot(wxyz1, wxyz2) < 0: wxyz2 = V(-q2.w, -q2.x, -q2.y, -q2.z) # Compute the maximum number of frames for the maximum possible # rotation (180 degrees) based on how long it takes to repaint one frame. self.gl_update_duration() max_frames = max(1, env.prefs[animateMaximumTime_prefs_key]/self._repaint_duration) # Compute the deltas for the quat, pov, scale and zoomFactor. deltaq = q2 - q1 deltap = vlen(p2 - p1) deltas = abs(s2 - s1) deltaz = abs(z2 - z1) # Do nothing if there is no change b/w the current view to the new view. # Fixes bugs 1350 and 1170. mark 060124. if deltaq.angle + deltap + deltas + deltaz == 0: # deltaq.angle is always positive. return # Compute the rotation angle (in degrees) b/w the current and destination view. rot_angle = deltaq.angle * 180/math.pi # rotation delta (in degrees) if rot_angle > 180: rot_angle = 360 - rot_angle # go the short way # For each delta, compute the total number of frames each would # require (by itself) for the animation sequence. ### REVIEW: LIKELY BUG: integer division in rot_angle/180 [bruce 080912 comment] rot_frames = int(rot_angle/180 * max_frames) pov_frames = int(deltap * .2) # .2 based on guess/testing. mark 060123 scale_frames = int(deltas * .05) # .05 based on guess/testing. mark 060123 zoom_frames = int(deltaz * .05) # Not tested. mark 060123 # Using the data above, this formula computes the ideal number of frames # to use for the animation loop. It attempts to keep animation speeds consistent. total_frames = int( min(max_frames, max(3, rot_frames, pov_frames, scale_frames, zoom_frames))) ##print "total_frames =", total_frames # Compute the increments for each view parameter to use in the animation loop. rot_inc = (wxyz2 - wxyz1) / total_frames scale_inc = (s2 - s1) / total_frames zoom_inc = (z2 - z1) / total_frames pov_inc = (p2 - p1) / total_frames # Disable standard view actions on toolbars/menus while animating. # This is a safety feature to keep the user from clicking another view # animation action while this one is still running. self.win.enableViews(False) # 'is_animating' is checked in SelectAtoms_GraphicsMode.update_selobj() to determine whether the # GLPane is currently animating between views. If True, then update_selobj() will # not select any object under the cursor. mark 060404. self.is_animating = True try: #bruce 060404 for exception safety (desirable for both enableViews and is_animating) # Main animation loop, which doesn't draw the final frame of the loop. # See comments below for explanation. for frame in range(1, total_frames): # Notice no +1 here. # TODO: Very desirable to adjust total_frames inside the loop to maintain # animation speed consistency. mark 060127. del frame wxyz1 += rot_inc self.quat = Q(norm(wxyz1)) self.pov += pov_inc self.zoomFactor += zoom_inc self.scale += scale_inc self.gl_update_duration() # does the drawing, using recursive event processing continue # The animation loop did not draw the last frame on purpose. Instead, # we snap to the destination view. This also eliminates the possibility # of any roundoff error in the increment values, which might result in a # slightly wrong final viewpoint. self.is_animating = False # piotr 080325: Moved the flag reset to here to make sure # the last frame is redrawn the same way as it was before # the animation has started (e.g. to show external bonds # if they were suppressed during the animation). # I'm not entirely sure if that is a safe solution. # The is_animating attribute is used to disable view and # object renaming and I'm not sure if setting it "False" # early will not interfere with the renaming code. self.snapToView(q2, s2, p2, z2, update_duration = True) # snapToView() must call gl_update_duration() and not gl_update(), # or we'll have an issue if total_frames ever ends up = 1. In that case, # self._repaint_duration would never get set again because gl_update_duration() # would never get called again. BTW, gl_update_duration() (as of 060127) # is only called in the main animation loop above or when a new part is loaded. # gl_update_duration() should be called at other times, too (i.e. when # the display mode changes or something significant happens to the # model or display mode that would impact the rendering duration), # or better yet, the number of frames should be adjusted in the # main animation loop as it plays. This is left as something for me to do # later (probably after A7). This verbose comment is left as a reminder # to myself about all this. mark 060127. except: print_compact_traceback("bug: exception (ignored) during animateToView's loop: ") pass # Enable standard view actions on toolbars/menus. self.win.enableViews(True) # Finished animating. # piotr 080325: set it off again just to make sure it is off # if there was an exception in the animation loop self.is_animating = False # == def center_and_scale_from_bbox(self, bbox, klugefactor = 1.0): #bruce 070919 split this out of some other methods here. ### REVIEW: should this be a BBox method (taking aspect as an argument)? # Probably yes -- it uses self only for self.aspect. """ Compute and return a center, and a value for self.scale, which are sufficient to show the contents which were used to construct bbox (a BBox object), taking self.aspect into account. But reduce its size by mutiplying it by klugefactor (typically 0.75 or so, though the default value is 1.0 since anything less can make some bbox contents out of the view), as a kluge for the typical bbox corners being farther away than they need to be for most shapes of bbox contents. (KLUGE) (TODO: Ideally this should be fixed by computing bbox.scale() differently, e.g. doing it in the directions corresponding to glpane axes.) """ center = bbox.center() scale = float( bbox.scale() * klugefactor) #bruce 050616 added float() as a precaution, probably not needed # appropriate height to show everything, for square or wide glpane [bruce 050616 comment] aspect = self.aspect if aspect < 1.0: # tall (narrow) glpane -- need to increase self.scale # (defined in terms of glpane height) so part bbox fits in width # [bruce 050616 comment] scale /= aspect return center, scale # == def gl_update_duration(self, new_part = False): """ Redraw GLPane and update the repaint duration variable <self._repaint_duration> used by animateToView() to compute the proper number of animation frames. Redraws the GLPane twice if <new_part> is True and only saves the repaint duration of the second redraw. This is needed in the case of drawing a newly opened part, which takes much longer to draw the first time than the second (or thereafter). """ # The first redraw of a new part takes much longer than the second redraw. if new_part: self.gl_update() env.call_qApp_processEvents() # Required! self._repaint_start_time = time.time() self.gl_update() env.call_qApp_processEvents() # This forces the GLPane to update before executing the next gl_update(). self._repaint_end_time = time.time() self._repaint_duration = max(MIN_REPAINT_TIME, self._repaint_end_time - self._repaint_start_time) # _last_few_repaint_times is currently unused. May need it later. Mark 060116. # (bruce 080912: disabling it. if we revive it, something needs to initialize it to [].) ## self._last_few_repaint_times.append( self._repaint_duration) ## self._last_few_repaint_times = self._last_few_repaint_times[-5:] # keep at most the last five times ##if new_part: ## print "new part, repaint duration = ", self._repaint_duration ##else: ## print "repaint duration = ", self._repaint_duration return pass # end
NanoCAD-master
cad/src/graphics/widgets/GLPane_view_change_methods.py
# Copyright 2004-2008 Nanorex, Inc. See LICENSE file for details. """ DynamicTip.py - supports dynamic, informative tooltips of highlighted objects in GLPane History: 060817 Mark created dynamicTip class 060818 Ninad moved DynamicTip class into this file DynamicTip.py and added more @author: Mark, Ninad @version: $Id$ @copyright: 2004-2008 Nanorex, Inc. See LICENSE file for details. TODO: This needs refactoring into the part which has the mechanics of displaying the tooltip at the right time (some of the code for which must be in the glpane passed to the constructor, and is in fact only in class GLPane), and the part which knows what the tooltip should contain. One way would be to separate it into an abstract class and concrete subclass, mostly just by splitting the existing methods between them (except that maybeTip, mostly tooltip mechanics, has some model-specific knowledge), but we'd then need to either tell GLPane where to get the model-specific concrete class, or have it ask its .graphicsMode for that. Alternatively, we could just have this class ask the glpane.graphicsMode for the content of what/whether to display in the tooltip, and move that code from this into a new method in GraphicsMode (adding a stub version to the GraphicsMode API). That's probably simpler and better. However we do it, when classifying modules, the tooltip mechanics part should end up being classified in the same way as the GLPane, and the tooltip-text- determining part in the same way as GraphicsMode. """ import math import time from PyQt4.Qt import QToolTip, QRect, QPoint import foundation.env as env from model.chem import Atom from model.elements import Singlet from model.bonds import Bond from model.jigs import Jig from geometry.VQT import vlen from geometry.VQT import atom_angle_radians from platform_dependent.PlatformDependent import fix_plurals from utilities.Log import redmsg, quote_html from utilities.debug_prefs import debug_pref from utilities.debug_prefs import Choice_boolean_False from utilities.prefs_constants import dynamicToolTipWakeUpDelay_prefs_key from utilities.prefs_constants import dynamicToolTipAtomDistancePrecision_prefs_key from utilities.prefs_constants import dynamicToolTipBendAnglePrecision_prefs_key from utilities.prefs_constants import dynamicToolTipTorsionAnglePrecision_prefs_key from utilities.prefs_constants import dynamicToolTipAtomChunkInfo_prefs_key from utilities.prefs_constants import dynamicToolTipBondChunkInfo_prefs_key from utilities.prefs_constants import dynamicToolTipAtomPosition_prefs_key from utilities.prefs_constants import dynamicToolTipAtomDistanceDeltas_prefs_key from utilities.prefs_constants import dynamicToolTipBondLength_prefs_key from utilities.prefs_constants import dynamicToolTipAtomMass_prefs_key from utilities.prefs_constants import dynamicToolTipVdwRadiiInAtomDistance_prefs_key # russ 080715: For graphics debug tooltip. from OpenGL.GL import GL_BACK from OpenGL.GL import GL_DEPTH_COMPONENT from OpenGL.GL import GL_FRONT from OpenGL.GL import GL_READ_BUFFER from OpenGL.GL import GL_RGBA from OpenGL.GL import GL_STENCIL_INDEX from OpenGL.GL import GL_UNSIGNED_BYTE from OpenGL.GL import glGetInteger from OpenGL.GL import glReadBuffer from OpenGL.GL import glReadPixels from OpenGL.GL import glReadPixelsi from OpenGL.GL import glReadPixelsf _last_tipText = None # only used for debugging class DynamicTip: # Mark and Ninad 060817. """ For the support of dynamic, informative tooltips of a highlighted object in the GLPane. """ def __init__(self, glpane): """ @param glpane: An instance of class GLPane (since only it has the necessary code to set some timer-related attributes we depend on). """ self.glpane = glpane # <toolTipShown> is a flag set to True when a tooltip is currently displayed for the # highlighted object under the cursor. self.toolTipShown = False def maybeTip(self, helpEvent): """ Determines if this tooltip should be displayed. The tooltip will be displayed at helpEvent.globalPos() if an object is highlighted and the mouse hasn't moved for some period of time, called the "wake up delay" period, which is a user pref (not yet implemented in the Preferences dialog) currently set to 1 second. maybeTip() is called by GLPane.timerEvent() whenever the cursor is not moving to determine if the tooltip should be displayed. @param helpEvent: a QHelpEvent constructed by the caller @type helpEvent: QHelpEvent """ # docstring used to also say: ## For more details about this member, see Qt documentation on QToolTip.maybeTip(). # but this is unclear to me (since this class does not inherit from # QToolTip), so I removed it. [bruce 081208] debug = debug_pref("GLPane: graphics debug tooltip?", Choice_boolean_False, prefs_key = True ) glpane = self.glpane selobj = glpane.selobj if debug: # russ 080715: Graphics debug tooltip. # bruce 081208/081211: revised, moved out of _getToolTipText, # made debug_pref. # note: we don't use glpane.MousePos since it's not reliable -- # only some graphicsModes store it, and only in mouse press events. # Note: double buffering applies only to the color buffer, # not the stencil or depth buffers, which have only one copy. # The setting of GL_READ_BUFFER should have no effect on # glReadPixelsf from those buffers. # [bruce 081211 comment, based on Russ report of OpenGL doc] pos = helpEvent.pos() wX = pos.x() wY = glpane.height - pos.y() #review: off by 1?? wZ = glReadPixelsf(wX, wY, 1, 1, GL_DEPTH_COMPONENT)[0][0] stencil = glReadPixelsi(wX, wY, 1, 1, GL_STENCIL_INDEX)[0][0] savebuff = glGetInteger(GL_READ_BUFFER) whichbuff = {GL_FRONT:"front", GL_BACK:"back"}.get(savebuff, "unknown") redraw_counter = env.redraw_counter # Pixel data is sign-wrapped, in spite of specifying unsigned_byte. def us(b): if b < 0: return 256 + b else: return b def pixvals(buff): glReadBuffer(buff) gl_format, gl_type = GL_RGBA, GL_UNSIGNED_BYTE rgba = glReadPixels( wX, wY, 1, 1, gl_format, gl_type )[0][0] return ( "rgba %u, %u, %u, %u" % (us(rgba[0]), us(rgba[1]), us(rgba[2]), us(rgba[3])) ) def redifnot(v1, v2, text): if v1 != v2: return redmsg(text) else: return text front_pixvals = pixvals(GL_FRONT) back_pixvals = pixvals(GL_BACK) glReadBuffer(savebuff) # restore the saved value tipText = ( "env.redraw = %d; selobj = %s<br>" % (redraw_counter, quote_html(str(selobj)),) + # note: sometimes selobj is an instance of _UNKNOWN_SELOBJ_class... relates to testmode bug from renderText # (confirmed that renderText zaps stencil and that that alone causes no bug in other graphicsmodes) # TODO: I suspect this can be printed even during rendering... need to print glpane variables # which indicate whether we're doing rendering now, e.g. current_glselect, drawing_phase; # also modkeys (sp?), glselect_wanted "mouse position (xy): %d, %d<br>" % (wX, wY,) + "depth %f, stencil %d<br>" % (wZ, stencil) + redifnot(whichbuff, "back", "current read buffer: %s<br>" % whichbuff ) + redifnot(glpane.glselect_wanted, 0, "glselect_wanted: %s<br>" % (glpane.glselect_wanted,) ) + redifnot(glpane.current_glselect, False, "current_glselect: %s<br>" % (glpane.current_glselect,) ) + redifnot(glpane.drawing_phase, "?", "drawing_phase: %s<br>" % (glpane.drawing_phase,) ) + "front: " + front_pixvals + "<br>" + redifnot(back_pixvals, front_pixvals, "back: " + back_pixvals ) ) global _last_tipText if tipText != _last_tipText: print print tipText _last_tipText = tipText pass # use tipText below else: # <motionlessCursorDuration> is the amount of time the cursor (mouse) has been motionless. motionlessCursorDuration = time.time() - glpane.cursorMotionlessStartTime # Don't display the tooltip yet if <motionlessCursorDuration> hasn't exceeded the "wake up delay". # The wake up delay is currently set to 1 second in prefs_constants.py. Mark 060818. if motionlessCursorDuration < env.prefs[dynamicToolTipWakeUpDelay_prefs_key]: self.toolTipShown = False return # If an object is not currently highlighted, don't display a tooltip. if not selobj: return # If the highlighted object is a singlet, # don't display a tooltip for it. if isinstance(selobj, Atom) and (selobj.element is Singlet): return if self.toolTipShown: # The tooltip is already displayed, so return. # Do not allow tip() to be called again or it will "flash". return tipText = self._getToolTipText() pass # show the tipText if not tipText: tipText = "" # This makes sure that dynamic tip is not displayed when # the highlightable object is 'unknown' to the dynamic tip class. # (From QToolTip.showText doc: "If text is empty the tool tip is hidden.") showpos = helpEvent.globalPos() if debug: # show it a little lower to avoid the cursor obscuring the tooltip. # (might be useful even when not debugging, depending on the cursor) # [bruce 081208] showpos = showpos + QPoint(0, 10) QToolTip.showText(showpos, tipText) #@@@ ninad061107 works fine but need code review self.toolTipShown = True def _getToolTipText(self): # Mark 060818, Ninad 060818 """ Return the tooltip text to display, which depends on what is selected and what is highlighted (found by examining self.glpane). @return: tooltip text to be shown @rtype: str Features implemented: - If nothing is selected, return the name of the highlighted object. - If one atom is selected, return the distance between it and the highlighted atom. - If two atoms are selected, return the angle between them and the highlighted atom. - Preferences for setting the precision (decimal place) for each measurement. - Preferences for displaying atom chunk info, bond chunk info, Atom distance Deltas, atom coordinates, bond length (nuclear distance), bond type. - Displays Jig info For later: - If three atoms are selected, return the torsion angle between them and the highlighted atom. - We also need to truncate long item info strings. For example, if an item has a very long name it should truncate it with 3 dots, like "item na...") """ glpane = self.glpane #ninad060831 - First I defined the following in the _init method of this class. But the preferences were #not updated immediately when changed from prefs dialog. So I moved those definitions below and now it works fine self.atomDistPrecision = env.prefs[dynamicToolTipAtomDistancePrecision_prefs_key] #int self.bendAngPrecision = env.prefs[dynamicToolTipBendAnglePrecision_prefs_key] #int self.torsionAngPrecision = env.prefs[dynamicToolTipTorsionAnglePrecision_prefs_key] #int self.isAtomChunkInfo = env.prefs[dynamicToolTipAtomChunkInfo_prefs_key]#boolean self.isBondChunkInfo = env.prefs[dynamicToolTipBondChunkInfo_prefs_key]#boolean self.isAtomPosition = env.prefs[dynamicToolTipAtomPosition_prefs_key]#boolean self.isAtomDistDeltas = env.prefs[dynamicToolTipAtomDistanceDeltas_prefs_key]#boolean self.isBondLength = env.prefs[dynamicToolTipBondLength_prefs_key] #boolean self.isAtomMass = env.prefs[dynamicToolTipAtomMass_prefs_key] #boolean objStr = self.getHighlightedObjectInfo(self.atomDistPrecision) selectedAtomList = glpane.assy.getOnlyAtomsSelectedByUser() selectedJigList = glpane.assy.getSelectedJigs() ppa2 = glpane.assy.ppa2 # previously picked atom ppa2Exists = self.lastPickedInSelAtomList(ppa2, selectedAtomList) ppa3 = glpane.assy.ppa3 #atom picked before ppa2 ppa3Exists = self.lastTwoPickedInSelAtomList(ppa2, ppa3, selectedAtomList) #checks if *both* ppa2 and ppa3 exist if len(selectedAtomList) == 0: return objStr #ninad060818 Give the distance info if only one atom is selected in the glpane (and is not the highlighted one) #If a 'last picked' atom exists (and is still selected, then it returns distance between that last picked and highlighted #If the highlighted atom is also selected/last picked , only give atom info don't give '0' distance info" #Known bug: If many atoms selected, if ppa2 and ppa2 exists and if ppa2 is deleted, it doesn't display the distance between #highlighted and ppa3. (as of 060818 it doesn't even display the atom info ..but thats not a bug just NIY that I need to #handle somewhere else. elif isinstance(glpane.selobj, Atom) and (len(selectedAtomList) == 1 ): if self.getDistHighlightedAtomAndSelectedAtom(selectedAtomList, ppa2, self.atomDistPrecision): distStr = self.getDistHighlightedAtomAndSelectedAtom(selectedAtomList, ppa2, self.atomDistPrecision) return objStr + "<br>" + distStr else: return objStr #ninad060821 Give the angle info if only 2 atoms are selected (and the selection doesn't include highlighted atom) #if ppa2 and ppa3 both exist (and still selected) then it returns angle between them #If the highlighted atom is also selected/last picked/lasttolastpicked , only give atom and distance info don't give angle info #If distance info is not available for some reasons (e.g. no ppa2 or more than 2 atoms region selected etc, return Distance info only) elif isinstance(glpane.selobj, Atom) and ( len(selectedAtomList) == 2 or len(selectedAtomList) == 3): if self.getAngleHighlightedAtomAndSelAtoms(ppa2, ppa3, selectedAtomList, self.bendAngPrecision): angleStr = \ self.getAngleHighlightedAtomAndSelAtoms(ppa2, ppa3, selectedAtomList, self.bendAngPrecision) return objStr + "<br>" + angleStr else: if self.getDistHighlightedAtomAndSelectedAtom(selectedAtomList, ppa2, self.atomDistPrecision): distStr = \ self.getDistHighlightedAtomAndSelectedAtom(selectedAtomList, ppa2, self.atomDistPrecision) return objStr + "<br>" + distStr else: return objStr #ninad060822 For all other cases, simply return the object info. else: return objStr #@@@ ninad060818 ...if we begin to support other objects (other than jig/chunk/bonds/atoms) #then we need to retirn glpane.selobj """elif "three atoms are selected": self torsionStr = self.getTorsionHighlightedAtomAndSelAtoms() angleStr = self.getAngleHighlightedAtomAndSelAtoms() distStr = self.getDistHighlightedAtomAndSelectedAtom() return torsionStr + "<br>" + angleStr + "<br>" + distStr""" def getHighlightedObjectInfo(self, atomDistPrecision): """ Returns the info such as name, id, xyz coordinates etc of the highlighed object. """ glpane = self.glpane atomposn = None atomChunkInfo = None selobj = glpane.selobj # ---- Atom Info ---- if isinstance(selobj, Atom): atomInfoStr = selobj.getToolTipInfo(self.isAtomPosition, self.isAtomChunkInfo, self.isAtomMass, atomDistPrecision) return atomInfoStr # ----Bond Info---- if isinstance(selobj, Bond): bondInfoStr = selobj.getToolTipInfo(self.isBondChunkInfo, self.isBondLength, atomDistPrecision) return bondInfoStr # ---- Jig Info ---- if isinstance(selobj, Jig): jigStr = selobj.getToolTipInfo() return jigStr if isinstance(selobj, glpane.assy.Chunk): chunkStr = selobj.getToolTipInfo() return chunkStr #@@@ninad060818 In future if we support other object types in glpane, do we need a check for that? # e.g. else: return "unknown object" . def getDistHighlightedAtomAndSelectedAtom(self, selectedAtomList, ppa2, atomDistPrecision): """ Returns the distance between the selected atom and the highlighted atom. If there is only one atom selected and is same as highlighed atom, then it returns an empty string. (then the function calling this routine needs to handle that case.) """ glpane = self.glpane selectedAtom = None atomDistDeltas = None #initial value of distStr. (an empty string) distStr = '' if len(selectedAtomList) > 2: # ninad060824 don't show atom distance info when there are more than 2 atoms selected. Fixes bug2225 return False #ninad060821 It is posible that 2 atoms are selected and one is highlighted. This condition allows the function use in the conditional loop that shows angle between the selkected and highlighted atoms if len(selectedAtomList) ==2 and glpane.selobj in selectedAtomList: #this means the highlighted object is also in this list i = selectedAtomList.index(glpane.selobj) if i == 0: #ninad060821 This is a clumsy way of knowing which atom is which. Okay for now since there are only 2 atoms selectedAtom = selectedAtomList[1] else: selectedAtom = selectedAtomList[0] if len(selectedAtomList) == 1: #ninad060821 disabled the case where many atoms are selected and there still exists a last picked. I did this becasue #it is confusing. Example: I picked an atom. Now I region selected another atom (after pick operation) then I highlight an atom. #it shows the distance between the highlighed and the picked and not highlighted and region selected. This is not good #If we have a way to know when region select operation was performed (before or after) then we can implement it #again. Probably selectedAtomList maintains this record? Should we check the list to see if ppa2 comes before or after the # region selection? It is complecated. Need to discuss with Bruce and Mark. Not implementing it right now. #This also invalidates the need to pass ppa2 as an arg to this function. Still keeping it until I hear back from Bruce/Mark #if ppa2: #selectedAtom = ppa2 #ninad060818 This handles a case when there are many atoms selected and there still exists a 'last picked' one #else: #selectedAtom = selectedAtomList[0] #buggy if there are more than 2 atoms selected. But its okay because I am handling it correctly elsewhere where (I am calling this function) ninad060821 selectedAtom = selectedAtomList[0] xyz = glpane.selobj.posn() # round the distance value using atom distance precision preference ninad 060822 #ninad060822: Note: In prefs constant.py, I am using for example-- # ('atom_distance_precision', 'int', dynamicToolTipAtomDistancePrecision_prefs_key, 3) #Notice that the digit is not 3.0 but is simply 3 as its an integer. #I changed to to plain 3 because I got a Deprecation warning: integer arg expected, got float roundedDist = str(round(vlen(xyz - selectedAtom.posn()), atomDistPrecision)) if env.prefs[dynamicToolTipVdwRadiiInAtomDistance_prefs_key]: rvdw1 = glpane.selobj.element.rvdw rvdw2 = selectedAtom.element.rvdw dist = vlen(xyz - selectedAtom.posn()) + rvdw1 + rvdw2 roundedDistIncludingVDWString = ("2.Including Vdw radii:" \ " %s A") %(str(round(dist, atomDistPrecision))) else: roundedDistIncludingVDWString = '' #ninad060818 No need to display disance info if highlighed object and #lastpicked/ only selected object are identical if selectedAtom: if selectedAtom is not glpane.selobj: distStr = ("<font color=\"#0000FF\">Distance %s-%s :</font><br>"\ "1.Center to center:</font>"\ " %s A" %(glpane.selobj, selectedAtom, roundedDist)) if roundedDistIncludingVDWString: distStr += "<br>" + roundedDistIncludingVDWString atomDistDeltas = self.getAtomDistDeltas(self.isAtomDistDeltas, atomDistPrecision, selectedAtom) if atomDistDeltas: distStr += "<br>" + atomDistDeltas return distStr def getAngleHighlightedAtomAndSelAtoms(self, ppa2, ppa3, selectedAtomList, bendAngPrecision): """ Returns the angle between the last two selected atoms and the current highlighted atom. If the highlighed atom is also one of the selected atoms and there are only 2 selected atoms other than the highlighted one then it returns None.(then the function calling this routine needs to handle that case.) """ glpane = self.glpane lastSelAtom = None secondLastSelAtom = None ppa3Exists = self.lastTwoPickedInSelAtomList(ppa2, ppa3, selectedAtomList) #checks if *both* ppa2 and ppa3 exist if len(selectedAtomList) ==3 and glpane.selobj in selectedAtomList: if ppa3Exists and not (glpane.selobj is ppa2 or glpane.selobj is ppa3): lastSelAtom = ppa2 secondLastSelAtom = ppa3 else: #ninad060825 revised the following. Earlier code in v1.8 was correct but this one is simpler. Suggested by Bruce. I have tested it and is safe. tempAtomList =list(selectedAtomList) tempAtomList.remove(glpane.selobj) lastSelAtom = tempAtomList[0] secondLastSelAtom = tempAtomList[1] if len(selectedAtomList) == 2: #here I (ninad) don't care about whether itselected atom is also highlighted. It is handled below. if ppa3Exists: lastSelAtom = ppa2 secondLastSelAtom = ppa3 else: lastSelAtom = selectedAtomList[0] secondLastSelAtom = selectedAtomList[1] #ninad060821 No need to display angle info if highlighed object and lastpicked or secondlast picked # object are identical if glpane.selobj in selectedAtomList: return False if lastSelAtom and secondLastSelAtom: angle = atom_angle_radians( glpane.selobj, lastSelAtom,secondLastSelAtom ) * 180 / math.pi roundedAngle = str(round(angle, bendAngPrecision)) angleStr = fix_plurals("<font color=\"#0000FF\">Angle %s-%s-%s:</font> %s degree(s)" %(glpane.selobj, lastSelAtom, secondLastSelAtom, roundedAngle)) return angleStr else: return False def getTorsionHighlightedAtomAndSelAtoms(self): """ Return the torsion angle between the last 3 selected atoms and the highlighed atom, If the highlighed atom is also selected, it excludes it while finding the last 3 selected atoms. If the highlighed atom is also one of the selected atoms and there are only 2 selected atoms other than the highlighted one then it returns None. (then the function calling this routine needs to handle that case.) """ return False def lastPickedInSelAtomList(self, ppa2, selectedAtomList): """ Checks whether the last atom picked (ppa2) exists in the atom list. @return: True if I{ppa2} is in the atom list. @rtype: bool """ if ppa2 in selectedAtomList: return True else: return False def lastTwoPickedInSelAtomList(self, ppa2, ppa3, selectedAtomList): """ Checks whether *both* the last two picked atoms (ppa2 and ppa3) exist in I{selectedAtomList}. @return: True if both atoms exist in the atom list. @rtype: bool """ if (ppa2 and ppa3) in selectedAtomList: return True else: return False def lastThreePickedInSelAtomList(self, ppa2, ppa3, ppa4): """ Checks whether *all* three picked atoms (ppa2 , ppa3 and ppa4) exist in the atom list. @return: True if all three exist in the atom list. @rtype: bool @note: there is no ppa4 yet - ninad060818 """ pass def getAtomDistDeltas(self, isAtomDistDeltas, atomDistPrecision, selectedAtom): """ Returns atom distance deltas (delX, delY, delZ) string if the 'Show atom distance delta info' in dynamic tooltip is checked from the user prefs. Otherwise returns None. """ glpane = self.glpane if isAtomDistDeltas: xyz = glpane.selobj.posn() xyzSelAtom = selectedAtom.posn() deltaX = str(round(vlen(xyz[0] - xyzSelAtom[0]), atomDistPrecision)) deltaY = str(round(vlen(xyz[1] - xyzSelAtom[1]), atomDistPrecision)) deltaZ = str(round(vlen(xyz[2] - xyzSelAtom[2]), atomDistPrecision)) atomDistDeltas = "<font color=\"#0000FF\">DeltaX:</font> " \ + deltaX + "<br>" \ + "<font color=\"#0000FF\">DeltaY:</font> " \ + deltaY + "<br>" \ + "<font color=\"#0000FF\">DeltaZ:</font> " \ + deltaZ return atomDistDeltas else: return None # end
NanoCAD-master
cad/src/graphics/widgets/DynamicTip.py
# Copyright 2004-2009 Nanorex, Inc. See LICENSE file for details. """ GLPane_minimal.py -- common superclass for GLPane-like widgets. @version: $Id$ @copyright: 2004-2009 Nanorex, Inc. See LICENSE file for details. History: bruce 070914 made this to remind us that GLPane and ThumbView need a common superclass (and have common code that needs merging). It needs to be in its own file to avoid import loop problems. """ import math from OpenGL.GL import GL_CULL_FACE from OpenGL.GL import GL_DEPTH_TEST from OpenGL.GL import GL_MODELVIEW from OpenGL.GL import GL_PROJECTION from OpenGL.GL import GL_SMOOTH from OpenGL.GL import GL_VIEWPORT from OpenGL.GL import glDepthRange from OpenGL.GL import glEnable from OpenGL.GL import glFrustum from OpenGL.GL import glGetIntegerv from OpenGL.GL import glLoadIdentity from OpenGL.GL import glMatrixMode from OpenGL.GL import glOrtho from OpenGL.GL import glRotatef from OpenGL.GL import glShadeModel from OpenGL.GL import glTranslatef from OpenGL.GL import glViewport from OpenGL.GLU import gluPickMatrix from PyQt4.QtOpenGL import QGLFormat from PyQt4.QtOpenGL import QGLWidget from Numeric import dot from geometry.VQT import norm, angleBetween from geometry.VQT import V, Q from graphics.behaviors.Trackball import Trackball from model.NamedView import NamedView from utilities.prefs_constants import undoRestoreView_prefs_key from utilities.prefs_constants import startup_GLPane_scale_prefs_key from utilities.prefs_constants import enableAntiAliasing_prefs_key from utilities.constants import default_display_mode from utilities.debug_prefs import Choice from utilities.debug_prefs import debug_pref from utilities.debug import print_compact_traceback import foundation.env as env import graphics.drawing.drawing_globals as drawing_globals from graphics.drawing.setup_draw import setup_drawer from graphics.drawing.draw_grid_lines import setup_draw_grid_lines from graphics.widgets.GLPane_drawingset_methods import GLPane_drawingset_methods # == DEPTH_TWEAK_UNITS = (2.0)**(-32) DEPTH_TWEAK_VALUE = 100000 # For bond cylinders subject to shorten_tubes: # on my iMac G5, 300 is enough to prevent "patchy highlighting" problems # except sometimes at the edges. 5000 even fixes the edges and causes no # known harm, so we'd use that value if only that platform mattered. # # But, on Windows XP (Ninad & Tom), much higher values are needed. # By experiment, 100000 is enough on those platforms, and doesn't seem to # be too large on them or on my iMac, so we'll go with that for now, # but leave it in as a debug_pref. (We made no attempt to get a precise # estimate of the required value -- we only know that 10000 is not enough.) # # We don't know why a higher value is needed on Windows. Could the # depth buffer bit depth be different?? This value works out to a bit # more than one resolution unit for a 16-bit depth buffer, so that might # be a plausible cause. But due to our limited testing, the true difference # in required values on these platforms might be much smaller. # # [bruce 070926] # Russ 080925: Moved DEPTH_TWEAK in to GLPane_minimal. # DEPTH_TWEAK = DEPTH_TWEAK_UNITS * DEPTH_TWEAK_VALUE # changed by setDepthRange_setup_from_debug_pref DEPTH_TWEAK_CHOICE = \ Choice( [0,1,3,10, 100,200,300,400,500,600,700,800,900,1000, 2000,3000,4000,5000, 10000, 100000, 10**6, 10**7, 10**8], defaultValue = DEPTH_TWEAK_VALUE ) # == class GLPane_minimal(QGLWidget, GLPane_drawingset_methods, object): #bruce 070914 """ Mostly a stub superclass, just so GLPane and ThumbView can have a common superclass. TODO: They share a lot of code, which ought to be merged into this superclass. Once that happens, it might as well get renamed. """ # bruce 070920 added object superclass to our subclass GLPane; # bruce 080220 moved object superclass from GLPane to this class. # Purpose is to make this a new-style class so as to allow # defining a python property in any subclass. # bruce 090219 added GLPane_drawingset_methods mixin superclass # (for draw_csdl method; ok to ignore pylint warning about not # calling its __init__ method (it doesn't have one); # requires calling _before_drawing_csdls and # _after_drawing_csdls in all our subclass draw-like methods; # to help with this the mixin provides methods # _call_func_that_draws_model and # _call_func_that_draws_objects) # note: every subclass defines .assy as an instance variable or property # (as of bruce 080220), but we can't define a default value or property # for that here, since some subclasses define it in each way # (and we'd have to know which way to define a default value correctly). # class constants SIZE_FOR_glSelectBuffer = 10000 # guess, probably overkill, seems to work, no other value was tried # default values of instance variables: shareWidget = None is_animating = False #bruce 080219 fix bug 2632 (unverified) initialised = False _resize_counter = 0 drawing_phase = '?' # overridden in GLPane_rendering_methods, but needed for # debug prints that might happen in any class of GLPane [bruce 090220] # default values of subclass-specific constants permit_draw_bond_letters = True #bruce 071023 permit_shaders = False #bruce 090224 # default False until shaders can work with more than one glpane # (set to true in the main GLPane) _general_appearance_change_indicator = 0 #bruce 090306 # note: strictly speaking, ThumbView should update this like GLPane does, # but that's difficult (it has no part or assy in general), # and not very important (cosmetic bug when user changes certain prefs, # worked around by changing what's shown in the ThumbView). useMultisample = env.prefs[enableAntiAliasing_prefs_key] glprefs = None def __init__(self, parent, shareWidget, useStencilBuffer): """ #doc @note: If shareWidget is specified, useStencilBuffer is ignored: set it in the widget you're sharing with. """ if shareWidget: self.shareWidget = shareWidget #bruce 051212 glformat = shareWidget.format() QGLWidget.__init__(self, glformat, parent, shareWidget) if not self.isSharing(): assert 0, "%r refused to share GL display list namespace " \ "with %r" % (self, shareWidget) return else: glformat = QGLFormat() if (useStencilBuffer): glformat.setStencil(True) # set gl format to request stencil buffer # (needed for mouseover-highlighting of objects of general # shape in BuildAtoms_Graphicsmode.bareMotion) [bruce 050610] if (self.useMultisample): # use full scene anti-aliasing on hardware that supports it # (note: setting this True works around bug 2961 on some systems) glformat.setSampleBuffers(True) QGLWidget.__init__(self, glformat, parent) pass self.glprefs = drawing_globals.glprefs # future: should be ok if this differs for different glpanes, # even between self and self.shareWidget. AFAIK, the refactoring # I'm doing yesterday and today means this would work fine, # or at least it does most of what would be required for that. # [bruce 090304] self._initialize_view_attributes() # Initial value of depth "constant" (changeable by prefs.) self.DEPTH_TWEAK = DEPTH_TWEAK_UNITS * DEPTH_TWEAK_VALUE self.trackball = Trackball(10, 10) self._functions_to_call_when_gl_context_is_current = [] # piotr 080714: Defined this attribute here in case # chunk.py accesses it in ThumbView. self.lastNonReducedDisplayMode = default_display_mode # piotr 080807 # Most recent quaternion to be used in animation timer. self.last_quat = None self.transforms = [] ### TODO: clear this at start of frame, complain if not clear # stack of current transforms (or Nodes that generate them) # [bruce 090220] # Note: this may be revised once we have TransformNode, # e.g. we might push their dt and st separately; # note we might need to push a "slot" for them if they might # change before being popped, or perhaps even if they might # change between the time pushed and the time later used # (by something that collects them from here in association # with a ColorSortedDisplayList). return def _initialize_view_attributes(self): #bruce 090220 split this out """ Initialize the current view attributes """ # note: these are sometimes saved in or loaded from # the currently displayed part or its mmp file # rotation self.quat = Q(1, 0, 0, 0) # point of view (i.e. negative of center of view) self.pov = V(0.0, 0.0, 0.0) # half-height of window in Angstroms (reset by certain view-changing operations) self.scale = float(env.prefs[startup_GLPane_scale_prefs_key]) # zoom factor self.zoomFactor = 1.0 # Note: I believe (both now, and in a comment dated 060829 which is # now being removed from GLPane.py) that nothing ever sets # self.zoomFactor to anything other than 1.0, though there is code # which could do this in theory. I think zoomFactor was added as # one way to implement zoomToArea, but another way (changing scale) # was chosen, which makes zoomFactor useless. Someday we should # consider removing it, unless we think it might be useful for # something in the future. [bruce 080910 comment] return # define properties which return model-space vectors # corresponding to various directions relative to the screen # (can be used during drawing or when handling mouse events) # # [bruce 080912 turned these into properties, and optimized; # before that, this was done by __getattr__ in each subclass] def __right(self, _q = V(1, 0, 0)): return self.quat.unrot(_q) right = property(__right) def __left(self, _q = V(-1, 0, 0)): return self.quat.unrot(_q) left = property(__left) def __up(self, _q = V(0, 1, 0)): return self.quat.unrot(_q) up = property(__up) def __down(self, _q = V(0, -1, 0)): return self.quat.unrot(_q) down = property(__down) def __out(self, _q = V(0, 0, 1)): return self.quat.unrot(_q) out = property(__out) def __lineOfSight(self, _q = V(0, 0, -1)): return self.quat.unrot(_q) lineOfSight = property(__lineOfSight) def get_angle_made_with_screen_right(self, vec): """ Returns the angle (in degrees) between screen right direction and the given vector. It returns positive angles (between 0 and 180 degrees) if the vector lies in first or second quadrants (i.e. points more up than down on the screen). Otherwise the angle returned is negative. """ #Ninad 2008-04-17: This method was added AFTER rattlesnake rc2. #bruce 080912 bugfix: don't give theta the wrong sign when # dot(vec, self.up) < 0 and dot(vec, self.right) == 0. vec = norm(vec) theta = angleBetween(vec, self.right) if dot(vec, self.up) < 0: theta = - theta return theta def __get_vdist(self): """ Recompute and return the desired distance between eyeball and center of view. """ #bruce 070920 revised; bruce 080912 moved from GLPane into GLPane_minimal # Note: an old comment from elsewhere in GLPane claims: # bruce 041214 comment: some code assumes vdist is always 6.0 * self.scale # (e.g. eyeball computations, see bug 30), thus has bugs for aspect < 1.0. # We should have glpane attrs for aspect, w_scale, h_scale, eyeball, # clipping planes, etc, like we do now for right, up, etc. ###e # I don't know if vdist could ever have a different value, # or if we still have aspect < 1.0 bugs due to some other cause. return 6.0 * self.scale vdist = property(__get_vdist) def eyeball(self): #bruce 060219 ##e should call this to replace equivalent formulae in other places """ Return the location of the eyeball in model coordinates. @note: this is not meaningful except when using perspective projection. """ ### REVIEW: whether this is correct for tall aspect ratio GLPane. # See also the comment in __get_vdist, above, mentioning bug 30. # There is related code in writepovfile which computes a camera position # which corrects vdist when aspect < 1.0: ## # Camera info ## vdist = cdist ## if aspect < 1.0: ## vdist = cdist / aspect ## eyePos = vdist * glpane.scale * glpane.out - glpane.pov # [bruce comment 080912] #bruce 0809122 moved this from GLPane into GLPane_minimal, # and made region selection code call it for the first time. return self.quat.unrot(V(0, 0, self.vdist)) - self.pov def __repr__(self): return "<%s at %#x>" % (self.__class__.__name__.split('.')[-1], id(self)) def initializeGL(self): """ Called once by Qt when the OpenGL context is first ready to use. """ #bruce 080912 merged this from subclass methods, guessed docstring self._setup_lighting() glShadeModel(GL_SMOOTH) glEnable(GL_DEPTH_TEST) glEnable(GL_CULL_FACE) glMatrixMode(GL_MODELVIEW) glLoadIdentity() if not self.isSharing(): self._setup_display_lists() return def resizeGL(self, width, height): """ Called by QtGL when the drawing window is resized. """ #bruce 080912 moved this from GLPane into GLPane_minimal self._resize_counter += 1 #bruce 080922 self.width = width self.height = height glViewport(0, 0, self.width, self.height) # example of using a smaller viewport: ## glViewport(10, 15, (self.width - 10)/2, (self.height - 15)/3) # modify width and height for trackball # (note: this was done in GLPane but not in ThumbView until 080912) if width < 300: width = 300 if height < 300: height = 300 self.trackball.rescale(width, height) self.initialised = True return def __get_aspect(self): #bruce 080912 made this a property, moved to this class return (self.width + 0.0) / (self.height + 0.0) aspect = property(__get_aspect) def _setup_projection(self, glselect = False): ### WARNING: This is not actually private! TODO: rename it. """ Set up standard projection matrix contents using various attributes of self (aspect, vdist, scale, zoomFactor). Also reads the current OpenGL viewport bounds in window coordinates. (Warning: leaves matrixmode as GL_PROJECTION.) @param glselect: False (default) normally, or a 4-tuple (format not documented here) to prepare for GL_SELECT picking by calling gluPickMatrix(). If you are really going to draw in the pick window (for GL_RENDER and glReadPixels picking, rather than GL_SELECT picking), don't forget to set the glViewport *after* calling _setup_projection. Here's why: gluPickMatrix needs to know the current *whole-window* viewport, in order to set up a projection matrix to map a small portion of it to the clipping boundaries for GL_SELECT. From the gluPickMatrix doc page: viewport: Specifies the current viewport (as from a glGetIntegerv call). Description: gluPickMatrix creates a projection matrix that can be used to restrict drawing to a small region of the viewport. In the graphics pipeline, the clipper actually works in homogeneous coordinates, clipping polygons to the {X,Y}==+-W boundaries. This saves the work of doing the homogeneous division: {X,Y}/W==+-1.0, (and avoiding problems when W is zero for points on the eye plane in Z,) but it comes down to the same thing as clipping to X,Y==+-1 in orthographic. So the projection matrix decides what 3D model-space planes map to +-1 in X,Y. (I think it maps [near,far] to [0,1] in Z, because they're not clipped symmetrically.) Then glViewport sets the hardware transform that determines where the +-1 square of clipped output goes in screen pixels within the window. Normally you don't actually draw pixels while picking in GL_SELECT mode because the pipeline outputs hits after the clipping stage, so gluPickMatrix only reads the viewport and sets the projection matrix. """ #bruce 080912 moved this from GLPane into GLPane_minimal glMatrixMode(GL_PROJECTION) glLoadIdentity() scale = self.scale * self.zoomFactor near, far = self.near, self.far aspect = self.aspect vdist = self.vdist if glselect: x, y, w, h = glselect gluPickMatrix( x, y, w, h, glGetIntegerv( GL_VIEWPORT ) #k is this arg needed? it might be the default... ) if self.ortho: glOrtho( - scale * aspect, scale * aspect, - scale, scale, vdist * near, vdist * far ) else: glFrustum( - scale * near * aspect, scale * near * aspect, - scale * near, scale * near, vdist * near, vdist * far) return def _setup_modelview(self): """ set up modelview coordinate system """ #bruce 080912 moved this from GLPane into GLPane_minimal # note: it's not yet used in ThumbView, but maybe it could be. glMatrixMode(GL_MODELVIEW) glLoadIdentity() glTranslatef( 0.0, 0.0, - self.vdist) # translate coordinate system for drawing, away from eye # (-Z direction) by vdist. This positions center of view # in eyespace. q = self.quat glRotatef( q.angle * 180.0 / math.pi, q.x, q.y, q.z) # rotate coordinate system for drawing by trackball quat # (this rotation is around the center of view, since that is what # is positioned at drawing coordsystem's current origin, # by the following code) glTranslatef( self.pov[0], self.pov[1], self.pov[2]) # translate model (about to be drawn) to bring its center of view # (cov == - pov) to origin of coordinate system for drawing. # We translate by -cov to bring model.cov to origin. return def _setup_lighting(self): # note: in subclass GLPane, as of 080911 this is defined in # its mixin superclass GLPane_lighting_methods assert 0, "subclass must override this" def _setup_display_lists(self): # bruce 071030 """ This needs to be called during __init__ if a new display list context is being used. WARNING: the functions this calls store display list names in global variables (as of 071030); until this is cleaned up, only the most recently set up display list context will work with the associated drawing functions in the same modules. """ # TODO: warn if called twice (see docstring for why) setup_drawer() setup_draw_grid_lines() return # == def model_is_valid(self): #bruce 080117 """ Subclasses should override this to return a boolean saying whether their model is currently valid for drawing. Subclass implementations of paintGL are advised to call this at the beginning and return immediately if it's false. """ return True #bruce 080913 False -> True (more useful default) # == def is_sphere_visible(self, center, radius): # piotr 080331 """ Frustum culling test. Subclasses should override it to disable drawing objects outside of the view frustum. """ return True # == def is_lozenge_visible(self, pos1, pos2, radius): # piotr 080402 """ Frustum culling test for lozenge-shaped objects. Subclasses should override it to disable drawing objects outside of the view frustum. """ return True # == def _call_whatever_waits_for_gl_context_current(self): #bruce 071103 """ For whatever functions have been registered to be called (once) when our GL context is next current, call them now (and then discard them). Note: subclasses wishing to support self.call_when_glcontext_is_next_current MUST call this at some point during their paintGL method (preferably before doing any drawing in that method, though this is not at present guaranteed). Subclasses not wishing to support that should override it to discard functions passed to it immediately. """ functions = self._functions_to_call_when_gl_context_is_current self._functions_to_call_when_gl_context_is_current = [] for func in functions: try: func() except: print_compact_traceback( "bug: %r._call_whatever_waits_for_gl_context_current " "ignoring exception in %r: " % \ (self, func) ) continue return def call_when_glcontext_is_next_current(self, func): #bruce 071103 """ Call func at the next convenient time when we know our OpenGL context is current. (Subclasses are permitted to call func immediately if they happen to know their gl context is current right when this is called. Conversely, subclasses are permitted to never call func, though that will defeat the optimizations this is used for, such as deallocating OpenGL display lists which are no longer needed.) """ self._functions_to_call_when_gl_context_is_current.append( func) return # == def should_draw_valence_errors(self): """ Return a boolean to indicate whether valence error indicators (of any kind) should ever be drawn in self. (Each specific kind may also be controlled by a prefs setting, checked independently by the caller. As of 070914 there is only one kind, drawn by class Atom.) """ return False def get_drawLevel(self, assy_or_part): """ Get the recommended sphere drawingLevel to use for drawing assy_or_part in self. @param assy_or_part: an Assembly, or its current .part, a Part """ #bruce 090306 split out of ChunkDrawer, optimized for shaders #bruce 090309 revised if self.permit_shaders and \ self.glprefs.sphereShader_desired() and \ drawing_globals.sphereShader_available(): # drawLevel doesn't matter (not used by shaders), # so return a constant value to avoid accessing assy.drawLevel, # and therefore (I hope) avoid recomputing the number of atoms # in assy. But in case of bugs in which this ends up being used, # let this constant be the usual level "2". # [todo: use a symbolic constant, probably there is one already] return 2 else: return assy_or_part.drawLevel # this might recompute it # (if that happens and grabs the pref value, I think this won't # subscribe our Chunks' display list to it, since we're called # outside the begin/ends for those, and that's good, since they # include this in havelist instead, which avoids some unneeded # redrawing, e.g. if pref changed and changed back while # displaying a different Part. [bruce 060215]) pass # == def setDepthRange_setup_from_debug_pref(self): self.DEPTH_TWEAK = DEPTH_TWEAK_UNITS * \ debug_pref("GLPane: depth tweak", DEPTH_TWEAK_CHOICE) return def setDepthRange_Normal(self): glDepthRange(0.0 + self.DEPTH_TWEAK, 1.0) # args are near, far return def setDepthRange_Highlighting(self): glDepthRange(0.0, 1.0 - self.DEPTH_TWEAK) return # == # REVIEW: # the following "Undo view" methods probably don't work in subclasses other # than GLPane. It might make sense to have them here, but only if they are # refactored a bit, e.g. so that self.animateToView works in other # subclassses even if it doesn't animate. Ultimately it might be better # to refactor them a lot and/or move them out of this class hierarchy # entirely. [bruce 080912 comment] def current_view_for_Undo(self, assy): #e shares code with saveNamedView """ Return the current view in this glpane (which we assume is showing this assy), with additional attributes saved along with the view by Undo (i.e. the index of the current selection group). (The assy arg is used for multiple purposes specific to Undo.) @warning: present implem of saving current Part (using its index in MT) is not suitable for out-of-order Redo. """ # WARNING: not reviewed for use in subclasses which don't # have and draw a .assy attribute, though by passing assy into this method, # we remove any obvious bug from that. [bruce 080220 comment] oldc = assy.all_change_indicators() namedView = NamedView(assy, "name", self.scale, self.pov, self.zoomFactor, self.quat) newc = assy.all_change_indicators() assert oldc == newc namedView.current_selgroup_index = assy.current_selgroup_index() # storing this on the namedView is a kluge, but should be safe return namedView # ideally would not return a Node but just a # "view object" with the same 4 elements in it as passed to NamedView def set_view_for_Undo(self, assy, namedView): """ Restore the view (and the current Part) to what was saved by current_view_for_Undo. @warning: present implem of saving current Part (using its index in MT) is not suitable for out-of-order Redo. @warning: might not gl_update, assume caller does so [#k obs warning?] """ # shares code with NamedView.set_view; might be very similar to some GLPane method, too ## compare to NamedView.set_view (which passes animate = True) -- not sure if we want # to animate in this case [we do, for A8], # but if we do, we might have to do that at a higher level in the call chain restore_view = env.prefs[undoRestoreView_prefs_key] #060314 restore_current_part = True # always do this no matter what ## restore_mode?? nah (not for A7 anyway; unclear what's best in long run) if restore_view: if type(namedView) == type(""): self._initialize_view_attributes() #bruce 090220 revision to remove copied code; not fully # equivalent to prior code (sets scale from prefs rather # than to 10.0) but I think that's ok, since I think this # functionality (Undo changing the view) is only cosmetic. else: self.animateToView(namedView.quat, namedView.scale, namedView.pov, namedView.zoomFactor, animate = False) # if we want this to animate, we probably have to move that # higher in the call chain and do it after everything else if restore_current_part: if type(namedView) == type(""): if env.debug(): print "debug: fyi: cys == '' still happens" # does it? ###@@@ 060314 remove if seen, or if not seen current_selgroup_index = 0 else: current_selgroup_index = namedView.current_selgroup_index sg = assy.selgroup_at_index(current_selgroup_index) assy.set_current_selgroup(sg) #e how might that interact with setting the selection? # Hopefully, not much, since selection (if any) should be inside sg. #e should we update_parts? return pass # end of class # end
NanoCAD-master
cad/src/graphics/widgets/GLPane_minimal.py
# Copyright 2004-2009 Nanorex, Inc. See LICENSE file for details. """ GLPane_text_and_color_methods.py - methods for GLPane related to text rendering or backgroundColor/backgroundGradient (Maybe it should be renamed GLPane_text_and_background_methods?) @version: $Id$ @copyright: 2004-2009 Nanorex, Inc. See LICENSE file for details. bruce 080910 split this out of class GLPane """ from OpenGL.GL import glEnable from OpenGL.GL import glDisable from OpenGL.GL import GL_LIGHTING from OpenGL.GL import GL_DEPTH_TEST from OpenGL.GL import glClear from OpenGL.GL import glClearColor from OpenGL.GL import GL_COLOR_BUFFER_BIT from OpenGL.GL import glTexEnvf from OpenGL.GL import GL_TEXTURE_ENV from OpenGL.GL import GL_TEXTURE_ENV_MODE from OpenGL.GL import GL_MODULATE from OpenGL.GL import glMatrixMode from OpenGL.GL import GL_MODELVIEW from OpenGL.GL import GL_PROJECTION from OpenGL.GL import glLoadIdentity from OpenGL.GL import glPushMatrix from OpenGL.GL import glPopMatrix from OpenGL.GLU import gluUnProject, gluProject from PyQt4.Qt import QFontMetrics from PyQt4.Qt import QFont, QString from PyQt4.Qt import QPalette from PyQt4.Qt import QColor from PyQt4.Qt import Qt from utilities.debug import print_compact_stack from utilities.constants import black, white from utilities.constants import getTextHaloColor from utilities.constants import bgSOLID, bgBLUE_SKY, bgEVENING_SKY, bgSEAGREEN from utilities.constants import bluesky, eveningsky, bg_seagreen from utilities.constants import ave_colors, colors_differ_sufficiently from utilities.prefs_constants import DarkBackgroundContrastColor_prefs_key from utilities.prefs_constants import LightBackgroundContrastColor_prefs_key from utilities.prefs_constants import backgroundColor_prefs_key from utilities.prefs_constants import backgroundGradient_prefs_key from utilities.prefs_constants import originAxisColor_prefs_key import foundation.env as env from graphics.drawing.drawers import drawFullWindow from widgets.widget_helpers import RGBf_to_QColor # == assert bgSOLID == 0 # some code in GLPane depends on this # == def _backgroundGradient_params(backgroundGradient, bgColor = None): """ Given a backgroundGradient code (a small int of the kind stored in self.backgroundGradient), and if that is bgSOLID, a background color, return a 4-tuple of colors (for glpane corners) which it represents, and a boolean about whether to consider it "dark" for purposes such as cursor selection. """ #bruce 080910 split this out of GLPane.standard_repaint_0; # ideally we'd turn this code into some sort of "background class" # with a subclass for solid and a few instances or singleton # subclasses for particular gradients, with the parameters # returned here (also fogColor) becoming attributes or methods. # for now only a few specific gradient backgrounds are supported if backgroundGradient == bgSOLID: assert bgColor is not None _bgGradient = (bgColor, bgColor, bgColor, bgColor) darkQ = not colors_differ_sufficiently(bgColor, black) elif backgroundGradient == bgBLUE_SKY: _bgGradient = bluesky darkQ = False elif backgroundGradient == bgEVENING_SKY: _bgGradient = eveningsky darkQ = True elif backgroundGradient == bgSEAGREEN: _bgGradient = bg_seagreen darkQ = False else: msg = "Warning: Unknown background gradient = %s. "\ "Setting gradient to evening sky" % backgroundGradient print_compact_stack(msg + ": ") _bgGradient = eveningsky darkQ = True return _bgGradient, darkQ # == class GLPane_text_and_color_methods(object): """ private mixin for providing text- and color-related methods to class GLPane """ def draw_glpane_label_text(self, text): """ Draw a text label for the glpane as a whole. @note: called indirectly from GLPane.paintGL shortly after it calls _do_graphicsMode_Draw(), via GraphicsMode.draw_glpane_label """ #bruce 090219 moved this here from part of Part.draw_text_label # (after a temporary stop in the short-lived class PartDrawer); # the other part is now our caller GraphicsMode.draw_glpane_label. # (note: caller catches exceptions, so we don't have to bother) glDisable(GL_LIGHTING) glDisable(GL_DEPTH_TEST) # Note: disabling GL_DEPTH_TEST properly affects 2d renderText # (as used here), but not 3d renderText. For more info see # today's comments in Guides.py. [bruce 081204 comment] glPushMatrix() # REVIEW: needed? [bruce 081204 question] font = QFont(QString("Helvetica"), 24, QFont.Bold) self.qglColor(Qt.red) # this needs to be impossible to miss -- not nice-looking! #e tho it might be better to pick one of several bright colors # by hashing the partname, so as to change the color when the part changes. # this version of renderText uses window coords (0,0 at upper left) # rather than model coords (but I'm not sure what point on the string-image # we're setting the location of here -- guessing it's bottom-left corner): self.renderText(25,40, QString(text), font) glPopMatrix() glEnable(GL_DEPTH_TEST) glEnable(GL_LIGHTING) return def renderTextAtPosition(self, position, textString, textColor = black, textFont = None, fontSize = 11, ): """ Renders the text at the specified position (x, y, z coordinates) @param position: The x, y, z coordinates of the object at which the text needs to be rendered. @type position: B{A} @param textString: the text to be rendered at the specified position. @type textString : str @see: self.renderTextNearCursor() This method is different than that method. That method uses QPoint (the current cursor position) to render the text (thus needs integers x and y) whereas this method uses the actual object coordinates @see: MultiplednaSegment_GraphicsMode._drawDnaRubberbandLine() [obsolete class name, what is correct one?] @see: QGLWidget.renderText() @TODO: refactor to move the common code in this method and self.renderTextNearCursor(). """ if textFont is not None: font = textFont else: font = self._getFontForTextNearCursor(fontSize = fontSize, isBold = True) x = position[0] y = position[1] z = position[2] glDisable(GL_LIGHTING) #Convert the object coordinates to the window coordinates. wX, wY, wZ = gluProject(x, y, z) halo_color = getTextHaloColor(textColor) offset_val = 1 bg_z_offset = 0 fg_z_offset = -1e-7 render_positions = (( offset_val, offset_val, bg_z_offset, halo_color), (-offset_val, -offset_val, bg_z_offset, halo_color), (-offset_val, offset_val, bg_z_offset, halo_color), ( offset_val, -offset_val, bg_z_offset, halo_color), ( 0, 0, fg_z_offset, textColor)) for dx, dy, dz, color in render_positions: x1, y1, z1 = gluUnProject(wX + dx, wY + dy, wZ + dz) self.qglColor(RGBf_to_QColor(color)) self.renderText(x1, y1, z1, QString(textString), font) ## self.qglClearColor(RGBf_to_QColor(color)) ## # question: is this related to glClearColor? [bruce 071214 question] ## # -- yes [Ninad 2008-08-20] glEnable(GL_LIGHTING) def renderTextNearCursor(self, textString, offset = 10, textColor = black, fontSize = 11): """ Renders text near the cursor position, on the top right side of the cursor (slightly above it). See example in DNA Line mode. @param textString: string @param offset: The offset that will be added to x and y values of the cursor position to get the base position of the text to be rendered. @see: DnaLineMode.Draw @see: self._getFontForTextNearCursor() @see: self.renderTextAtPosition() """ if not textString: return #Extra precaution if the caller passes a junk value such as None #for the color if not isinstance(textColor, tuple) and isinstance(textColor, list): textColor = black pos = self.cursor().pos() # x, y coordinates need to be in window coordinate system. # See QGLWidget.mapToGlobal for more details. pos = self.mapFromGlobal(pos) # Important to turn off the lighting. Otherwise the text color would # be dull and may also become even more light if some other object # is rendered as a transparent object. Example in DNA Line mode, when the # second axis end sphere is rendered as a transparent sphere, it affects # the text rendering as well (if GL_LIGHTING is not disabled) # [-- Ninad 2007-12-03] glDisable(GL_LIGHTING) #Add 'stoppers' for the cursor text. Example: If the cursor is near the #extreme right hand corner of the 3D workspace, the following code #ensures that all the text string is visible. It does this check for #right(x) and top(for y) borders of the glpane. xOffset = offset yOffset = offset #signForDX and signForDY are used by the code that draws the same #text in the background (offset by 1 pixel in 4 directions) signForDX = 1 signForDY = 1 xLimit = self.width - pos.x() #Note that at the top edge, y coord is 0 yLimit = pos.y() textString = QString(textString) font = self._getFontForTextNearCursor(fontSize = fontSize, isBold = True) #Now determine the total x and y pixels used to render the text #(add some tolerance to that number) fm = QFontMetrics(font) xPixels = fm.width(textString) + 10 yPixels = fm.height() + 10 if xLimit < xPixels: xOffset = - (xPixels - xLimit) signForDX = -1 if yLimit < yPixels: yOffset = - (yPixels - pos.y()) signForDY = -1 x = pos.x() + xOffset y = pos.y() - yOffset offset_val = 1 deltas_for_halo_color = (( offset_val, offset_val), (-offset_val, -offset_val), (-offset_val, offset_val), ( offset_val, -offset_val)) # halo color halo_color = getTextHaloColor(textColor) for dx, dy in deltas_for_halo_color: self.qglColor(RGBf_to_QColor(halo_color)) # Note: self.renderText is QGLWidget.renderText method. self.renderText(x + dx*signForDX , y + dy*signForDY, textString, font) ## self.qglClearColor(RGBf_to_QColor(halo_color)) ## # REVIEW: why is qglClearColor needed here? Why is it done *after* renderText? ## # [bruce 081204 questions; same Qs for the other uses of qglClearColor in this file] # Note: It is necessary to set the font color, otherwise it may change! self.qglColor(RGBf_to_QColor(textColor)) x = pos.x() + xOffset y = pos.y() - yOffset self.renderText(x , y , textString, font) ## self.qglClearColor(RGBf_to_QColor(textColor)) ## # is qglClearColor related to glClearColor? [bruce 071214 question] glEnable(GL_LIGHTING) def _getFontForTextNearCursor(self, fontSize = 10, isBold = False): """ Returns the font for text near the cursor. @see: self.renderTextNearCursor """ font = QFont("Arial", fontSize) font.setBold(isBold) return font # == Background color helper methods. written and/or moved to GLPane by Mark 060814. def restoreDefaultBackground(self): """ Restore the default background color and gradient (Sky Blue). Always do a gl_update. """ env.prefs.restore_defaults([ backgroundColor_prefs_key, backgroundGradient_prefs_key, ]) self.setBackgroundColor(env.prefs[ backgroundColor_prefs_key ]) self.setBackgroundGradient(env.prefs[ backgroundGradient_prefs_key ] ) self.gl_update() def setBackgroundColor(self, color): # bruce 050105 new feature [bruce 050117 cleaned it up] """ Set the background color and store it in the prefs db. @param color: r,g,b tuple with values between 0.0-1.0 @type color: tuple with 3 floats """ self.backgroundColor = color env.prefs[ backgroundColor_prefs_key ] = color self.setBackgroundGradient(0) return def getBackgroundColor(self): """ Returns the current background color. @return color: r,g,b tuple with values between 0.0-1.0 @rtype color: tuple with 3 floats """ return self.backgroundColor def setBackgroundGradient(self, gradient): # mark 050808 new feature """ Stores the background gradient prefs value in the prefs db. gradient can be either: 0 - No gradient. The background color is a solid color. 1 - the background gradient is set to the 'Blue Sky' gradient. 2 - the background gradient is set to the 'Evening Sky' gradient. 3 - the background gradient is set to the 'Sea Green' gradient. See GLPane.standard_repaint_0() to see how this is used when redrawing the glpane. """ self.backgroundGradient = gradient env.prefs[ backgroundGradient_prefs_key ] = gradient self._updateOriginAxisColor() self._updateSpecialContrastColors() return def _updateOriginAxisColor(self): """ [private] Update the color of the origin axis to a shade that will contrast well with the background. """ env.prefs.restore_defaults([originAxisColor_prefs_key]) axisColor = env.prefs[originAxisColor_prefs_key] gradient = env.prefs[ backgroundGradient_prefs_key ] if gradient == bgSOLID: if not colors_differ_sufficiently(self.backgroundColor, axisColor): env.prefs[originAxisColor_prefs_key] = ave_colors( 0.5, axisColor, white) elif gradient == bgEVENING_SKY: env.prefs[originAxisColor_prefs_key] = ave_colors( 0.9, axisColor, white) return def _updateSpecialContrastColors(self): # [probably by Mark, circa 080710] """ [private] Update the special contrast colors (used to draw lines, etc.) to a shade that contrasts well with the current background. @see: get_background_contrast_color() """ # REVIEW: the following is only legitimate since these prefs variables # are (I think) not actual user prefs, but just global state variables. # However, if that's true, they should not really be stored in the # prefs db. Furthermore, if we had multiple GLPanes with different # background colors, I think these variables would need to be # per-glpane, so really they ought to be GLPane instance variables. # [bruce 080711 comment] env.prefs.restore_defaults([DarkBackgroundContrastColor_prefs_key, LightBackgroundContrastColor_prefs_key]) dark_color = env.prefs[DarkBackgroundContrastColor_prefs_key] # black lite_color = env.prefs[LightBackgroundContrastColor_prefs_key] # white gradient = env.prefs[ backgroundGradient_prefs_key ] if gradient == bgSOLID: if not colors_differ_sufficiently(self.backgroundColor, dark_color): env.prefs[DarkBackgroundContrastColor_prefs_key] = ave_colors( 0.5, dark_color, white) if not colors_differ_sufficiently(self.backgroundColor, lite_color): env.prefs[LightBackgroundContrastColor_prefs_key] = ave_colors( 0.5, lite_color, black) elif gradient == bgEVENING_SKY: env.prefs[DarkBackgroundContrastColor_prefs_key] = ave_colors( 0.6, dark_color, white) return def get_background_contrast_color(self): """ Return a color that contrasts well with the background color of the 3D workspace (self). @see: MultipleDnaSegmentResize_GraphicsMode where it is used for rendering text with a proper contrast. @see: self._updateSpecialContrastColors() """ #NOTE: This method mitigates bug 2927 dark_color = env.prefs[DarkBackgroundContrastColor_prefs_key] # black ##lite_color = env.prefs[LightBackgroundContrastColor_prefs_key] # white gradient = env.prefs[ backgroundGradient_prefs_key ] color = black if gradient == bgSOLID: if not colors_differ_sufficiently(self.backgroundColor, dark_color): color = ave_colors( 0.5, dark_color, white) elif gradient == bgEVENING_SKY: color = ave_colors( 0.6, dark_color, white) return color # == def _set_widget_erase_color(self): # revised, bruce 071011 """ Change this widget's erase color (seen only if it's resized, and only briefly -- it's independent of OpenGL clearColor) to self.backgroundColor. This is intended to minimize the visual effect of widget resizes which temporarily show the erase color. See comments in this method for caveats about that. """ # Note: this was called in GLPane.update_after_new_graphicsMode # when the graphicsMode could determine the background color, # but that's no longer true, so it could probably # just be called at startup and whenever the background color is changed. # Try that sometime, it might be an optim. For now it continues # to be called from there. [bruce 071011, still true 080910] # # REVIEW: what is self.backgroundColor when we're using the new default # of "Blue Sky Gradient". For best effect here, what it ought to be # is the average or central bg color in that gradient. I think it's not, # which makes me wonder if this bugfix is still needed at all. [bruce 071011] # # Note: calling this fixed the bug in which the glpane or its edges # flickered to black during a main-window resize. [bruce 050408] # # Note: limited this to Mac [in caller], since it turns out that bug (which has # no bug number yet) was Mac-specific, but this change caused a new bug 530 # on Windows. (Not sure about Linux.) See also bug 141 (black during # mode-change), related but different. [bruce 050413] # # Note: for graphicsModes with a translucent surface covering the screen # (i.e. Build Atoms water surface), it would be better to blend that surface # color with self.backgroundColor for passing to this method, to approximate # the effective background color. Alternatively, we could change how those # graphicsModes set up OpenGL clearcolor, so that their empty space areas # looked like self.backgroundColor.) [bruce 050615 comment] bgcolor = self.backgroundColor r = int(bgcolor[0]*255 + 0.5) # (same formula as in elementSelector.py) g = int(bgcolor[1]*255 + 0.5) b = int(bgcolor[2]*255 + 0.5) pal = QPalette() pal.setColor(self.backgroundRole(), QColor(r, g, b)) self.setPalette(pal) # see Qt docs for this and for backgroundRole return # == def is_background_dark(self): #bruce 080910 de-inlined this _bgGradient_junk, darkQ = _backgroundGradient_params( self.backgroundGradient, self.backgroundColor ) return darkQ def background_gradient_corner_colors(self): #bruce 080910 de-inlined this _bgGradient, darkQ_junk = _backgroundGradient_params( self.backgroundGradient, self.backgroundColor ) return _bgGradient def _init_background_from_prefs(self): #bruce 080910 de-inlined this self.backgroundColor = env.prefs[backgroundColor_prefs_key] self.backgroundGradient = env.prefs[backgroundGradient_prefs_key] return # == def clear_and_draw_background(self, other_glClear_buffer_bits): #bruce 080910 de-inlined this """ @param other_glClear_buffer_bits: whichever of GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT you want to pass to glClear, in addition to GL_COLOR_BUFFER_BIT, which we pass if needed """ c = self.backgroundColor # note: self.backgroundGradient and self.backgroundColor # are used and maintained entirely in this mixin class, as of 080910 # (unless other files access them as public attrs -- not reviewed) glClearColor(c[0], c[1], c[2], 0.0) self.fogColor = (c[0], c[1], c[2], 1.0) # piotr 080515 del c glClear(GL_COLOR_BUFFER_BIT | other_glClear_buffer_bits ) # potential optims: # - if stencil clear is expensive, we could do it only when needed [bruce ca. 050615] # - if color clear is expensive, we needn't do it when self.backgroundGradient self.kluge_reset_texture_mode_to_work_around_renderText_bug() if self.backgroundGradient: glMatrixMode(GL_PROJECTION) glLoadIdentity() glMatrixMode(GL_MODELVIEW) glLoadIdentity() _bgGradient = self.background_gradient_corner_colors() drawFullWindow(_bgGradient) # fogColor is an average of the gradient components # piotr 080515 self.fogColor = \ (0.25 * (_bgGradient[0][0] + _bgGradient[1][0] + _bgGradient[2][0] + _bgGradient[3][0]), \ 0.25 * (_bgGradient[0][1] + _bgGradient[1][1] + _bgGradient[2][1] + _bgGradient[3][1]), \ 0.25 * (_bgGradient[0][2] + _bgGradient[1][2] + _bgGradient[2][2] + _bgGradient[3][2])) # Note: it would be possible to optimize by not clearing the color buffer # when we'll call drawFullWindow, if we first cleared depth buffer (or got # drawFullWindow to ignore it and effectively clear it by writing its own # depths into it everywhere, if that's possible). [bruce 070913 comment] return def draw_solid_color_everywhere(self, color): #bruce 090105, for debugging glMatrixMode(GL_PROJECTION) glPushMatrix() glLoadIdentity() glMatrixMode(GL_MODELVIEW) glPushMatrix() glLoadIdentity() try: drawFullWindow([color, color, color, color]) finally: glPopMatrix() glMatrixMode(GL_PROJECTION) glPopMatrix() glMatrixMode(GL_MODELVIEW) return def kluge_reset_texture_mode_to_work_around_renderText_bug(self): """ This helps work around a renderText bug in Qt 4.3.x (fixed in Qt 4.4.0). It should be called after anything which might set GL_TEXTURE_ENV_MODE to something other than GL_MODULATE (e.g. after drawing an ESP Image, or textures used in testmode), and before drawing the main model or when initializing the graphics context. """ #bruce 081205 made this a separate method, called it from more places. # for more info, see: # http://trolltech.com/developer/task-tracker/index_html?method=entry&id=183995 # http://trolltech.com/developer/changes/changes-4.4.0 (issue 183995) # http://www.nanoengineer-1.net/mediawiki/index.php?title=Qt_bugs_in_renderText#glTexEnvf_turns_all_renderText_characters_into_solid_rectangles # In theory this should no longer be needed once we upgrade to Qt 4.4.0. # # piotr 080620 - fixed "white text" bug when using Qt 4.3.x # [by doing this inline in clear_and_draw_background] -- # before rendering text, the texture mode should be set to GL_MODULATE # to reflect current color changes. glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE) pass # end
NanoCAD-master
cad/src/graphics/widgets/GLPane_text_and_color_methods.py
# Copyright 2004-2008 Nanorex, Inc. See LICENSE file for details. """ GLPane_event_methods.py @version: $Id$ @copyright: 2004-2008 Nanorex, Inc. See LICENSE file for details. bruce 080910 split this out of class GLPane """ import time from PyQt4.Qt import QEvent from PyQt4.Qt import QMouseEvent from PyQt4.Qt import QHelpEvent from PyQt4.Qt import QPoint from PyQt4.Qt import Qt from PyQt4.Qt import SIGNAL, QTimer from PyQt4.QtOpenGL import QGLWidget from OpenGL.GL import GL_DEPTH_COMPONENT from OpenGL.GL import glReadPixelsf from OpenGL.GLU import gluUnProject from geometry.VQT import V, A, norm from geometry.VQT import planeXline, ptonline from Numeric import dot import foundation.env as env from utilities import debug_flags from utilities.debug import print_compact_traceback from utilities.debug_prefs import debug_pref from utilities.debug_prefs import Choice from utilities.debug_prefs import Choice_boolean_False from utilities.constants import GL_FAR_Z from utilities.constants import MULTIPANE_GUI from utilities.GlobalPreferences import DEBUG_BAREMOTION import utilities.qt4transition as qt4transition from platform_dependent.PlatformDependent import fix_event_helper from platform_dependent.PlatformDependent import wrap_key_event from widgets.menu_helpers import makemenu_helper from widgets.DebugMenuMixin import DebugMenuMixin from graphics.widgets.DynamicTip import DynamicTip from ne1_ui.cursors import createCompositeCursor # == ## button_names = {0:None, 1:'LMB', 2:'RMB', 4:'MMB'} button_names = {Qt.NoButton:None, Qt.LeftButton:'LMB', Qt.RightButton:'RMB', Qt.MidButton:'MMB'} #bruce 070328 renamed this from 'button' (only in Qt4 branch), and changed the dict keys from ints to symbolic constants, # and changed the usage from dict lookup to iteration over items, to fix some cursor icon bugs. # For the constants, see http://www.riverbankcomputing.com/Docs/PyQt4/html/qmouseevent.html # [Note: if there is an import of GLPane.button elsewhere, that'll crash now due to the renaming. Unfortunately, for such # a common word, it's not practical to find out except by renaming it and seeing if that causes bugs.] # == class GLPane_event_methods(object, DebugMenuMixin): """ """ # bruce 041220: handle keys in GLPane (see also setFocusPolicy, above). # Also call these from MWsemantics whenever it has the focus. This fixes # some key-focus-related bugs. We also wrap the Qt events with our own # type, to help fix Qt's Mac-specific Delete key bug (bug 93), and (in the # future) for other reasons. The fact that clicking in the GLPane now gives # it the focus (due to the setFocusPolicy, above) is also required to fully # fix bug 93. def _init_GLPane_event_methods(self): """ """ DebugMenuMixin._init1(self) # provides self.debug_event() [might provide or require more things too... #doc] # Current coordinates of the mouse (public attribute for event handlers; # they can set it by calling SaveMouse) self.MousePos = V(0, 0) # Selection lock state of the mouse for this glpane. # Public attribute for read and modification by external # event handling code. # See selectionLock() in the ops_select_Mixin class for details. self.mouse_selection_lock_enabled = False # not selecting anything currently # [I think this is for region selection --bruce 080912 guess] # [as of 050418 (and before), this is used in BuildCrystal_Command and selectMode] self.shape = None # Cursor position of the last timer event. Mark 060818 self.timer_event_last_xy = (0, 0) self.setMouseTracking(True) # bruce 041220 let the GLPane have the keyboard focus, to fix bugs. # See comments above our keyPressEvent method. ###e I did not yet review the choice of StrongFocus in the Qt docs, # just copied it from MWsemantics. self.setFocusPolicy(Qt.StrongFocus) ## self.singlet = None #bruce 060220 zapping this, seems to be old and to no longer be used self.selatom = None # josh 10/11/04 supports BuildAtoms_Command self.jigSelectionEnabled = True # mark 060312 self.triggerBareMotionEvent = True # Supports timerEvent() to minimize calls to bareMotion(). Mark 060814. self.wheelHighlight = False # russ 080527: Fix Bug 2606 (highlighting not turned on after wheel event.) # Indicates handling bareMotion for highlighting after a mousewheel event. self.cursorMotionlessStartTime = time.time() #bruce 070110 fix bug when debug_pref turns off glpane timer from startup # Triple-click Timer: for the purpose of implementing a triple-click # event handler, which is not supported by Qt. # # See: mouseTripleClickEvent() self.tripleClick = False self.tripleClickTimer = QTimer(self) self.tripleClickTimer.setSingleShot(True) self.connect(self.tripleClickTimer, SIGNAL('timeout()'), self._tripleClickTimeout) self.dynamicToolTip = DynamicTip(self) return # == related to DebugMenuMixin def makemenu(self, menu_spec, menu = None): # this overrides the one from DebugMenuMixin (with the same code), but that's ok, # since we want to be self-contained in case someone later removes that mixin class; # this method is called by our modes to make their context menus. # [bruce 050418 comment] return makemenu_helper(self, menu_spec, menu) def debug_menu_items(self): #bruce 050515 """ [overrides method from DebugMenuMixin] """ usual = DebugMenuMixin.debug_menu_items(self) # list of (text, callable) pairs, None for separator ours = list(usual) try: # submenu for available custom modes [bruce 050515] # todo [080209]: just include this submenu in the DebugMenuMixin version # (no reason it ought to be specific to glpane) modemenu = self.win.commandSequencer.custom_modes_menuspec() if modemenu: ours.append(("custom modes", modemenu)) except: print_compact_traceback("exception ignored: ") return ours # == related to key events def keyPressEvent(self, e): #e future: also track these to match releases with presses, to fix # dialogs intercepting keyRelease? Maybe easier if they just pass it on. mc = env.begin_op("(keypress)") #bruce 060127 # Note: we have to wrap press and release separately; later, we might pass them tags # to help the diffs connect up for merging # (same as in drags and maybe as in commands doing recursive event processing). # [bruce 060127] try: #print "GLPane.keyPressEvent(): self.in_drag=",self.in_drag if not self.in_drag: #bruce 060220 new code; should make it unnecessary (and incorrect) # for modes to track mod key press/release for cursor, # once update_modkeys calls a cursor updating routine #but = e.stateAfter() #self.update_modkeys(but) self.update_modkeys(e.modifiers()) self.graphicsMode.keyPressEvent( wrap_key_event(e) ) finally: env.end_op(mc) return def keyReleaseEvent(self, e): mc = env.begin_op("(keyrelease)") #bruce 060127 try: if not self.in_drag: #bruce 060220 new code; see comment in keyPressEvent #but = e.stateAfter() #self.update_modkeys(but) self.update_modkeys(e.modifiers()) self.graphicsMode.keyReleaseEvent( wrap_key_event(e) ) finally: env.end_op(mc) return # == def makeCurrent(self): QGLWidget.makeCurrent(self) # also tell the MainWindow that my PartWindow is the active one # REVIEW: when Qt calls makeCurrent before calling e.g. resizeGL, # does it call this method, or just QGLWidget.makeCurrent? # [bruce 080912 question] if MULTIPANE_GUI: pw = self.partWindow pw.parent._activepw = pw return # == _cursorWithoutSelectionLock = None #bruce 080918 added def, made private def setCursor(self, inCursor = None): """ Sets the cursor for the glpane. This method is also responsible for adding special symbols to the cursor that should be persistent as cursors change (i.e. the selection lock symbol). That's controlled by attrs of self, not by arguments. @param inCursor: Either a cursor or a list of 2 cursors (one for a dark background, one for a light background). If cursor is None, reset the cursor to the most recent version without the selection lock symbol. @type inCursor: U{B{QCursor}<http://doc.trolltech.com/4/qcursor.html>} or a list of two {B{QCursors}<http://doc.trolltech.com/4/qcursor.html>} (but None can be used in place of any QCursor). """ # If inCursor is a list (of a dark and light bg cursor), set # cursor to one or the other based on the current background. if isinstance(inCursor, list): if self.is_background_dark(): cursor = inCursor[0] # dark bg cursor else: cursor = inCursor[1] # light bg cursor pass else: cursor = inCursor # Cache unmodified version of cursor, # or use the cached cursor if None is provided. if not cursor: cursor = self._cursorWithoutSelectionLock self._cursorWithoutSelectionLock = cursor if not cursor: #bruce 080918 print "BUG: can't set cursor from %r -- no cached cursor so far" % (inCursor,) return None # Apply modifications before setting cursor. # (review: also cache modified cursors as optim? Or does the subr do that? [bruce 080918 Q]) if self.mouse_selection_lock_enabled: # Add the selection lock symbol. cursor = createCompositeCursor(cursor, self.win.selectionLockSymbol, offsetX = 2, offsetY = 19) return QGLWidget.setCursor(self, cursor) # review: retval used? ever not None? [bruce 080918 Q] # == #bruce 060220 changes related to supporting self.modkeys, self.in_drag. # These changes are unfinished in the following ways: ###@@@ # - need to fix the known bugs in fix_event_helper, listed below # - update_modkeys needs to call some sort of self.graphicsMode.updateCursor routine # - then the modes which update the cursor for key press/release of modkeys need to stop doing that # and instead just define that updateCursor routine properly # - ideally we'd capture mouseEnter and call both update_modkeys and the same updateCursor routine # - (and once the cursor works for drags between widgets, we might as well fix the statusbar text for that too) modkeys = None in_drag = False button = None mouse_event_handler = None # None, or an object to handle mouse events and related queries instead of self.graphicsMode # [bruce 070405, new feature for confirmation corner support, and for any other overlay widgets which are handled # mostly independently of the current mode -- and in particular which are not allowed to depend on the recent APIs # added to selectMode, and/or which might need to be active even if current mode is doing xor-mode OpenGL drawing.] _last_event_wXwY = (-1, -1) #bruce 070626 def fix_event(self, event, when, target): #bruce 060220 added support for self.modkeys """ [For most documentation, see fix_event_helper. Argument <when> is one of 'press', 'release', or 'move'. We also set self.modkeys to replace the obsolete mode.modkey variable. This only works if we're called for all event types which want to look at that variable.] """ qt4transition.qt4todo('reconcile state and stateAfter') # fyi: for info about event methods button and buttons (related to state and stateAfter in Qt3) see # http://www.riverbankcomputing.com/Docs/PyQt4/html/qmouseevent.html#button # [bruce 070328] but, mod = fix_event_helper(self, event, when, target) # fix_event_helper has several known bugs as of 060220, including: # - target is not currently used, and it's not clear what it might be for # [in this method, it's self.mode ###REVIEW WHAT IT IS] # - it's overly bothered by dialogs that capture press and not release; # - maybe it can't be called for key events, but self.modkeys needs update then [might be fixed using in_drag #k]; # - not sure it's always ok when user moves from one widget to another during a drag; # - confused if user releases two mouse buttons at different times to end a drag (thinks the first one ended it). # All these can be fixed straightforwardly when they become important enough. [bruce 060220] # How we'll update self.mouse_event_handler, so its new value can handle this event after we return # (and handle queries by update_cursor and the like, either after we return or in this same method call): # - press: change based on current point (event position in window coords) # - move: if in_drag, leave unchanged, else (bareMotion) change based on current point. # - release: leave unchanged (since release is part of the ongoing drag). # We can't do this all now, since we don't know in_drag yet, # nor all later, since that would be after a call of update_cursor -- except that # in that case, we're not changing it, so (as a kluge) we can ignore that issue # and do it all later. wX = event.pos().x() wY = self.height - event.pos().y() self._last_event_wXwY = wX, wY #bruce 070626 for use by mouse_event_handler (needed for confcorner) if when == 'release': self.in_drag = False self.button = None # leave self.mouse_event_handler unchanged, so it can process the release if it was handling the drag self.graphicsMode.update_cursor() else: #bruce 070328 adding some debug code/comments to this (for some Qt4 or Qt4/Mac specific bugs), and bugfixing it. olddrag = self.in_drag self.in_drag = but & (Qt.LeftButton|Qt.MidButton|Qt.RightButton) # Qt4 note: this is a PyQt4.QtCore.MouseButtons object # you can also use this to see which mouse buttons are involved. # WARNING: that would only work in Qt4 if you use the symbolic constants listed in button_names.keys(). if not olddrag: # this test seems to still work in Qt4 (apparently MouseButtons.__nonzero__ is sensibly defined) #bruce 070328 revised algorithm, since PyQt evidently forgot to make MouseButtons constants work as dict keys. # It works now for bareMotion (None), real buttons (LMB or RMB), and simulated MMB (option+LMB). # In the latter case I think it fixes a bug, by displaying the rotate cursor during option+LMB drag. for lhs, rhs in button_names.iteritems(): if self.in_drag == lhs: self.button = rhs break continue # Note: if two mouse buttons were pressed at the same time (I think -- bruce 070328), we leave self.button unchanged. if when == 'press' or (when == 'move' and not self.in_drag): new_meh = self.graphicsMode.mouse_event_handler_for_event_position( wX, wY) self.set_mouse_event_handler( new_meh) # includes update_cursor if handler is different pass self.update_modkeys(mod) # need to call this when drag starts; ok to call it during drag too, # since retval is what came from fix_event return but, mod def set_mouse_event_handler(self, mouse_event_handler): #bruce 070628 (related to fixing bug 2476 (leftover CC Done cursor)) """ [semi-private] Set self.mouse_event_handler (to a handler meeting the MouseEventHandler_API, or to None) and do some related updates. """ if self.mouse_event_handler is not mouse_event_handler: self.mouse_event_handler = mouse_event_handler self.graphicsMode.update_cursor() #e more updates? # - maybe tell the old mouse_event_handler it's no longer active # (i.e. give it a "leave event" if when == 'move') # and/or tell the new one it is (i.e. give it an "enter event" if when == 'move') -- # not needed for now [bruce 070405] # - maybe do an incremental gl_update, i.e. gl_update_confcorner? return def update_modkeys(self, mod): """ Call this whenever you have some modifier key flags from an event (as returned from fix_event, or found directly on the event as stateAfter in events not passed to fix_event). Exception: don't call it during a drag, except on values returned from fix_event, or bugs will occur. There is not yet a good way to follow this advice. This method and/or fix_event should provide one. ###e This method updates self.modkeys, setting it to None, 'Shift', 'Control' or 'Shift+Control'. (All uses of the obsolete mode.modkey variable should be replaced by this one.) """ shift_control_flags = mod & (Qt.ShiftModifier | Qt.ControlModifier) oldmodkeys = self.modkeys if shift_control_flags == Qt.ShiftModifier: self.modkeys = 'Shift' elif shift_control_flags == Qt.ControlModifier: self.modkeys = 'Control' elif shift_control_flags == (Qt.ShiftModifier | Qt.ControlModifier): self.modkeys = 'Shift+Control' else: self.modkeys = None if self.modkeys != oldmodkeys: # This would be a good place to tell the GraphicsMode it might want to update the cursor, # based on all state it knows about, including self.modkeys and what the mouse is over, # but it's not enough, since it doesn't cover mouseEnter (or mode Enter), # where we need that even if modkeys didn't change. [bruce 060220] self.graphicsMode.update_cursor() highlighting_enabled = self.graphicsMode.command.isHighlightingEnabled() if self.selobj and highlighting_enabled: if self.modkeys == 'Shift+Control' or oldmodkeys == 'Shift+Control': # If something is highlighted under the cursor and we just pressed or released # "Shift+Control", repaint to update its correct highlight color. self.gl_update_highlight() return def begin_select_cmd(self): """ #doc [to be called near the beginning of certain event handlers] """ # Warning: same named method exists in assembly, GLPane, and ops_select, with different implems. # More info in comments in assembly version. [bruce 051031] if self.assy: self.assy.begin_select_cmd() return def _tripleClickTimeout(self): """ [private method] This method is called whenever the tripleClickTimer expires. """ return def mouseTripleClickEvent(self, event): """ Triple-click event handler for the L{GLPane}. Code can check I{self.tripleClick} to determine if an event is a triple click. @param event: A Qt mouse event. @type event: U{B{QMouseEvent}<http://doc.trolltech.com/4/qmouseevent.html>} @see: L{ops_connected_Mixin.getConnectedAtoms()} for an example of use. """ # Implementation: We start a <tripleClickTimer> (a single shot timer) # whenever we get a double-click mouse event, but only if there is no # other active tripleClickTimer. # If we get another mousePressEvent() before <tripleClickTimer> expires, # then we consider that event a triple-click event and mousePressEvent() # sends the event here. # # We then set instance variable <tripleClick> to True and send the # event to mouseDoubleClickEvent(). After mouseDoubleClickEvent() # processes the event and returns, we reset <tripleClick> to False. # Code can check <tripleClick> to determine if an event is a # triple click. # # For an example, see ops_connected_Mixin.getConnectedAtoms() # # Note: This does not fully implement a triple-click event handler # (i.e. include mode.left/middle/rightTriple() methods), # but it does provides the guts for one. I intend to discuss this with # Bruce to see if it would be worth adding these mode methods. # Since we only need this to implement NFR 2516 (i.e. select all # connected PAM5 atoms when the user triple-clicks a PAM5 atom), # it isn't necessary. # # See: mouseDoubleClickEvent(), mousePressEvent(), _tripleClickTimeout() #print "Got TRIPLE-CLICK" self.tripleClick = True try: self.mouseDoubleClickEvent(event) finally: self.tripleClick = False return def mouseDoubleClickEvent(self, event): """ Double-click event handler for the L{GLPane}. @param event: A Qt mouse event. @type event: U{B{QMouseEvent}<http://doc.trolltech.com/4/qmouseevent.html>} """ if not self.tripleClickTimer.isActive(): # See mouseTripleClickEvent(). self.tripleClickTimer.start( 200 ) # 200-millisecond singleshot timer. # (note: mouseDoubleClickEvent and mousePressEvent share a lot of code) self.makeCurrent() #bruce 060129 precaution, presumably needed for same reasons as in mousePressEvent self.begin_select_cmd() #bruce 060129 bugfix (needed now that this can select atoms in BuildAtoms_Command) self.debug_event(event, 'mouseDoubleClickEvent') but, mod_unused = self.fix_event(event, 'press', self.graphicsMode) ## but = event.stateAfter() #k I'm guessing this event comes in place of a mousePressEvent; # need to test this, and especially whether a releaseEvent then comes # [bruce 040917 & 060124] ## print "Double clicked: ", but self.checkpoint_before_drag(event, but) #bruce 060323 for bug 1747 (caused by no Undo checkpoint for doubleclick) # Q. Why didn't that bug show up earlier?? # A. guess: modelTree treeChanged signal, or (unlikely) GLPane paintGL, was providing a checkpoint # which made up for the 'checkpoint_after_drag' that this one makes happen (by setting self.__flag_and_begin_retval). # But I recently removed the checkpoint caused by treeChanged, and (unlikely cause) fiddled with code related to after_op. # Now I'm thinking that checkpoint_after_drag should do one whether or not checkpoint_before_drag # was ever called. Maybe that would fix other bugs... but not cmenu op bugs like 1411 (or new ones the above-mentioned # change also caused), since in those, the checkpoint_before_drag happens, but the cmenu swallows up the # releaseEvent so the checkpoint_after_drag never has a chance to run. Instead, I'm fixing those by wrapping # _paintGL_drawing in its own begin/end checkpoints, and (unlike the obs after_op) putting them after # env.postevent_updates (see its call to find them). But I might do the lone-releaseEvent checkpoint too. [bruce 060323] # Update, 060326: reverting the _paintGL_drawing checkpointing, since it caused bug 1759 (more info there). handler = self.mouse_event_handler # updated by fix_event [bruce 070405] if handler is not None: handler.mouseDoubleClickEvent(event) return if but & Qt.LeftButton: self.graphicsMode.leftDouble(event) if but & Qt.MidButton: self.graphicsMode.middleDouble(event) if but & Qt.RightButton: self.graphicsMode.rightDouble(event) return __pressEvent = None #bruce 060124 for Undo __flag_and_begin_retval = None def checkpoint_before_drag(self, event, but): #bruce 060124; split out of caller, 060126 if but & (Qt.LeftButton|Qt.MidButton|Qt.RightButton): # Do undo_checkpoint_before_command if possible. # #bruce 060124 for Undo; will need cleanup of begin-end matching with help of fix_event; # also, should make redraw close the begin if no releaseEvent came by then (but don't # forget about recursive event processing) [done in a different way in redraw, bruce 060323] if self.__pressEvent is not None and debug_flags.atom_debug: # this happens whenever I put up a context menu in GLPane, so don't print it unless atom_debug ###@@@ print "atom_debug: bug: pressEvent didn't get release:", self.__pressEvent self.__pressEvent = event self.__flag_and_begin_retval = None ##e we could simplify the following code using newer funcs external_begin_cmd_checkpoint etc in undo_manager if self.assy: begin_retval = self.assy.undo_checkpoint_before_command("(mouse)") # text was "(press)" before 060126 eve # this command name should be replaced sometime during the command self.__flag_and_begin_retval = True, begin_retval pass return def mousePressEvent(self, event): """ Mouse press event handler for the L{GLPane}. It dispatches mouse press events depending on B{Shift} and B{Control} key state. @param event: A Qt mouse event. @type event: U{B{QMouseEvent}<http://doc.trolltech.com/4/qmouseevent.html>} """ if self.tripleClickTimer.isActive(): # This event is a triple-click event. self.mouseTripleClickEvent(event) return # (note: mouseDoubleClickEvent and mousePressEvent share a lot of code) self.makeCurrent() ## Huaicai 2/25/05. This is to fix item 2 of bug 400: make this rendering context ## as current, otherwise, the first event will get wrong coordinates self.begin_select_cmd() #bruce 051031 if self.debug_event(event, 'mousePressEvent', permit_debug_menu_popup = 1): #e would using fix_event here help to avoid those "release without press" messages, # or fix bugs from mouse motion? or should we set some other flag to skip subsequent # drag/release events until the next press? [bruce 060126 questions] return ## but = event.stateAfter() but, mod = self.fix_event(event, 'press', self.graphicsMode) # Notes [bruce 070328]: # but = <PyQt4.QtCore.MouseButtons object at ...>, # mod = <PyQt4.QtCore.KeyboardModifiers object at ...>. # for doc on these objects see http://www.riverbankcomputing.com/Docs/PyQt4/html/qt-mousebuttons.html # and for info about event methods button and buttons (related to state and stateAfter in Qt3) see # http://www.riverbankcomputing.com/Docs/PyQt4/html/qmouseevent.html#button # (I hope fix_event makes sure at most one button flag remains; if not, # following if/if/if should be given some elifs. ###k # Note that same applies to mouseReleaseEvent; mouseMoveEvent already does if/elif. # It'd be better to normalize it all in fix_event, though, in case user changes buttons # without releasing them all, during the drag. Some old bug reports are about that. #e # [bruce 060124-26 comment]) self.checkpoint_before_drag(event, but) self.current_stereo_image = self.stereo_image_hit_by_event(event) # note: self.current_stereo_image will remain unchanged until the # next mouse press event. (Thus even drags into the other image # of a left/right pair will not change it.) ### REVIEW: even bareMotion won't change it -- will this cause # trouble for highlighting when the mouse crosses the boundary? # [bruce 080911 question] handler = self.mouse_event_handler # updated by fix_event [bruce 070405] if handler is not None: handler.mousePressEvent(event) return if but & Qt.LeftButton: if mod & Qt.ShiftModifier: self.graphicsMode.leftShiftDown(event) elif mod & Qt.ControlModifier: self.graphicsMode.leftCntlDown(event) else: self.graphicsMode.leftDown(event) if but & Qt.MidButton: if mod & Qt.ShiftModifier and mod & Qt.ControlModifier: # mark 060228. self.graphicsMode.middleShiftCntlDown(event) elif mod & Qt.ShiftModifier: self.graphicsMode.middleShiftDown(event) elif mod & Qt.ControlModifier: self.graphicsMode.middleCntlDown(event) else: self.graphicsMode.middleDown(event) if but & Qt.RightButton: if mod & Qt.ShiftModifier: self.graphicsMode.rightShiftDown(event) elif mod & Qt.ControlModifier: self.graphicsMode.rightCntlDown(event) else: self.graphicsMode.rightDown(event) return def mouseReleaseEvent(self, event): """ The mouse release event handler for the L{GLPane}. @param event: A Qt mouse event. @type event: U{B{QMouseEvent}<http://doc.trolltech.com/4/qmouseevent.html>} """ self.debug_event(event, 'mouseReleaseEvent') ## but = event.state() but, mod = self.fix_event(event, 'release', self.graphicsMode) ## print "Button released: ", but handler = self.mouse_event_handler # updated by fix_event [bruce 070405] if handler is not None: handler.mouseReleaseEvent(event) self.checkpoint_after_drag(event) return try: if but & Qt.LeftButton: if mod & Qt.ShiftModifier: self.graphicsMode.leftShiftUp(event) elif mod & Qt.ControlModifier: self.graphicsMode.leftCntlUp(event) else: self.graphicsMode.leftUp(event) if but & Qt.MidButton: if mod & Qt.ShiftModifier and mod & Qt.ControlModifier: # mark 060228. self.graphicsMode.middleShiftCntlUp(event) elif mod & Qt.ShiftModifier: self.graphicsMode.middleShiftUp(event) elif mod & Qt.ControlModifier: self.graphicsMode.middleCntlUp(event) else: self.graphicsMode.middleUp(event) if but & Qt.RightButton: if mod & Qt.ShiftModifier: self.graphicsMode.rightShiftUp(event) elif mod & Qt.ControlModifier: self.graphicsMode.rightCntlUp(event) else: self.graphicsMode.rightUp(event) except: print_compact_traceback("exception in mode's mouseReleaseEvent handler (bug, ignored): ") #bruce 060126 # piotr 080320: # "fast manipulation" mode where the external bonds are not displayed # the glpane has to be redrawn after mouse button is released # to show the bonds again # # this has to be moved to GlobalPreferences (this debug_pref is # also called in chunk.py) piotr 080325 if debug_pref("GLPane: suppress external bonds when dragging?", Choice_boolean_False, non_debug = True, prefs_key = True ): self.gl_update() self.checkpoint_after_drag(event) #bruce 060126 moved this later, to fix bug 1384, and split it out, for clarity return def checkpoint_after_drag(self, event): #bruce 060124; split out of caller, 060126 (and called it later, to fix bug 1384) """ Do undo_checkpoint_after_command(), if a prior press event did an undo_checkpoint_before_command() to match. @note: This should only be called *after* calling the mode-specific event handler for this event! """ del event # (What if there's recursive event processing inside the event handler... when it's entered it'll end us, then begin us... # so an end-checkpoint is still appropriate; not clear it should be passed same begin-retval -- most likely, # the __attrs here should all be moved into env and used globally by all event handlers. I'll solve that when I get to # the other forms of recursive event processing. ###@@@ # So for now, I'll assume recursive event processing never happens in the event handler # (called just before this method is called) -- then the simplest # scheme for this code is to do it all entirely after the mode's event handler (as done in this routine), # rather than checking __attrs before the handlers and using the values afterwards. [bruce 060126]) # Maybe we should simulate a pressEvent's checkpoint here, if there wasn't one, to fix hypothetical bugs from a # missing one. Seems like a good idea, but save it for later (maybe the next commit, maybe a bug report). [bruce 060323] if self.__pressEvent is not None: ###@@@ and if no buttons are still pressed, according to fix_event? self.__pressEvent = None if self.__flag_and_begin_retval: flagjunk, begin_retval = self.__flag_and_begin_retval self.__flag_and_begin_retval = None if self.assy: #k should always be true, and same assy as before # (even for file-closing cmds? I bet not, but: # - unlikely as effect of a mouse-click or drag in GLPane; # - probably no harm from these checkpoints getting into different assys # But even so, when solution is developed (elsewhere, for toolbuttons), bring it here # or (better) put it into these checkpoint methods. ###@@@) self.assy.undo_checkpoint_after_command( begin_retval) return def mouseMoveEvent(self, event): """ Mouse move event handler for the L{GLPane}. It dispatches mouse motion events depending on B{Shift} and B{Control} key state. @param event: A Qt mouse event. @type event: U{B{QMouseEvent}<http://doc.trolltech.com/4/qmouseevent.html>} """ ## Huaicai 8/4/05. self.makeCurrent() ##self.debug_event(event, 'mouseMoveEvent') ## but = event.state() but, mod = self.fix_event(event, 'move', self.graphicsMode) handler = self.mouse_event_handler # updated by fix_event [bruce 070405] if handler is not None: handler.mouseMoveEvent(event) return if but & Qt.LeftButton: if mod & Qt.ShiftModifier: self.graphicsMode.leftShiftDrag(event) elif mod & Qt.ControlModifier: self.graphicsMode.leftCntlDrag(event) else: self.graphicsMode.leftDrag(event) elif but & Qt.MidButton: if mod & Qt.ShiftModifier and mod & Qt.ControlModifier: # mark 060228. self.graphicsMode.middleShiftCntlDrag(event) elif mod & Qt.ShiftModifier: self.graphicsMode.middleShiftDrag(event) elif mod & Qt.ControlModifier: self.graphicsMode.middleCntlDrag(event) else: self.graphicsMode.middleDrag(event) elif but & Qt.RightButton: if mod & Qt.ShiftModifier: self.graphicsMode.rightShiftDrag(event) elif mod & Qt.ControlModifier: self.graphicsMode.rightCntlDrag(event) else: self.graphicsMode.rightDrag(event) else: self.graphicsMode.bareMotion(event) return def wheelEvent(self, event): """ Mouse wheel event handler for the L{GLPane}. @param event: A Qt mouse wheel event. @type event: U{B{QWheelEvent}<http://doc.trolltech.com/4/qwheelevent.html>} """ self.debug_event(event, 'wheelEvent') if not self.in_drag: #but = event.buttons() # I think this event has no stateAfter() [bruce 060220] self.update_modkeys(event.modifiers()) #bruce 060220 self.graphicsMode.Wheel(event) # mode bindings use modkeys from event; maybe this is ok? # Or would it be better to ignore this completely during a drag? [bruce 060220 questions] # russ 080527: Fix Bug 2606 (highlighting not turned on after wheel event.) self.wheelHighlight = True return #== Timer helper methods highlightTimer = None #bruce 070110 (was not needed before) def _timer_debug_pref(self): #bruce 070110 split this out and revised it #bruce 080129 removed non_debug and changed prefs_key # (so all developer settings for this will start from scratch), # since behavior has changed since it was first implemented # in a way that makes it likely that changing this will cause bugs. res = debug_pref("GLPane: timer interval", Choice([100, 0, 5000, None]), # NOTE: the default value defined here (100) # determines the usual timer behavior, # not just debug pref behavior. ## non_debug = True, prefs_key = "A10 devel/glpane timer interval" ) if res is not None and type(res) is not type(1): # support prefs values stored by future versions (or by a brief bug workaround which stored "None") res = None return res #russ 080505: Treat focusIn/focusOut events the same as enter/leave events. # On the Mac at least, Cmd-Tabbing to another app window that pops up on top # of our pane doesn't deliver a leave event, but does deliver a focusOut. # Unless we handle it as a leave, the timer is left active, and a highlight # draw can occur. This steals the focus from the upper window, popping NE1 # on top of it, which is very annoying to the user. def focusInEvent(self, event): if DEBUG_BAREMOTION: print "focusInEvent" pass self.enterEvent(event) def focusOutEvent(self, event): if DEBUG_BAREMOTION: print "focusOutEvent" pass self.leaveEvent(event) def enterEvent(self, event): # Mark 060806. [minor revisions by bruce 070110] """ Event handler for when the cursor enters the GLPane. @param event: The mouse event after entering the GLpane. @type event: U{B{QMouseEvent}<http://doc.trolltech.com/4/qmouseevent.html>} """ del event if DEBUG_BAREMOTION: print "enterEvent" pass choice = self._timer_debug_pref() if choice is None: if not env.seen_before("timer is turned off"): print "warning: GLPane's timer is turned off by a debug_pref" if self.highlightTimer: self.killTimer(self.highlightTimer) if DEBUG_BAREMOTION: print " Killed highlight timer %r"% self.highlightTimer pass pass self.highlightTimer = None return if not self.highlightTimer: interval = int(choice) self.highlightTimer = self.startTimer(interval) # Milliseconds interval. if DEBUG_BAREMOTION: print " Started highlight timer %r"% self.highlightTimer pass pass return def leaveEvent(self, event): # Mark 060806. [minor revisions by bruce 070110] """ Event handler for when the cursor leaves the GLPane. @param event: The last mouse event before leaving the GLpane. @type event: U{B{QMouseEvent}<http://doc.trolltech.com/4/qmouseevent.html>} """ del event if DEBUG_BAREMOTION: print "leaveEvent" pass # If an object is "hover highlighted", unhighlight it when leaving the GLpane. if self.selobj is not None: ## self.selobj = None # REVIEW: why not set_selobj? self.set_selobj(None) #bruce 080508 bugfix (turn off MT highlight) self.gl_update_highlight() # REVIEW: this redraw can be slow -- is it worthwhile? pass # Kill timer when the cursor leaves the GLpane. # It is (re)started in enterEvent() above. if self.highlightTimer: self.killTimer(self.highlightTimer) if DEBUG_BAREMOTION: print " Killed highlight timer %r"% self.highlightTimer pass self.highlightTimer = None pass return def timerEvent(self, event): # Mark 060806. """ When the GLpane's timer expires, a signal is generated calling this slot method. The timer is started in L{enterEvent()} and killed in L{leaveEvent()}, so the timer is only active when the cursor is in the GLpane. This method is part of a hover highlighting optimization and works in concert with mouse_exceeded_distance(), which is called from L{selectMode.bareMotion()}. It works by creating a 'MouseMove' event using the current cursor position and sending it to L{mode.bareMotion()} whenever the mouse hasn't moved since the previous timer event. @see: L{enterEvent()}, L{leaveEvent()}, L{selectMode.mouse_exceeded_distance()}, and L{selectMode.bareMotion()} """ del event if not self.highlightTimer or (self._timer_debug_pref() is None): #bruce 070110 if debug_flags.atom_debug or DEBUG_BAREMOTION: print "note (not a bug unless happens a lot): GLPane got timerEvent but has no timer" # should happen once when we turn it off or maybe when mouse leaves -- not other times, not much #e should we do any of the following before returning?? return # Get the x, y position of the cursor and store as tuple in <xy_now>. cursor = self.cursor() cursorPos = self.mapFromGlobal(cursor.pos()) # mapFromGlobal() maps from screen coords to GLpane coords. xy_now = (cursorPos.x(), cursorPos.y()) # Current cursor position xy_last = self.timer_event_last_xy # Cursor position from last timer event. # If this cursor position hasn't changed since the last timer event, and no mouse button is # being pressed, create a 'MouseMove' mouse event and pass it to mode.bareMotion(). # This event is intended only for eventual use in selectMode.mouse_exceeded_distance # by certain graphicsModes, but is sent to all graphicsModes. if (xy_now == xy_last and self.button == None) or self.wheelHighlight: # Only pass a 'MouseMove" mouse event once to bareMotion() when the mouse stops # and hasn't moved since the last timer event. if self.triggerBareMotionEvent or self.wheelHighlight: #print "Calling bareMotion. xy_now = ", xy_now mouseEvent = QMouseEvent( QEvent.MouseMove, cursorPos, Qt.NoButton, Qt.NoButton, Qt.NoModifier) #Qt.NoButton & Qt.MouseButtonMask, #Qt.NoButton & Qt.KeyButtonMask ) if DEBUG_BAREMOTION: #bruce 080129 re highlighting bug 2606 reported by Paul print "debug fyi: calling %r.bareMotion with fake zero-motion event" % (self.graphicsMode,) # russ 080527: Fix Bug 2606 (highlighting not turned on after wheel event.) # Keep generating fake zero-motion events until one is handled rather than discarded. discarded = self.graphicsMode.bareMotion(mouseEvent) if not discarded: self.triggerBareMotionEvent = False self.wheelHighlight = False # The cursor hasn't moved since the last timer event. See if we should display the tooltip now. # REVIEW: # - is it really necessary to call this 10x/second? # - Does doing so waste significant cpu time? # [bruce 080129 questions] helpEvent = QHelpEvent(QEvent.ToolTip, QPoint(cursorPos), QPoint(cursor.pos()) ) if self.dynamicToolTip: # Probably always True. Mark 060818. self.dynamicToolTip.maybeTip(helpEvent) # maybeTip() is responsible for displaying the tooltip. else: self.cursorMotionlessStartTime = time.time() # Reset the cursor motionless start time to "zero" (now). # Used by maybeTip() to support the display of dynamic tooltips. self.triggerBareMotionEvent = True self.timer_event_last_xy = xy_now return #== end of Timer helper methods def mousepoints(self, event, just_beyond = 0.0): """ @return: a pair (2-tuple) of points (Numeric arrays of x,y,z in model coordinates) that lie under the mouse pointer. The first point lies at (or just beyond) the near clipping plane; the other point lies in the plane of the center of view. @rtype: (point, point) @param just_beyond: how far beyond the near clipping plane the first point should lie. Default value of 0.0 means on the near plane; 1.0 would mean on the far plane. Callers often pass 0.01 for this. Some callers pass this positionally, and some as a keyword argument. @type just_beyond: float If stereo is enabled, self.current_stereo_image determines which stereo image's coordinate system is used to get the mousepoints (even if the mouse pointer is not inside that image now). (Note that self.current_stereo_image is set (by other code in self) based on the mouse position in each mouse press event. It's not affected by mouse position in mouse drag, release, or bareMotion events.) """ x = event.pos().x() y = self.height - event.pos().y() # modify modelview matrix in side-by-side stereo view modes [piotr 080529] # REVIEW: does no_clipping disable enough? especially in anaglyph mode, # we might want to disable even more side effects, for efficiency. # [bruce 080912 comment] self._enable_stereo(self.current_stereo_image, no_clipping = True) p1 = A(gluUnProject(x, y, just_beyond)) p2 = A(gluUnProject(x, y, 1.0)) self._disable_stereo() los = self.lineOfSight k = dot(los, -self.pov - p1) / dot(los, p2 - p1) p2 = p1 + k*(p2-p1) return (p1, p2) def SaveMouse(self, event): """ Extracts the mouse position from event and saves it in the I{MousePos} property. (localizes the API-specific code for extracting the info) @param event: A Qt mouse event. @type event: U{B{QMouseEvent}<http://doc.trolltech.com/4/qmouseevent.html>} """ self.MousePos = V(event.pos().x(), event.pos().y()) def dragstart_using_GL_DEPTH(self, event, more_info = False, always_use_center_of_view = False): #bruce 061206 added more_info option """ Use the OpenGL depth buffer pixel at the coordinates of event (which works correctly only if the proper GL context (of self) is current -- caller is responsible for this) to guess the 3D point that was visually clicked on. If that was too far away to be correct, use a point under the mouse and in the plane of the center of view. By default, return (False, point) when point came from the depth buffer, or (True, point) when point came from the plane of the center of view. Callers should typically do further sanity checks on point and the "farQ" flag (the first value in the returned tuple), perhaps replacing point with an object's center, projected onto the mousepoints line, if point is an unrealistic dragpoint for the object which will be dragged. [#e there should be a canned routine for doing that to our retval] If the optional flag more_info is true, then return a larger tuple (whose first two members are the same as in the 2-tuple we return by default). The larger tuple is (farQ, point, wX, wY, depth, farZ) where wX, wY are the OpenGL window coordinates of event within self (note that Y is 0 on the bottom, unlike in Qt window coordinates; glpane.height minus wY gives the Qt window coordinate of the event), and depth is the current depth buffer value at the position of the event -- larger values are deeper; 0.0 is the nearest possible value; depths of farZ or greater are considered "background", even though they might be less than 1.0 due to drawing of a background rectangle. (In the current implementation, farZ is always GL_FAR_Z, a public global constant defined in constants.py, but in principle it might depend on the GLPane and/or vary with differently drawn frames.) @param always_use_center_of_view: If True it always uses the depth of the center of view (returned by self.mousepoints) . This is used by Line_GraphicsMode.leftDown(). """ #@NOTE: Argument always_use_center_of_view added on April 20, 2008 to #fix a bug for Mark's Demo. #at FNANO08 -- This was the bug: In CPK display style,, start drawing #a duplex,. When the rubberbandline draws 20 basepairs, move the cursor #just over the last sphere drawn and click to finish duplex creation #Switch the view to left view -- the duplex axis is not vertical wX = event.pos().x() wY = self.height - event.pos().y() wZ = glReadPixelsf(wX, wY, 1, 1, GL_DEPTH_COMPONENT) depth = wZ[0][0] farZ = GL_FAR_Z if depth >= farZ or always_use_center_of_view: junk, point = self.mousepoints(event) farQ = True else: point = A(gluUnProject(wX, wY, depth)) farQ = False if more_info: return farQ, point, wX, wY, depth, farZ return farQ, point def dragstart_using_plane_depth(self, event, plane = None, planeAxis = None, planePoint = None ): """ Returns the 3D point on a specified plane, at the coordinates of event @param plane: The point is computed such that it lies on this Plane at the given event coordinates. @see: Line_GraphicsMode.leftDown() @see: InsertDna_GraphicsMode. @TODO: There will be some cases where the intersection of the mouseray and the given plane is not possible or returns a very large number. Need to discuss this. """ # TODO: refactor this so the caller extracts Plane attributes, # and this method only receives geometric parameters (more general). # [bruce 080912 comment] #First compute the intersection point of the mouseray with the plane p1, p2 = self.mousepoints(event) linePoint = p2 lineVector = norm(p2 - p1) if plane is not None: planeAxis = plane.getaxis() planeNorm = norm(planeAxis) planePoint = plane.center else: assert not (planeAxis is None or planePoint is None) planeNorm = norm(planeAxis) #Find out intersection of the mouseray with the plane. intersection = planeXline(planePoint, planeNorm, linePoint, lineVector) if intersection is None: intersection = ptonline(planePoint, linePoint, lineVector) point = intersection return point def rescale_around_point(self, factor, point = None): #bruce 060829; 070402 moved user prefs functionality into caller """ Rescale around point (or center of view == - self.pov, if point is not supplied), by multiplying self.scale by factor (and shifting center of view if point is supplied). Note: factor < 1 means zooming in, since self.scale is the model distance from screen center to edge in plane of center of view. Note: not affected by zoom in vs. zoom out, or by user prefs. For that, see callers such as basicMode.rescale_around_point_re_user_prefs. Note that point need not be in the plane of the center of view, and if it's not, the depth of the center of view will change. If callers wish to avoid this, they can project point onto the plane of the center of view. """ self.gl_update() #bruce 070402 precaution self.scale *= factor ###e The scale variable needs to set a limit, otherwise, it will set self.near = self.far = 0.0 ### because of machine precision, which will cause OpenGL Error. [needed but NIM] [Huaicai comment 10/18/04] # [I'm not sure that comment is still correct -- nothing is actually changing self.near and self.far. # But it may be referring to the numbers made from them and fed to the glu projection routines; # if so, it might still apply. [bruce 060829]] # Now use point, so that it, not center of view, gets preserved in screen x,y position and "apparent depth" (between near/far). # Method: we're going to move point, in eyespace, relative to center of view (aka cov == -self.pov) # from oldscale * (point - cov) to newscale * (point - cov), in units of oldscale (since we're in them now), # so we're moving it by (factor - 1) * (point - cov), so translate back, by moving cov the other way (why the other way??): # cov -= (factor - 1) * (point - cov). I think this will work the same in ortho and perspective, and can ignore self.quat. # Test shows that works; but I don't yet understand why I needed to move cov in the opposite direction as I assumed. # But I worry about whether it will work if more than one Wheel event occurs between redraws (which rewrite depth buffer). # [bruce 060829] if point is not None: self.pov += (factor - 1) * (point - (-self.pov)) return pass # end
NanoCAD-master
cad/src/graphics/widgets/GLPane_event_methods.py
# Copyright 2004-2009 Nanorex, Inc. See LICENSE file for details. """ GLPane.py -- NE1's main model view. A subclass of Qt's OpenGL widget, QGLWidget. @version: $Id$ @copyright: 2004-2009 Nanorex, Inc. See LICENSE file for details. NOTE: If you add code to class GLPane, please carefully consider whether it belongs in one of its mixin superclasses (GLPane_*.py) instead of in the main class in this file. These separate files are topic-specific and should be kept as self-contained as possible, in methods, attributes, helper functions, and imports. (Someday, some of them should evolve into separate cooperating objects and not be part of GLPane's class hierarchy at all.) (Once the current refactoring is complete, most new code will belong in one of those superclass files, not in this file. [bruce 080912]) Module classification: [bruce 080104] It's graphics/widgets, but this is not as obvious as it sounds. It is "optimistic", as if we'd already refactored -- it's not fully accurate today. Refactoring needed: [bruce 080104] - split into several classes (either an inheritance tree, or cooperating objects); [080910 doing an initial step to this: splitting into mixins in their own files] - move more common code into GLPane_minimal [mostly done, 080914 or so, except for GL_SELECT code, common to several files]; Some of this will make more practical some ways of optimizing the graphics code. History: Mostly written by Josh; partly revised by Bruce for mode code revision, 040922-24. Revised by many other developers since then (and perhaps before). bruce 080910 splitting class GLPane into several mixin classes in other files. bruce 080925 removed support for GLPANE_IS_COMMAND_SEQUENCER """ # TEST_DRAWING has been moved to GLPane_rendering_methods _DEBUG_SET_SELOBJ = False # do not commit with true import sys from OpenGL.GL import GL_STENCIL_BITS from OpenGL.GL import glGetInteger from command_support.GraphicsMode_API import GraphicsMode_interface # for isinstance assertion import foundation.env as env from utilities import debug_flags from utilities.debug_prefs import debug_pref from utilities.debug_prefs import Choice_boolean_False from utilities.debug_prefs import Choice_boolean_True from utilities.debug import print_compact_traceback, print_compact_stack from utilities.prefs_constants import compassPosition_prefs_key from utilities.prefs_constants import defaultProjection_prefs_key from utilities.prefs_constants import startupGlobalDisplayStyle_prefs_key from utilities.prefs_constants import startup_GLPane_scale_prefs_key from utilities.prefs_constants import GLPane_scale_for_atom_commands_prefs_key from utilities.prefs_constants import GLPane_scale_for_dna_commands_prefs_key from utilities.constants import diDEFAULT from utilities.constants import diDNACYLINDER from utilities.constants import diPROTEIN from utilities.constants import default_display_mode from utilities.GlobalPreferences import pref_show_highlighting_in_MT from graphics.widgets.GLPane_lighting_methods import GLPane_lighting_methods from graphics.widgets.GLPane_frustum_methods import GLPane_frustum_methods from graphics.widgets.GLPane_event_methods import GLPane_event_methods from graphics.widgets.GLPane_rendering_methods import GLPane_rendering_methods from graphics.widgets.GLPane_highlighting_methods import GLPane_highlighting_methods from graphics.widgets.GLPane_text_and_color_methods import GLPane_text_and_color_methods from graphics.widgets.GLPane_stereo_methods import GLPane_stereo_methods from graphics.widgets.GLPane_view_change_methods import GLPane_view_change_methods from graphics.widgets.GLPane_minimal import GLPane_minimal from foundation.changes import SubUsageTrackingMixin from graphics.widgets.GLPane_mixin_for_DisplayListChunk import GLPane_mixin_for_DisplayListChunk from PyQt4.Qt import QApplication, QCursor, Qt # == class GLPane( # these superclasses need to come first, since they need to # override methods in GLPane_minimal: GLPane_lighting_methods, # needs to override _setup_lighting GLPane_frustum_methods, # needs to override is_sphere_visible etc GLPane_event_methods, # needs to override makeCurrent, setCursor, # and many *Event methods (not sure if GLPane_minimal defines # those, so it may not matter) GLPane_rendering_methods, # needs to override paintGL, several more # these don't yet need to come first, but we'll put them first # anyway in case someone adds a default def of some method # into GLPane_minimal in the future: GLPane_highlighting_methods, GLPane_text_and_color_methods, GLPane_stereo_methods, GLPane_view_change_methods, GLPane_minimal, # the "main superclass"; inherits QGLWidget SubUsageTrackingMixin, GLPane_mixin_for_DisplayListChunk ): """ Widget for OpenGL graphics and associated mouse/key input, with lots of associated/standard behavior and helper methods. Note: if you want to add code to this class, consider whether it ought to go into one of the mixin superclasses listed above. (Once the current refactoring is complete, most new code will belong in one of those superclasses, not in this file. [bruce 080912]) See module docstring for more info. Qt-called methods are overridden in some superclasses: * GLPane_event_methods overrides makeCurrent, setCursor, and many *Event methods * this class overrides paintGL, resizeGL, initializeGL Effectively a singleton object: * owned by main window (perhaps indirectly via class PartWindow) * never remade duringan NE1 session * contains public references to other singletons (e.g. win (permanent), assy (sometimes remade)) * some old code stores miscellaneous attributes inside it (e.g. shape, stored by Build Crystal) A few of the GLPane's public attributes: * several "point of view" attributes (some might be inherited from superclass GLPane_minimal) * graphicsMode - an instance of GraphicsMode_interface """ # Note: classes GLPane and ThumbView still share lots of code, # which ought to be merged into their common superclass GLPane_minimal. # [bruce 070914/080909 comment] always_draw_hotspot = False #bruce 060627; not really needed, added for compatibility with class ThumbView permit_shaders = True #bruce 090224 assy = None #bruce 080314 # the stereo attributes are maintained by the methods in # our superclass GLPane_stereo_methods, and used in that class, # and GLPane_rendering_methods, and GLPane_event_methods. stereo_enabled = False # piotr 080515 - stereo disabled by default stereo_images_to_draw = (0,) current_stereo_image = 0 # note: is_animating is defined and maintained in our superclass # GLPane_view_change_methods ## self.is_animating = False _resize_just_occurred = False #bruce 080922 #For performance reasons, whenever the global display style #changes, the current cursor is replaced with an hourglass cursor. #The following flag determines whether to turn off this wait cursor. #(It is turned off after global display style operation is complete. # see self._setWaitCursor_globalDisplayStyle().) [by Ninad, late 2008] _waitCursor_for_globalDisplayStyleChange = False def __init__(self, assy, parent = None, name = None, win = None): """ """ self.name = name or "glpane" # [bruce circa 080910 revised this; probably not used] shareWidget = None useStencilBuffer = True GLPane_minimal.__init__(self, parent, shareWidget, useStencilBuffer) self.win = win self.partWindow = parent # used in GLPane_event_methods superclass self._nodes_containing_selobj = [] # will be set during set_selobj to a list of 0 or more nodes # [bruce 080507 new feature] self._nodes_containing_selobj_is_from_selobj = None # records which selobj was used to set _nodes_containing_selobj self.stencilbits = 0 # conservative guess, will be set to true value below if not self.format().stencil(): # It's apparently too early to also test "or glGetInteger(GL_STENCIL_BITS) < 1" -- # that glGet returns None even when the bits are actually there # (on my system this is 8 when tested later). Guess: this won't work until # the context is initialized. msg = ("Warning: your graphics hardware did not provide an OpenGL stencil buffer.\n" "This will slow down some graphics operations.") ## env.history.message( regmsg( msg)) -- too early for that to work (need to fix that sometime, to queue the msg) print msg if debug_flags.atom_debug: print "atom_debug: details of lack of stencil bits: " \ "self.format().stencil() = %r, glGetInteger(GL_STENCIL_BITS) = %r" % \ ( self.format().stencil() , glGetInteger(GL_STENCIL_BITS) ) # Warning: these values can be False, None -- I don't know why, since None is not an int! # But see above for a guess. [bruce 050610] pass else: ## self.stencilbits = int( glGetInteger(GL_STENCIL_BITS) ) -- too early! self.stencilbits = 1 # conservative guess that if we got the buffer, it has at least one bitplane #e could probably be improved by testing this in initializeGL or paintGL (doesn't matter yet) ## if debug_flags.atom_debug: ## print "atom_debug: glGetInteger(GL_STENCIL_BITS) = %r" % ( glGetInteger(GL_STENCIL_BITS) , ) pass # [bruce 050419 new feature:] # The current Part to be displayed in this GLPane. # Logically this might not be the same as it's assy's current part, self.assy.part, # though in initial implem it will be the same except # when the part is changing... but the brief difference is important # since that's how the GLPane knows which previous part to store its # current view attributes in, before grabbing them from the new current part. # But some code might (incorrectly in principle, ok for now) # use self.assy.part when it should be using self.part. # The only thing we're sure self.part must be used for is to know in which # part the view attributes belong. self.part = None # Other "current preference" attributes. ###e Maybe some of these should # also be part-specific and/or saved in the mmp file? [bruce 050418] # == User Preference initialization == # Get glpane related settings from prefs db. # Default values are set in "prefs_table" in prefs_constants.py. # Mark 050919. self._init_background_from_prefs() # defined in GLPane_text_and_color_methods self.compassPosition = env.prefs[compassPosition_prefs_key] ### TODO: eliminate self.compassPosition (which is used and set, # in sync with this pref, in ne1_ui/prefs/Preferences.py) # and just use the pref directly when rendering. [bruce 080913 comment] self.ortho = env.prefs[defaultProjection_prefs_key] # REVIEW: should self.ortho be replaced with a property that refers # to that pref, or would that be too slow? If too slow, is there # a refactoring that would clean up the current requirement # to keep these in sync? [bruce 080913 questions] self.setViewProjection(self.ortho) # This updates the checkmark in the View menu. Fixes bug #996 Mark 050925. # default display style for objects in the window. # even though there is only one assembly to a window, # this is here in anticipation of being able to have # multiple windows on the same assembly. # Start the GLPane's current display mode in "Default Display Mode" (pref). self.displayMode = env.prefs[startupGlobalDisplayStyle_prefs_key] # TODO: rename self.displayMode (widely used as a public attribute # of self) to self.displayStyle. [bruce 080910 comment] # piotr 080714: Remember last non-reduced display style. if self.displayMode == diDNACYLINDER or \ self.displayMode == diPROTEIN: self.lastNonReducedDisplayMode = default_display_mode else: self.lastNonReducedDisplayMode = self.displayMode #self.win.statusBar().dispbarLabel.setText( "Current Display: " + dispLabel[self.displayMode] ) # == End of User Preference initialization == self._init_GLPane_rendering_methods() self.setAssy(assy) # leaves self.currentCommand/self.graphicsMode as nullmode, as of 050911 # note: this loads view from assy.part (presumably the default view) self._init_GLPane_event_methods() return # from GLPane.__init__ def resizeGL(self, width, height): """ Called by QtGL when the drawing window is resized. """ #bruce 080912 moved most of this into superclass self._resize_just_occurred = True GLPane_minimal.resizeGL(self, width, height) # call superclass method self.gl_update() # REVIEW: ok for superclass? # needed here? (Guess yes, to set needs_repaint flag) return _defer_statusbar_msg = False _deferred_msg = None _selobj_statusbar_msg = " " def paintGL(self): """ [PRIVATE METHOD -- call gl_update instead!] The main OpenGL-widget-drawing method, called internally by Qt when our superclass needs to repaint (and quite a few other times when it doesn't need to). THIS METHOD SHOULD NOT BE CALLED DIRECTLY BY OUR OWN CODE -- CALL gl_update INSTEAD. """ # debug_prefs related to bug 2961 in swapBuffers on Mac # (maybe specific to Leopard; seems to be a MacOS bug in which # swapBuffers works but the display itself is not updated after # that, or perhaps is not updated from the correct physical buffer) # [bruce 081222] debug_print_paintGL_calls = \ debug_pref("GLPane: print all paintGL calls?", Choice_boolean_False, non_debug = True, # temporary ### prefs_key = True ) manual_swapBuffers = \ debug_pref("GLPane: do swapBuffers manually?", # when true, disable QGLWidget.autoBufferSwap and # call swapBuffers ourselves when desired; # this is required for some of the following to work, # so it's also done when they're active even if it's False Choice_boolean_False, non_debug = True, # temporary ### prefs_key = True ) no_swapBuffers_when_nothing_painted = \ debug_pref("GLPane: no swapBuffers when paintGL returns early?", # I hoped this might fix some bugs in zoom to area # rubber rect when swapBuffers behaves differently # (e.g. after the bug in swapBuffers mentioned above), # but it doesn't. Choice_boolean_True, # using True fixes a logic bug in this case, # which fixes "related bug (B)" in bug report 2961 non_debug = True, # temporary ### prefs_key = True ) simulate_swapBuffers_with_CopyPixels = False ## simulate_swapBuffers_with_CopyPixels = \ ## debug_pref("GLPane: simulate swapBuffers with CopyPixels?", # NIM ## Choice_boolean_False, ## non_debug = True, # temporary ### ## prefs_key = True ) debug_verify_swapBuffers = False ## debug_verify_swapBuffers = \ ## debug_pref("GLPane: verify swapBuffers worked?", # NIM ## # verify by reading back a changed pixel, one in each corner ## Choice_boolean_False, ## non_debug = True, # temporary ### ## prefs_key = True ) if debug_verify_swapBuffers: manual_swapBuffers = True # required if simulate_swapBuffers_with_CopyPixels: pass ## manual_swapBuffers = True # not strictly required, left out for now, but put it in if this becomes real ### if debug_print_paintGL_calls: print print "calling paintGL" #bruce 081230 part of a fix for bug 2964 # (statusbar not updated by hover highlighted object, on Mac OS 10.5.5-6) self._defer_statusbar_msg = True self._deferred_msg = None glselect_was_wanted = self.glselect_wanted # note: self.glselect_wanted is defined and used in a mixin class # in another file; review: can this be more modular? painted_anything = self._paintGL() # _paintGL method is defined in GLPane_rendering_methods # (probably paintGL itself would work fine if defined there -- # untested, since having it here seems just as good) want_swapBuffers = True # might be modified below if painted_anything: if debug_print_paintGL_calls: print " it painted (redraw %d)" % env.redraw_counter pass else: if debug_print_paintGL_calls: print " it didn't paint ***" # note: not seen during zoom to area (nor is painted); maybe no gl_update then? if no_swapBuffers_when_nothing_painted: want_swapBuffers = False pass if want_swapBuffers and manual_swapBuffers: # do it now (and later refrain from doing it automatically) self.do_swapBuffers( debug = debug_print_paintGL_calls, use_CopyPixels = simulate_swapBuffers_with_CopyPixels, verify = debug_verify_swapBuffers ) want_swapBuffers = False # it's done, so we no longer want to do it this frame # tell Qt whether to do swapBuffers itself when we return if want_swapBuffers: self.setAutoBufferSwap(True) ## assert not simulate_swapBuffers_with_CopyPixels # Qt can't do this on its own swapBuffers call -- ok for now assert not debug_verify_swapBuffers # Qt can't do this on its own swapBuffers call else: self.setAutoBufferSwap(False) if debug_print_paintGL_calls: print " (not doing autoBufferSwap)" # note: before the above code was added, we could test the default state # like this: ## if not self.autoBufferSwap(): ## print " *** BUG: autoBufferSwap is off" # but it never printed, so there is no bug there # when the above-mentioned bug in swapBuffers occurs. #bruce 081230 part of a fix for bug 2964 self._defer_statusbar_msg = False if self._deferred_msg is not None: # do this now rather than inside set_selobj (re bug 2964) env.history.statusbar_msg( self._deferred_msg) elif glselect_was_wanted: # This happens when the same selobj got found again; # this is common when rulers are on, and rare but happens otherwise # (especially when moving mouse slowly from one selobj to another); # when it happens, I think we need to use this other way to get the # desired message out. Review: could we simplify by making # this the *only* way, or would that change the interaction # between this code and unrelated sources of statusbar_msg calls # whose messages we should avoid overriding unless selobj changes? env.history.statusbar_msg( self._selobj_statusbar_msg ) pass self._resize_just_occurred = False self._resetWaitCursor_globalDisplayStyle() return def do_swapBuffers( self, debug = False, use_CopyPixels = False, verify = False ): #bruce 081222 """ """ if verify: # record pixels, change colors to make buffers differ, compare later print "verify is nim" ### if use_CopyPixels: print "use_CopyPixels is nim, no swapBuffers is occurring" ### Q: does this prevent all drawing?? else: self.swapBuffers() if verify: # compare, print pass ### return # == #bruce 080813 get .graphicsMode from commandSequencer def _get_graphicsMode(self): res = self.assy.commandSequencer.currentCommand.graphicsMode # don't go through commandSequencer.graphicsMode, # maybe that attr is not needed assert isinstance(res, GraphicsMode_interface) return res graphicsMode = property( _get_graphicsMode) # == # self.part maintenance [bruce 050419] def set_part(self, part): """ change our current part to the one given, and take on that part's view; ok if old or new part is None; note that when called on our current part, effect is to store our view into it (which might not actually be needed, but is fast enough and harmless) """ if self.part is not part: self.gl_update() # we depend on this not doing the redraw until after we return self._close_part() # saves view into old part (if not None) self.part = part self._open_part() # loads view from new part (if not None) def forget_part(self, part): """ [public] if you know about this part, forget about it (call this from dying parts) """ if self.part is part: self.set_part(None) return def _close_part(self): """ [private] save our current view into self.part [if not None] and forget about self.part """ if self.part: self._saveLastViewIntoPart( self.part) self.part = None def _open_part(self): """ [private] after something set self.part, load our current view from it """ if self.part: self._setInitialViewFromPart( self.part) # else our current view doesn't matter return def saveLastView(self): """ [public method] update the view of all parts you are displaying (presently only one or none) from your own view """ if self.part: self._saveLastViewIntoPart( self.part) #bruce 050418 split the following NamedView methods into two methods each, # so MWsemantics can share code with them. Also revised their docstrings, # and revised them for assembly/part split (i.e. per-part csys records), # and renamed them as needed to reflect that. # #bruce 080912: the ones that are slot methods are now moved to # GLPane_view_change_methods.py. The "view" methods that remain are involved # in the relation between self and self.part, rather than in implementing # view changes for the UI, so they belong here rather than in that file. def _setInitialViewFromPart(self, part): """ Set the initial (or current) view used by this GLPane to the one stored in part.lastView, i.e. to part's "Last View". """ # Huaicai 1/27/05: part of the code of this method comes # from original setAssy() method. This method can be called # after setAssy() has been called, for example, when opening # an mmp file. self.snapToNamedView( part.lastView) # defined in GLPane_view_change_methods def _saveLastViewIntoPart(self, part): """ Save the current view used by this GLPane into part.lastView, which (when this part's assy is later saved in an mmp file) will be saved as that part's "Last View". [As of 050418 this still only gets saved in the file for the main part] """ # Huaicai 1/27/05: before mmp file saving, this method # should be called to save the last view user has, which will # be used as the initial view when it is opened again. part.lastView.setToCurrentView(self) # == def setAssy(self, assy): #bruce 050911 revised this """ [bruce comment 040922, partly updated 080812] This is called from self.__init__, and from MWSemantics._make_and_init_assy when user asks to open a new file or close current file. Apparently, it is supposed to forget whatever is happening now, and reinitialize the entire GLPane. However, it does nothing to cleanly leave the current mode, if any; my initial guess [040922] is that that's a bug. (As of 040922 I didn't yet try to fix that... only to emit a warning when it happens. Any fix requires modifying our callers.) I also wonder if setAssy ought to do some of the other things now in __init__, e.g. setting some display prefs to their defaults. Yet another bug (in how it's called now): user is evidently not given any chance to save unsaved changes, or get back to current state if the openfile fails... tho I'm not sure I'm right about that, since I didn't test it. Revised 050911: leaves mode as nullmode. """ if self.assy: # make sure the old assy (if any) was closed [bruce 080314] # Note: if future changes to permit MDI allow one GLPane to switch # between multiple assys, then the following might not be a bug. # Accordingly, we only complain, we don't close it. # Callers should close it before calling this method. if not self.assy.assy_closed: print "\nlikely bug: GLPane %r .setAssy(%r) but old assy %r " \ "was not closed" % (self, assy, self.assy) ##e should previous self.assy be destroyed, or at least # made to no longer point to self? [bruce 051227 question] pass self.assy = assy mainpart = assy.tree.part assert mainpart #bruce 050418; depends on the order in which # global objects (glpane, assy) are set up during startup # or when opening a new file, so it might fail someday. # It might not be needed if set_part (below) doesn't mind # a mainpart of None and/or if we initialize our viewpoint # to default, according to an older version of this comment. # [comment revised, bruce 080812] assy.set_glpane(self) # sets assy.o and assy.glpane # logically I'd prefer to move this to just after set_part, # but right now I have no time to fully analyze whether set_part # might depend on this having been done, so I won't move it down # for now. [bruce 080314] self.set_part( mainpart) self.assy.commandSequencer._reinit_modes() # TODO: move this out of this method, now that it's the usual case return # from GLPane.setAssy # == update methods [refactored between self and CommandSequencer, bruce 080813] def update_after_new_graphicsMode(self): # maybe rename to update_GLPane_after_new_graphicsMode? """ do whatever updates are needed in self after self.graphicsMode might have changed (ok if this is called more than needed, except it might be slower) @note: this should only do updates related specifically to self (as a GLPane). Any updates to assy, command sequencer or stack, active commands, or other UI elements should be done elsewhere. """ # note: as of 080813, called from _cseq_update_after_new_mode and Move_Command # TODO: optimize: some of this is not needed if the old & new graphicsMode are equivalent... # the best solution is to make them the same object in that case, # i.e. to get their owning commands to share that object, # and then to compare old & new graphicsMode objects before calling this. [bruce 071011] # note: self.selatom is deprecated in favor of self.selobj. # self.selobj will be renamed, perhaps to self.objectUnderMouse. # REVIEW whether it belongs in self at all (vs the graphicsMode, # or even the currentCommand if it can be considered part of the model # like the selection is). [bruce 071011] # selobj if self.selatom is not None: #bruce 050612 precaution (scheme could probably be cleaned up #e) if debug_flags.atom_debug: print "atom_debug: update_after_new_graphicsMode storing None over self.selatom", self.selatom self.selatom = None if self.selobj is not None: #bruce 050612 bugfix; to try it, in Build drag selatom over Select Atoms toolbutton & press it if debug_flags.atom_debug: print "atom_debug: update_after_new_graphicsMode storing None over self.selobj", self.selobj self.set_selobj(None) # event handlers self.set_mouse_event_handler(None) #bruce 070628 part of fixing bug 2476 (leftover CC Done cursor) # cursor (is this more related to event handlers or rendering?) self.graphicsMode.update_cursor() # do this always (since set_mouse_event_handler only does it if the handler changed) [bruce 070628] # Note: the above updates are a good idea, # but they don't help with generators [which as of this writing don't change self.currentCommand], # thus the need for other parts of that bugfix -- and given those, I don't know if this is needed. # But it seems a good precaution even if not. [bruce 070628] # rendering-related if sys.platform == 'darwin': self._set_widget_erase_color() # sets it from self.backgroundColor; # attr and method defined in GLPane_text_and_color_methods; # see comments in that method's implem for caveats self.gl_update() #bruce 080829 return def update_GLPane_after_new_command(self): #bruce 080813 """ [meant to be called only from CommandSequencer._cseq_update_after_new_mode] """ self._adjust_GLPane_scale_if_needed() return def _adjust_GLPane_scale_if_needed(self): # by Ninad """ Adjust the glpane scale while in a certain command. Behavior -- Default scale remains the same (i.e. value of startup_GLPane_scale_prefs_key) If user enters BuildDna command and if -- a) there is no model in the assembly AND b) user didn't change the zoom factor , the glpane.scale would be adjusted to 50.0 (GLPane_scale_for_dna_commands_prefs_key) If User doesn't do anything in BuildDna AND also doesn't modify the zoom factor, exiting BuildDna and going into the default command (or any command such as BuildAtoms), it should restore zoom scale to 10.0 (value for GLPane_scale_for_atom_commands_prefs_key) @see: self.update_after_new_current_command() where it is called. This method in turn, gets called after you enter a new command. @see: Command.start_using_new_mode() """ #Implementing this method fixes bug 2774 #bruce 0808013 revised order of tests within this method #hasattr test fixes bug 2813 if hasattr(self.assy.part.topnode, 'members'): numberOfMembers = len(self.assy.part.topnode.members) else: #It's a clipboard part, probably a chunk or a jig not contained in #a group. numberOfMembers = 1 if numberOfMembers != 0: # do nothing except for an empty part return # TODO: find some way to refactor this to avoid knowing the # explicit list of commandNames (certainly) and prefs_keys / # preferred scales (if possible). At least, define a # "command scale kind" attribute to test here in place of # having the list of command names. [bruce 080813 comment] dnaCommands = ('BUILD_DNA', 'INSERT_DNA', 'DNA_SEGMENT', 'DNA_STRAND') startup_scale = float(env.prefs[startup_GLPane_scale_prefs_key]) dna_preferred_scale = float( env.prefs[GLPane_scale_for_dna_commands_prefs_key]) atom_preferred_scale = float( env.prefs[GLPane_scale_for_atom_commands_prefs_key]) if self.assy.commandSequencer.currentCommand.commandName in dnaCommands: if self.scale == startup_scale: self.scale = dna_preferred_scale else: if self.scale == dna_preferred_scale: self.scale = atom_preferred_scale return def _setWaitCursor_globalDisplayStyle(self): """ For performance reasons, whenever the global display style changes, the current cursor is replaced with an hourglass cursor, by calling this method. @see: self._paintGL() @see: self.setGlobalDisplayStyle() @see: self._setWaitCursor() @see: self._resetWaitCursor_globalDisplayStyle """ if self._waitCursor_for_globalDisplayStyleChange: #This avoids setting the wait cursor twice. return self._waitCursor_for_globalDisplayStyleChange = True self._setWaitCursor() def _resetWaitCursor_globalDisplayStyle(self): """ Reset hourglass cursor that was set while NE1 was changing the global display style of the model (by _setWaitCursor_globalDisplayStyle). @see: self._paintGL() @see: self.setGlobalDisplayStyle() @see: self._setWaitCursor() @see: self._setWaitCursor_globalDisplayStyle() """ if self._waitCursor_for_globalDisplayStyleChange: self._resetWaitCursor() self._waitCursor_for_globalDisplayStyleChange = False return def _setWaitCursor(self): """ Set the hourglass cursor whenever required. """ QApplication.setOverrideCursor( QCursor(Qt.WaitCursor) ) def _resetWaitCursor(self): """ Reset the hourglass cursor. @see: self._paintGL() @see: self.setGlobalDisplayStyle() @see: self._setWaitCursor() @see: self._setWaitCursor_globalDisplayStyle() """ QApplication.restoreOverrideCursor() def setGlobalDisplayStyle(self, disp): """ Set the global display style of self (the GLPane). @param disp: The desired global display style, which should be one of the following constants (this might not be a complete list; for all definitions see constants.py): - diDEFAULT (the "NE1 start-up display style", as defined in the Preferences | General dialog) - diLINES (Lines display style) - diTUBES (Tubes display style) - diBALL (Ball and stick display style) - diTrueCPK (Space filling display style) - diDNACYLINDER (DNA cylinder display style) @type disp: int @note: doesn't update the MT, and callers typically won't need to, since the per-node display style icons are not changing. @see: setDisplayStyle methods in some model classes @see: setDisplayStyle_of_selection method in another class @see: self.self._setWaitCursor_globalDisplayStyle() """ self._setWaitCursor_globalDisplayStyle() # review docstring: what about diINVISIBLE? diPROTEIN? if disp == diDEFAULT: disp = env.prefs[ startupGlobalDisplayStyle_prefs_key ] #e someday: if self.displayMode == disp, no actual change needed?? # not sure if that holds for all init code, so being safe for now. self.displayMode = disp # note: chunks check this when needed before drawing, so this code # doesn't need to tell them to invalidate their display lists. # piotr 080714: Remember last non-reduced display style. if disp != diDNACYLINDER and \ disp != diPROTEIN: self.lastNonReducedDisplayMode = disp # Huaicai 3/29/05: Add the condition to fix bug 477 (keep this note) if self.assy.commandSequencer.currentCommand.commandName == 'CRYSTAL': self.win.statusBar().dispbarLabel.setEnabled(False) self.win.statusBar().globalDisplayStylesComboBox.setEnabled(False) else: self.win.statusBar().dispbarLabel.setEnabled(True) self.win.statusBar().globalDisplayStylesComboBox.setEnabled(True) self.win.statusBar().globalDisplayStylesComboBox.setDisplayStyle(disp) return _needs_repaint = True #bruce 050516 # used/modified in both this class and GLPane_rendering_methods # (see also wants_gl_update) def gl_update(self): #bruce 050127 """ External code should call this when it thinks the GLPane needs redrawing, rather than directly calling paintGL, unless it really knows it needs to wait until the redrawing has been finished (which should be very rare). Unlike calling paintGL directly (which can be very slow for large models, and redoes all its work each time it's called), this method is ok to call many times during the handling of one user event, since this will cause only one call of paintGL, after that user event handler has finished. @see: gl_update_duration (defined in superclass GLPane_view_change_methods) """ self._needs_repaint = True # (To restore the pre-050127 behavior, it would be sufficient to # change the next line from "self.update()" to "self.paintGL()".) self.update() # QWidget.update() method -- ask Qt to call self.paintGL() # (via some sort of paintEvent to our superclass) # very soon after the current event handler returns # ### REVIEW: why does this not call self.updateGL() like ThumbView.py does? # I tried calling self.updateGL() here, and got an exception # inside a paintGL subroutine (AttributeError on self.guides), # captured somewhere inside it by print_compact_stack, # which occurred before a print statement here just after my call. # The toplevel Python call shown in print_compact_stack was paintGL. # This means: updateGL causes an immediate call by Qt into paintGL, # in the same event handler, but from C code which stops print_compact_stack # from seeing what was outside it. (Digression: we could work around # that by grabbing the stack frame here and storing it somewhere!) # Conclusion: never call updateGL in GLPane, and review whether # ThumbView should continue to call it. [bruce 080912 comment] return def gl_update_highlight(self): #bruce 070626 """ External code should call this when it thinks the hover-highlighting in self needs redrawing (but when it doesn't need to report any other need for redrawing). This is an optimization, since if there is no other reason to redraw, the highlighting alone may be redrawn faster by using a saved color/depth image of everything except highlighting, rather than by redrawing everything else. [That optim is NIM as of 070626.] """ self.gl_update() # stub for now return def gl_update_for_glselect(self): #bruce 070626 """ External code should call this instead of gl_update when the only reason it would have called that is to make us notice self.glselect_wanted and use it to update self.selobj. [That optim is NIM as of 070626.] """ self.gl_update() # stub for now return def gl_update_confcorner(self): #bruce 070627 """ External code should call this when it thinks the confirmation corner may need redrawing (but when it doesn't need to report any other need for redrawing). This is an optimization, since if there is no other reason to redraw, the confirmation corner alone may be redrawn faster by using a saved color image of the portion of the screen it covers (not including the CC overlay itself), rather than by redrawing everything. [That optim is NIM as of 070627 and A9.1. Its OpenGL code would make use of the conf_corner_bg_image code in this class. Deciding when to do it vs full update is the harder part.] """ self.gl_update() # stub for now return # The following behavior (in several methods herein) related to wants_gl_update # should probably also be done in ThumbViews # if they want to get properly updated when graphics prefs change. [bruce 050804 guess] wants_gl_update = True #bruce 050804 # this is set to True after we redraw, and to False by wants_gl_update_was_True # used/modified in both this class and GLPane_rendering_methods # (see also _needs_repaint) def wants_gl_update_was_True(self): #bruce 050804 """ Outside code should call this if it changes what our redraw would draw, and then sees self.wants_gl_update being true, if it might not otherwise call self.gl_update (which is also ok to do, but might be slower -- whether it's actually slower is not known). This can also be used as an invalidator for passing to self.end_tracking_usage(). """ #bruce 070109 comment: it looks wrong to me that the use of this as an invalidator in end_tracking_usage # is not conditioned on self.wants_gl_update, either inside or outside this routine. I'm not sure it's really wrong, # and I didn't analyze all calls of this, nor how it might interact with self._needs_repaint. # If it's wrong, it means the intended optim (avoiding lots of Qt update calls) is not happening. #bruce 080913 comment: I doubt the intended optim matters, anyway. # REVIEW whether this should simply be scrapped in favor of just # calling gl_update instead. self.wants_gl_update = False self.gl_update() # == ## selobj = None #bruce 050609 _selobj = None #bruce 080509 made this private def __get_selobj(self): #bruce 080509 return self._selobj def __set_selobj(self, val): #bruce 080509 self.set_selobj(val) # this indirection means a subclass could override set_selobj, # or that we could revise this code to pass it an argument return selobj = property( __get_selobj, __set_selobj) #bruce 080509 bugfix for MT crosshighlight sometimes lasting too long def set_selobj(self, selobj, why = "why?"): """ Set self._selobj to selobj (might be None) and do appropriate updates. Possible updates include: - env.history.statusbar_msg( selobj.mouseover_statusbar_message(), or "" if selobj is None ) - help the model tree highlight the nodes containing selobj @note: as of 080509, all sets of self.selobj call this method, via a property. If some of them don't want all our side effects, they will need to call this method directly and pass options [nim] to prevent those. """ # note: this method should access and modify self._selobj, # not self.selobj (setting that here would cause an infinite recursion). if selobj is not self._selobj: previous_selobj = self._selobj self._selobj = selobj #bruce 080507 moved this here # Note: we don't call gl_update_highlight here, so the caller needs to # if there will be a net change of selobj. I don't know if we should call it here -- # if any callers call this twice with no net change (i.e. use this to set selobj to None # and then back to what it was), it would be bad to call it here. [bruce 070626 comment] if _DEBUG_SET_SELOBJ: # todo: make more calls pass "why" argument print_compact_stack("_DEBUG_SET_SELOBJ: %r -> %r (%s): " % (previous_selobj, selobj, why)) #bruce 050702 partly address bug 715-3 (the presently-broken Build mode statusbar messages). # Temporary fix, since Build mode's messages are better and should be restored. if selobj is not None: try: try: #bruce 050806 let selobj control this method = selobj.mouseover_statusbar_message # only defined for some objects which inherit Selobj_API except AttributeError: msg = "%s" % (selobj,) else: msg = method() except: msg = "<exception in selobj statusbar message code>" if debug_flags.atom_debug: #bruce 070203 added this print; not if 1 in case it's too verbose due as mouse moves print_compact_traceback(msg + ': ') else: print "bug: %s; use ATOM_DEBUG to see details" % msg else: msg = " " self._selobj_statusbar_msg = msg #bruce 081230 re bug 2964 if self._defer_statusbar_msg: self._deferred_msg = msg #bruce 081230 re bug 2964 else: env.history.statusbar_msg(msg) if pref_show_highlighting_in_MT(): # help the model tree highlight the nodes containing selobj # [bruce 080507 new feature] self._update_nodes_containing_selobj( selobj, # might be None, and we do need to call this then repaint_nodes = True, # this causes a side effect which is the only reason we're called here even_if_selobj_unchanged = False # optimization; # should be safe, since changes to selobj parents or node parents # which would otherwise require this to be passed as true # should also call mt_update separately, thus doing a full # MT redraw soon enough ) pass # if selobj is not self._selobj self._selobj = selobj # redundant (as of bruce 080507), but left in for now #e notify more observers? return def _update_nodes_containing_selobj(self, selobj, repaint_nodes = False, even_if_selobj_unchanged = False ): #bruce 080507 """ private; recompute self._nodes_containing_selobj from the given selobj, optimizing when selobj and/or our result has not changed, and do updates as needed and as options specify. @return: None @param repaint_nodes: if this is true and we change our cached value of self._nodes_containing_selobj, then also call the model tree method repaint_some_nodes. @param even_if_selobj_unchanged: if this is true, assume that our result might differ even if selobj itself has not changed since our last call. @note: called in two circumstances: - when we know selobj has changed (repaint_nodes should be True then) - when the MT explicitly calls get_nodes_containing_selobj (repaint_nodes should probably be False then) @note: does not use or set self._selobj (assuming external code it calls doesn't do so). @warning: if this method or code it calls sets self.selobj, that would cause infinite recursion, since self.selobj is a property whose setter calls this method. """ # review: are there MT update bugs related to dna updater moving nodes # into new groups? if selobj is self._nodes_containing_selobj_is_from_selobj and \ not even_if_selobj_unchanged: # optimization: nothing changed, no updates needed return # recompute and perhaps update nodes = [] if selobj is not None: try: method = selobj.nodes_containing_selobj except AttributeError: # should never happen, since Selobj_API defines this method print "bug: no method nodes_containing_selobj in %r" % (selobj,) pass else: try: nodes = method() assert type(nodes) == type([]) except: msg = "bug in %r.nodes_containing_selobj " \ "(or invalid return value from it)" % (selobj,) print_compact_traceback( msg + ": ") nodes = [] pass pass if self._nodes_containing_selobj != nodes: # assume no need to sort, since they'll typically be # returned in inner-to-outer order all_changed_nodes = self._nodes_containing_selobj + nodes # assume duplications are ok; # could optim by leaving out any nodes that appear # in both lists, assuming the way they're highlighted in # the MT doesn't depend on anything but their presence # in the list; doesn't matter for now, since the MT # redraw is not yet incremental [as of 080507] self._nodes_containing_selobj = nodes if repaint_nodes: ## self._nodes_containing_selobj_has_changed(all_changed_nodes) self.assy.win.mt.repaint_some_nodes( all_changed_nodes) # review: are we sure self.assy.win.mt.repaint_some_nodes will never # use self.selobj by accessing it externally? self._nodes_containing_selobj_is_from_selobj = selobj return def get_nodes_containing_selobj(self): #bruce 080507 """ @return: a list of nodes that contain self.selobj (possibly containing some nodes more than once). @warning: repeated calls with self.selobj unchanged are *not* optimized. (Doing so correctly would be difficult.) Callers should temporarily store our return value as needed. """ self._update_nodes_containing_selobj( self.selobj, repaint_nodes = False, even_if_selobj_unchanged = True ) return self._nodes_containing_selobj pass # end of class GLPane # end
NanoCAD-master
cad/src/graphics/widgets/GLPane.py
# Copyright 2004-2009 Nanorex, Inc. See LICENSE file for details. """ ThumbView.py - a simpler OpenGL widget, similar to GLPane (which unfortunately has a lot of duplicated but partly modified code copied from GLPane) @author: Huaicai @version: $Id$ @copyright: 2004-2009 Nanorex, Inc. See LICENSE file for details. """ from Numeric import dot from OpenGL.GL import GL_NORMALIZE from OpenGL.GL import glEnable from OpenGL.GL import GL_MODELVIEW from OpenGL.GL import glMatrixMode from OpenGL.GL import glLoadIdentity from OpenGL.GL import glClearColor from OpenGL.GL import GL_COLOR_BUFFER_BIT from OpenGL.GL import GL_DEPTH_BUFFER_BIT from OpenGL.GL import glClear from OpenGL.GL import GL_STENCIL_INDEX from OpenGL.GL import glReadPixelsi from OpenGL.GL import GL_DEPTH_COMPONENT from OpenGL.GL import glReadPixelsf from OpenGL.GL import glPushMatrix from OpenGL.GL import glSelectBuffer from OpenGL.GL import GL_SELECT from OpenGL.GL import glRenderMode from OpenGL.GL import glInitNames from OpenGL.GL import GL_CLIP_PLANE0 from OpenGL.GL import glClipPlane from OpenGL.GL import GL_RENDER from OpenGL.GL import glFlush from OpenGL.GL import GL_STENCIL_BUFFER_BIT from OpenGL.GL import GL_FALSE from OpenGL.GL import GL_ALWAYS from OpenGL.GL import glStencilFunc from OpenGL.GL import GL_REPLACE from OpenGL.GL import GL_TRUE from OpenGL.GL import glDepthMask from OpenGL.GL import GL_KEEP from OpenGL.GL import glStencilOp from OpenGL.GL import GL_STENCIL_TEST from OpenGL.GL import glDisable from OpenGL.GL import GL_PROJECTION from OpenGL.GL import glPopMatrix from OpenGL.GL import glDepthFunc from OpenGL.GL import GL_LEQUAL from OpenGL.GLU import gluUnProject from PyQt4.Qt import Qt from geometry.VQT import V, Q, A from graphics.drawing.drawers import drawFullWindow from graphics.drawing.gl_lighting import _default_lights from graphics.drawing.gl_lighting import setup_standard_lights from model.assembly import Assembly import foundation.env as env from utilities import debug_flags from utilities.debug import print_compact_traceback from utilities.constants import diTrueCPK from utilities.constants import gray from utilities.constants import bluesky, eveningsky, bg_seagreen, bgEVENING_SKY, bgSEAGREEN from utilities.constants import GL_FAR_Z from utilities.prefs_constants import bondpointHighlightColor_prefs_key from utilities.prefs_constants import backgroundGradient_prefs_key from utilities.prefs_constants import backgroundColor_prefs_key from foundation.Group import Group from model.chem import Atom from model.elements import Singlet from model.chunk import Chunk from operations.pastables import find_hotspot_for_pasting from graphics.widgets.GLPane_minimal import GLPane_minimal from platform_dependent.PlatformDependent import fix_event_helper class ThumbView(GLPane_minimal): """ A simple version of OpenGL widget, which can be used to show a simple thumb view of models when loading models or color changing. General rules for multiple QGLWidget uses: make sure the rendering context is current. Remember makeCurrent() will be called implicitly before any initializeGL, resizeGL, paintGL virtual functions call. Ideally, this class should coordinate with class GLPane in some ways. """ # Note: classes GLPane and ThumbView share lots of code, # which ought to be merged into their common superclass GLPane_minimal # [bruce 070914 comment; since then some of it has been merged, some # still needs to be] [I merged a bunch more now -- bruce 080912] # class constants and/or default values of instance variables [not sure which are which] SIZE_FOR_glSelectBuffer = 500 # different value from that in GLPane_minimal # [I don't know whether this matters -- bruce 071003 comment] shareWidget = None #bruce 051212 always_draw_hotspot = False #bruce 060627 _always_remake_during_movies = True #bruce 090224 # default values of subclass-specific constants permit_draw_bond_letters = False #bruce 071023, overrides superclass def __init__(self, parent, name, shareWidget): """ Constructs an instance of a Thumbview. """ useStencilBuffer = False GLPane_minimal.__init__(self, parent, shareWidget, useStencilBuffer) self.elementMode = None #@@@Add the QGLWidget to the parentwidget's grid layout. This is done #here for improving the loading speed. Needs further optimization and #a better place to put this code if possible. -- Ninad 20070827 try: parent.gridLayout.addWidget(self, 0, 0, 1, 1) except: print_compact_traceback("bug: Preview Pane's parent widget doesn't" \ " have a layout. Preview Pane not added to the layout.") pass self.picking = False self.selectedObj = None #This enables the mouse bareMotion() event self.setMouseTracking(True) # clipping planes, as percentage of distance from the eye self.near = 0.66 self.far = 2.0 # start in perspective mode self.ortho = False #True self.scale # make sure superclass set this [bruce 080219] # default color and gradient values. self.backgroundColor = env.prefs[backgroundColor_prefs_key] self.backgroundGradient = env.prefs[ backgroundGradient_prefs_key ] def drawModel(self): """ This is an abstract method for drawing self's "model". [subclasses which need to draw anything must override this method] """ pass def _drawModel_using_DrawingSets(self): #bruce 090219 """ """ def func(): self.drawModel() self._call_func_that_draws_model( func, drawing_phase = 'main' ) return def drawSelected(self, obj): """ Draw the selected object. [subclasses can override this method] """ pass def _drawSelected_using_DrawingSets(self, obj): #bruce 090219 """ """ def func(): self.drawSelected(obj) self._call_func_that_draws_model( func, drawing_phase = 'selobj', whole_model = False ) ### REVIEW: should we use _call_func_that_draws_objects instead? # That requires passing a part which contains obj, # and I don't know for sure whether there is one, or how to find it # in all cases. Guess: this is desirable, but not yet essential. # [bruce 090219 comment] return def _get_assy(self): #bruce 080220 """ Return the assy which contains all objects we are drawing (or None if this is not possible). [subclasses must override this method] """ return None def __get_assy(self): #bruce 080220 # this glue method is a necessary kluge so that the following property # for self.assy will use a subclass's overridden version of _get_assy return self._get_assy() assy = property(__get_assy) #bruce 080220, for per-assy glname dict def _setup_lighting(self): """ [private method] Set up lighting in the model. [Called from both initializeGL and paintGL.] """ # note: there is some duplicated code in this method # in GLPane_lighting_methods (has more comments) and ThumbView, # but also significant differences. Should refactor sometime. # [bruce 060415/080912 comment] glEnable(GL_NORMALIZE) glMatrixMode(GL_PROJECTION) glLoadIdentity() glMatrixMode(GL_MODELVIEW) glLoadIdentity() #bruce 060415 moved following from ThumbView.initializeGL to this split-out method... #bruce 051212 revised lighting code to share prefs and common code with GLPane # (to fix bug 1200 and mitigate bugs 475 and 1158; # fully fixing those would require updating lighting in all ThumbView widgets # whenever lighting prefs change, including making .update calls on them, # and is not planned for near future since it's easy enough to close & reopen them) try: lights = self.shareWidget._lights #bruce 060415 shareWidget --> self.shareWidget; presumably always failed before that ###@@@ will this fix some bugs about common lighting prefs?? except: lights = _default_lights setup_standard_lights( lights, self.glprefs) return def resetView(self): """ Reset the view. Subclass can override this method with different <scale>, so call this version in the overridden version. """ self.pov = V(0.0, 0.0, 0.0) self.quat = Q(1, 0, 0, 0) def setBackgroundColor(self, color, gradient): """ Set the background to 'color' or 'gradient' (Sky Blue). """ self.backgroundColor = color # Ninad and I discussed this and decided that the background should always be set to skyblue. # This issue has to do with Build mode's water surface introducing inconsistencies # with the thumbview background color whenever Build mode's bg color is solid. # Change to "if 0:" to have the thubview background match the current mode background. # This fixes bug 1229. Mark 060116 if 1: self.backgroundGradient = env.prefs[ backgroundGradient_prefs_key ] else: self.backgroundGradient = gradient def paintGL(self): """ Called by QtGL when redrawing is needed. For every redraw, color & depth butter are cleared, view projection are reset, view location & orientation are also reset. """ if not self.initialised: return self._call_whatever_waits_for_gl_context_current() #bruce 071103 glDepthFunc( GL_LEQUAL) self.setDepthRange_setup_from_debug_pref() self.setDepthRange_Normal() from utilities.debug_prefs import debug_pref, Choice_boolean_False if debug_pref("always setup_lighting?", Choice_boolean_False): #bruce 060415 added debug_pref("always setup_lighting?"), in GLPane and ThumbView [KEEP DFLTS THE SAME!!]; # see comments in GLPane_lighting_methods self._setup_lighting() #bruce 060415 added this call self.backgroundColor = env.prefs[backgroundColor_prefs_key] c = self.backgroundColor glClearColor(c[0], c[1], c[2], 0.0) del c glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) self.backgroundGradient = env.prefs[ backgroundGradient_prefs_key ] if self.backgroundGradient: glMatrixMode(GL_PROJECTION) glLoadIdentity() glMatrixMode(GL_MODELVIEW) glLoadIdentity() # Setting to blue sky (default), but might change to something else _bgGradient = bluesky if self.backgroundGradient == bgEVENING_SKY: _bgGradient = eveningsky if self.backgroundGradient == bgSEAGREEN: _bgGradient = bg_seagreen drawFullWindow(_bgGradient)# gradient color self._setup_projection() self._setup_modelview() ## glMatrixMode(GL_MODELVIEW) ## glLoadIdentity() ## glTranslatef(0.0, 0.0, - self.vdist) ## q = self.quat ## glRotatef(q.angle * 180.0 / math.pi, q.x, q.y, q.z) ## glTranslatef(self.pov[0], self.pov[1], self.pov[2]) if self.model_is_valid(): #bruce 080117 [testing this at start of paintGL to skip most of it]: # precaution (perhaps a bugfix); see similar code in GLPane. # # update, bruce 080220: this may have caused a bug by making this # not draw a blank-background graphics area when it has no model. # E.g. the partlib has no model when first entered. # Fixing this by only not drawing the model itself in that case [UNTESTED]. # (The GLPane always has a model, so has no similar issue.) # # I'm not moving the coordinate transforms into this if statement, # since I don't know if they might be depended on by non-paintGL # drawing (e.g. for highlighting, which btw is called "selection" # in some method names and comments in this file). [bruce 080220] self._drawModel_using_DrawingSets() def mousePressEvent(self, event): """ Dispatches mouse press events depending on shift and control key state. """ ## Huaicai 2/25/05. This is to fix item 2 of bug 400: make this rendering context ## as current, otherwise, the first event will get wrong coordinates self.makeCurrent() buttons, modifiers = event.buttons(), event.modifiers() #print "Button pressed: ", but if 1: #bruce 060328 kluge fix of undo part of bug 1775 (overkill, but should be ok) (part 1 of 2) import foundation.undo_manager as undo_manager main_assy = env.mainwindow().assy self.__begin_retval = undo_manager.external_begin_cmd_checkpoint(main_assy, cmdname = "(mmkit)") if buttons & Qt.LeftButton: if modifiers & Qt.ShiftModifier: pass # self.graphicsMode.leftShiftDown(event) elif modifiers & Qt.ControlModifier: pass # self.graphicsMode.leftCntlDown(event) else: self.leftDown(event) if buttons & Qt.MidButton: if modifiers & Qt.ShiftModifier: pass # self.graphicsMode.middleShiftDown(event) elif modifiers & Qt.ControlModifier: pass # self.graphicsMode.middleCntlDown(event) else: self.middleDown(event) if buttons & Qt.RightButton: if modifiers & Qt.ShiftModifier: pass # self.graphicsMode.rightShiftDown(event) elif modifiers & Qt.ControlModifier: pass # self.graphicsMode.rightCntlDown(event) else: pass # self.rightDown(event) __begin_retval = None def mouseReleaseEvent(self, event): """ Only used to detect the end of a freehand selection curve. """ buttons, modifiers = event.buttons(), event.modifiers() #print "Button released: ", but if buttons & Qt.LeftButton: if modifiers & Qt.ShiftModifier: pass # self.leftShiftUp(event) elif modifiers & Qt.ControlModifier: pass # self.leftCntlUp(event) else: self.leftUp(event) if buttons & Qt.MidButton: if modifiers & Qt.ShiftModifier: pass # self.graphicsMode.middleShiftUp(event) elif modifiers & Qt.ControlModifier: pass # self.graphicsMode.middleCntlUp(event) else: self.middleUp(event) if buttons & Qt.RightButton: if modifiers & Qt.ShiftModifier: pass # self.rightShiftUp(event) elif modifiers & Qt.ControlModifier: pass # self.rightCntlUp(event) else: pass # self.rightUp(event) if 1: #bruce 060328 kluge fix of undo part of bug 1775 (part 2 of 2) import foundation.undo_manager as undo_manager main_assy = env.mainwindow().assy undo_manager.external_end_cmd_checkpoint(main_assy, self.__begin_retval) return def mouseMoveEvent(self, event): """ Dispatches mouse motion events depending on shift and control key state. """ ##self.debug_event(event, 'mouseMoveEvent') buttons, modifiers = event.buttons(), event.modifiers() if buttons & Qt.LeftButton: if modifiers & Qt.ShiftModifier: pass # self.leftShiftDrag(event) elif modifiers & Qt.ControlModifier: pass # self.leftCntlDrag(event) else: pass # self.leftDrag(event) elif buttons & Qt.MidButton: if modifiers & Qt.ShiftModifier: pass # self.middleShiftDrag(event) elif modifiers & Qt.ControlModifier: pass # self.middleCntlDrag(event) else: self.middleDrag(event) elif buttons & Qt.RightButton: if modifiers & Qt.ShiftModifier: pass # self.rightShiftDrag(event) elif modifiers & Qt.ControlModifier: pass # self.rightCntlDrag(event) else: pass # self.rightDrag(event) else: #Huaicai: To fix bugs related to multiple rendering contexts existed in our application. # See comments in mousePressEvent() for more detail. self.makeCurrent() self.bareMotion(event) def wheelEvent(self, event): buttons, modifiers = event.buttons(), event.modifiers() # The following copies some code from basicMode.Wheel, but not yet the call of rescale_around_point, # since that is not implemented in this class; it ought to be made a method of a new common superclass # of this class and GLPane (and there are quite a few methods of GLPane about which that can be said, # some redundantly implemented here and some not). # [bruce 060829 comment] # # update [bruce 070402 comment]: # sharing that code would now be a bit more complicated (but is still desirable), # since GLPane.rescale_around_point is now best called by basicMode.rescale_around_point_re_user_prefs. # The real lesson is that even ThumbViews ought to use some kind of "graphicsMode" (like full-fledged modes, # even if some aspects of them would not be used), to handle mouse bindings. But this is likely to be # nontrivial since full-fledged modes might have extra behavior that's inappropriate but hard to # turn off. So if we decide to make ThumbView zoom compatible with that of the main graphics area, # the easiest quick way is just to copy and modify rescale_around_point_re_user_prefs and basicMode.Wheel # into this class. dScale = 1.0/1200.0 if modifiers & Qt.ShiftModifier: dScale *= 0.5 if modifiers & Qt.ControlModifier: dScale *= 2.0 self.scale *= 1.0 + dScale * event.delta() ### BUG: The scale variable needs to set a limit; otherwise, it will # set self.near = self.far = 0.0 because of machine precision, # which will cause OpenGL Error. [Huaicai 10/18/04] # NOTE: this bug may have been fixed in other defs of wheelEvent. # TODO: review, and fix it here too (or, better, use common code). # See also the longer comment above in this method. # [bruce 080917 addendum] self.updateGL() return def bareMotion(self, event): wX = event.pos().x() wY = self.height - event.pos().y() if self.selectedObj is not None: stencilbit = glReadPixelsi(wX, wY, 1, 1, GL_STENCIL_INDEX)[0][0] if stencilbit: # If it's the same highlighting object, no display change needed. return self.updateGL() self.selectedObj = self.select(wX, wY) self.highlightSelected(self.selectedObj) return False # russ 080527 def leftDown(self, event): pass def leftUp(self, event): pass def middleDown(self, event): pos = event.pos() self.trackball.start(pos.x(), pos.y()) self.picking = True return def middleDrag(self, event): if self.picking: pos = event.pos() q = self.trackball.update(pos.x(), pos.y()) self.quat += q self.updateGL() return def middleUp(self, event): self.picking = False return def select(self, wX, wY): """ Use the OpenGL picking/selection to select any object. Return the selected object, otherwise, return None. Restore projection and modelview matrices before returning. """ ### NOTE: this code is similar to (and was copied and modified from) # GLPane_highlighting_methods.do_glselect_if_wanted, but also differs # in significant ways (too much to make it worth merging, unless we # decide to merge the differing algorithms as well). It's one of # several instances of hit-test code that calls glRenderMode. # [bruce 060721/080917 comment] wZ = glReadPixelsf(wX, wY, 1, 1, GL_DEPTH_COMPONENT) gz = wZ[0][0] if gz >= GL_FAR_Z: # Empty space was clicked return None pxyz = A(gluUnProject(wX, wY, gz)) pn = self.out pxyz -= 0.0002 * pn # Note: if this runs before the model is drawn, this can have an # exception "OverflowError: math range error", presumably because # appropriate state for gluUnProject was not set up. That doesn't # normally happen but can happen due to bugs (no known open bugs # of that kind). # Sometimes our drawing area can become "stuck at gray", # and when that happens, the same exception can occur from this line. # Could it be that too many accidental mousewheel scrolls occurred # and made the scale unreasonable? (To mitigate, we should prevent # those from doing anything unless we have a valid model, and also # reset that scale when loading a new model (latter is probably # already done, but I didn't check). See also the comments # in def wheelEvent.) [bruce 080220 comment] dp = - dot(pxyz, pn) # Save projection matrix before it's changed. glMatrixMode(GL_PROJECTION) glPushMatrix() current_glselect = (wX, wY, 1, 1) self._setup_projection(glselect = current_glselect) glSelectBuffer(self.SIZE_FOR_glSelectBuffer) glRenderMode(GL_SELECT) glInitNames() glMatrixMode(GL_MODELVIEW) # Save model view matrix before it's changed. glPushMatrix() # Draw model using glRenderMode(GL_SELECT) as set up above try: glClipPlane(GL_CLIP_PLANE0, (pn[0], pn[1], pn[2], dp)) glEnable(GL_CLIP_PLANE0) self._drawModel_using_DrawingSets() except: #bruce 080917 fixed predicted bugs in this except clause (untested) print_compact_traceback("exception in ThumbView._drawModel_using_DrawingSets() during GL_SELECT; ignored; restoring matrices: ") glDisable(GL_CLIP_PLANE0) glMatrixMode(GL_PROJECTION) glPopMatrix() glMatrixMode(GL_MODELVIEW) glPopMatrix() glRenderMode(GL_RENDER) return None else: glDisable(GL_CLIP_PLANE0) # Restore model/view matrix glPopMatrix() # Restore projection matrix and set matrix mode to Model/View glMatrixMode(GL_PROJECTION) glPopMatrix() glMatrixMode(GL_MODELVIEW) glFlush() hit_records = list(glRenderMode(GL_RENDER)) ## print "%d hits" % len(hit_records) for (near, far, names) in hit_records: ## print "hit record: near, far, names:", near, far, names # note from testing: near/far are too far apart to give actual depth, # in spite of the 1-pixel drawing window (presumably they're vertices # taken from unclipped primitives, not clipped ones). ### REVIEW: this just returns the first candidate object found. # The clip plane may restrict the set of candidates well enough to # make sure that's the right one, but this is untested and unreviewed. # (And it's just my guess that that was Huaicai's intention in # setting up clipping, since it's not documented. I'm guessing that # the plane is just behind the hitpoint, but haven't confirmed this.) # [bruce 080917 comment] if names: name = names[-1] assy = self.assy obj = assy and assy.object_for_glselect_name(name) #k should always return an obj return obj return None # from ThumbView.select def highlightSelected(self, obj): # TODO: merge with GLPane (from which this was copied and modified) """ Highlight the selected object <obj>. In the mean time, we do stencil test to update stencil buffer, so it can be used to quickly test if pick is still on the same <obj> as last test. """ if not obj: return if not isinstance(obj, Atom) or (obj.element is not Singlet): return self._preHighlight() self._drawSelected_using_DrawingSets(obj) self._endHighlight() glFlush() self.swapBuffers() return def _preHighlight(self): ### TODO: rename; move into GLPane_minimal, use in GLPane.py """ Change OpenGL settings to prepare for highlighting. """ self.makeCurrent() glClear(GL_STENCIL_BUFFER_BIT) glDepthMask(GL_FALSE) # turn off depth writing (but not depth test) ## glDisable(GL_DEPTH_TEST) glStencilFunc(GL_ALWAYS, 1, 1) glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE) glEnable(GL_STENCIL_TEST) self.setDepthRange_Highlighting() glMatrixMode(GL_MODELVIEW) return def _endHighlight(self): """ Restore OpenGL settings changed by _preHighlight to standard values. """ glDepthMask(GL_TRUE) ## glEnable(GL_DEPTH_TEST) glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP) glDisable(GL_STENCIL_TEST) self.setDepthRange_Normal() glMatrixMode(GL_MODELVIEW) return def saveLastView(self): #bruce 060627 for compatibility with GLPane (for sake of assy.update_parts) pass def forget_part(self, part): #bruce 060627 for compatibility with GLPane (for sake of chunk.kill) pass pass # end of class ThumbView # == class ElementView(ThumbView): """ Element graphical display class. """ # note: as of 080403 this is only used by elementColors.py and elementSelector.py def __init__(self, parent, name, shareWidget = None): ThumbView.__init__(self, parent, name, shareWidget) self.scale = 2.0 #5.0 ## the possible largest rvdw of all elements self.pos = V(0.0, 0.0, 0.0) self.mol = None ## Dummy attributes. A kludge, just try to make other code ## think it looks like a glpane object. self.displayMode = 0 self.selatom = None def resetView(self, scale = 2.0): """ Reset current view. """ ThumbView.resetView(self) self.scale = scale def drawModel(self): """ The method for element drawing. """ if self.mol: self.mol.draw(self, None) def model_is_valid(self): #bruce 080117 """ whether our model is currently valid for drawing [overrides GLPane_minimal method] """ return self.mol and self.mol.assy.assy_valid def _get_assy(self): """ [overrides ThumbView method] """ return self.mol and self.mol.assy def refreshDisplay(self, elm, dispMode = diTrueCPK): """ Display the new element or the same element but new display mode. """ self.makeCurrent() self.mol = self.constructModel(elm, self.pos, dispMode) self.updateGL() def updateColorDisplay(self, elm, dispMode = diTrueCPK): """ Display the new element or the same element but new display mode. """ self.makeCurrent() self.mol = self.constructModel(elm, self.pos, dispMode) self.updateGL() def constructModel(self, elm, pos, dispMode): """ This is to try to repeat what 'make_Atom_and_bondpoints()' method does, but hope to remove some stuff not needed here. The main purpose is to build the geometry model for element display. @param elm: An object of class Elem @param elm: L{Elem} @param dispMode: the display mode of the atom @type dispMode: int @return: the Chunk which contains the geometry model. @rtype: L{Chunk} """ assy = Assembly(None, run_updaters = False) assy.set_glpane(self) # sets .o and .glpane mol = Chunk(assy, 'dummy') atm = Atom(elm.symbol, pos, mol) atm.display = dispMode ## bruce 050510 comment: this is approximately how you should change the atom type (e.g. to sp2) for this new atom: ## atm.set_atomtype_but_dont_revise_singlets('sp2') ## see also atm.element.atomtypes -> a list of available atomtype objects for that element ## (which can be passed to set_atomtype_but_dont_revise_singlets) atm.make_bondpoints_when_no_bonds() return mol def drawSelected(self, obj): """ Override the parent version. Specific drawing code for the object. """ if isinstance(obj, Atom) and (obj.element is Singlet): obj.draw_in_abs_coords(self, env.prefs[bondpointHighlightColor_prefs_key]) pass # end of class ElementView class MMKitView(ThumbView): """ Currently used as the GLWidget for the graphical display and manipulation for element/clipboard/part. Initial attempt was to subclass this for each of above type models, but find trouble to dynamically change the GLWidget when changing tab page. """ # note: as of 080403 this is constructed only by PM_PreviewGroupBox.py # and required (assert isinstance(self.elementViewer, MMKitView)) by # PM_Clipboard.py, PM_MolecularModelingKit.py, and PM_PartLib.py. # I think that means it is used for MMKit atoms, PasteFromClipboard_Command clipboard, # and PartLib parts. [bruce 080403 comment] always_draw_hotspot = True #bruce 060627 to help with bug 2028 # (replaces a horribe kluge in old code which broke a fix to that bug) def __init__(self, parent, name, shareWidget = None): ThumbView.__init__(self, parent, name, shareWidget) self.scale = 2.0 self.pos = V(0.0, 0.0, 0.0) self.model = None ## Dummy attributes. A kludge, just try to make other code ## think it looks like a glpane object. self.displayMode = 0 self.selatom = None self.hotspotAtom = None #The current hotspot singlet for the part self.lastHotspotChunk = None # The previous chunk of the hotspot for the part hybrid_type_name = None elementMode = True #Used to differentiate elment page versus clipboard/part page def drawModel(self): """ The method for element drawing. """ if self.model: if isinstance(self.model, Chunk) or \ isinstance(self.model, Group): self.model.draw(self, None) else: ## Assembly self.model.draw(self) return def model_is_valid(self): #bruce 080117, revised 080220, 080913 """ whether our model is currently valid for drawing [overrides GLPane_minimal method] """ return self.assy and self.assy.assy_valid def _get_assy(self): #bruce 080220 """ [overrides ThumbView method] """ if self.model: if isinstance(self.model, Chunk) or \ isinstance(self.model, Group): assy = self.model.assy # Note: assy can be None, if the dna updater kills a bare Ax, # since its chunk is then killed and its .assy set to None. # But the following is too verbose to be useful; also it # seemingly happens even for Ss3 (why??). # Todo: check if it's due to Ax (ok to not print it here) # or to something we didn't expect (needs print so as not # to risk hiding other bugs). ## if res is None: ## print "dna updater fyi: in model_is_valid: " \ ## "%r.model %r has .assy None" % \ ## (self, self.model) return assy else: ## self.model is an Assembly return self.model return None def refreshDisplay(self, elm, dispMode = diTrueCPK): """ Display the new element or the same element but new display mode. """ self.makeCurrent() self.model = self.constructModel(elm, self.pos, dispMode) self.updateGL() def changeHybridType(self, name): self.hybrid_type_name = name def resetView(self): """ Reset current view. """ ThumbView.resetView(self) self.scale = 2.0 def drawSelected(self, obj): """ Override the parent version. Specific drawing code for the object. """ if isinstance(obj, Atom) and (obj.element is Singlet): obj.draw_in_abs_coords(self, env.prefs[bondpointHighlightColor_prefs_key]) return def constructModel(self, elm, pos, dispMode): """ This is to try to repeat what 'make_Atom_and_bondpoints()' method does, but hope to remove some stuff not needed here. The main purpose is to build the geometry model for element display. @param elm: An object of class Elem @param elm: L{Elem} @param dispMode: the display mode of the atom @type dispMode: int @return: the Chunk which contains the geometry model. @rtype: L{Chunk} """ assy = Assembly(None, run_updaters = False) assy.set_glpane(self) # sets .o and .glpane mol = Chunk(assy, 'dummy') atm = Atom(elm.symbol, pos, mol) atm.display = dispMode ## bruce 050510 comment: this is approximately how you should change the atom type (e.g. to sp2) for this new atom: if self.hybrid_type_name: atm.set_atomtype_but_dont_revise_singlets(self.hybrid_type_name) ## see also atm.element.atomtypes -> a list of available atomtype objects for that element ## (which can be passed to set_atomtype_but_dont_revise_singlets) atm.make_bondpoints_when_no_bonds() self.elementMode = True return mol def leftDown(self, event): """ When in clipboard mode, set hotspot if a Singlet is highlighted. """ if self.elementMode: return obj = self.selectedObj if isinstance(obj, Atom) and (obj.element is Singlet): mol = obj.molecule if not mol is self.lastHotspotChunk: if self.lastHotspotChunk: # Unset previous hotspot [bruce 060629 fix bug 1974 -- only if in same part] if mol.part is self.lastHotspotChunk.part and mol.part is not None: # Old and new hotspot chunks are in same part. Unset old hotspot, # so as to encourage there to be only one per Part. # This should happen when you try to make more than one hotspot in one # library part or clipboard item, using the MMKit to make both. # It might make more sense for more general code in Part to prevent # more than one hotspot per part... but we have never decided whether # that would be a good feature. (I have long suspected that hotspots # should be replaced by some sort of jig, to give more control....) # I don't know if this case can ever happen as of now, since multichunk # clipboard items aren't shown in MMKit -- whether it can happen now # depends on whether any multichunk library parts have bondpoints on # more than one chunk. [bruce 060629] if env.debug() and self.lastHotspotChunk.hotspot: #bruce 060629 re bug 1974 print "debug: unsetting hotspot of %r (was %r)" % \ (self.lastHotspotChunk, self.lastHotspotChunk.hotspot) self.lastHotspotChunk.set_hotspot(None) else: # Don't unset hotspot in this case (doing so was causing bug 1974). if env.debug() and self.lastHotspotChunk.hotspot: print "debug: NOT unsetting hotspot of %r" % (self.lastHotspotChunk, ) pass self.lastHotspotChunk = mol # [as of 060629, the only purpose of this is to permit the above code to unset it in some cases] mol.set_hotspot(obj) if 1: #bruce 060328 fix gl_update part of bug 1775 (the code looks like that was a bug forever, don't know for sure) main_glpane = env.mainwindow().glpane if mol.part is main_glpane.part: main_glpane.gl_update() self.hotspotAtom = obj self.updateGL() return def gl_update(self): #bruce 070502 bugfix (can be called when ESPImage jigs appear in a partlib part) self.updateGL() #k guess at correct/safe thing to do return def gl_update_highlight(self): #bruce 070626 precaution (not sure if any code will call this) self.gl_update() return def gl_update_for_glselect(self): #bruce 070626 precaution (not sure if any code will call this) self.gl_update() return def updateModel(self, newObj): """ Set new chunk or Assembly for display. """ self.model = newObj #Reset hotspot related stuff for a new Assembly if isinstance(newObj, Assembly): self._find_and_set_hotSpotAtom_in_new_model(newObj) self._fitInWindow() self.elementMode = False self.updateGL() def _find_and_set_hotSpotAtom_in_new_model(self, newModel): """ If the model being viewed in the thumbView window already has a hotspot, set it as self.hotSpotAtom (which then will be used by client code) @see: self.updateModel @Note that , in self.leftDown, we can actually temporarily change the the hotspot for the partlib model. But then if you view another part and go back to this model, the hotspot will be reset to the one that already exists in the model (or None if one doesn't exist) """ assert isinstance(newModel, Assembly) chunkList = [] def func(node): if isinstance(node, Chunk): chunkList.append(node) newModel.part.topnode.apply2all(func) ok = False if len(chunkList) == 1: ok, hotspot_or_whynot = find_hotspot_for_pasting(chunkList[0]) elif len(chunkList) > 1: for chunk in chunkList: ok, hotspot_or_whynot = find_hotspot_for_pasting(chunk) if ok: break if ok: self.hotspotAtom = hotspot_or_whynot self.lastHotspotChunk = self.hotspotAtom.molecule else: self.hotspotAtom = None self.lastHotspotChunk = None return def setDisplay(self, disp): self.displayMode = disp return def _fitInWindow(self): if not self.model: return self.quat = Q(1, 0, 0, 0) if isinstance(self.model, Chunk): self.model._recompute_bbox() bbox = self.model.bbox else: ## Assembly part = self.model.part bbox = part.bbox self.scale = bbox.scale() # guess: the following is a KLUGE for width and height # being the names of Qt superclass methods # but also being assigned to ints by our own code. # I don't know why it could ever be needed, since resizeGL # sets them -- maybe this can be called before that ever is?? # [bruce 080912 comment] if isinstance(self.width, int): width = self.width else: width = float(self.width()) if isinstance(self.height, int): height = self.height else: height = float(self.height()) aspect = width / height # REVIEW: likely bug: integer division is possible [bruce 080912 comment] ##aspect = float(self.width) / self.height if aspect < 1.0: self.scale /= aspect center = bbox.center() self.pov = V(-center[0], -center[1], -center[2]) pass # end of class MMKitView # end
NanoCAD-master
cad/src/graphics/widgets/ThumbView.py
# Copyright 2004-2009 Nanorex, Inc. See LICENSE file for details. """ GLPane_highlighting_methods.py - highlight drawing and hit-detection @author: Bruce @version: $Id$ @copyright: 2004-2009 Nanorex, Inc. See LICENSE file for details. bruce 080915 split this out of class GLPane_rendering_methods Russ added some shader-related code. """ from OpenGL.GL import GL_ALWAYS from OpenGL.GL import GL_DEPTH_BUFFER_BIT from OpenGL.GL import GL_DEPTH_COMPONENT from OpenGL.GL import GL_DEPTH_FUNC from OpenGL.GL import GL_DEPTH_TEST from OpenGL.GL import GL_EQUAL from OpenGL.GL import GL_FALSE from OpenGL.GL import GL_KEEP from OpenGL.GL import GL_MODELVIEW from OpenGL.GL import GL_RENDER from OpenGL.GL import GL_REPLACE from OpenGL.GL import GL_RGBA from OpenGL.GL import GL_SELECT from OpenGL.GL import GL_STENCIL_TEST from OpenGL.GL import GL_TRUE from OpenGL.GL import GL_UNSIGNED_BYTE from OpenGL.GL import GL_VIEWPORT from OpenGL.GL import glClear from OpenGL.GL import glColorMask from OpenGL.GL import glDepthMask from OpenGL.GL import glDepthFunc from OpenGL.GL import glDisable from OpenGL.GL import glDrawPixels from OpenGL.GL import glEnable from OpenGL.GL import glFinish from OpenGL.GL import glFlush from OpenGL.GL import glGetInteger from OpenGL.GL import glGetIntegerv from OpenGL.GL import glInitNames from OpenGL.GL import glMatrixMode from OpenGL.GL import glWindowPos3i from OpenGL.GL import glReadPixels from OpenGL.GL import glReadPixelsf from OpenGL.GL import glRenderMode from OpenGL.GL import glSelectBuffer from OpenGL.GL import glStencilFunc from OpenGL.GL import glStencilOp from OpenGL.GL import glViewport from utilities import debug_flags from utilities.debug import print_compact_traceback import foundation.env as env from utilities.constants import white, orange from utilities.debug_prefs import debug_pref from utilities.debug_prefs import Choice_boolean_False # suspicious imports [should not really be needed, according to bruce 070919] from model.bonds import Bond # used only for selobj ordering # == class GLPane_highlighting_methods(object): """ private mixin for providing highlighting/hit-test methods to class GLPane (mostly or entirely called from its other mixin GLPane_rendering_methods, rather than directly from methods defined in class GLPane) """ # default values for instance variables related to glSelectBuffer feature # (note, SIZE_FOR_glSelectBuffer is also part of this set, but is # defined in GLPane_minimal.py) glselect_wanted = 0 # whether the next paintGL should start with a glSelectBuffer call current_glselect = False # False, or a 4-tuple of parameters for GL_SELECT rendering ### TODO: document this better # note: self.glselect_dict is defined and initialized in # GLPane_rendering_methods, since it's also used there, # as well as in methods defined here and called there. def do_glselect_if_wanted(self): #bruce 070919 split this out """ Do the glRenderMode(GL_SELECT) drawing, and/or the glname-color drawing for shader primitives, used to guess which object might be under the mouse, for one drawing frame, if desired for this frame. Report results by storing candidate mouseover objects in self.glselect_dict. The depth buffer is initially clear, and must be clear when we're done as well. @note: does not do related individual object depth/stencil buffer drawing -- caller must do that on some or all of the objects we store into self.glselect_dict. """ if self.glselect_wanted: # note: this will be reset below. ###@@@ WARNING: The original code for this, here in GLPane, has been duplicated and slightly modified # in at least three other places (search for glRenderMode to find them). This is bad; common code # should be used. Furthermore, I suspect it's sometimes needlessly called more than once per frame; # that should be fixed too. [bruce 060721 comment] wX, wY, self.targetdepth = self.glselect_wanted # wX, wY is the point to do the hit-test at # targetdepth is the depth buffer value to look for at that point, during ordinary drawing phase # (could also be used to set up clipping planes to further restrict hit-test, but this isn't yet done) # (Warning: targetdepth could in theory be out of date, if more events come between bareMotion # and the one caused by its gl_update, whose paintGL is what's running now, and if those events # move what's drawn. Maybe that could happen with mousewheel events or (someday) with keypresses # having a graphical effect. Ideally we'd count intentional redraws, and disable this picking in that case.) self.wX, self.wY = wX, wY self.glselect_wanted = 0 pwSize = 1 # Pick window size. Russ 081128: Was 3. # Bruce: Replace 3, 3 with 1, 1? 5, 5? not sure whether this will # matter... in principle should have no effect except speed. # Russ: For glname rendering, 1x1 is better because it doesn't # have window boundary issues. We get the coords of a single # pixel in the window for the mouse position. #bruce 050615 for use by nodes which want to set up their own projection matrix. self.current_glselect = (wX, wY, pwSize, pwSize) self._setup_projection( glselect = self.current_glselect ) # option makes it use gluPickMatrix # Russ 081209: Added. debugPicking = debug_pref("GLPane: debug mouseover picking?", Choice_boolean_False, prefs_key = True ) if self.enabled_shaders(): # TODO: optimization: find an appropriate place to call # _compute_frustum_planes. [bruce 090105 comment] # Russ 081122: There seems to be no way to access the GL name # stack in shaders. Instead, for mouseover, draw shader # primitives with glnames as colors in glRenderMode(GL_RENDER), # then read back the pixel color (glname) and depth value. # Temporarily replace the full-size viewport with a little one # at the mouse location, matching the pick matrix location. # Otherwise, we will draw a closeup of that area into the whole # window, rather than a few pixels. (This wasn't needed when we # only used GL_SELECT rendering mode here, because that doesn't # modify the frame buffer -- it just returns hits by graphics # primitives when they are inside the clipping boundaries.) # # (Don't set the viewport *before* _setup_projection(), since # that method needs to read the current whole-window viewport # to set up glselect. See explanation in its docstring.) savedViewport = glGetIntegerv(GL_VIEWPORT) glViewport(wX, wY, pwSize, pwSize) # Same as current_glselect. # First, clear the pixel RGBA to zeros and a depth of 1.0 (far), # so we won't confuse a color with a glname if there are # no shader primitives drawn over this pixel. saveDepthFunc = glGetInteger(GL_DEPTH_FUNC) glDepthFunc(GL_ALWAYS) glWindowPos3i(wX, wY, 1) # Note the Z coord. gl_format, gl_type = GL_RGBA, GL_UNSIGNED_BYTE glDrawPixels(pwSize, pwSize, gl_format, gl_type, (0, 0, 0, 0)) glDepthFunc(saveDepthFunc) # needed, though we'll change it again # We must be in glRenderMode(GL_RENDER) (as usual) when this is called. # Note: _setup_projection leaves the matrix mode as GL_PROJECTION. glMatrixMode(GL_MODELVIEW) shaders = self.enabled_shaders() try: # Set flags so that we will use glnames-as-color mode # in shaders, and draw only shader primitives. # (Ideally we would also draw all non-shader primitives # as some other color, unequal to all glname colors # (or derived from a fake glname for that purpose), # in order to obscure shader primitives where appropriate. # This is intended to be done but is not yet implemented. # [bruce 090105 addendum]) for shader in shaders: shader.setPicking(True) self.set_drawing_phase("glselect_glname_color") for stereo_image in self.stereo_images_to_draw: self._enable_stereo(stereo_image) try: self._do_graphicsMode_Draw(for_mouseover_highlighting = True) # note: we can't disable depth writing here, # since we need it to make sure the correct # shader object comes out on top, or is # obscured by a DL object. Instead, we'll # clear the depth buffer again (at this pixel) # below. [bruce 090105] finally: self._disable_stereo() except: print_compact_traceback( "exception in or around _do_graphicsMode_Draw() during glname_color;" "drawing ignored; restoring modelview matrix: ") # REVIEW: what does "drawing ignored" mean, in that message? [bruce 090105 question] glMatrixMode(GL_MODELVIEW) self._setup_modelview( ) ### REVIEW: correctness of this is unreviewed! # now it's important to continue, at least enough to restore other gl state pass for shader in shaders: shader.setPicking(False) self.set_drawing_phase('?') # Restore the viewport. glViewport(savedViewport[0], savedViewport[1], savedViewport[2], savedViewport[3]) # Read pixel value from the back buffer and re-assemble glname. glFinish() # Make sure the drawing has completed. # REVIEW: is this glFinish needed? [bruce 090105 comment] rgba = glReadPixels( wX, wY, 1, 1, gl_format, gl_type )[0][0] pixZ = glReadPixelsf( wX, wY, 1, 1, GL_DEPTH_COMPONENT)[0][0] # Clear our depth pixel to 1.0 (far), so we won't mess up the # subsequent call of preDraw_glselect_dict. # (The following is not the most direct way, but it ought to work. # Note that we also clear the color pixel, since (being a glname) # it has no purpose remaining in the color buffer -- either it's # changed later, or, if not, that's a bug, but we'd rather have # it black than a random color.) [bruce 090105 bugfix] glDepthFunc(GL_ALWAYS) glWindowPos3i(wX, wY, 1) # Note the Z coord. glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE) gl_format, gl_type = GL_RGBA, GL_UNSIGNED_BYTE glDrawPixels(pwSize, pwSize, gl_format, gl_type, (0, 0, 0, 0)) glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE) glDepthFunc(saveDepthFunc) # Comes back sign-wrapped, in spite of specifying UNSIGNED_BYTE. def us(b): if b < 0: return 256 + b return b bytes = tuple([us(b) for b in rgba]) ##glname = (bytes[0] << 24 | bytes[1] << 16 | bytes[2] << 8 | bytes[3]) ## Temp fix: Ignore the last byte, which always comes back 255 on Windows. glname = (bytes[0] << 16 | bytes[1] << 8 | bytes[2]) if debugPicking: print ("shader mouseover xy %d %d, " % (wX, wY) + "rgba bytes (0x%x, 0x%x, 0x%x, 0x%x), " % bytes + "Z %f, glname 0x%x" % (pixZ, glname)) pass ### XXX This ought to be better-merged with the DL selection below. if glname: obj = self.object_for_glselect_name(glname) if debugPicking: print "shader mouseover glname=%r, obj=%r." % (glname, obj) if obj is None: # REVIEW: does this happen for mouse over a non-shader primitive? # [bruce 090105 question] #### Note: this bug is common. Guess: we are still drawing # ordinary colors for some primitives and/or for the # background, and they are showing up here and confusing # us. To help debug this, print the color too. But testing # shows it's not so simple -- e.g. for rung bonds it happens # where shader sphere and cylinder overlap, but not on either # one alone; for strand bonds it also happens on the bonds alone # (tested in Build DNA, in or not in Insert DNA). # [bruce 090218] # # Update: Since it's so common, I need to turn it off by default. # Q: is the situation safe? # A: if a color looks like a real glname by accident, # we'll get some random candidate object -- perhaps a killed one # or from a different Part or even a closed assy -- # and try to draw it. That doesn't sound very safe. Unfortunately # there is no perfect way to filter selobjs for safety, in the # current still-informal Selobj_API. The best approximation is # selobj_still_ok, and it should always say yes for the usual kinds, # so I'll add it as a check in the 'else' clause below. # [bruce 090311] if debug_flags.atom_debug: print "bug: object_for_glselect_name returns None for glname %r (color %r)" % (glname, bytes) else: if self.graphicsMode.selobj_still_ok(obj): #bruce 090311 added condition, explained above self.glselect_dict[id(obj)] = obj else: # This should be rare but possible. Leave it on briefly and see # if it's ever common. If possible, gate it by atom_debug before # the release. [bruce 090311] print "fyi: glname-color selobj %r rejected since not selobj_still_ok" % obj pass pass pass if self._use_frustum_culling: self._compute_frustum_planes() # piotr 080331 - the frustum planes have to be setup after the # projection matrix is setup. I'm not sure if there may # be any side effects - see the comment below about # possible optimization. glSelectBuffer(self.SIZE_FOR_glSelectBuffer) # Note: this allocates a new select buffer, # and glRenderMode(GL_RENDER) returns it and forgets it, # so it's required before *each* call of glRenderMode(GL_SELECT) + # glRenderMode(GL_RENDER), not just once to set the size. # Ref: http://pyopengl.sourceforge.net/documentation/opengl_diffs.html # [bruce 080923 comment] glInitNames() # REVIEW: should we also set up a clipping plane just behind the # hit point, as (I think) is done in ThumbView, to reduce the # number of candidate objects? This might be a significant # optimization, though I don't think it eliminates the chance # of having multiple candidates. [bruce 080917 comment] glRenderMode(GL_SELECT) glMatrixMode(GL_MODELVIEW) try: self.set_drawing_phase('glselect') #bruce 070124 for stereo_image in self.stereo_images_to_draw: self._enable_stereo(stereo_image) try: self._do_graphicsMode_Draw(for_mouseover_highlighting = True) finally: self._disable_stereo() except: print_compact_traceback("exception in or around _do_graphicsMode_Draw() during GL_SELECT; " "ignored; restoring modelview matrix: ") glMatrixMode(GL_MODELVIEW) self._setup_modelview( ) ### REVIEW: correctness of this is unreviewed! # now it's important to continue, at least enough to restore other gl state self._frustum_planes_available = False # piotr 080331 # just to be safe and not use the frustum planes computed for # the pick matrix self.set_drawing_phase('?') self.current_glselect = False # REVIEW: On systems with no stencil buffer, I think we'd also need # to draw selobj here in highlighted form (in case that form is # bigger than when it's not highlighted), or (easier & faster) # just always pretend it passes the hit test and add it to # glselect_dict -- and, make sure to give it "first dibs" for being # the next selobj. I'll implement some of this now (untested when # no stencil buffer) but not yet all. [bruce 050612] selobj = self.selobj if selobj is not None: self.glselect_dict[id(selobj)] = selobj # (review: is the following note correct?) # note: unneeded, if the func that looks at this dict always # tries selobj first (except for a kluge near # "if self.glselect_dict", commented on below) glFlush() hit_records = list(glRenderMode(GL_RENDER)) if debugPicking: print "DLs %d hits" % len(hit_records) for (near, far, names) in hit_records: # see example code, renderpass.py ## print "hit record: near, far, names:", near, far, names # e.g. hit record: near, far, names: 1439181696 1453030144 (1638426L,) # which proves that near/far are too far apart to give actual depth, # in spite of the 1- or 3-pixel drawing window (presumably they're vertices # taken from unclipped primitives, not clipped ones). del near, far if 1: # partial workaround for bug 1527. This can be removed once that bug (in drawer.py) # is properly fixed. This exists in two places -- GLPane.py and modes.py. [bruce 060217] if names and names[-1] == 0: print "%d(g) partial workaround for bug 1527: removing 0 from end of namestack:" % env.redraw_counter, names names = names[:-1] if names: # For now, we only use the last element of names, # though (as of long before 080917) it is often longer: # - some code pushes the same name twice (directly and # via ColorSorter) (see 060725 debug print below); # - chunks push a name even when they draw atoms/bonds # which push their own names (see 080411 comment below). # # Someday: if we ever support "name/subname paths" we'll # probably let first name interpret the remaining ones. # In fact, if nodes change projection or viewport for # their kids, and/or share their kids, they'd need to # push their own names on the stack, so we'd know how # to redraw the kids, or which ones are meant when they # are shared. if debug_flags.atom_debug and len(names) > 1: # bruce 060725 if len(names) == 2 and names[0] == names[1]: if not env.seen_before("dual-names bug"): # this happens for Atoms (colorsorter bug??) print "debug (once-per-session message): why are some glnames duplicated on the namestack?", names else: # Note: as of sometime before 080411, this became common -- # I guess that chunks (which recently acquired glselect names) # are pushing their names even while drawing their atoms and bonds. # I am not sure if this can cause any problems -- almost surely not # directly, but maybe the nestedness of highlighted appearances could # violate some assumptions made by the highlight code... anyway, # to reduce verbosity I need to not print this when the deeper name # is that of a chunk, and there are exactly two names. [bruce 080411] if len(names) == 2 and \ isinstance( self.object_for_glselect_name(names[0]), self.assy.Chunk ): if not env.seen_before("nested names for Chunk"): print "debug (once-per-session message): nested glnames for a Chunk: ", names else: print "debug fyi: len(names) == %d (names = %r)" % (len(names), names) obj = self.object_for_glselect_name(names[-1]) #k should always return an obj if obj is None: print "bug: object_for_glselect_name returns None for name %r at end of namestack %r" % (names[-1], names) else: self.glselect_dict[id(obj)] = obj # note: outside of this method, one of these will be # chosen to be saved as self.selobj and rerendered # in "highlighted" form ##if 0: ## # this debug print was useful for debugging bug 2945, ## # and when it happens it's usually a bug, ## # but not always: ## # - it's predicted to happen for ChunkDrawer._renderOverlayText ## # - and whenever we're using a whole-chunk display style ## # so we can't leave it in permanently. [bruce 081211] ## if isinstance( obj, self.assy.Chunk ): ## print "\n*** namestack topped with a chunk:", obj pass continue # next hit_record #e maybe we should now sort glselect_dict by "hit priority" # (for depth-tiebreaking), or at least put selobj first. # (or this could be done lower down, where it's used.) # [I think we do this now...] return # from do_glselect_if_wanted def object_for_glselect_name(self, glname): #bruce 080220 """ """ return self.assy.object_for_glselect_name(glname) def alloc_my_glselect_name(self, obj): #bruce 080917 """ """ return self.assy.alloc_my_glselect_name(obj) def _draw_highlighted_selobj(self, selobj, hicolor): #bruce 070920 split this out; 090311 renamed it """ Draw selobj in highlighted form, using its "selobj drawing interface" (not yet a formal interface; we use several methods including draw_in_abs_coords). Record the drawn pixels in the OpenGL stencil buffer to optimize future detection of the mouse remaining over the same selobj (to avoid redraws then). Assume we have standard modelview and projection matrices on entry, and restore that state on exit (copying or recreating it as we prefer). Note: Current implementation uses an extra level on the projection matrix stack by default (selobj can override this). This could be easily revised if desired. """ # draw the selobj as highlighted, and make provisions for fast test # (by external code) of mouse still being over it (using stencil buffer) # note: if selobj highlight is partly translucent or transparent (neither yet supported), # we might need to draw it depth-sorted with other translucent objects # (now drawn by some modes using Draw_after_highlighting, not depth-sorted or modularly); # but our use of the stencil buffer assumes it's drawn at the end (except for objects which # don't obscure it for purposes of highlighting hit-test). This will need to be thought through # carefully if there can be several translucent objects (meant to be opaque re hit-tests), # and traslucent highlighting. See also the comment about highlight_into_depth, below. [bruce 060724 comment] # first gather info needed to know what to do -- highlight color (and whether to draw that at all) # and whether object might be bigger when highlighted (affects whether depth write is needed now). assert hicolor is not None #bruce 070919 highlight_might_be_bigger = True # True is always ok; someday we might let some objects tell us this can be False # color-writing is needed here, iff the mode asked for it, for this selobj. # # Note: in current code this is always True (as assertion above implies), # but it's possible we'll decide to retain self.selobj even if its # hicolor is None, but just not draw it in that case, or even to draw it # in some ways and not others -- so just in case, keep this test for now. # [bruce 070919 comment] highlight_into_color = (hicolor is not None) if highlight_into_color: # depth-writing is needed here, if highlight might be drawn in front of not-yet-drawn transparent surfaces # (like Build mode water surface) -- otherwise they will look like they're in front of some of the highlighting # even though they're not. (In principle, the preDraw_glselect_dict call above needs to know whether this depth # writing occurred ###doc why. Probably we should store it into the object itself... ###@@@ review, then doit ) highlight_into_depth = highlight_might_be_bigger else: highlight_into_depth = False ###@@@ might also need to store 0 into obj...see discussion above if not highlight_into_depth: glDepthMask(GL_FALSE) # turn off depth writing (but not depth test) if not highlight_into_color: glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE) # don't draw color pixels # Note: stencil buffer was cleared earlier in this paintGL call. glStencilFunc(GL_ALWAYS, 1, 1) # These args make sure stencil test always passes, so color is drawn if we want it to be, # and so we can tell whether depth test passes in glStencilOp (even if depth *writing* is disabled ###untested); # this also sets reference value of 1 for use by GL_REPLACE. # (Args are: func to say when drawing-test passes; ref value; comparison mask. # Warning: Passing -1 for reference value, to get all 1's, does not work -- it makes ref value 0!) glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE) # turn on stencil-buffer writing based on depth test # (args are: what to do on fail, zfail, zpass (see OpenGL "red book" p. 468)) glEnable(GL_STENCIL_TEST) # this enables both aspects of the test: effect on drawing, and use of stencil op (I think #k); # apparently they can't be enabled separately ##print glGetIntegerv( GL_STENCIL_REF) # Now "translate the world" slightly closer to the screen, # to ensure depth test passes for appropriate parts of highlight-drawing # even if roundoff errors would make it unreliable to just let equal depths pass the test. # As of 070921 we use glDepthRange for this. self.setDepthRange_Highlighting() try: colorsorter_safe = getattr(selobj, '_selobj_colorsorter_safe', False) # colorsorter_safe being False (in two places in this file) # is a bugfix for the breaking of expr handle highlighting # by the debug_pref('GLPane: highlight atoms in CSDLs?') # (but bug's cause is not understood) [bruce 090311] self.set_drawing_phase('selobj') #bruce 070124 #bruce 070329 moved set of drawing_phase from just after selobj.draw_in_abs_coords to just before it. # [This should fix the Qt4 transition issue which is the subject of reminder bug 2300, # though it can't be tested yet since it has no known effect on current code, only on future code.] def func(): self.graphicsMode.Draw_highlighted_selobj( self, selobj, hicolor) # TEST someday: test having color writing disabled here -- does stencil write still happen?? # (not urgent, since we definitely need color writing here.) return self._call_func_that_draws_objects(func, self.part, bare_primitives = colorsorter_safe) except: # try/except added for GL-state safety, bruce 061218 print_compact_traceback( "bug: exception in %r.Draw_highlighted_selobj for %r ignored: " % \ (self.graphicsMode, selobj) ) pass self.set_drawing_phase('?') self.setDepthRange_Normal() # restore other gl state # (but don't do unneeded OpenGL ops # in case that speeds up OpenGL drawing) glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP) # no need to undo glStencilFunc state, I think -- whoever cares will set it up again # when they reenable stenciling. if not highlight_into_color: glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE) if not highlight_into_depth: glDepthMask(GL_TRUE) if debug_pref("GLPane: draw stencil buffer?", Choice_boolean_False, prefs_key = True ): # draw stencil buffer in orange [bruce 090105] glStencilFunc(GL_EQUAL, 1, 1) # only draw where stencil is set glDepthMask(GL_FALSE) glDisable(GL_DEPTH_TEST) # Note: according to some web forum (not confirmed in red book or by test), # glDisable(GL_DEPTH_TEST) also disables depth writing, # so the above glDepthMask(GL_FALSE) is redundant. # This differs from my recollection, so should be checked if it matters. # [bruce 090105] self.draw_solid_color_everywhere(orange) # note: we already drew highlighting selobj above, so that won't obscure this glEnable(GL_DEPTH_TEST) glDepthMask(GL_TRUE) pass glDisable(GL_STENCIL_TEST) return # from _draw_highlighted_selobj def preDraw_glselect_dict(self): #bruce 050609 """ Assume the depth buffer is clear. Draw each object in self.glselect_dict (in a certain order) (drawing them into depth buffer only) and measure its depth, until you find one near (undeep) enough (at the target pixel) to account for the target depth (self.targetdepth). Return that one, but first clear the depth buffer again. @note: some details are not documented here; see the code. """ # We need to draw glselect_dict objects separately, # so their drawing code runs now rather than in the past # (when some display list was being compiled), # so they can notice they're in that dict. # We also draw them first, so that the nearest one # (or one of them, if there's a tie) # is sure to update the depth buffer. # (Then we clear the depth buffer, so that this drawing # doesn't mess up later drawing at the same depth.) # (If some mode with special drawing code wants to join this system, # it should be refactored to store special nodes in the model # which can be drawn in the standard way.) glMatrixMode(GL_MODELVIEW) glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE) # optimization -- don't draw color pixels (depth is all we need) newpicked = None # in case of errors, and to record found object # here we should sort the objs to check the ones we most want first # (especially selobj)... #bruce 050702 try sorting this, see if it helps pick bonds rather than # invisible selatoms -- it seems to help. # This removes a bad side effect of today's earlier fix of bug 715-1. objects = self.glselect_dict.values() items = [] # (order, obj) pairs, for sorting objects for obj in objects: ### MAYBE TODO: add a special order for the object found previously # by the glname-to-color code for shader primitives. # But only do this after we're sure we draw all other objects # then too. And its order should be worse than selobj, I think. # [bruce 090105 comment] if obj is self.selobj: order = 0 elif isinstance(obj, Bond): #bruce 080402 precaution: don't say obj.__class__ is Bond, # in case obj has no __class__ order = 1 else: order = 2 order = (order, id(obj)) #bruce 080402 work around bug in Bond.__eq__ for bonds not on # the same atom; later on 080402 I fixed that bug, but I'll # leave this for safety in case of __eq__ bugs on other kinds # of selobjs (e.g. dependence on other.__class__) items.append( (order, obj) ) items.sort() report_failures = debug_pref( "GLPane: preDraw_glselect_dict: report failures?", Choice_boolean_False, prefs_key = True ) if debug_pref("GLPane: check_target_depth debug prints?", Choice_boolean_False, prefs_key = True): debug_prefix = "check_target_depth" else: debug_prefix = None fudge = self.graphicsMode.check_target_depth_fudge_factor #bruce 070115 kluge for testmode ### REVIEW: should this be an attribute of each object which can be drawn as selobj, instead? # The reasons it's needed are the same ones that require a nonzero DEPTH_TWEAK in GLPane_minimal. # See also the comment about it inside check_target_depth. [bruce 070921 comment] for orderjunk, obj in items: # iterate over candidates try: method = obj.draw_in_abs_coords except AttributeError: print "bug? ignored: %r has no draw_in_abs_coords method" % (obj,) print " items are:", items else: try: colorsorter_safe = getattr(obj, '_selobj_colorsorter_safe', False) # colorsorter_safe being False (in two places in this file) # is a bugfix for the breaking of expr handle highlighting # by the debug_pref('GLPane: highlight atoms in CSDLs?') # (but bug's cause is not understood) [bruce 090311] for stereo_image in self.stereo_images_to_draw: # REVIEW: would it be more efficient, and correct, # to iterate over stereo images outside, and candidates # inside (i.e. turn this pair of loops inside out)? # I guess that would require knowing which stereo_image # we're sampling in... and in that case we'd want to use # only one of them anyway to do the testing # (probably even if they overlap, just pick one and # use that one -- see related comments in _enable_stereo). # [bruce 080911 comment] self._enable_stereo(stereo_image) self.set_drawing_phase('selobj/preDraw_glselect_dict') # bruce 070124 def func(): method(self, white) # draw depth info # (color doesn't matter since we're not drawing pixels) return self._call_func_that_draws_objects( func, self.part, bare_primitives = colorsorter_safe ) self._disable_stereo() self.set_drawing_phase('?') #bruce 050822 changed black to white in case some draw methods have boolean-test bugs for black (unlikely) ###@@@ in principle, this needs bugfixes; in practice the bugs are tolerable in the short term # (see longer discussion in other comments): # - if no one reaches target depth, or more than one does, be smarter about what to do? # - try current selobj first [this is done, as of 050702], # or give it priority in comparison - if it passes be sure to pick it # - be sure to draw each obj in same way it was last drawn, esp if highlighted: # maybe drawn bigger (selatom) # moved towards screen newpicked = self.check_target_depth( obj, fudge, debug_prefix = debug_prefix) # returns obj or None -- not sure if that should be guaranteed [bruce 050822 comment] if newpicked is not None: break except: self.set_drawing_phase('?') print_compact_traceback("exception in or near %r.draw_in_abs_coords ignored: " % (obj,)) ##e should check depth here to make sure it's near enough but not too near # (if too near, it means objects moved, and we should cancel this pick) glClear(GL_DEPTH_BUFFER_BIT) # prevent those predraws from messing up the subsequent main draws # REVIEW: is this slow? If so, it could be optimized by drawing them # into only one pixel and clearing only that pixel (see related code # in the glname-color code in do_glselect_if_wanted). # [bruce 090105 comment] glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE) self.glselect_dict.clear() #k needed? even if not, seems safer this way. # do this now to avoid confusing the main draw methods, # in case they check this dict to decide whether they're # being called by draw_in_abs_coords # [which would be deprecated! but would work, not counting display lists.] #bruce 050822 new feature: objects which had no highlight color should not be allowed in self.selobj # (to make sure they can't be operated on without user intending this), # though they should still obscure other objects. if newpicked is not None: if debug_prefix and len(items) > 1: #bruce 081209 print "%s (%d): complete list of candidates were:" % (debug_prefix, env.redraw_counter), items hicolor = self.selobj_hicolor( newpicked) if hicolor is None: if report_failures: print "debug_pref: preDraw_glselect_dict failure: " \ "it worked, but %r hicolor is None, so discarding it" % \ (newpicked,) #bruce 081209 newpicked = None # [note: there are one or two other checks of the same thing, # e.g. to cover preexisting selobjs whose hicolor might have changed [bruce 060726 comment]] else: #bruce 060217 debug code re bug 1527. Not sure only happens on a bug, so using atom_debug. # (But I couldn't yet cause this to be printed while testing that bug.) #bruce 060224 disabling it since it's happening all the time when hover-highlighting in Build # (though I didn't reanalyze my reasons for thinking it might be a bug, so I don't know if it's a real one or not). #070115 changing condition from if 0 to a debug_pref, and revised message if report_failures: print "debug_pref: preDraw_glselect_dict failure: targetdepth is %r, items are %r" % (self.targetdepth, items) ###e try printing it all -- is the candidate test just wrong? return newpicked # might be None in case of errors (or if selobj_hicolor returns None) def check_target_depth(self, candidate, fudge, debug_prefix = None): #bruce 050609; revised 050702, 070115 """ [private helper method] [required arg fudge is the fudge factor in threshhold test] WARNING: docstring is obsolete -- no newpicked anymore, retval details differ: ###@@@ Candidate is an object which drew at the mouse position during GL_SELECT drawing mode (using the given gl_select name), and which (1) has now noticed this, via its entry in self.glselect_dict (which was made when GL_SELECT mode was exited; as of 050609 this is in the same paintGL call as we're in now), and (2) has already drawn into the depth buffer during normal rendering (or an earlier rendering pass). (It doesn't matter whether it's already drawn into the color buffer when it calls this method.) We should read pixels from the depth buffer (after glFlush) to check whether it has just reached self.targetdepth at the appropriate point, which would mean candidate is the actual newly picked object. If so, record this fact and return True, else return False. We might quickly return False (checking nothing) if we already returned True in the same pass, or we might read pixels anyway for debugging or assertions. It's possible to read a depth even nearer than targetdepth, if the drawing passes round their coordinates differently (as the use of gluPickMatrix for GL_SELECT is likely to do), or if events between the initial targetdepth measurement and this redraw tell any model objects to move. Someday we should check for this. """ glFlush() # In theory, glFinish might be needed here; # in practice, I don't know if even glFlush is needed. # [bruce 070921 comment] wX, wY = self.wX, self.wY wZ = glReadPixelsf(wX, wY, 1, 1, GL_DEPTH_COMPONENT) newdepth = wZ[0][0] targetdepth = self.targetdepth ### possible change: here we could effectively move selobj forwards # (to give it an advantage over other objects)... # but we'd need to worry about scales of coord systems in doing that... # due to that issue it is probably easier to fix this solely when # drawing it, instead. if newdepth <= targetdepth + fudge: # test passes -- return candidate below # note: condition uses fudge factor in case of roundoff errors # (hardcoded as 0.0001 before 070115) or slight differences in # highlighted vs plain form of object (e.g. due to inconsistent # orientation of polygonal approximation to a cylinder) # # [bruce 050702: 0.000001 was not enough! 0.00003 or more was needed, to properly highlight some bonds # which became too hard to highlight after today's initial fix of bug 715-1.] # [update, bruce 070921: fyi: one reason this factor is needed is the shorten_tubes flag used to # highlight some bonds, which changes the cylinder scaling, and conceivably (due solely to # roundoff errors) the precise axis direction, and thus the precise cross-section rotation # around the axis. Another reason was a bug in bond_drawer which I fixed today, so the # necessary factor may now be smaller, but I didn't test this.] # #e could check for newdepth being < targetdepth - 0.002 (error), but best # to just let caller do that (NIM), since we would often not catch this error anyway, # since we're turning into noop on first success # (no choice unless we re-cleared depth buffer now, which btw we could do... #e). if debug_prefix: counter = env.redraw_counter print "%s (%d): target depth %r reached by %r at %r" % \ (debug_prefix, counter, targetdepth, candidate, newdepth) if newdepth > targetdepth: print " (too deep by %r, but fudge factor is %r)" % \ (newdepth - targetdepth, fudge) elif newdepth < targetdepth: print " (in fact, object is nearer than targetdepth by %r)" % \ (targetdepth - newdepth,) pass return candidate # caller should not call us again without clearing depth buffer, # otherwise we'll keep returning every object even if its true # depth is too deep if debug_prefix: counter = env.redraw_counter print "%s (%d): target depth %r NOT reached by %r at %r" % \ (debug_prefix, counter, targetdepth, candidate, newdepth) print " (too deep by %r, but fudge factor is only %r)" % \ (newdepth - targetdepth, fudge) return None pass # end
NanoCAD-master
cad/src/graphics/widgets/GLPane_highlighting_methods.py
# Copyright 2004-2009 Nanorex, Inc. See LICENSE file for details. """ GLPane_rendering_methods.py @version: $Id$ @copyright: 2004-2009 Nanorex, Inc. See LICENSE file for details. bruce 080913 split this out of class GLPane """ TEST_DRAWING = False # True ## Debug/test switch. Never check in a True value. # Also can be changed at runtime by external code. if TEST_DRAWING: from prototype.test_drawing import test_drawing # review: is this needed here for its side effects? # guess yes, should document if so. pass from OpenGL.GL import GL_DEPTH_BUFFER_BIT from OpenGL.GL import GL_LEQUAL from OpenGL.GL import GL_MODELVIEW from OpenGL.GL import GL_MODELVIEW_STACK_DEPTH from OpenGL.GL import GL_STENCIL_BUFFER_BIT from OpenGL.GL import glDepthFunc from OpenGL.GL import glFlush from OpenGL.GL import glGetInteger from OpenGL.GL import glMatrixMode from OpenGL.GL import glPopMatrix # kluge for debug bruce 081218 (temporary) ##from OpenGL.GL import glEnable ##from OpenGL.GL import glLogicOp ##from OpenGL.GL import glDisable ##from OpenGL.GL import GL_COLOR_LOGIC_OP ##from OpenGL.GL import GL_XOR from PyQt4.QtOpenGL import QGLWidget from utilities import debug_flags from utilities.debug import print_compact_traceback, print_compact_stack from utilities.Comparison import same_vals from utilities.prefs_constants import displayCompass_prefs_key from utilities.prefs_constants import displayOriginAxis_prefs_key from utilities.prefs_constants import displayOriginAsSmallAxis_prefs_key from utilities.prefs_constants import displayCompassLabels_prefs_key from utilities.prefs_constants import displayRulers_prefs_key from utilities.prefs_constants import showRulersInPerspectiveView_prefs_key from utilities.prefs_constants import fogEnabled_prefs_key from utilities.debug_prefs import debug_pref from utilities.debug_prefs import Choice_boolean_False from utilities.GlobalPreferences import use_frustum_culling from utilities.GlobalPreferences import pref_skip_redraws_requested_only_by_Qt import foundation.env as env import graphics.drawing.drawing_globals as drawing_globals from graphics.drawing.drawers import drawOriginAsSmallAxis from graphics.drawing.drawers import drawaxes from graphics.drawing.gl_lighting import disable_fog from graphics.drawing.gl_lighting import enable_fog from graphics.drawing.gl_lighting import setup_fog from graphics.drawing.drawcompass import Compass from graphics.drawing.Guides import Guides from graphics.widgets.GLPane_image_methods import GLPane_image_methods # == class GLPane_rendering_methods(GLPane_image_methods): """ private mixin for providing rendering methods to class GLPane (including calls to highlighting/hit-test methods defined in mixin class GLPane_highlighting_methods, which must be a mixin of class GLPane along with this class) """ def _init_GLPane_rendering_methods(self): """ """ # clipping planes, as percentage of distance from the eye self.near = 0.25 # After testing, this is much, much better. Mark 060116. [Prior value was 0.66 -- bruce 060124 comment] self.far = 12.0 ##2.0, Huaicai: make this bigger, so models will be ## more likely sitting within the view volume ##Huaicai 2/8/05: If this is true, redraw everything. It's better to split ##the paintGL() to several functions, so we may choose to draw ##every thing, or only some thing that has been changed. self.redrawGL = True # [bruce 050608] self.glselect_dict = {} # only used within individual runs [of what? paintGL I guess?] # see also self.object_for_glselect_name(), defined in GLPane_highlighting_methods self.makeCurrent() # REVIEW: safe now? needed for loadLighting? [bruce 080913 questions] # don't call GLPane_minimal._setup_display_lists yet -- this will be # called later by GLPane_minimal.initializeGL. [bruce 080913 change] # NOTE: before bruce 080913 split out this file, setAssy was done # at this point. Hopefully it's ok to do it just after we return, # instead. (Seems to work.) self.loadLighting() #bruce 050311 [defined in GLPane_lighting_methods] #bruce question 051212: why doesn't this prevent bug 1204 # in use of lighting directions on startup? self.guides = Guides(self) # rulers, and soon, grid lines. Mark 2008-02-24. self.compass = Compass(self) #bruce 081015 refactored this return def model_is_valid(self): #bruce 080117 """ whether our model is currently valid for drawing [overrides GLPane_minimal method] """ return self.assy.assy_valid def should_draw_valence_errors(self): """ [overrides GLPane_minimal method] """ return True def _paintGL(self): """ [private; the body of paintGL in GLPane.py] Decide whether we need to call _paintGL_drawing, and if so, prepare for that (this might modify the model) and then call it. Also (first) call self._call_whatever_waits_for_gl_context_current() if that would be safe. @return: whether we modified GL buffer state (by clear or draw). @rtype: boolean """ #bruce 081222 added return flag if TEST_DRAWING: # See prototype/test_drawing.py from prototype.test_drawing import test_drawing, USE_GRAPHICSMODE_DRAW # intentionally redundant with toplevel import [bruce 080930] if USE_GRAPHICSMODE_DRAW: # Init and continue on, assuming that test_Draw_model will be called # separately (in an override of graphicsMode.Draw_model). # LIKELY BUG: USE_GRAPHICSMODE_DRAW is now a constant # but needs to depend on the testCase or be a separately # settable variable. This might be fixable inside test_drawing.py # since we reimport it each time here. [bruce 081211 comment] test_drawing(self, True) else: self.graphicsMode.gm_start_of_paintGL(self) test_drawing(self) self.graphicsMode.gm_end_of_paintGL(self) return True self._frustum_planes_available = False if not self.initialised: return False if not self.model_is_valid(): #bruce 080117 bugfix in GLPane and potential bugfix in ThumbView; # for explanation see my same-dated comment in files_mmp # near another check of assy_valid. return False env.after_op() #bruce 050908; moved a bit lower, 080117 # [disabled in changes.py, sometime before 060323; # probably obs as of 060323; see this date below] # SOMEDAY: it might be good to set standard GL state, e.g. matrixmode, # before checking self.redrawGL here, in order to mitigate bugs in other # code (re bug 727), but only if the current mode gets to redefine what # "standard GL state" means, since some modes which use this flag to # avoid standard repaints also maintain some GL state in nonstandard # forms (e.g. for XOR-mode drawing). [bruce 050707 comment] if not self.redrawGL: return False self._call_whatever_waits_for_gl_context_current() #bruce 071103 if not self._needs_repaint and \ pref_skip_redraws_requested_only_by_Qt(): # if we don't think this redraw is needed, # skip it (but print '#' if atom_debug is set -- disabled as of 080512). #bruce 070109 restored/empowered the following code, but # only within this new debug pref [persistent as of 070110]. # # ITS USE IS PREDICTED TO CAUSE SOME BUGS: one in changed bond # redrawing [described below, "bruce 050717 bugfix"] # (though the fact that _needs_repaint is not reset until below # makes me think it either won't happen now, # or is explained incorrectly in that comment), # and maybe some in look of glpane after resizing, toolbar changes, # or popups/dialogs going up or down, any of which might be # platform-dependent. The debug_pref's purpose is experimentation -- # if we could figure out which repaints are really needed, we could # probably optimize away quite a few unneeded ones. # # Update, bruce 070414: so far I only found one bug this debug_pref # causes: MT clicks which change chunk selection don't cause redraws, # but need to (to show their selection wireframes). That could be # easily fixed. [Bug no longer exists as of 080512; I don't recall # why. But I have had this always on for a long time and don't # recall noticing any bugs. So I'm turning it on by default, and # disabling the printing of '#'; if we need it back for debugging # we can add a debug_pref for it and/or for drawing redraw_counter # as text in the frame. bruce 080512] # # older comments: # #bruce 050516 experiment # # This probably happens fairly often when Qt calls paintGL but # our own code didn't change anything and therefore didn't call # gl_update. # # This is known to happen when a context menu is put up, # the main app window goes into bg or fg, etc. # # SOMEDAY: # An alternative to skipping the redraw would be to optimize it # by redrawing a saved image. We're likely to do that for other # reasons as well (e.g. to optimize redraws in which only the # selection or highlighting changes). # [doing this experimentally, 080919; see class GLPane_image_methods] # disabling this debug print (see long comment above), bruce 080512 ## if debug_flags.atom_debug: ## sys.stdout.write("#") # indicate a repaint is being skipped ## sys.stdout.flush() return False # skip the following repaint # at this point, we've decided to call _paintGL_drawing. env.redraw_counter += 1 #bruce 050825 #bruce 050707 (for bond inference -- easiest place we can be sure to update bonds whenever needed) #bruce 050717 bugfix: always do this, not only when "self._needs_repaint"; otherwise, # after an atomtype change using Build's cmenu, the first redraw (caused by the cmenu going away, I guess) # doesn't do this, and then the bad bond (which this routine should have corrected, seeing the atomtype change) # gets into the display list, and then even though the bondtype change (set_v6) does invalidate the display list, # nothing triggers another gl_update, so the fixed bond is not drawn right away. I suppose set_v6 ought to do its own # gl_update, but for some reason I'm uncomfortable with that for now (and even if it did, this bugfix here is # probably also needed). And many analogous LL changers don't do that. env.do_post_event_updates( warn_if_needed = False) # WARNING: this calls command-specific ui updating methods # like model_changed, even when it doesn't need to (still true # 080804). They all need to be revised to be fast when no changes # are needed, or this will make redraw needlessly slow. # [bruce 071115/080804 comment] # TODO: doc what else it does - break interpart bonds? dna updater? undo checkpoint? # Note: at one point we surrounded this repaint with begin/end undo # checkpoints, to fix bugs from missing mouseReleases (like bug 1411) # (provided they do a gl_update like that one does), from model changes # during env.do_post_event_updates(), or from unexpected model changes # during the following repaint. But this was slow, and caused bug 1759, # and a better fix for 1411 was added (in the menu_spec processor in # widgets.py). So the checkpoints were zapped [by bruce 060326]. # There might be reasons to revive that someday, and ways to avoid # its slowness and bugs, but it's not needed for now. try: self._paintGL_drawing() except: print_compact_traceback("exception in _paintGL_drawing ignored: ") return True # from paintGL def _paintGL_drawing(self): """ [private submethod of _paintGL] Do whatever OpenGL drawing paintGL should do (then glFlush). @note: caller must handle TEST_DRAWING, redrawGL, _needs_repaint. """ #bruce 080919 renamed this from most_of_paintGL to _paintGL_drawing ## if 'kluge for debug bruce 081218': ## glEnable(GL_COLOR_LOGIC_OP) ## glLogicOp(GL_XOR) ## glDisable(GL_COLOR_LOGIC_OP) self._needs_repaint = False # do this now, even if we have an exception during the repaint self.graphicsMode.gm_start_of_paintGL(self) #k not sure whether _restore_modelview_stack_depth is also needed # in the split-out standard_repaint [bruce 050617] self._restore_modelview_stack_depth() self._use_frustum_culling = use_frustum_culling() # there is some overhead calling the debug_pref, # and we want the same answer used throughout # one call of paintGL. Note that this is checked both # in this file and in GLPane_highlighting_methods.py. assert not self._frustum_planes_available glDepthFunc( GL_LEQUAL) #bruce 070921; GL_LESS causes bugs # (e.g. in exprs/Overlay.py) # TODO: put this into some sort of init function in GLPane_minimal; # not urgent, since all instances of GLPane_minimal share one GL # context for now, and also they all contain this in paintGL. self.setDepthRange_setup_from_debug_pref() self.setDepthRange_Normal() method = self.graphicsMode.render_scene # revised, bruce 070406/071011 if method is None: self.render_scene() # usual case # [TODO: move that code into basicGraphicsMode and let it get # called in the same way as the following] else: method( self) # let the graphicsMode override it glFlush() self.graphicsMode.gm_end_of_paintGL(self) ##self.swapBuffers() ##This is a redundant call, Huaicai 2/8/05 return # from _paintGL_drawing def _restore_modelview_stack_depth(self): """ restore GL_MODELVIEW_STACK_DEPTH to 1, if necessary """ #bruce 040923 [updated 080910]: # I'd like to reset the OpenGL state # completely, here, including the stack depths, to mitigate some # bugs. How?? Note that there might be some OpenGL init code # earlier which I'll have to not mess up, including _setup_display_lists. # What I ended up doing is just to measure the # stack depth and pop it 0 or more times to make the depth 1. # BTW I don't know for sure whether this causes a significant speed # hit for some OpenGL implementations (esp. X windows)... # TODO: test the performance effect sometime. glMatrixMode(GL_MODELVIEW) depth = glGetInteger(GL_MODELVIEW_STACK_DEPTH) # this is normally 1 # (by experiment, qt-mac-free-3.3.3, Mac OS X 10.2.8...) if depth > 1: print "apparent bug: glGetInteger(GL_MODELVIEW_STACK_DEPTH) = %r in GLPane.paintGL" % depth print "workaround: pop it back to depth 1" while depth > 1: depth -= 1 glPopMatrix() newdepth = glGetInteger(GL_MODELVIEW_STACK_DEPTH) if newdepth != 1: print "hmm, after depth-1 pops we should have reached depth 1, but instead reached depth %r" % newdepth pass return def render_scene(self):#bruce 061208 split this out so some modes can override it (also removed obsolete trans_feature experiment) #k not sure whether next things are also needed in the split-out standard_repaint [bruce 050617] self.glprefs.update() #bruce 051126; kluge: have to do this before lighting *and* inside standard_repaint_0 # [addendum, bruce 090304: I assume that's because we need it for lighting, but also # need its prefs accesses to be usage-tracked, so changes in them do gl_update; # maybe a better solution would be to start usage-tracking sooner?] self.setup_lighting_if_needed() # defined in GLPane_lighting_methods self.standard_repaint() return # from render_scene __subusage = None #bruce 070110 def standard_repaint(self): """ call standard_repaint_0 inside "usage tracking". This is so subsequent changes to tracked variables (such as env.prefs values) automatically cause self.gl_update to be called. @warning: this trashes both gl matrices! caller must push them both if it needs the current ones. this routine sets its own matrixmode, but depends on other gl state being standard when entered. """ # zap any leftover usage tracking from last time # # [bruce 070110 new feature, for debugging and possibly as a bugfix; # #e it might become an option of begin_tracking_usage, but an "aspect" would need to be passed # to permit more than one tracked aspect to be used -- it would determine the attr # corresponding to __subusage in this code. Maybe the same aspect could be passed to # methods of SelfUsageTrackingMixin, but I'm not sure whether the two tracking mixins # would or should interact -- maybe one would define an invalidator for the other to use?] # if self.__subusage is None: # usual the first time pass elif self.__subusage == 0: # should never happen print_compact_stack( "bug: apparent recursive usage tracking in GLPane: ") pass # it'd be better if we'd make invals illegal in this case, but in current code # we don't know the obj to tell to do that (easy to fix if needed) elif self.__subusage == -1: print "(possible bug: looks like the last begin_tracking_usage raised an exception)" pass else: # usual case except for the first time self.__subusage.make_invals_illegal(self) self.__subusage = -1 match_checking_code = self.begin_tracking_usage() #bruce 050806 self.__subusage = 0 debug_prints_prefs_key = "A9 devel/debug prints for my bug?" # also defined in exprs/test.py if env.prefs.get(debug_prints_prefs_key, False): print "glpane begin_tracking_usage" #bruce 070110 try: try: self.standard_repaint_0() except: print "exception in standard_repaint_0 (being reraised)" # we're not restoring stack depths here, so this will mess up callers, so we'll reraise; # so the caller will print a traceback, thus we don't need to print one here. [bruce 050806] raise finally: self.wants_gl_update = True #bruce 050804 self.__subusage = self.end_tracking_usage( match_checking_code, self.wants_gl_update_was_True ) # same invalidator even if exception if env.prefs.get(debug_prints_prefs_key, False): print "glpane end_tracking_usage" #bruce 070110 return drawing_phase = '?' # set to different fixed strings for different drawing phases # [new feature, bruce 070124] [also defined in GLPane_minimal] # # WARNING: some of the strings are hardcoded in condition checks in # various places in the code. If spelling is changed, or new strings are # added, or the precise drawing covered by each string is modified, # all existing uses need to be examined for possibly needing changes. # (Ideally, this would be cleaned up by defining in one place the # possible values, as symbolic constants, and the functions for testing # aspect of interest from them, e.g. whether to draw shader primitives, # whether to draw OpenGL display lists, which DrawingSet cache to use.) # [bruce 090227 comment] drawing_globals.drawing_phase = drawing_phase # KLUGE (as is everything about drawing_globals) def set_drawing_phase(self, drawing_phase): """ Set self.drawing_phase to the specified value, and do any updates this requires (presently, copy it into drawing_globals.drawing_phase). Various internal code looks at self.drawing_phase (and/or drawing_globals.drawing_phase) so it can behave differently during different drawing phases. See code and code comments for details, and a list of permitted values of drawing_phase and what they mean. @note: setting self.drawing_phase directly (not using this method) would cause bugs. """ # Russ 081208: Encapsulate setting, to tell shaders as well. self.drawing_phase = drawing_phase drawing_globals.drawing_phase = drawing_phase # Note, there are direct calls of GL_SELECT drawing not from class # GLPane, which ought to set this but don't. (They have a lot of other # things wrong with them too, especially duplicated code). The biggest # example is for picking jigs. During those calls, this attr will # probably equal '?' -- all the draw calls here reset it to that right # after they're done. (## todo: We ought to set it to that at the end of # paintGL as well, for safety.) # # Explanation of possible values: [### means explan needs to be filled in] # - '?' -- drawing at an unexpected time, or outside of paintGL # - 'glselect' -- only used if mode requested object picking # -- Only draws Display Lists since the glSelect stack is not available to shaders. # -- glRenderMode(GL_SELECT) in effect; reduced projection matrix # - 'glselect_glname_color' -- only used if mode requested object picking # -- Only draws shader primitives, and reads the glnames back as pixel colors. # -- glRenderMode(GL_RENDER) in effect; reduced projection matrix and viewport (one pixel.) # - 'main' -- normal drawing, main coordinate system for model (includes trackball/zoom effect) # - 'main/Draw_after_highlighting' -- normal drawing, but after selobj is drawn ### which coord system? # - 'main/draw_glpane_label' -- ### # - 'overlay' -- ### # - 'selobj' -- we're calling selobj.draw_in_abs_coords (not drawing the entire model), within same coordsys as 'main' # - 'selobj/preDraw_glselect_dict' -- like selobj, but color buffer drawing is off ### which coord system, incl projection?? # [end] return _drawingset_cachename_from_drawing_phase = { '?': 'main', # theory: used by event methods that draw entire model for # selection, e.g. jigGLselect (sp?); should clean them up #### review 'glselect': 'main', 'glselect_glname_color': 'main', 'main': 'main', 'main/Draw_after_highlighting': 'main/Draw_after_highlighting', 'main/draw_glpane_label': 'temp', 'overlay': 'temp', 'selobj': 'selobj', 'selobj/preDraw_glselect_dict': 'temp', } _drawingset_temporary_cachenames = { 'temp': True } def _choose_drawingset_cache_policy(self): #bruce 090227 """ Based on self.drawing_phase, decide which cache to keep DrawingSets in and whether it should be temporary. @return: (temporary, cachename) @rtype: (bool, string) [overrides a method defined in a mixin of a superclass of the class we mix into] """ # Note: mistakes in what we return will reduce graphics performance, # and could increase VRAM usage, but have no effect on what is drawn. # About the issue of using too much ram: all whole-model caches should # be the same; small ones don't matter too much, but might be best # temporary in case they are not always small; # at least use the same cache in all temp cases. # todo: Further optimization is possible but not yet done: # for drawing main model for selobj tests, just reuse # the cached drawingsets without even scanning the model # to see if they need to be modified. This is worth # doing if we have time, but less urgent than several # other things we need to do. drawing_phase = self.drawing_phase if drawing_phase == '?': print_compact_stack("warning: _choose_drawingset_cache_policy during '?' -- should clean up: ") ###### cachename = self._drawingset_cachename_from_drawing_phase.get(drawing_phase) if cachename is None: cachename = 'temp' print "bug: unknown drawing_phase %r, using cachename %r" % \ (drawing_phase, cachename) assert self._drawingset_temporary_cachenames.get(cachename, False) == True pass temporary = self._drawingset_temporary_cachenames.get(cachename, False) return (temporary, cachename) # == def setup_shaders_each_frame(self): #bruce 090304 """ This must be called once near the start of each call of paintGL, sometime after self.glprefs.update has been first called during that call of paintGL. It makes sure shaders exist and are loaded, but does not configure them (since that requires some GL state which is not yet set when this is called, and may need to be done more than once per frame). """ if self.permit_shaders: drawing_globals.setup_desired_shaders( self.glprefs) # review: is it good that we condition this on self.permit_shaders? # it doesn't matter for now, since ThumbView never calls it. return def enabled_shaders(self): #bruce 090303 return drawing_globals.enabled_shaders(self) #### todo: refactor: self.drawing_globals (but renamed) def configure_enabled_shaders(self): #bruce 090303 """ This must be called before any drawing that might use shaders, but after all preferences are cached (by glprefs.update or any other means), and after certain other GL drawing state is set up (in case configShader reads that state). The state it reads from glpane (including from glpane.glprefs) are related to debug_code, material, perspective, clip/DEPTH_TWEAK, and lights (see configShader for details). It is ok to call it multiple times per paintGL call. If in doubt about where to correctly call it, just call it in both places. However, it is believed that in current code, it only uses state set by user pref changes, which means a single call per paintGL call should be sufficient if it's in the right place. (It never uses the GL matrices or glpane.drawing_phase. But see setPicking.) @note: setup_shaders_each_frame must have been called before this, during the same paintGL call. """ for shader in self.enabled_shaders(): shader.configShader(self) return # == _cached_bg_image_comparison_data = None # note: for the image itself, see attrs of class GLPane_image_methods _last_general_appearance_prefs_summary = None #bruce 090306 _general_appearance_change_indicator = 0 # also defined in GLPane_minimal def standard_repaint_0(self): """ [private indirect submethod of paintGL] This is the main rendering routine -- it clears the OpenGL window, does all drawing done during paintGL, and does hit-testing if requested by event handlers before this call of paintGL. @note: this is called inside a begin_tracking_usage/end_tracking_usage pair, invalidation of which results (indirectly) in self.gl_update(). @note: self.graphicsMode can control whether this gets called; for details see the call of self.render_scene in this class. """ if self.width != QGLWidget.width(self) or \ self.height != QGLWidget.height(self): #bruce 080922; never yet seen print "\n*** debug fyi: inconsistent: self width/height %r, %r vs QGLWidget %r, %r" % \ (self.width, self.height, QGLWidget.width, QGLWidget.height) pass self.glprefs.update() # (kluge: have to do this before lighting *and* inside standard_repaint_0) # (this is also required to come BEFORE setup_shaders_each_frame) # optimization: compute a change indicator for Chunk & ExternalBondSet # display lists here, not every time we draw one of them! # (kluge: assume no need for same_vals, i.e. no Numeric arrays # in this value) # [bruce 090306] current_summary = self.part.general_appearance_prefs_summary(self) if self._last_general_appearance_prefs_summary != current_summary: self._general_appearance_change_indicator += 1 # invalidates display lists self._last_general_appearance_prefs_summary = current_summary pass self.clear_and_draw_background( GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT) # also sets self.fogColor # fog added by bradg 20060224 # piotr 080605 1.1.0 rc1 - replaced fog debug pref with user pref self._fog_test_enable = env.prefs[fogEnabled_prefs_key] if self._fog_test_enable: # piotr 080515 fixed fog # I think that the bbox_for_viewing_model call can be expensive. # I have to preserve this value or find another way of computing it. bbox = self.assy.bbox_for_viewing_model() scale = bbox.scale() enable_fog() #k needed?? [bruce 080915 question] setup_fog(self.vdist - scale, self.vdist + scale, self.fogColor) # [I suspect the following comment is about a line that has since # been moved elsewhere -- bruce 080911] # this next line really should be just before rendering # the atomic model itself. I dunno where that is. [bradg I think] # ask mode to validate self.selobj (might change it to None) # (note: self.selobj is used in do_glselect_if_wanted) self._selobj_and_hicolor = self.validate_selobj_and_hicolor() # do modelview setup (needed for GL_SELECT or regular drawing) self._setup_modelview() #bruce 050608 moved modelview setup here, from just before the mode.Draw call # set self.stereo_* attributes based on current user prefs values # (just once per draw event, before anything might use these attributes) self._update_stereo_settings() # do hit-testing, if requested by some event handler before this # call of paintGL (mostly done in do_glselect_if_wanted) ###e note: if any objects moved since they were last rendered, # this hit-test will still work (using their new posns), # but the later depth comparison (below, inside preDraw_glselect_dict) # might not work right. See comments there for details. self.glselect_dict.clear() # this will be filled iff we do a gl_select draw, # then used only in the same paintGL call to alert some objects # they might be the one under the mouse self.setup_shaders_each_frame() self.configure_enabled_shaders() # I don't know if this is needed this early (i.e. before # do_glselect_if_wanted), but it shouldn't hurt (though it # can't come much earlier than this, and must come after # setup_shaders_each_frame which must come after glprefs.update). # Supposedly we only need one call of this per paintGL call # (see its docstring for details), so we'll see if only this one # is sufficient. [bruce 090304] try: self.graphicsMode.Draw_preparation() except: msg = "bug: exception in %r.Draw_preparation ignored" % self.graphicsMode print_compact_traceback(msg + ": ") # Q: then skip the rest of this frame? # A: No, typically that worsens bugs -- it's better to see # something than nothing. pass self.do_glselect_if_wanted() # review: rename: _do_mouseover_picking? # note: this might call _do_graphicsMode_Draw up to 2 times # (as of before 090311). # note: if self.glselect_wanted, this sets up a special projection # matrix, and leaves it in place (effectively trashing the # projection matrix of the caller) self._setup_projection() # setup the usual projection matrix # Compute frustum planes required for frustum culling - piotr 080331 # Moved it right after _setup_projection is called (piotr 080331) # Note that this method is also called by "do_glselect_if_wanted", # but computes different planes. The second call (here) will # re-compute the frustum planes according to the current projection # matrix. if self._use_frustum_culling: self._compute_frustum_planes() # In the glselect_wanted case, we now know (in glselect_dict) # which objects draw any pixels at the mouse position, # but not which one is in front. (The near/far info from # GL_SELECT has too wide a range to tell us that.) # (In the shader primitive case we might know a specific object, # but not always, as long as some objects are not drawn # using shaders.) # So we have to get them to tell us their depth at that point # (as it was last actually drawn) ###@@@ should do that for bugfix; also selobj first # (and how it compares to the prior measured depth-buffer value there, # as passed in glselect_wanted, if we want to avoid selecting # something when it's obscured by non-selectable drawing in # front of it). if self.glselect_dict: # kluge: this is always the case if self.glselect_wanted was set # and self.selobj was set, since selobj is always stored in # glselect_dict then; if not for that, we might need to reset # selobj to None here for empty glselect_dict -- not sure, not # fully analyzed. [bruce 050612] ## self.configure_enabled_shaders() #### new call 090304, maybe not needed newpicked = self.preDraw_glselect_dict() # retval is new mouseover object, or None # now record which object is hit by the mouse in self.selobj # (or None if none is hit); and (later) overdraw it for highlighting. if newpicked is not self.selobj: self.set_selobj( newpicked, "newpicked") self._selobj_and_hicolor = self.validate_selobj_and_hicolor() # REVIEW: should set_selobj also call that, and save hicolor # in an attr of self, so self._selobj_and_hicolor is not needed? # future: we'll probably need to notify some observers that # selobj changed (if in fact it did). # REVIEW: we used to print this in the statusbar: ## env.history.statusbar_msg("%s" % newpicked) # but it was messed up by Build Atoms "click to do x" msg. # that message is nim now, so we could restore this if desired. # should we? [bruce 080915 comment] # otherwise don't change prior selobj -- we have a separate system # to set it back to None when needed (which has to be implemented # in the bareMotion methods of instances stored in self.graphicsMode -- # would self.bareMotion (which doesn't exist now) be better? (REVIEW) # [later: see also UNKNOWN_SELOBJ, I think] ### REVIEW: I suspect the above comment, and not resetting selobj here, # is wrong, at least when selobj has no depth at all at the current # location; and that this error causes a "selobj stickiness" bug # when moving the mouse directly from selobj onto non-glname objects # (or buggy-glname objects, presently perhaps including shader spheres # in Build Atoms when the debug_pref 'Use batched primitive shaders?' # is set). [bruce 090105 comment] # draw according to self.graphicsMode glMatrixMode(GL_MODELVIEW) # this is assumed within Draw methods # these are modified below as needed: draw_saved_bg_image = False # whether to draw previously cached image, this frame capture_saved_bg_image = False # whether to capture a new image from what we draw this frame bg_image_comparison_data = None # if this changes, discard any previously cached image if debug_pref("GLPane: use cached bg image? (experimental)", Choice_boolean_False, ## non_debug = True, [bruce 090311 removed non_debug] prefs_key = True): # experimental implementation, has bugs (listed here or in # submethods when known, mostly in GLPane_image_methods) ### REVIEW: this doesn't yet work, and it's never been reviewed # for compatibility with cached DrawingSet optimizations # (which may mostly supercede the need for it). # [bruce 090311 comment] if self._resize_just_occurred: self._cached_bg_image_comparison_data = None # discard cached image, and do *neither* capture nor draw of # cached image on this frame (the first one drawn after resize). # This seems to prevent crash due to resize (in GEForceFX OpenGL # driver, in a "processing colors" routine), # at least when we meet all of these conditions: [bruce 080922] # - test on iMac G5, Mac OS 10.3.9 # - do the print below # - comment out self.do_glselect_if_wanted() above (highlighting) # - comment out drawing the depth part of the cached image ## print "debug fyi: skipping bg image ops due to resize" # ... Actually, crash can still happen if we slightly expand width # and then trigger redraw by mouseover compass. else: bg_image_comparison_data = self._get_bg_image_comparison_data() cached_image_is_valid = same_vals( bg_image_comparison_data, self._cached_bg_image_comparison_data) if cached_image_is_valid: draw_saved_bg_image = True else: capture_saved_bg_image = True if bg_image_comparison_data == self._cached_bg_image_comparison_data: print "DEBUG FYI: equal values not same_vals:\n%r, \n%r" % \ ( bg_image_comparison_data, self._cached_bg_image_comparison_data ) ### pass pass else: self._cached_bg_image_comparison_data = None if draw_saved_bg_image: self._draw_saved_bg_image() # in GLPane_image_methods # saved and drawn outside of stereo loop (intentional) # (instead of ordinary drawing inside it, separate code below) else: # capture it below, and only after that, do this assignment: # self._cached_bg_image_comparison_data = bg_image_comparison_data pass for stereo_image in self.stereo_images_to_draw: self._enable_stereo(stereo_image) # note: this relies on modelview matrix already being correctly # set up for non-stereo drawing if not draw_saved_bg_image: self._do_drawing_for_bg_image_inside_stereo() # note: this calls _do_graphicsMode_Draw once. # otherwise, no need, we called _draw_saved_bg_image above if not capture_saved_bg_image: self._do_other_drawing_inside_stereo() # otherwise, do this later (don't mess up captured image) self._disable_stereo() continue # to next stereo_image if capture_saved_bg_image: self._capture_saved_bg_image() # in GLPane_image_methods self._cached_bg_image_comparison_data = bg_image_comparison_data for stereo_image in self.stereo_images_to_draw: self._enable_stereo(stereo_image) self._do_other_drawing_inside_stereo() self._disable_stereo() continue # to next stereo_image pass # let parts (other than the main part) draw a text label, to warn # the user that the main part is not being shown [bruce 050408] # [but let the GM control this: moved and renamed # part.draw_text_label -> GM.draw_glpane_label; bruce 090219] try: self.set_drawing_phase('main/draw_glpane_label') #bruce 070124, renamed 090219 self.graphicsMode.draw_glpane_label(self) except: # if this happens at all, it'll happen too often to bother non-debug # users with a traceback (but always print an error message) if debug_flags.atom_debug: print_compact_traceback( "atom_debug: exception in self.graphicsMode.draw_glpane_label(self): " ) else: print "bug: exception in self.graphicsMode.draw_glpane_label; use ATOM_DEBUG to see details" self.set_drawing_phase('?') # draw the compass (coordinate-orientation arrows) in chosen corner if env.prefs[displayCompass_prefs_key]: self.drawcompass() # review: needs drawing_phase? [bruce 070124 q] # draw the "origin axes" ### TODO: put this, and the GM part of it (now in basicGraphicsMode.Draw_axes), # into one of the methods # _do_other_drawing_inside_stereo or _do_drawing_for_bg_image_inside_stereo if env.prefs[displayOriginAxis_prefs_key]: for stereo_image in self.stereo_images_to_draw: self._enable_stereo(stereo_image, preserve_colors = True) # REVIEW: can we simplify and/or optim by moving this into # the same stereo_image loop used earlier for _do_graphicsMode_Draw? # [bruce 080911 question] # WARNING: this code is duplicated, or almost duplicated, # in GraphicsMode.py and GLPane.py. # It should be moved into a common method in drawers.py. # [bruce 080710 comment] #ninad060921 The following draws a dotted origin axis # if the correct preference is checked. The GL_DEPTH_TEST is # disabled while drawing this, so that if axis is behind a # model object, it will just draw it as a dotted line (since # this drawing will occur, but the solid origin axes drawn # in other code, overlapping these, will be obscured). #bruce 080915 REVIEW: can we clarify that by doing the solid # axis drawing here as well? if env.prefs[displayOriginAsSmallAxis_prefs_key]: drawOriginAsSmallAxis(self.scale, (0.0, 0.0, 0.0), dashEnabled = True) else: drawaxes(self.scale, (0.0, 0.0, 0.0), coloraxes = True, dashEnabled = True) self._disable_stereo() self._draw_cc_test_images() # draw some test images related to the confirmation corner # (needs to be done before draw_overlay) # draw various overlays self.set_drawing_phase('overlay') # Draw ruler(s) if "View > Rulers" is checked # (presently in main menus, not in prefs dialog) if env.prefs[displayRulers_prefs_key]: if (self.ortho or env.prefs[showRulersInPerspectiveView_prefs_key]): self.guides.draw() # draw the confirmation corner try: glMatrixMode(GL_MODELVIEW) #k needed? self.graphicsMode.draw_overlay() #bruce 070405 (misnamed) except: print_compact_traceback( "exception in self.graphicsMode.draw_overlay(): " ) self.set_drawing_phase('?') # restore standard glMatrixMode, in case drawing code outside of paintGL # forgets to do this [precaution] glMatrixMode(GL_MODELVIEW) # (see discussion in bug 727, which was caused by that) # (todo: it might also be good to set mode-specific # standard GL state before checking self.redrawGL in paintGL) return # from standard_repaint_0 (the main rendering submethod of paintGL) def _do_drawing_for_bg_image_inside_stereo(self): """ """ #bruce 080919 split this out if self._fog_test_enable: enable_fog() self.set_drawing_phase('main') try: self._do_graphicsMode_Draw() finally: self.set_drawing_phase('?') if self._fog_test_enable: #bruce 090219 moved inside 'finally' disable_fog() return def _do_graphicsMode_Draw(self, for_mouseover_highlighting = False): """ Private helper for various places in which we need to draw the model (in this GLPane mixin and others). This draws self.part (the model) (or some portion of it or none of it, depending on self.graphicsMode), with chunk & atom selection indicators, and graphicsMode-specific extras such as handles/rubberbands/labels (Draw_other). It draws (some of) the axes only when for_mouseover_highlighting is false. @note: this is used for both normal visible rendering, and finding candidate objects to be "selobj" for mouseover-highlighting. In the latter case, for_mouseover_highlighting = True tells us to skip some drawing. """ #bruce 090219, revised 090311 def prefunc(): if not for_mouseover_highlighting: self.graphicsMode.Draw_axes() # review: best place to do this? self.graphicsMode.Draw_other_before_model() def func(): # not always called (see _call_func_that_draws_model for details) self.graphicsMode.Draw_model() def postfunc(): self.graphicsMode.Draw_other() self._call_func_that_draws_model( func, prefunc = prefunc, postfunc = postfunc ) return def _whole_model_drawingset_change_indicator(self): """ #doc """ ## BUGS: # # The following implementation is not correct: # # - view changes are not taken into account, but need to affect # drawingsets due to frustum culling # # - doesn't include effect of visual preferences # (or PM settings implemented via env.prefs) # # (workaround for both: select something to update the display) # # Also, current code that uses this has bugs: # # - ignores necessary drawing not inside DrawingSets # - jigs, dna/protein styles, overlap indicators, atom sel wireframes, bond vanes... # - extra drawing by graphicsMode, e.g. expr handles, dna ribbons # - probably more # # So it is only used when a debug_pref is set. # Another comment or docstring has more info on purpose and status. # # [bruce 090309] res = self.part and \ (self.part, self.assy.model_change_indicator(), self.assy.selection_change_indicator(), self.displayMode, #bruce 090312 bugfix ) return res def _do_other_drawing_inside_stereo(self): #bruce 080919 split this out """ [might be misnamed -- does not (yet) do *all* other drawing currently done inside stereo] """ # highlight selobj if necessary, by drawing it again in highlighted # form (never inside fog). # It was already drawn normally, but we redraw it now for three reasons: # - it might be in a display list in non-highlighted form (and if so, # the above draw used that form); # - if fog is enabled, the above draw was inside fog; this one won't be; # - we need to draw it into the stencil buffer too, so subsequent calls # of self.graphicsMode.bareMotion event handlers can find out whether # the mouse is still over it, and avoid asking for hit-test again # if it was (probably an important optimization). selobj, hicolor = self._selobj_and_hicolor if selobj is not None: self._draw_highlighted_selobj(selobj, hicolor) # REVIEW: is it ok that the mode had to tell us selobj and hicolor # (and validate selobj) before drawing the model? # draw transparent things (e.g. Build Atoms water surface, # parts of Plane or ESPImage nodes) # [bruce 080919 bugfix: do this inside the stereo loop] self.call_Draw_after_highlighting(self.graphicsMode) return def call_Draw_after_highlighting(self, graphicsMode, pickCheckOnly = False): """ Call graphicsMode.Draw_after_highlighting() in the correct way (with appropriate drawing_phase), with exception protection, and return whatever it returns. Pass pickCheckOnly. @note: calls of this should be inside a stereo loop, to be correct. @note: event processing or drawing code should use this method to call graphicsMode.Draw_after_highlighting(), rather than calling it directly. But implementations of Draw_after_highlighting itself should call their superclass versions directly. """ # note: some existing calls of this are buggy since not in a stereo # loop. They are bad in other ways too. See comment there for more info. ### REVIEW: any need for _call_func_that_draws_model? I guess not now, # but revise if we ever want to use csdls with objects drawn by this, # in any GraphicsMode. [bruce 090219 comment] self.set_drawing_phase('main/Draw_after_highlighting') try: res = self.graphicsMode.Draw_after_highlighting( pickCheckOnly) # e.g. draws water surface in Build mode [###REVIEW: ok inside stereo loop?], # or transparent parts of ESPImage or Plane (must be inside stereo loop). # Note: this is called in the main model coordinate system # (perhaps modified for current stereo image), # just like self.graphicsMode.Draw_model, etc # [bruce 061208/080919 comment] except: res = None msg = "bug in %r.Draw_after_highlighting ignored" % (graphicsMode,) print_compact_traceback(msg + ": ") pass self.set_drawing_phase('?') return res def validate_selobj_and_hicolor(self): #bruce 070919 split this out, slightly revised behavior, and simplified code """ Return the selobj to use, and its highlight color (according to self.graphicsMode), after validating the graphicsmode says it's still ok and has a non-None hicolor. Return a tuple (selobj, hicolor) (with selobj and hicolor not None) or (None, None). """ selobj = self.selobj # we'll use this, or set it to None and use None if selobj is None: return None, None if not self.graphicsMode.selobj_still_ok(selobj): #bruce 070919 removed local exception-protection from this method call self.set_selobj(None) return None, None hicolor = self.selobj_hicolor(selobj) # ask the mode; protected from exceptions if hicolor is None: # the mode wants us to not use it. # REVIEW: is anything suboptimal about set_selobj(None) here, # like disabling the stencil buffer optim? # It might be better to retain self.selobj but not draw it in this case. # [bruce 070919 comment] self.set_selobj(None) return None, None # both selobj and hicolor are ok and not None return selobj, hicolor def selobj_hicolor(self, obj): """ If obj was to be highlighted as selobj (whether or not it's presently self.selobj), what would its highlight color be? Or return None if obj should not be allowed as selobj. """ try: hicolor = self.graphicsMode.selobj_highlight_color( obj) #e should implem noop version in basicMode [or maybe i did] # mode can decide whether selobj should be highlighted # (return None if not), and if so, in what color except: if debug_flags.atom_debug: msg = "atom_debug: selobj_highlight_color exception for %r" % (obj,) print_compact_traceback(msg + ": ") else: print "bug: selobj_highlight_color exception for %r; " \ "for details use ATOM_DEBUG" % (obj,) hicolor = None return hicolor def drawcompass(self): #bruce 080910 moved body into its own file #bruce 080912 removed aspect argument #bruce 081015 put constant parts into a display list (possible speedup), # and created class Compass to make this easier self.compass.draw( self.aspect, self.quat, self.compassPosition, self.graphicsMode.compass_moved_in_from_corner, env.prefs[displayCompassLabels_prefs_key] ) return pass # end of class # == if "test same_vals during import": #bruce 080922, of interest to GLPane_image_methods # note: we don't want to define this test in utilities.Comparison itself, # since it should not import geometry.VQT. REVIEW: move it into VQT? from utilities.Comparison import same_vals, SAMEVALS_SPEEDUP # not a full test, just look for known bugs and print warnings if found ALWAYS_PRINT = False used_version = SAMEVALS_SPEEDUP and "C" or "python" # no way to test the other version (see comment where same_vals is defined) from geometry.VQT import Q if not same_vals( Q(1,0,0,0), Q(1,0,0,0) ): # this bug was in the C version but not the Python version; # Eric M fixed it in samevalshelp.c rev 14311, 080922 print "BUG: not same_vals( Q(1,0,0,0), Q(1,0,0,0) ) [%s version]" % used_version elif ALWAYS_PRINT: print "fyi: same_vals( Q(1,0,0,0), Q(1,0,0,0) ) is True (correct) [%s version]" % used_version pass # end
NanoCAD-master
cad/src/graphics/widgets/GLPane_rendering_methods.py
# Copyright 2008 Nanorex, Inc. See LICENSE file for details. """ GLPane_frustum_methods.py @author: Piotr @version: $Id$ @copyright: 2008 Nanorex, Inc. See LICENSE file for details. History: piotr circa 080331 wrote these in GLPane.py bruce 080912 split this code into its own file Explanation of code: # The following comment comes from emails exchanged between Russ and Piotr # on 080403. # # This code is based on the information from OpenGL FAQ on clipping and culling: # http://www.opengl.org/resources/faq/technical/clipping.htm # # I tried to dust off the math behind it and I found the following paper # dealing with the homogeneous coordinates in great detail: # http://www.unchainedgeometry.com/jbloom/pdf/homog-coords.pdf # # The computations are in homogeneous coordinates, so every vertex is # represented by four coordinates (x,y,z,w). The composite matrix C (cmat # in the code) transforms a point from the Euclidean coordinates to the # homogeneous coordinates. # # Let's transform a point p(xp,yp,zp,wp) using the computed composite # matrix: # # C[4][4] (in 3D Euclidean space, wp = 1): # # r = p^T * C # # so we get a transformed point r(p*C0,p*C1,p*C2,p*C3), where Cx represents # a corresponding row of the matrix C. In homogeneous coordinates, if # the transformed point is inside the viewing frustum, the following # inequalities have to be true: # # -wr < xr < wr # -wr < yr < wr # -wr < zr < wr # # So if -wr < xr, the point p is on + side of the left frustum plane, # if xr < wr it is on + side of the right frustum plane, if -wr < yr, # the point is on + side of the bottom plane, and so on. Let's take the # left frustum plane: # # -wr < xr # # so: # # -p*C3 < p*C0 # # so: # # 0 < p*C0+p*C3 # # that is equal to: # # 0 < p*(C0+C3) # # which gives us the plane equation (ax+bx+cx+d=0): # # x*(C0[0]+C3[0]) + y*(C0[1]+C3[1]) + z*(C0[2]+C3[2]) + w(C0[3]+C3[3]) = 0 # # Because w = 1: # # x*(C0[0]+C3[0]) + y*(C0[1]+C3[1]) + z*(C0[2]+C3[2]) + (C0[3]+C3[3]) = 0 # # so the plane coefficients are as follows: # # a = C0[0] + C3[0] # b = C0[1] + C3[1] # c = C0[2] + C3[2] # d = C0[3] + C3[3] # # Similarly, for the right plane (xr < wr) we get: # # a = -C0[0] + C3[0] # b = -C0[1] + C3[1] # c = -C0[2] + C3[2] # d = -C0[3] + C3[3] # # and so on for every plane. """ import math from geometry.VQT import vlen from OpenGL.GL import GL_MODELVIEW_MATRIX from OpenGL.GL import GL_PROJECTION_MATRIX from OpenGL.GL import glGetFloatv class GLPane_frustum_methods(object): """ Private mixin superclass to provide frustum culling support to class GLPane. The main class needs to call these methods at appropriate times and use some attributes we maintain in appropriate ways. For documentation see the method docstrings and code comments. All our attribute names and method names contain the string 'frustum', making them easy to find by text-searching the main class source code. """ def _compute_frustum_planes(self): # Piotr 080331 """ Compute six planes to be used for frustum culling (assuming the use of that feature is enabled, which is up to the client code in the main class). Whenever the main class client code changes the projection matrix, it must either call this method, or set self._frustum_planes_available = False to turn off frustum culling. @note: this must only be called when the matrices are set up to do drawing in absolute model space coordinates. Callers which later change those matrices should review whether they need to set self._frustum_planes_available = False when they change them, to avoid erroneous culling. """ # Get current projection and modelview matrices pmat = glGetFloatv(GL_PROJECTION_MATRIX) mmat = glGetFloatv(GL_MODELVIEW_MATRIX) # Allocate a composite matrix float[4, 4] cmat = [None] * 4 for i in range(0, 4): cmat[i] = [0.0] * 4 # Compute a composite transformation matrix. # cmat = mmat * pmat for i in range(0, 4): for j in range (0, 4): cmat[i][j] = (mmat[i][0] * pmat[0][j] + mmat[i][1] * pmat[1][j] + mmat[i][2] * pmat[2][j] + mmat[i][3] * pmat[3][j]) # Allocate six frustum planes self.fplanes = [None] * 6 for p in range(0, 6): self.fplanes[p] = [0.0] * 4 # subtract and add the composite matrix rows to get the plane equations for p in range(0, 3): for i in range(0, 4): self.fplanes[2*p][i] = cmat[i][3] - cmat[i][p] self.fplanes[2*p+1][i] = cmat[i][3] + cmat[i][p] # normalize the plane normals for p in range(0, 6): n = math.sqrt(float(self.fplanes[p][0] * self.fplanes[p][0] + self.fplanes[p][1] * self.fplanes[p][1] + self.fplanes[p][2] * self.fplanes[p][2])) if n > 1e-8: self.fplanes[p][0] /= n self.fplanes[p][1] /= n self.fplanes[p][2] /= n self.fplanes[p][3] /= n # cause self.is_sphere_visible() to use these planes self._frustum_planes_available = True # [bruce 080331] return def is_sphere_visible(self, center, radius): # Piotr 080331 """ Perform a simple frustum culling test against a spherical object in absolute model space coordinates. Assume that the frustum planes are allocated, i.e. glpane._compute_frustum_planes was already called. (If it wasn't, the test will always succeed.) @warning: this will give incorrect results unless the current GL matrices are in the same state as when _compute_frustum_planes was last called (i.e. in absolute model space coordinates). """ ### uncomment the following line for the bounding sphere debug ### drawwiresphere(white, center, radius, 2) if self._frustum_planes_available: c0 = center[0] c1 = center[1] c2 = center[2] for p in range(0, 6): # go through all frustum planes # calculate a distance to the frustum plane 'p' # the sign corresponds to the plane normal direction # piotr 080801: getting the frustum plane equation # before performing the test gives about 30% performance # improvement fp = self.fplanes[p] dist = (fp[0] * c0 + fp[1] * c1 + fp[2] * c2 + fp[3]) # sphere outside of the plane - exit if dist < -radius: return False continue # At this point, the sphere might still be outside # of the box (e.g. if it is bigger than the box and a # box corner is close to the sphere and points towards it), # but this is an acceptable approximation for now # (since false positives are safe, and this will not affect # most chunks in typical uses where this is a speedup.) # [bruce 080331 comment] pass return True def is_lozenge_visible(self, pos1, pos2, radius): # piotr 080402 """ Perform a simple frustum culling test against a "lozenge" object in absolute model space coordinates. The lozenge is a cylinder with two hemispherical caps. Assume that the frustum planes are allocated, i.e. glpane._compute_frustum_planes was already called. (If it wasn't, the test will always succeed.) Currently, this is a loose (but correct) approximation which calls glpane.is_sphere_visible on the lozenge's bounding sphere. @warning: this will give incorrect results unless the current GL matrices are in the same state as when _compute_frustum_planes was last called (i.e. in absolute model space coordinates). """ if self._frustum_planes_available: center = 0.5 * (pos1 + pos2) sphere_radius = 0.5 * vlen(pos2 - pos1) + radius res = self.is_sphere_visible(center, sphere_radius) # Read Bruce's comment in glpane.is_sphere_visible # It applies here, as well. return res return True pass # end
NanoCAD-master
cad/src/graphics/widgets/GLPane_frustum_methods.py
""" This directory is for startup code. $Id$ Note: new startup functionality should be added to an appropriate file herein, but if possible, not to startup_before_most_imports.py. """
NanoCAD-master
cad/src/ne1_startup/__init__.py
# Copyright 2004-2008 Nanorex, Inc. See LICENSE file for details. """ startup_misc.py - miscellaneous application startup functions which are free to do whatever imports they need to. @version: $Id$ @copyright: 2004-2008 Nanorex, Inc. See LICENSE file for details. History: bruce 050902 made startup_funcs.py by moving some code out of main.py, and adding some stub functions which will be filled in later. bruce 071005 moved these functions from startup_funcs.py into this new file startup/startup_misc.py. """ # note: toplevel imports are now ok in this module [bruce 071008 change] from utilities.debug import print_compact_traceback def call_module_init_functions(): #bruce 071005 split this out of main_startup.startup_script """ Call the module initialize functions that are needed before creating the main window object. This includes functions that need to be called before model data structures can be safely created or modified. These functions can assume that the main application object exists. """ # [added by ericm 20070701, along with "remove import star", just after NE1 # A9.1 release, into main_startup.startup_script] # WARNING: the order of calling these matters, for many of them. We should document # that order dependency in their docstrings, and perhaps also right here. # One reason for order dependency is registration order of post_event_updater functions, # though this is mitigated now that we register model and ui updaters separately. # (We may decide to call those more directly here, not inside generic initialize methods, # as a clarification. Likely desirable change (###TODO): register a model updater in assy, # which calls the bond updater presently registered by bond_updater.initialize.) # [bruce 070925 comment] import model_updater.master_model_updater as master_model_updater master_model_updater.initialize() import model.assembly model.assembly.Assembly.initialize() import PM.GroupButtonMixin as GroupButtonMixin GroupButtonMixin.GroupButtonMixin.initialize() return def register_MMP_RecordParsers(): #bruce 071019 """ Register MMP_RecordParser subclasses for the model objects that can be read from mmp files, and whose parsers are not hardcoded into files_mmp.py. """ import model.Comment as Comment Comment.register_MMP_RecordParser_for_Comment() import analysis.GAMESS.jig_Gamess as jig_Gamess jig_Gamess.register_MMP_RecordParser_for_Gamess() import model.PovrayScene as PovrayScene PovrayScene.register_MMP_RecordParser_for_PovrayScene() try: import dna.model.DnaMarker as DnaMarker DnaMarker.register_MMP_RecordParser_for_DnaMarkers() except: print_compact_traceback("bug: ignoring exception in register_MMP_RecordParser_for_DnaMarkers: ") pass # TODO: add more of these. return # (MWsemantics.__init__ is presumably run after the above functions and before the following ones.) def pre_main_show( win): """ Do whatever should be done after the main window is created but before it's first shown. """ # Determine the screen resolution and compute the normal window size for NE-1 # [bruce 041230 corrected this for Macintosh, and made sure it never exceeds # screen size even on a very small screen.] # [bruce 050118 further modified this and removed some older comments # (see cvs for those); also split out some code into platform.py.] from platform_dependent.PlatformDependent import screen_pos_size ((x0, y0), (screen_w, screen_h)) = screen_pos_size() # note: y0 is nonzero on mac, due to menubar at top of screen. # use 85% of screen width and 90% of screen height, or more if that would be # less than 780 by 560 pixels, but never more than the available space. norm_w = int( min(screen_w - 2, max(780, screen_w * 0.85))) norm_h = int( min(screen_h - 2, max(560, screen_h * 0.90))) #bruce 050118 reduced max norm_h to never overlap mac menubar (bugfix?) # determine normal window origin # [bruce 041230 changed this to center it, but feel free to change this back # by changing the next line to center_it = 0] center_it = 1 if center_it: # centered in available area norm_x = (screen_w - norm_w) / 2 + x0 norm_y = (screen_h - norm_h) / 2 + y0 else: # at the given absolute position within the available area # (but moved towards (0,0) from that, if necessary to keep it all on-screen) want_x = 4 # Left (4 pixels) want_y = 36 # Top (36 pixels) norm_x = min( want_x, (screen_w - norm_w)) + x0 norm_y = min( want_y, (screen_h - norm_h)) + y0 # Set the main window geometry, hopefully before the caller shows the window from PyQt4.Qt import QRect win.setGeometry(QRect(norm_x, norm_y, norm_w, norm_h)) ###e it might be good to register this as the default geom. in the prefs system, and use that to implement "restore defaults" # After the above (whose side effects on main window geom. are used as defaults by the following code), # load any mainwindow geometry present in prefs db. [bruce 051218 new feature; see also new "save" features in UserPrefs.py] from utilities.debug import print_compact_stack try: # this code is similar to debug.py's _debug_load_window_layout from ne1_ui.prefs.Preferences import load_window_pos_size from utilities.prefs_constants import mainwindow_geometry_prefs_key_prefix keyprefix = mainwindow_geometry_prefs_key_prefix load_window_pos_size( win, keyprefix) win._ok_to_autosave_geometry_changes = True except: print_compact_stack("exception while loading/setting main window pos/size from prefs db: ") win.setGeometry(QRect(norm_x, norm_y, norm_w, norm_h)) _initialize_custom_display_modes(win) ### TODO: this would be a good place to add miscellaneous commands to the UI, # provided they are fully supported (not experimental, unlikely to cause bugs when added) # and won't take a lot of runtime to add. Otherwise they can be added after the # main window is shown. [bruce 071005 comment] ###@@@ return # from pre_main_show # This is debugging code used to find out the origin and size of the fullscreen window # foo = win # foo.setGeometry(QRect(600,50,1000,800)) # KEEP FOR DEBUGGING # fooge = QRect(foo.geometry()) # print "Window origin = ",fooge.left(),",",fooge.top() # print "Window width =",fooge.width(),", Window height =",fooge.height() def _initialize_custom_display_modes(win): # note (kluge): the following imports do side effects whose order matters. # They must match the order of related display style list-index definitions # in constants.py. # [bruce 080212 comment; related code has comments with same signature] # diDNACYLINDER import graphics.display_styles.DnaCylinderChunks as DnaCylinderChunks #mark 2008-02-11 # diCYLINDER import graphics.display_styles.CylinderChunks as CylinderChunks #bruce 060609 from utilities.debug_prefs import debug_pref, Choice_boolean_False enable_CylinderChunks = debug_pref("enable CylinderChunks next session?", Choice_boolean_False, non_debug = True, prefs_key = True) win.dispCylinderAction.setText("Cylinder (experimental)") win.dispCylinderAction.setEnabled(enable_CylinderChunks) win.dispCylinderAction.setVisible(enable_CylinderChunks) if enable_CylinderChunks: win.displayStylesToolBar.addAction(win.dispCylinderAction) # diSURFACE import graphics.display_styles.SurfaceChunks as SurfaceChunks #mark 060610 enable_SurfaceChunks = debug_pref("enable SurfaceChunks next session?", Choice_boolean_False, ## non_debug = True, # bruce 080416 hiding this since it's # broken at the moment when CSDL is # enabled and psurface.so is not found. # If/when it's fixed, it should be # made visible again. prefs_key = True) win.dispSurfaceAction.setText("Surface (experimental, may be slow)") win.dispSurfaceAction.setEnabled(enable_SurfaceChunks) win.dispSurfaceAction.setVisible(enable_SurfaceChunks) if enable_SurfaceChunks: win.displayStylesToolBar.addAction(win.dispSurfaceAction) # diPROTEIN display style # piotr 080624 import graphics.display_styles.ProteinChunks as ProteinChunks return # == def post_main_show( win): """ Do whatever should be done after the main window is shown, but before the Qt event loop is started. @param win: the single Main Window object. @type win: L{MWsemantics} """ # NOTE: if possible, new code should be added into one of the following # functions, or into a new function called by this one, rather than # directly into this function. # TODO: rebuild pyx modules if necessary and safe -- but only for # developers, not end-users # TODO: initialize Python extensions: ## import experimental/pyrex_test/extensions.py _initialize_plugin_generators() _init_experimental_commands() _init_miscellaneous_commands() # Set default splitter position in the part window. pw = win.activePartWindow() pw.setSplitterPosition() return def _init_experimental_commands(): """ Initialize experimental commands in the UI. This is called after the main window is shown. """ # Note: if you are not sure where to add init code for a new command in # the UI, this is one possible place. But if it's more complicated than # importing and calling an initialize function, it's best if the # complicated part is defined in some other module and just called from # here. See also the other places from which initialize functions are # called, for other places that might be better for adding new command # initializers. This place is mainly for experimental or slow-to-initialize # commands. # [bruce 071005] _init_command_Atom_Generator() _init_command_Select_Bad_Atoms() _init_command_Peptide_Generator() # piotr 080304 _init_test_commands() return def _init_command_Atom_Generator(): # TODO: this function should be moved into AtomGenerator.py # Atom Generator debug pref. Mark and Jeff. 2007-06-13 from utilities.debug_prefs import debug_pref, Choice_boolean_False from commands.BuildAtom.AtomGenerator import enableAtomGenerator _atomGeneratorIsEnabled = \ debug_pref("Atom Generator example code: enabled?", Choice_boolean_False, non_debug = True, prefs_key = "A9/Atom Generator Visible", call_with_new_value = enableAtomGenerator ) enableAtomGenerator(_atomGeneratorIsEnabled) return def _init_command_Peptide_Generator(): # piotr 080304 # This function enables an experimental peptide generator. from utilities.debug_prefs import debug_pref, Choice_boolean_True from protein.commands.InsertPeptide.PeptideGenerator import enablePeptideGenerator _peptideGeneratorIsEnabled = \ debug_pref("Peptide Generator: enabled?", Choice_boolean_True, prefs_key = "A10/Peptide Generator Visible", call_with_new_value = enablePeptideGenerator ) enablePeptideGenerator(_peptideGeneratorIsEnabled) return def _init_command_Select_Bad_Atoms(): # note: I think this was imported at one point # (which initialized it), and then got left out of the startup code # by mistake for awhile, when init code was revised. [bruce 071008] import operations.chem_patterns as chem_patterns chem_patterns.initialize() return def _init_test_commands(): #bruce 070613 from utilities.debug_prefs import debug_pref, Choice_boolean_False if debug_pref("test_commands enabled (next session)", Choice_boolean_False, prefs_key = True): import prototype.test_commands_init as test_commands_init test_commands_init.initialize() return def _init_miscellaneous_commands(): import model.virtual_site_indicators as virtual_site_indicators virtual_site_indicators.initialize() #bruce 080519 import operations.ops_debug as ops_debug ops_debug.initialize() #bruce 080722 return def _initialize_plugin_generators(): #bruce 060621 # The CoNTub generator isn't working - commented out until it's fixed. # Brian Helfrich, 2007/06/04 # (see also some related code in main_startup.py) pass #import CoNTubGenerator # note: this adds the Insert -> Heterojunction menu item. # kluge (sorry): as of 060621, it adds it at a hardcoded menu index. def just_before_event_loop(): """ do post-startup, pre-event-loop, non-profiled things, if any (such as run optional startup commands for debugging) """ #bruce 081003 from utilities.debug_prefs import debug_pref, Choice_boolean_False if debug_pref("startup in Test Graphics command (next session)?", Choice_boolean_False, prefs_key = True ): import foundation.env as env win = env.mainwindow() from commands.TestGraphics.TestGraphics_Command import enter_TestGraphics_Command_at_startup enter_TestGraphics_Command_at_startup( win) pass return # end
NanoCAD-master
cad/src/ne1_startup/startup_misc.py
# Copyright 2004-2008 Nanorex, Inc. See LICENSE file for details. """ startup_before_most_imports.py - some application startup functions which need to be run before most imports are done, and which therefore need to be careful about doing imports themselves. @version: $Id$ @copyright: 2004-2008 Nanorex, Inc. See LICENSE file for details. History: bruce 050902 made startup_funcs.py by moving some code out of main.py, and adding some stub functions which will be filled in later. bruce 071005 moved these functions from startup_funcs.py into this new file startup/startup_before_most_imports.py. """ import sys, os import utilities.EndUser as EndUser # NOTE: this module (or EndUser) must not do toplevel imports of our other # source modules, because it contains functions which need to be called # by main_startup before most imports are done. def before_most_imports( main_globals ): """ Do things that should be done before most imports occur. main_globals should be the value of globals() in the __main__ module. """ # user-specific debug code to be run before any other imports [bruce 040903] # gpl_only check at startup [bruce 041217] try: import platform_dependent.gpl_only as _gpl_only # if this module is there, this lets it verify it should be there, # and if not, complain (to developers) whenever the program starts print "(running a GPL distribution)" #e retain or zap this? except ImportError: print "(running a non-GPL distribution)" #e retain or zap this? [should never happen for Qt4, as of 070425] pass # this is normal for non-GPL distributions try: rc = "~/.atom-debug-rc" rc = os.path.expanduser(rc) if os.path.exists(rc): ## execfile(rc) -- not allowed! import utilities.debug as _debug _debug.legally_execfile_in_globals(rc, main_globals, error_exception = False) # might fail in non-GPL versions; prints error message but # does not raise an exception. # (doing it like this is required by our licenses for Qt/PyQt) except: print """exception in execfile(%r); traceback printed to stderr or console; exiting""" % (rc,) raise # Figure out whether we're run by a developer from cvs sources # (EndUser.enableDeveloperFeatures() returns True), or by an # end-user from an installer-created program (it returns False). # Use two methods, warn if they disagree, and if either one # think's we're an end user, assume we are (so as to turn off # certain code it might not be safe for end-users to run). # [bruce 050902 new feature; revised 051006 to work in Windows # built packages] # [Russ 080905: Fixed after this file moved into ne1_startup. # bruce 080905 slightly revised that fix. # Note: see also NE1_Build_Constants.py, which has constants # that might be useable for this.] _OUR_PACKAGE = "ne1_startup" # should be this file's package inside cad/src # todo: this could be derived entirely from __name__. our_basename = __name__.split('.')[-1] # e.g. startup_before_most_imports assert _OUR_PACKAGE == __name__.split('.')[-2], \ "need to revise this code for moved file" # this will fail if _OUR_PACKAGE has more than one component, or no # components; that's intentional, since some of the code below would # also fail in that case. If it fails, generalize this and that code. # Method 1. As of 050902, package builders on all platforms reportedly move main.py # (the __main__ script) into a higher directory than the compiled python files. # But developers running from cvs leave them all in cad/src. # So we compare the directories. endUser = True # conservative initial assumption (might be changed below) import __main__ ourdir = None # hack for print statement test in except clause # this is still being imported, but we only need its __file__ attribute, which should be already defined [but see below] try: # It turns out that for Windows (at least) package builds, __main__.__file__ is either never defined or not yet # defined at this point, so we have no choice but to silently guess endUser = True in that case. I don't know whether # this module's __file__ is defined, whether this problem is Windows-specific, etc. What's worse, this problem disables # *both* guessing methods, so on an exception we just have to skip the whole thing. Further study might show that there is # no problem with ourdir, only with maindir, but I won't force us to test that right now. [bruce 051006] # REVIEW: is this still correct now that this code is in a non-toplevel module? [bruce 080111 question] ourdir = os.path.split(__file__)[0] maindir = os.path.split(__main__.__file__)[0] except: # unfortunately it's not ok to print the exception or any error message, in case endUser = True is correct... # but maybe I can get away with printing something cryptic (since our code is known to print things sometimes anyway)? # And I can make it depend on whether ourdir was set, so we have a chance of finding out whether this module defined __file__. # [bruce 051006] if ourdir is not None: print "end-user build" else: print "end user build" # different text -- no '-' else: # we set maindir and ourdir; try both guess-methods, etc def canon(path): #bruce 050908 bugfix in case developer runs python with relative (or other non-canonical) path as argument return os.path.normcase(os.path.abspath(path)) maindir = canon(maindir) ourdir = canon(ourdir) guess1 = (os.path.join(maindir, _OUR_PACKAGE) != ourdir) # Russ 080905: Loaded from package subdirectory. # Method 2. As of 050902, package builders on all platforms remove the .py files, leaving only .pyc files. guess2 = not os.path.exists(os.path.join(ourdir, our_basename + ".py")) endUser = guess1 or guess2 if EndUser.getAlternateSourcePath() != None: # special case when using ALTERNATE_CAD_SRC_PATH feature # (which can cause these guesses to differ or be incorrect): # assume anyone using it is a developer [bruce 070704] endUser = False else: if guess1 != guess2: print "Warning: two methods of guessing whether we're being run by an end-user disagreed (%r and %r)." % (guess1, guess2) print "To be safe, assuming we are (disabling some developer-only features)." print "If this ever happens, it's a bug, and the methods need to be updated." if guess1: print "(debug info: guess1 is true because %r != %r)" % (maindir, ourdir) #bruce 050908 to debug Linux bug in guess1 reported by Ninad (it's True (i.e. wrong) when he runs nE-1 from source) print pass EndUser.setDeveloperFeatures(not endUser) if EndUser.enableDeveloperFeatures(): print "enabling developer features" # The actual enabling is done by other code which checks the value of EndUser.enableDeveloperFeatures(). # Note: most code should NOT behave differently based on that value! # (Doing so might cause bugs to exist in the end-user version but not the developer version, # which would make them very hard to notice or debug. This risk is only justified in a few # special cases.) return # from before_most_imports def before_creating_app(): """ Do other things that should be done before creating the application object. """ # the default (1000) bombs with large molecules sys.setrecursionlimit(5000) # cause subsequent signal->slot connections to be wrapped for undo support # (see comment in caller about whether this could be moved later in caller # due to the imports it requires) import foundation.undo_internals as undo_internals undo_internals.call_asap_after_QWidget_and_platform_imports_are_ok() #bruce 050917 return # end
NanoCAD-master
cad/src/ne1_startup/startup_before_most_imports.py
# Copyright 2004-2008 Nanorex, Inc. See LICENSE file for details. """ main_startup.py -- provides the startup_script function called by main.py @version: $Id$ @copyright: 2004-2008 Nanorex, Inc. See LICENSE file for details. History: mostly unrecorded, except in cvs; originally by Josh (under the name atom.py); lots of changes by various developers at various times. renamed from atom.py to main.py before release of A9, mid-2007, and split out of main.py into this file (main_startup.py) by bruce 070704. """ import sys import time import os import NE1_Build_Constants # Note -- Logic in startup_before_most_imports depends on its load location. # If you move it, fix the endUser code in before_most_imports(). from ne1_startup import startup_before_most_imports # NOTE: all other imports MUST be added inside the following function, # since they must not be done before startup_before_most_imports.before_most_imports is executed. def startup_script( main_globals): """ This is the main startup script for NE1. It is intended to be run only once, and only by the code in main.py. When this function returns, the caller is intended to immediately exit normally. Parameter main_globals should be the value of globals() in __main__, which is needed in case .atom-debug-rc is executed, since it must be executed in that global namespace. """ # Note: importing all of NE1's functionality can take a long time. # To the extent possible, we want that time to be spent after # something is visible to the user, but (mostly) before the main # window is shown to the user (since showing the main window implies # that NE1 is almost ready to go). So we display a splashscreen # before doing most imports and initializations, then set up most # of our data structures and UI commands (thus importing the code # needed to implement them), and then show the main window. # (Some experimental commands are initialized after that, so that # errors that occur then can't prevent the main window from becoming # visible.) # TODO: turn the sections of code below into named functions or methods, # and perhaps split before_most_imports and before_creating_app into # more named functions or methods. The biggest split should be between # functions that need to be careful to do very few or no imports, # and functions that are free to do any imports. # Windows machines spawn and remove the shell, so no info is normally # captured. This is a first attempt to try to capture some of the console # prints that would normally be lost. The default for this code is that # it's turned off, and should remain that way until it's improved. if NE1_Build_Constants.NE1_CONSOLE_REDIRECT and os.name == "nt": capture_console = False capture_file = "" # if it's not reporting as python is the executable if not sys.executable.upper().endswith("PYTHON.EXE") and \ not sys.executable.upper().endswith("PYTHON"): try: capture_file = u"".join((sys.executable[:-4], "_console.log")) sys.stdout = open(capture_file, 'w') capture_console = True # already trapped, don't try more. except: pass if not capture_console: # Haven't captured the console log yet. Find the default user # path and try to capture there this happens if we can't write to # the normal log location, or if python.exe is the executable. tmpFilePath = os.path.normpath(os.path.expanduser("~/Nanorex/")) if not os.path.exists(tmpFilePath): #If it doesn't exist try: os.mkdir(tmpFilePath) #Try making one capture_console = True except: pass # we tried, but there's no easy way to capture the console if capture_console or os.path.isdir(tmpFilePath): try: # We made the directory or it already existed, try # creating the log file. capture_file = os.path.normpath(u"".join((tmpFilePath, \ "/NE1_console.log"))) sys.stdout = open(capture_file, 'w') capture_console = True except: print >> sys.__stderr__, \ "Failed to create any console log file." capture_console = False if capture_console: # Next two lines are specifically printed to the original console print >> sys.__stdout__, "The console has been redirected into:" print >> sys.__stdout__, capture_file.encode("utf_8") print print "starting NanoEngineer-1 in [%s]," % os.getcwd(), time.asctime() print "using Python: " + sys.version try: print "on path: " + sys.executable except: pass # print the version information including official release candidate if it # is not 0 (false) if NE1_Build_Constants.NE1_OFFICIAL_RELEASE_CANDIDATE: print "Version: NanoEngineer-1 v%s_RC%s" % \ (NE1_Build_Constants.NE1_RELEASE_VERSION, \ NE1_Build_Constants.NE1_OFFICIAL_RELEASE_CANDIDATE) else: print "Version: NanoEngineer-1 v%s" % \ NE1_Build_Constants.NE1_RELEASE_VERSION # "Do things that should be done before most imports occur." startup_before_most_imports.before_most_imports( main_globals ) from PyQt4.Qt import QApplication, QSplashScreen # "Do things that should be done before creating the application object." startup_before_most_imports.before_creating_app() ### TODO: this imports undo, env, debug, and it got moved earlier # in the startup process at some point. Those imports are probably not # too likely to pull in a lot of others, but if possible we should put up # the splash screen before doing most of them. Sometime try to figure out # how to do that. The point of this function is mostly to wrap every signal->slot # connection -- maybe it's sufficient to do that before creating the main # window rather than before creating the app? [bruce 071008 comment] # do some imports used for putting up splashscreen # (this must be done before any code that loads images from cad/src/ui) import utilities.icon_utilities as icon_utilities icon_utilities.initialize_icon_utilities() # Create the application object (an instance of QApplication). QApplication.setColorSpec(QApplication.CustomColor) #russ 080505: Make it global so it can be run under debugging below. global app app = QApplication(sys.argv) # Put up the splashscreen (if its image file can be found in cad/images). # # Note for developers: # If you don't want the splashscreen, just rename the splash image file. splash_pixmap = icon_utilities.imagename_to_pixmap( "images/splash.png" ) # splash_pixmap will be null if the image file was not found if not splash_pixmap.isNull(): splash = QSplashScreen(splash_pixmap) # create the splashscreen splash.show() MINIMUM_SPLASH_TIME = 3.0 # I intend to add a user pref for MINIMUM_SPLASH_TIME for A7. mark 060131. splash_start = time.time() else: print "note: splash.png was not found" # connect the lastWindowClosed signal from PyQt4.Qt import SIGNAL app.connect(app, SIGNAL("lastWindowClosed ()"), app.quit) # NOTE: At this point, it is ok to do arbitrary imports as needed, # except of experimental code. # import MWsemantics. # An old comment (I don't know if it's still true -- bruce 071008): # this might have side effects other than defining things. from ne1_ui.MWsemantics import MWsemantics # initialize modules and data structures from ne1_startup import startup_misc # do this here, not earlier, so it's free to do whatever toplevel imports it wants # [bruce 071008 change] startup_misc.call_module_init_functions() startup_misc.register_MMP_RecordParsers() # do this before reading any mmp files # create the single main window object foo = MWsemantics() # This does a lot of initialization (in MainWindow.__init__) import __main__ __main__.foo = foo # developers often access the main window object using __main__.foo when debugging, # so this is explicitly supported # initialize CoNTubGenerator # TODO: move this into one of the other initialization functions #Disabling the following code that initializes the ConTub plugin #(in UI it is called Heterojunction.) The Heterojunction generator or #ConTubGenerator was never ported to Qt4 platform. The plugin generator #needs a code cleanup -- ninad 2007-11-16 ##import CoNTubGenerator ##CoNTubGenerator.initialize() # for developers: run a hook function that .atom-debug-rc might have defined # in this module's global namespace, for doing things *before* showing the # main window. try: # do this, if user asked us to by defining it in .atom-debug-rc func = atom_debug_pre_main_show except NameError: pass else: func() # Do other things that should be done just before showing the main window startup_misc.pre_main_show(foo) # this sets foo's geometry, among other things foo._init_after_geometry_is_set() if not splash_pixmap.isNull(): # If the MINIMUM_SPLASH_TIME duration has not expired, sleep for a moment. while time.time() - splash_start < MINIMUM_SPLASH_TIME: time.sleep(0.1) splash.finish( foo ) # Take away the splashscreen # show the main window foo.show() # for developers: run a hook function that .atom-debug-rc might have defined # in this module's global namespace, for doing things *after* showing the # main window. try: # do this, if user asked us to by defining it in .atom-debug-rc func = atom_debug_post_main_show except NameError: pass else: func() # do other things after showing the main window startup_misc.post_main_show(foo) # start psyco runtime optimizer (EXPERIMENTAL) -- # for doc see http://psyco.sourceforge.net/ # # Example: it speeds up code like this by 17 times: # (in my test, Intel Mac OS 10.4, Python 2.4.4) # x = 17 # for i in range(10**7): # x += i % 3 - 1 # # [bruce 080524] from utilities.debug_prefs import debug_pref, Choice_boolean_False if debug_pref("Use psyco runtime optimizer (next session)?", Choice_boolean_False, prefs_key = True ): # Import Psyco if available try: import psyco ## psyco.full() -- insert dna takes a lot of time, then segfaults # after printing "inside this what's this"; # plan: be more conservative about what it should optimize... # preferably bind specific functions using psyco.bind(). # For now, just tell it to only optimize the most important ones. psyco.log() # manual says: log file name looks like xxx.log-psyco # by default, where xxx is the name of the script you ran # (when I ran "python main.py" in cad/src, it wrote to main.log-psyco there) # (maybe we can pass our own pathname as an argument?) ## psyco.profile(0.2) # use profiling, optimize funcs that use # more than 20% of the time (not sure what that means exactly) # (seems safe, but from log file, i guess it doesn't do much) psyco.profile(0.05) # "aggressive" print "using psyco" pass except ImportError: print "not using psyco" pass pass # Decide whether to do profiling, and if so, with which # profiling command and into what file. Set local variables # to record the decision, which are used later when running # the Qt event loop. # If the user's .atom-debug-rc specifies PROFILE_WITH_HOTSHOT = True, # use hotshot, otherwise fall back to vanilla Python profiler. # (Note: to work, it probably has to import this module # and set this variable in this module's namespace.) try: PROFILE_WITH_HOTSHOT except NameError: PROFILE_WITH_HOTSHOT = False try: # user can set atom_debug_profile_filename to a filename in .atom-debug-rc, # to enable profiling into that file. For example: # % cd # % cat > .atom-debug-rc # atom_debug_profile_filename = '/tmp/profile-output' # ^D # ... then run NE1, and quit it # ... then in a python shell: # import pstats # p = pstats.Stats('<filename>') # p.strip_dirs().sort_stats('time').print_stats(100) # order by internal time (top 100 functions) # p.strip_dirs().sort_stats('cumulative').print_stats(100) # order by cumulative time atom_debug_profile_filename = main_globals.get('atom_debug_profile_filename') if atom_debug_profile_filename: print ("\nUser's .atom-debug-rc requests profiling into file %r" % (atom_debug_profile_filename,)) if not type(atom_debug_profile_filename) in [type("x"), type(u"x")]: print "error: atom_debug_profile_filename must be a string" assert 0 # caught and ignored, turns off profiling if PROFILE_WITH_HOTSHOT: try: import hotshot except: print "error during 'import hotshot'" raise # caught and ignored, turns off profiling else: try: import cProfile as py_Profile except ImportError: print "Unable to import cProfile. Using profile module instead." py_Profile = None if py_Profile is None: try: import profile as py_Profile except: print "error during 'import profile'" raise # caught and ignored, turns off profiling except: print "exception setting up profiling (hopefully reported above); running without profiling" atom_debug_profile_filename = None # Create a fake "current exception", to help with debugging # (in case it's shown inappropriately in a later traceback). # One time this is seen is if a developer inserts a call to print_compact_traceback # when no exception is being handled (instead of the intended print_compact_stack). try: assert 0, "if you see this exception in a traceback, it is from the" \ " startup script called by main.py, not the code that printed the traceback" except: pass # Handle a mmp file passed to it via the command line. The mmp file # must be the first argument (after the program name) found on the # command line. All other arguments are currently ignored and only # one mmp file can be loaded from the command line. # old revision with --initial-file is at: svn rev 12759 # Derrick 20080520 if ((len(sys.argv) >= 2) and sys.argv[1].endswith(".mmp")): foo.fileOpen(sys.argv[1]) # Do other post-startup, pre-event-loop, non-profiled things, if any # (such as run optional startup commands for debugging). startup_misc.just_before_event_loop() if os.environ.has_key('WINGDB_ACTIVE'): # Hack to burn some Python bytecode periodically so Wing's # debugger can remain responsive while free-running # [from http://wingware.com/doc/howtos/pyqt; added by bruce 081227] # Addendum [bruce 090107]: this timer doesn't noticeably slow down NE1, # but with or without it, NE1 is about 4x slower in Wing than running # alone, at least when running test_selection_redraw.py. print "running under Wing IDE debugger; setting up timer" from PyQt4 import QtCore timer = QtCore.QTimer() def donothing(*args): x = 0 for i in range(0, 100): x += i timer.connect(timer, QtCore.SIGNAL("timeout()"), donothing) timer.start(200) # Finally, run the main Qt event loop -- # perhaps with profiling, depending on local variables set above. # This does not normally return until the user asks NE1 to exit. # Note that there are three copies of the statement which runs that loop, # two inside string literals, all of which presumably should be the same. if atom_debug_profile_filename: if PROFILE_WITH_HOTSHOT: profile = hotshot.Profile(atom_debug_profile_filename) profile.run('app.exec_()') else: py_Profile.run('from ne1_startup.main_startup import app; app.exec_()', atom_debug_profile_filename) print ("\nProfile data was presumably saved into %r" % (atom_debug_profile_filename,)) else: # if you change this code, also change both string literals just above app.exec_() # Now return to the caller in order to do a normal immediate exit of NE1. return # from startup_script # end
NanoCAD-master
cad/src/ne1_startup/main_startup.py
# Copyright 2004-2008 Nanorex, Inc. See LICENSE file for details. """ widgets.py - helpers related to widgets, and some simple custom widgets. @author: Mark, Ninad, perhaps others @version: $Id$ @copyright: 2004-2008 Nanorex, Inc. See LICENSE file for details. TODO: Probably should be split into a few modules (e.g. has several color-related helpers). [bruce 080203 has done some of this splitting but not all. I moved some of it into undo_manager, some into a new module menu_helpers, and some into an outtakes file "old_extrude_widgets.py".] In the meantime we might rename it to widget_helpers.py. """ from PyQt4 import QtGui from PyQt4.Qt import QDialog from PyQt4.Qt import QVBoxLayout from PyQt4.Qt import SIGNAL from PyQt4.Qt import QString from PyQt4.Qt import QValidator from PyQt4.Qt import QColor from PyQt4.Qt import QTextEdit from PyQt4.Qt import QPushButton from PyQt4.Qt import QSize from PyQt4.Qt import QMessageBox from utilities.qt4transition import qt4todo # == def double_fixup(validator, text, prevtext): """ Returns a string that represents a float which meets the requirements of validator. text is the input string to be checked, prevtext is returned if text is not valid. """ r, c = validator.validate(QString(text), 0) if r == QValidator.Invalid: return prevtext elif r == QValidator.Intermediate: if len(text) == 0: return "" return prevtext else: return text # == # bruce 050614 [comment revised 050805] found colorchoose as a method in MWsemantics.py, nowhere used, # so I moved it here for possible renovation and use. # See also some color utilities in debug_prefs.py and prefs_widgets.py. # Maybe some of them should all go into a new file specifically for colors. #e def colorchoose(self, r, g, b): """ #doc -- note that the args r,g,b should be ints, but the retval is a 3-tuple of floats. (Sorry, that's how I found it.) """ # r, g, b is the default color displayed in the QColorDialog window. from PyQt4.Qt import QColorDialog color = QColorDialog.getColor(QColor(r, g, b), self, "choose") #k what does "choose" mean? if color.isValid(): return color.red()/255.0, color.green()/255.0, color.blue()/255.0 else: return r/255.0, g/255.0, b/255.0 # returning None might be more useful, since it lets callers "not change anything" pass def RGBf_to_QColor(fcolor): # by Mark 050730 """ Converts RGB float to QColor. """ # moved here by bruce 050805 since it requires QColor and is only useful with Qt widgets r = int (fcolor[0]*255 + 0.5) # (same formula as in elementSelector.py) g = int (fcolor[1]*255 + 0.5) b = int (fcolor[2]*255 + 0.5) return QColor(r, g, b) def QColor_to_RGBf(qcolor): # by Mark 050921 """ Converts QColor to RGB float. """ return qcolor.red()/255.0, qcolor.green()/255.0, qcolor.blue()/255.0 def QColor_to_Hex(qcolor): # by Mark 050921 """ Converts QColor to a hex color string. For example, a QColor of blue (0, 0, 255) returns "0000FF". """ return "%02X%02X%02X" % (qcolor.red(), qcolor.green(), qcolor.blue()) def get_widget_with_color_palette(frame, color): """ Return the widget <frame> after setting its palette based on <color> (a QColor provided by the user). """ #ninad070502: This is used in many dialogs which show a colored frame #that represents the current color of the object in the glpane. #Example, in Rotary motor prop dialog, you will find a colored frame #that shows the present color of the rotary motor. frame.setAutoFillBackground(True) plt = QtGui.QPalette() plt.setColor(QtGui.QPalette.Active, QtGui.QPalette.Window, color) plt.setColor(QtGui.QPalette.Inactive, QtGui.QPalette.Window, color) plt.setColor(QtGui.QPalette.Disabled, QtGui.QPalette.Window, color) frame.setPalette(plt) return frame # == class TextMessageBox(QDialog): """ The TextMessageBox class provides a modal dialog with a textedit widget and a close button. It is used as an option to QMessageBox when displaying a large amount of text. It also has the benefit of allowing the user to copy and paste the text from the textedit widget. Call the setText() method to insert text into the textedit widget. """ def __init__(self, parent = None, name = None, modal = 1, fl = 0): #QDialog.__init__(self,parent,name,modal,fl) QDialog.__init__(self,parent) self.setModal(modal) qt4todo("handle flags in TextMessageBox.__init__") if name is None: name = "TextMessageBox" self.setObjectName(name) self.setWindowTitle(name) TextMessageLayout = QVBoxLayout(self) TextMessageLayout.setMargin(5) TextMessageLayout.setSpacing(1) self.text_edit = QTextEdit(self) TextMessageLayout.addWidget(self.text_edit) self.close_button = QPushButton(self) self.close_button.setText("Close") TextMessageLayout.addWidget(self.close_button) self.resize(QSize(350, 300).expandedTo(self.minimumSizeHint())) # Width changed from 300 to 350. Now hscrollbar doesn't appear in # Help > Graphics Info textbox. mark 060322 qt4todo('self.clearWState(Qt.WState_Polished)') # what is this? self.connect(self.close_button, SIGNAL("clicked()"),self.close) def setText(self, txt): """ Sets the textedit's text to txt """ self.text_edit.setPlainText(txt) pass #== def PleaseConfirmMsgBox(text = 'Please Confirm.'): # mark 060302. """ Prompts the user to confirm/cancel by pressing a 'Confirm' or 'Cancel' button in a QMessageBox. <text> is the confirmation string to explain what the user is confirming. Returns: True - if the user pressed the Confirm button False - if the user pressed the Cancel button (or Enter, Return or Escape) """ ret = QMessageBox.warning( None, "Please Confirm", str(text) + "\n", "Confirm", "Cancel", "", 1, # The "default" button, when user presses Enter or Return (1 = Cancel) 1) # Escape (1= Cancel) if ret == 0: return True # Confirmed else: return False # Cancelled # end
NanoCAD-master
cad/src/widgets/widget_helpers.py
# Copyright 2004-2009 Nanorex, Inc. See LICENSE file for details. """ Mixin class to help some of our widgets offer a debug menu. @version: $Id$ @copyright: 2004-2009 Nanorex, Inc. See LICENSE file for details. Needs refactoring: [bruce 080104] - to move the global variable (sim_params_set) elsewhere (and maybe a lot of the surrounding code too -- I didn't analyze it) - maybe to permit or require host widget to supply some items -- see classification comment below. Module classification: [bruce 080104] Essentially this is a "widget helper" to let a widget provide a "standard debug menu". It also includes a lot of the specific menu items and their implementations, even some that only work in some widgets. For now I'll classify it in "widgets" due to its widget helper role. Ideally we'd refactor it in such a way that that was completely accurate (moving the rest into the specific widgets or into other modules which register items for general use in this menu). """ import sys import time from PyQt4.Qt import QDialog, QGridLayout, QLabel, QPushButton, QLineEdit, SIGNAL from PyQt4.Qt import QFontDialog, QInputDialog import foundation.env as env from utilities import debug_flags import utilities.debug as debug import utilities.debug_prefs as debug_prefs from ne1_ui.prefs.Preferences import save_window_pos_size, load_window_pos_size from utilities.prefs_constants import mainwindow_geometry_prefs_key_prefix from utilities.debug import registered_commands_menuspec from utilities.debug import print_compact_traceback from utilities.debug import debug_timing_test_pycode_from_a_dialog from utilities.debug import debug_run_command from utilities.constants import debugModifiers from utilities.constants import noop from time import clock from utilities.debug import profile_single_call_if_enabled, set_enabled_for_profile_single_call from widgets.simple_dialogs import grab_text_line_using_dialog # enable the undocumented debug menu by default [bruce 040920] # (moved here from GLPane, now applies to all widgets using DebugMenuMixin [bruce 050112]) debug_menu_enabled = 1 debug_events = 0 # set this to 1 to print info about many mouse events # this can probably be made a method on DebugMenuMixin def debug_runpycode_from_a_dialog( source = "some debug menu??"): # TODO: rewrite this to call grab_text_using_dialog (should be easy) title = "debug: run py code" label = "one line of python to exec in debug.py's globals()\n(or use @@@ to fake \\n for more lines)\n(or use execfile)" parent = None #bruce 070329 Qt4 bugfix -- in Qt4 a new first argument (parent) is needed by QInputDialog.getText. # [FYI, for a useful reference to QInputDialog with lots of extra info, see # http://www.bessrc.aps.anl.gov/software/qt4-x11-4.2.2-browser/d9/dcb/class_q_input_dialog.html ] text, ok = QInputDialog.getText(parent, title, label) if ok: # fyi: type(text) == <class '__main__.qt.QString'> command = str(text) command = command.replace("@@@",'\n') debug_run_command(command, source = source) else: print "run py code: cancelled" return class DebugMenuMixin: """ Helps widgets have the "standard undocumented debug menu". Provides some methods and attrs to its subclasses, all starting debug or _debug, especially self.debug_event(). Caller of _init1 should provide main window win, or [temporary kluge?] let this be found at self.win; some menu items affect it or emit history messages to it. [As of 050913 they should (and probably do) no longer use win for history, but use env.history instead.] """ #doc better #e rename private attrs to start with '_debug' instead of 'debug' #e generalize so the debug menu can be customized? not sure it's needed. ## debug_menu = None # needed for use before _init1 or if that fails def _init1(self, win = None): # figure out this mixin's idea of main window if not win: try: self.win # no need: assert isinstance( self.win, QWidget) except AttributeError: pass else: win = self.win self._debug_win = win # figure out classname for #doc try: self._debug_classname = "class " + self.__class__.__name__ except: self._debug_classname = "<some class>" # make the menu -- now done each time it's needed return def makemenu(self, menu_spec, menu = None): """ Make and return a menu object for use in this widget, from the given menu_spec. If menu is provided (should be a QMenu), append to it instead. For more info see docstring of widgets.menu_helpers.makemenu_helper. [This can be overridden by a subclass, but probably never needs to be, unless it needs to make *all* menus differently (thus we do use the overridden version if one is present) or unless it uses it independently from this mixin and wants to be self-contained.] """ from widgets.menu_helpers import makemenu_helper return makemenu_helper(self, menu_spec, menu) def debug_menu_items(self): """ #doc; as of 050416 this will be called every time the debug menu needs to be put up, so that the menu contents can be different each time (i.e. so it can be a dynamic menu) [subclasses can override this; best if they call this superclass method and modify its result, e.g. add new items at top or bottom] """ res = [ ('debugging menu (unsupported)', noop, 'disabled'), #bruce 060327 revised text # None, # separator ] if 0 and self._debug_win: #bruce 060327 disabled this, superseded by prefs dialog some time ago res.extend( [ ('load window layout', self._debug_load_window_layout ), ('save window layout', self._debug_save_window_layout ), #bruce 050117 prototype "save window layout" here; when it works, move it elsewhere ] ) if debug.exec_allowed(): #bruce 041217 made this item conditional on whether it will work res.extend( [ ('run py code', self._debug_runpycode), ('sim param dialog', self._debug_sim_param_dialog), ('force sponsor download', self._debug_force_sponsor_download), ('speed-test py code', self._debug_timepycode), #bruce 051117; include this even if not debug_flags.atom_debug ] ) #bruce 050416: use a "checkmark item" now that we're remaking this menu dynamically: if debug_flags.atom_debug: res.extend( [ ('ATOM_DEBUG', self._debug_disable_atom_debug, 'checked' ), ] ) else: res.extend( [ ('ATOM_DEBUG', self._debug_enable_atom_debug ), ] ) #bruce 060124 changes: always call debug_prefs_menuspec, but pass debug_flags.atom_debug to filter the prefs, # and change API to return a list of menu items (perhaps empty) rather than exactly one res.extend( debug_prefs.debug_prefs_menuspec( debug_flags.atom_debug ) ) #bruce 050614 (submenu) if 1: #bruce 050823 some = registered_commands_menuspec( self) res.extend(some) res.extend( [ ('choose font', self._debug_choose_font), ] ) if self._debug_win: res.extend( [ ('call update_parts()', self._debug_update_parts ), ###e also should offer check_parts ] ) if 1: #bruce 060327; don't show them in the menu itself, we need to see them in time, in history, with and without atom_debug res.extend( [ ('print object counts', self._debug_print_object_counts), ] ) if 1: #piotr 080311: simple graphics benchmark res.extend( [ ('measure graphics performance', self._debug_do_benchmark), ] ) #command entered profiling res.extend( [ ('Profile entering a command...', self._debug_profile_userEnterCommand), ('(print profile output)', self._debug_print_profile_output), ] ) if debug_flags.atom_debug: # since it's a dangerous command res.extend( [ ('debug._widget = this widget', self._debug_set_widget), ('destroy this widget', self._debug_destroy_self), ] ) res.extend( [ ('print self', self._debug_printself), ] ) return res def _debug_save_window_layout(self): # [see also Preferences.save_current_win_pos_and_size, new as of 051218] win = self._debug_win keyprefix = mainwindow_geometry_prefs_key_prefix save_window_pos_size( win, keyprefix) def _debug_load_window_layout(self): # [similar code is in pre_main_show in a startup module, new as of 051218] win = self._debug_win keyprefix = mainwindow_geometry_prefs_key_prefix load_window_pos_size( win, keyprefix) def _debug_update_parts(self): win = self._debug_win win.assy.update_parts() def _debug_print_object_counts(self): #bruce 060327 for debugging memory leaks: report Atom & Bond refcounts, and objs that might refer to them # Note: these counts include not only instances, but imports of classes into modules. # That's probably why the initial counts seem too high: # 40 Atoms, 24 Bonds, 40 Chunks, 34 Groups, 8 Parts, 10 Assemblies # [as of 080403] from utilities.Log import _graymsg msglater = "" # things to print all in one line for clasname, modulename in ( #bruce 080403 fixed modulenames (since the modules were moved into # packages); the dotted names seem to work. ('Atom', 'model.chem'), ('Bond', 'model.bonds'), # ('Node', 'Utility'), # Node or Jig is useless here, we need the specific subclasses! ('Chunk', 'model.chunk'), # DnaLadderRailChunk ## ('PiBondSpChain', 'pi_bond_sp_chain'), # no module pi_bond_sp_chain -- due to lazy load or atom-debug reload?? ('Group', 'foundation.Group'), # doesn't cover subclasses PartGroup, ClipboardItemGroup, RootGroup(sp?), Dna groups ('Part', 'model.part'), ('Assembly', 'model.assembly')): # should also have a command to look for other classes with high refcounts if sys.modules.has_key(modulename): module = sys.modules[modulename] clas = getattr(module, clasname, None) if clas: msg = "%d %ss" % (sys.getrefcount(clas), clasname) msg = msg.replace("ys","ies") # for spelling of Assemblies # print these things all at once if msglater: msglater += ', ' msglater += msg msg = None else: msg = "%s not found in %s" % (clasname, modulename) else: msg = "no module %s" % (modulename,) if msg: env.history.message( _graymsg( msg)) if msglater: env.history.message( _graymsg( msglater)) return def _debug_choose_font(self): #bruce 050304 experiment; works; could use toString/fromString to store it in prefs... oldfont = self.font() newfont, ok = QFontDialog.getFont(oldfont) ##e can we change QFontDialog to let us provide initial sample text, # and permit typing \n into it? If not, can we fool it by providing # it with a fake "paste" event? if ok: self.setFont(newfont) try: if debug_flags.atom_debug: print "atom_debug: new font.toString():", newfont.toString() except: print_compact_traceback("new font.toString() failed: ") return def _debug_enable_atom_debug(self): debug_flags.atom_debug = 1 def _debug_disable_atom_debug(self): debug_flags.atom_debug = 0 def debug_event(self, event, funcname, permit_debug_menu_popup = 0): #bruce 040916 """ [the main public method for subclasses] Debugging method -- no effect on normal users. Does two things -- if a global flag is set, prints info about the event; if a certain modifier key combination is pressed, and if caller passed permit_debug_menu_popup = 1, puts up an undocumented debugging menu, and returns 1 to caller. Modifier keys to bring it up: Mac: Shift-Option-Command-click Linux: <cntrl><shift><alt><left click> Windows: probably same as linux """ # In constants.py: debugModifiers = cntlModifier | shiftModifier | altModifier # On the mac, this really means command-shift-alt [alt == option]. if debug_menu_enabled and permit_debug_menu_popup and \ int(event.modifiers() & debugModifiers) == debugModifiers: ## print "\n* * * fyi: got debug click, will try to put up a debug menu...\n" # bruce 050316 removing this self.do_debug_menu(event) return 1 # caller should detect this and not run its usual event code... if debug_events: try: before = event.state() except: before = "<no state>" # needed for Wheel events, at least try: after = event.stateAfter() except: after = "<no stateAfter>" # needed for Wheel events, at least print "%s: event; state = %r, stateAfter = %r; time = %r" % (funcname, before, after, time.asctime()) # It seems, from doc and experiments, that event.state() is # from just before the event (e.g. a button press or release, # or move), and event.stateAfter() is from just after it, so # they differ in one bit which is the button whose state # changed (if any). But the doc is vague, and the experiments # incomplete, so there is no guarantee that they don't # sometimes differ in other ways. # -- bruce ca. 040916 return 0 def do_debug_menu(self, event): """ [public method for subclasses] #doc """ ## menu = self.debug_menu #bruce 050416: remake the menu each time it's needed menu_spec = None try: menu_spec = self.debug_menu_items() menu = self.makemenu(menu_spec, None) if menu: # might be [] menu.exec_(event.globalPos()) except: print_compact_traceback("bug in do_debug_menu ignored; menu_spec is %r" % (menu_spec,) ) def _debug_printself(self): print self def _debug_set_widget(self): #bruce 050604 debug._widget = self print "set debug._widget to",self def _debug_destroy_self(self): #bruce 050604 #e should get user confirmation ## self.destroy() ###k this doesn't seem to work. check method name. self.deleteLater() def _draw_hundred_frames(self, par1, par2): # redraw 100 frames, piotr 080403 for i in range(0, 100): self.win.glpane.paintGL() # BUG; see below. [bruce 090305 comment] def _debug_do_benchmark(self): # simple graphics benchmark, piotr 080311 from time import clock print "Entering graphics benchmark. Drawing 100 frames... please wait." win = self._debug_win self.win.resize(1024,768) # resize the window to a constant size self.win.glpane.paintGL() # draw once just to make sure the GL context is current # piotr 080405 # [BUG: the right way is gl_update -- direct call of paintGL won't # always work, context might not be current -- bruce 090305 comment] env.call_qApp_processEvents() # make sure all events were processed tm0 = clock() profile_single_call_if_enabled(self._draw_hundred_frames, self, None) tm1 = clock() print "Benchmark complete. FPS = ", 100.0 / (tm1 - tm0) return def _debug_profile_userEnterCommand(self): """ Debug menu command for profiling userEnterCommand(commandName). This creates a profile.output file on each use (replacing a prior one if any, even if it was created during the same session). Note that for some commands, a lot more work will be done the first time they are entered during a session (or in some cases, the first time since opening a new file) than in subsequent times. """ # Ninad 2008-10-03; renamed/revised by bruce 090305 RECOGNIZED_COMMAND_NAMES = ( 'DEPOSIT', 'BUILD_DNA', 'DNA_SEGMENT', 'DNA_STRAND', 'CRYSTAL', 'BUILD_NANOTUBE', 'EDIT_NANOTUBE', 'EXTRUDE', 'MODIFY', 'MOVIE' ) ok, commandName = grab_text_line_using_dialog( title = "profile entering given command", label = "Enter the command.commandName e.g. 'BUILD_DNA' , 'DEPOSIT'" ) if not ok: print "No command name entered, returning" return commandName = str(commandName) commandName = commandName.upper() if not commandName in RECOGNIZED_COMMAND_NAMES: #bruce 090305 changed this to just a warning, added try/except print "Warning: command name %r might or might not work. " \ "Trying it anyway." % (commandName,) pass print "Profiling command enter for %s" % (commandName,) win = self._debug_win meth = self.win.commandSequencer.userEnterCommand set_enabled_for_profile_single_call(True) tm0 = clock() try: profile_single_call_if_enabled(meth, commandName) except: print "exception entering command caught and discarded." #e improve sys.stdout.flush() pass tm1 = clock() set_enabled_for_profile_single_call(False) print "Profiling complete. Total CPU time to enter %s = %s" % \ (commandName, (tm1 - tm0)) return def _debug_print_profile_output(self): #bruce 090305 """ """ # todo: improve printing options used inside the following debug.print_profile_output() return def debug_menu_source_name(self): #bruce 050112 """ can be overriden by subclasses #doc more """ try: return "%s debug menu" % self.__class__.__name__ except: return "some debug menu" def _debug_runpycode(self): debug_runpycode_from_a_dialog( source = self.debug_menu_source_name() ) # e.g. "GLPane debug menu" return def _debug_sim_param_dialog(self): global _sim_parameter_dialog if _sim_parameter_dialog is None: _sim_parameter_dialog = SimParameterDialog() _sim_parameter_dialog.show() return def _debug_force_sponsor_download(self): from sponsors.Sponsors import _force_download _force_download() return def _debug_timepycode(self): #bruce 051117 debug_timing_test_pycode_from_a_dialog( ) return pass # end of class DebugMenuMixin ########################################################## BOOLEAN = "boolean" INT = "int" FLOAT = "float" STRING = "string" sim_params_set = False # We get mysterious core dumps if we turn all these other guys on. We # didn't have time before the A8 release to investigate the matter in # depth, so we just switched off the ones we didn't need immediately. _sim_param_table = [ ("debug_flags", INT), # ("IterPerFrame", INT), # ("NumFrames", INT), # ("DumpAsText", BOOLEAN), # ("DumpIntermediateText", BOOLEAN), # ("PrintFrameNums", BOOLEAN), # ("OutputFormat", INT), # ("KeyRecordInterval", INT), # ("DirectEvaluate", BOOLEAN), # ("IDKey", STRING), # ("Dt", FLOAT), # ("Dx", FLOAT), # ("Dmass", FLOAT), # ("Temperature", FLOAT), ] sim_param_values = { "debug_flags": 0, # "IterPerFrame": 10, # "NumFrames": 100, # "DumpAsText": False, # "DumpIntermediateText": False, # "PrintFrameNums": True, # "OutputFormat": 1, # "KeyRecordInterval": 32, # "DirectEvaluate": False, # "IDKey": "", # "Dt": 1.0e-16, # "Dx": 1.0e-12, # "Dmass": 1.0e-27, # "Temperature": 300.0, } class SimParameterDialog(QDialog): def __init__(self, win = None): import string QDialog.__init__(self, win) self.setWindowTitle('Manually edit sim parameters') layout = QGridLayout(self) layout.setMargin(1) layout.setSpacing(-1) layout.setObjectName("SimParameterDialog") for i in range(len(_sim_param_table)): attr, paramtype = _sim_param_table[i] current = sim_param_values[attr] currentStr = str(current) label = QLabel(attr + ' (' + paramtype + ')', self) layout.addWidget(label, i, 0) if paramtype == BOOLEAN: label = QLabel(currentStr, self) layout.addWidget(label, i, 1) def falseFunc(attr = attr, label = label): sim_param_values[attr] = False label.setText('False') def trueFunc(attr = attr, label = label): sim_param_values[attr] = True label.setText('True') btn = QPushButton(self) btn.setText('True') layout.addWidget(btn, i, 2) self.connect(btn,SIGNAL("clicked()"), trueFunc) btn = QPushButton(self) btn.setText('False') layout.addWidget(btn, i, 3) self.connect(btn,SIGNAL("clicked()"), falseFunc) else: label = QLabel(self) label.setText(currentStr) layout.addWidget(label, i, 1) linedit = QLineEdit(self) linedit.setText(currentStr) layout.addWidget(linedit, i, 2) def change(attr = attr, linedit = linedit, paramtype = paramtype, label = label): txt = str(linedit.text()) label.setText(txt) if paramtype == STRING: sim_param_values[attr] = txt elif paramtype == INT: if txt.startswith('0x') or txt.startswith('0X'): n = string.atoi(txt[2:], 16) else: n = string.atoi(txt) sim_param_values[attr] = n elif paramtype == FLOAT: sim_param_values[attr] = string.atof(txt) btn = QPushButton(self) btn.setText('OK') layout.addWidget(btn, i, 3) self.connect(btn, SIGNAL("clicked()"), change) btn = QPushButton(self) btn.setText('Done') layout.addWidget(btn, len(_sim_param_table), 0, len(_sim_param_table), 4) def done(self = self): global sim_params_set sim_params_set = True #import pprint #pprint.pprint(sim_param_values) self.close() self.connect(btn, SIGNAL("clicked()"), done) _sim_parameter_dialog = None ###################################################
NanoCAD-master
cad/src/widgets/DebugMenuMixin.py
# Copyright 2006-2008 Nanorex, Inc. See LICENSE file for details. """ StatusBar.py - status bar widgets, AbortHandler, ProgressReporters @author: Mark, EricM @version: $Id$ @copyright: 2006-2008 Nanorex, Inc. See LICENSE file for details. Module classification: [bruce 071228] It appears to have no requirement of being a singleton and to be general purpose, and it's just one file, so I'll just put it into "widgets" rather than into its own toplevel module StatusBar or into ne1_ui. TODO: Needs refactoring to move NanoHiveProgressReporter elsewhere., probably into its sole user, NanoHiveUtils. [bruce comment 071228] History: Started with ProgressBar.py and widdled it down, replacing the original progressbar dialog with the new MainWindow progress bar and simAbort "Stop Sign" button. by mark on 060105. Majorly rewritten/refactored by Eric M circa 12/2007 [bruce comment 071228] """ import os, time from PyQt4.Qt import QProgressBar, QFrame, QToolButton, QIcon, QLabel, SIGNAL from PyQt4.Qt import QMessageBox, QStatusBar, QWidget, QFrame, QHBoxLayout, QToolBar from utilities import debug_flags from platform_dependent.PlatformDependent import hhmmss_str #bruce 060106 moved that function there import foundation.env as env from utilities.icon_utilities import geticon from utilities.icon_utilities import getpixmap from utilities.qt4transition import qt4todo from utilities.debug import print_compact_traceback from widgets.GlobalDisplayStylesComboBox import GlobalDisplayStylesComboBox class StatusBar(QStatusBar): def __init__(self, win): QStatusBar.__init__(self, win) self._progressLabel = QLabel() self._progressLabel.setMinimumWidth(200) self._progressLabel.setFrameStyle( QFrame.Panel | QFrame.Sunken ) self.addPermanentWidget(self._progressLabel) self.progressBar = QProgressBar(win) self.progressBar.setMaximumWidth(250) qt4todo('StatusBar.progressBar.setCenterIndicator(True)') self.addPermanentWidget(self.progressBar) self.progressBar.hide() self.simAbortButton = QToolButton(win) self.simAbortButton.setIcon( geticon("ui/actions/Simulation/Stopsign.png")) self.simAbortButton.setMaximumWidth(32) self.addPermanentWidget(self.simAbortButton) self.connect(self.simAbortButton,SIGNAL("clicked()"),self.simAbort) self.simAbortButton.hide() self.dispbarLabel = QLabel(win) #self.dispbarLabel.setFrameStyle( QFrame.Panel | QFrame.Sunken ) self.dispbarLabel.setText( "Global display style:" ) self.addPermanentWidget(self.dispbarLabel) # Global display styles combobox self.globalDisplayStylesComboBox = GlobalDisplayStylesComboBox(win) self.addPermanentWidget(self.globalDisplayStylesComboBox) # Selection lock button. It always displays the selection lock state # and it is available to click. self.selectionLockButton = QToolButton(win) self.selectionLockButton.setDefaultAction(win.selectLockAction) self.addPermanentWidget(self.selectionLockButton) self.abortableCommands = {} #bruce 081230 debug code: ## self.connect(self, SIGNAL('messageChanged ( const QString &)'), ## self.slotMessageChanged ) ## def slotMessageChanged(self, message): # bruce 081230 debug code ## print "messageChanged: %r" % str(message) def showMessage(self, text): #bruce 081230 """ [extends superclass method] """ ## QStatusBar.showMessage(self, " ") QStatusBar.showMessage(self, text) ## print "message was set to %r" % str(self.currentMessage()) return def _f_progress_msg(self, text): #bruce 081229 refactoring """ Friend method for use only by present implementation of env.history.progress_msg. Display text in our private label widget dedicated to progress messages. """ self._progressLabel.setText(text) return def makeCommandNameUnique(self, commandName): index = 1 trial = commandName while (self.abortableCommands.has_key(trial)): trial = "%s [%d]" % (commandName, index) index += 1 return trial def addAbortableCommand(self, commandName, abortHandler): uniqueCommandName = self.makeCommandNameUnique(commandName) self.abortableCommands[uniqueCommandName] = abortHandler return uniqueCommandName def removeAbortableCommand(self, commandName): del self.abortableCommands[commandName] def simAbort(self): """ Slot for Abort button. """ if debug_flags.atom_debug and self.sim_abort_button_pressed: #bruce 060106 print "atom_debug: self.sim_abort_button_pressed is already True before we even put up our dialog" # Added confirmation before aborting as part of fix to bug 915. Mark 050824. # Bug 915 had to do with a problem if the user accidently hit the space bar or espace key, # which would call this slot and abort the simulation. This should no longer be an issue here # since we aren't using a dialog. I still like having this confirmation anyway. # IMHO, it should be kept. Mark 060106. ret = QMessageBox.warning( self, "Confirm", "Please confirm you want to abort.\n", "Confirm", "Cancel", "", 1, # The "default" button, when user presses Enter or Return (1 = Cancel) 1) # Escape (1= Cancel) if ret == 0: # Confirmed for abortHandler in self.abortableCommands.values(): abortHandler.pressed() def show_indeterminate_progress(self): value = self.progressBar.value() self.progressBar.setValue(value) def possibly_hide_progressbar_and_stop_button(self): if (len(self.abortableCommands) <= 0): self.progressBar.reset() self.progressBar.hide() self.simAbortButton.hide() def show_progressbar_and_stop_button(self, progressReporter, cmdname = "<unknown command>", showElapsedTime = False): """ Display the statusbar's progressbar and stop button, and update it based on calls to the progressReporter. When the progressReporter indicates completion, hide the progressbar and stop button and return 0. If the user first presses the Stop button on the statusbar, hide the progressbar and stop button and return 1. Parameters: progressReporter - See potential implementations below. cmdname - name of command (used in some messages and in abort button tooltip) showElapsedTime - if True, display duration (in seconds) below progress bar Return value: 0 if file reached desired size, 1 if user hit abort button. """ updateInterval = .1 # seconds startTime = time.time() elapsedTime = 0 displayedElapsedTime = 0 ###e the following is WRONG if there is more than one task at a time... [bruce 060106 comment] self.progressBar.reset() self.progressBar.setMaximum(progressReporter.getMaxProgress()) self.progressBar.setValue(0) self.progressBar.show() abortHandler = AbortHandler(self, cmdname) # Main loop while progressReporter.notDoneYet(): self.progressBar.setValue(progressReporter.getProgress()) env.call_qApp_processEvents() # Process queued events (e.g. clicking Abort button, # but could be anything -- no modal dialog involved anymore). if showElapsedTime: elapsedTime = int(time.time() - startTime) if (elapsedTime != displayedElapsedTime): displayedElapsedTime = elapsedTime env.history.progress_msg("Elapsed Time: " + hhmmss_str(displayedElapsedTime)) # note: it's intentional that this doesn't directly call # self._f_progress_msg. [bruce 081229 comment] if abortHandler.getPressCount() > 0: env.history.statusbar_msg("Aborted.") abortHandler.finish() return 1 time.sleep(updateInterval) # Take a rest # End of Main loop (this only runs if it ended without being aborted) self.progressBar.setValue(progressReporter.getMaxProgress()) time.sleep(updateInterval) # Give the progress bar a moment to show 100% env.history.statusbar_msg("Done.") abortHandler.finish() return 0 class FileSizeProgressReporter(object): """ Report progress of sub-process for StatusBar.show_progressbar_and_stop_button(). This class reports progress based on the growth of a file on disk. It's used to show the progress of a dynamics simulation, where the output file will grow by a fixed amount each timestep until it reaches a final size which is known in advance. """ def __init__(self, fileName, expectedSize): self.fileName = fileName self.expectedSize = expectedSize self.currentSize = 0 def getProgress(self): if os.path.exists(self.fileName): self.currentSize = os.path.getsize(self.fileName) else: self.currentSize = 0 return self.currentSize def getMaxProgress(self): return self.expectedSize def notDoneYet(self): return self.currentSize < self.expectedSize class NanoHiveProgressReporter(object): """ Report progress of sub-process for StatusBar.show_progressbar_and_stop_button(). This class talks to the sub-process directly, and asks for a status report including the percent complete. """ def __init__(self, nanoHiveSocket, simulationID): self.nanoHiveSocket = nanoHiveSocket self.simulationID = simulationID self.responseCode = -1 self.lastPercent = 0 def getProgress(self): success, response = self.nanoHiveSocket.sendCommand("status " + self.simulationID) responseCode, percent = response.split(self.simulationID) self.responseCode = int(responseCode) # Need to do this since we only get a percent value when responseCode == 5 (sim is running). # If responseCode != 5, p can be None (r=10) or a whitespace char (r=4). if self.responseCode == 5: self.lastPercent = int(percent) return self.lastPercent def getMaxProgress(self): return 100 def notDoneYet(self): return self.responseCode != 4 # == class AbortHandler: def __init__(self, statusBar, commandName): self.statusBar = statusBar name = commandName or '<unknown command>' # required argument self.commandName = statusBar.addAbortableCommand(name, self) self.pressCount = 0 statusBar.simAbortButton.show() def pressed(self): self.pressCount += 1 # could call a callback here def getPressCount(self): self.statusBar.show_indeterminate_progress() return self.pressCount def finish(self): """This should be called when the task it's about ends for any reason, whether success or error or abort or even crash; if not called it will prevent all other abortable tasks from running! """ ####e should try to figure out a way to auto-call it for tasks that user clicked abort for but that failed to call it... # for example, if user clicks abort button twice for same task. or if __del__ called (have to not save .win). #####@@@@@ try: self.statusBar.removeAbortableCommand(self.commandName) except: if debug_flags.atom_debug: print_compact_traceback("atom_debug: bug: failure in StatusBar.removeAbortableCommand(): ") self.statusBar.possibly_hide_progressbar_and_stop_button() # end
NanoCAD-master
cad/src/widgets/StatusBar.py
# Copyright 2004-2008 Nanorex, Inc. See LICENSE file for details. """ menu_helpers.py - helpers for creating or modifying Qt menus @author: Josh, Bruce @version: $Id$ @copyright: 2004-2008 Nanorex, Inc. See LICENSE file for details. History: Originally by Josh, as part of GLPane.py. Bruce 050112 moved this code into widgets.py, later added features including checkmark & Undo support, split it into more than one function, and on 080203 moved it into its own file. At some point Will ported it to Qt4 (while it was in widgets.py). Module classification: [bruce 080203] Might have been in utilities except for depending on undo_manager (foundation). Since its only purpose is to help make or modify menus for use in Qt widgets, it seems more useful to file it in widgets than in foundation. (Reusable widgets are in a sense just a certain kind of "ui utility".) """ from PyQt4.Qt import QMenu from PyQt4.Qt import QAction from PyQt4.Qt import SIGNAL from PyQt4.Qt import QPixmap from PyQt4.Qt import QIcon from utilities import debug_flags from foundation.undo_manager import wrap_callable_for_undo # == # helper for making popup menus from our own "menu specs" description format, # consisting of nested lists of text, callables or submenus, options. def makemenu_helper(widget, menu_spec, menu = None): """ Make and return a reusable or one-time-use (at caller's option) popup menu whose structure is specified by menu_spec, which is a list of menu item specifiers, each of which is either None (for a separator) or a tuple of the form (menu text, callable or submenu, option1, option2, ...) with 0 or more options (described below). A submenu can be either another menu_spec list, or a QMenu object (but in the latter case the menu text is ignored -- maybe it comes from that QMenu object somehow -- not sure if this was different in Qt3). In either case it is the 2nd menu-item-tuple element, in place of the callable. Otherwise the callable must satisfy the python 'callable' predicate, and is executed if the menu item is chosen, wrapped inside another function which handles Undo checkpointing and Undo-command-name setting. The options in a menu item tuple can be zero or more (in any order, duplicates allowed) of the following: 'disabled' -- the menu item should be disabled; 'checked' -- the menu item will be checked; None -- this option is legal but ignored (but the callable must still satisfy the python predicate "callable"; constants.noop might be useful for that case). The Qt3 version also supported tuple-options consisting of one of the words 'iconset' and 'whatsThis' followed by an appropriate argument, but those have not yet been ported to Qt4 (except possibly for disabled menu items -- UNTESTED). Unrecognized options may or may not generate warnings, and are otherwise ignored. [###FIX that -- they always ought to print a warning to developers. Note that right now they do iff 'disabled' is one of the options and ATOM_DEBUG is set.] The 'widget' argument should be the Qt widget which is using this function to put up a menu. If the menu argument is provided, it should be a QMenu to which we'll add items; otherwise we create our own QMenu and add items to it. """ from utilities.debug import print_compact_traceback import types if menu is None: menu = QMenu(widget) ## menu.show() #bruce 070514 removed menu.show() to fix a cosmetic and performance bug # (on Mac, possibly on other platforms too; probably unreported) # in which the debug menu first appears in screen center, slowly grows # to full size while remaining blank, then moves to its final position # and looks normal (causing a visual glitch, and a 2-3 second delay # in being able to use it). May fix similar issues with other menus. # If this causes harm for some menus or platforms, we can adapt it. # bruce 040909-16 moved this method from basicMode to GLPane, # leaving a delegator for it in basicMode. # (bruce was not the original author, but modified it) #menu = QMenu( widget) for m in menu_spec: try: #bruce 050416 added try/except as debug code and for safety menutext = m and widget.trUtf8(m[0]) if m and isinstance(m[1], QMenu): #bruce 041010 added this case submenu = m[1] #menu.insertItem( menutext, submenu ) menu.addMenu(submenu) # how do I get menutext in there? # (similar code might work for QAction case too, not sure) elif m and isinstance(m[1], types.ListType): #bruce 041103 added this case submenu = QMenu(menutext, menu) submenu = makemenu_helper(widget, m[1], submenu) # [this used to call widget.makemenu] menu.addMenu(submenu) elif m: assert callable(m[1]), \ "%r[1] needs to be a callable" % (m,) #bruce 041103 # transform m[1] into a new callable that makes undo checkpoints and provides an undo command-name # [bruce 060324 for possible bugs in undo noticing cmenu items, and for the cmdnames] func = wrap_callable_for_undo(m[1], cmdname = m[0]) # guess about cmdname, but it might be reasonable for A7 as long as we ensure weird characters won't confuse it import foundation.changes as changes changes.keep_forever(func) # THIS IS BAD (memory leak), but it's not a severe one, so ok for A7 [bruce 060324] # (note: the hard part about removing these when we no longer need them is knowing when to do that # if the user ends up not selecting anything from the menu. Also, some callers make these # menus for reuse multiple times, and for them we never want to deallocate func even when some # menu command gets used. We could solve both of these by making the caller pass a place to keep these # which it would deallocate someday or which would ensure only one per distinct kind of menu is kept. #e) if 'disabled' not in m[2:]: act = QAction(widget) act.setText( menutext) if 'checked' in m[2:]: act.setCheckable(True) act.setChecked(True) menu.addAction(act) widget.connect(act, SIGNAL("activated()"), func) else: # disabled case # [why is this case done differently, in this Qt4 port?? -- bruce 070522 question] insert_command_into_menu(menu, menutext, func, options = m[2:], raw_command = True) else: menu.addSeparator() #bruce 070522 bugfix -- before this, separators were placed lower down or dropped # so as not to come before disabled items, for unknown reasons. # (Speculation: maybe because insertSeparator was used, since addSeparator didn't work or wasn't noticed, # and since disabled item were added by an older function (also for unknown reasons)?) pass except Exception, e: if isinstance(e, SystemExit): raise print_compact_traceback("exception in makemenu_helper ignored, for %r:\n" % (m,) ) #bruce 070522 restored this (was skipped in Qt4 port) pass #e could add a fake menu item here as an error message return menu # from makemenu_helper # == def insert_command_into_menu(menu, menutext, command, options = (), position = -1, raw_command = False, undo_cmdname = None): """ [This was part of makemenu_helper in the Qt3 version; in Qt4 it's only used for the disabled case, presumably for some good reason but not one which has been documented. It's also used independently of makemenu_helper.] Insert a new item into menu (a QMenu), whose menutext, command, and options are as given, with undo_cmdname defaulting to menutext (used only if raw_command is false), where options is a list or tuple in the same form as used in "menu_spec" lists such as are passed to makemenu_helper (which this function helps implement). The caller should have already translated/localized menutext if desired. If position is given, insert the new item at that position, otherwise at the end. Return the Qt menu item id of the new menu item. (I am not sure whether this remains valid if other items are inserted before it. ###k) If raw_command is False (default), this function will wrap command with standard logic for nE-1 menu commands (presently, wrap_callable_for_undo), and ensure that a python reference to the resulting callable is kept forever. If raw_command is True, this function will pass command unchanged into the menu, and the caller is responsible for retaining a Python reference to command. ###e This might need an argument for the path or function to be used to resolve icon filenames. """ #bruce 060613 split this out of makemenu_helper. # Only called for len(options) > 0, though it presumably works # just as well for len 0 (try it sometime). import types from foundation.whatsthis_utilities import turn_featurenames_into_links, ENABLE_WHATSTHIS_LINKS if not raw_command: command = wrap_callable_for_undo(command, cmdname = undo_cmdname or menutext) import foundation.changes as changes changes.keep_forever(command) # see comments on similar code above about why this is bad in theory, but necessary and ok for now iconset = None for option in options: # some options have to be processed first # since they are only usable when the menu item is inserted. [bruce 050614] if type(option) is types.TupleType: if option[0] == 'iconset': # support iconset, pixmap, or pixmap filename [bruce 050614 new feature] iconset = option[1] if type(iconset) is types.StringType: filename = iconset from utilities.icon_utilities import imagename_to_pixmap iconset = imagename_to_pixmap(filename) if isinstance(iconset, QPixmap): # (this is true for imagename_to_pixmap retval) iconset = QIcon(iconset) if iconset is not None: import foundation.changes as changes changes.keep_forever(iconset) #e memory leak; ought to make caller pass a place to keep it, or a unique id of what to keep #mitem_id = menu.insertItem( iconset, menutext, -1, position ) #bruce 050614, revised 060613 (added -1, position) mitem = menu.addAction( iconset, menutext ) #bruce 050614, revised 060613 (added -1, position) # Will this work with checkmark items? Yes, but it replaces the checkmark -- # instead, the icon looks different for the checked item. # For the test case of gamess.png on Mac, the 'checked' item's icon # looked like a 3d-depressed button. # In the future we can tell the iconset what to display in each case # (see QIcon and/or QMenu docs, and helper funcs presently in debug_prefs.py.) else: # mitem_id = len(menu) -- mitem_id was previously an integer, indexing into the menu mitem = menu.addAction(menutext) for option in options: if option == 'checked': mitem.setChecked(True) elif option == 'unchecked': #bruce 050614 -- see what this does visually, if anything mitem.setChecked(False) elif option == 'disabled': mitem.setEnabled(False) elif type(option) is types.TupleType: if option[0] == 'whatsThis': text = option[1] if ENABLE_WHATSTHIS_LINKS: text = turn_featurenames_into_links(text) mitem.setWhatsThis(text) elif option[0] == 'iconset': pass # this was processed above else: if debug_flags.atom_debug: print "atom_debug: fyi: don't understand menu_spec option %r", (option,) pass elif option is None: pass # this is explicitly permitted and has no effect else: if debug_flags.atom_debug: print "atom_debug: fyi: don't understand menu_spec option %r", (option,) pass #e and something to use QMenuData.setShortcut #e and something to run whatever func you want on menu and mitem_id return mitem # from insert_command_into_menu # end
NanoCAD-master
cad/src/widgets/menu_helpers.py
# Copyright 2004-2009 Nanorex, Inc. See LICENSE file for details. """ simple_dialogs.py - simple dialogs, collected here for convenience. TODO: merge some of them into one function. @author: Bruce, based on code by others @version: $Id$ @copyright: 2004-2009 Nanorex, Inc. See LICENSE file for details. """ from PyQt4.Qt import QInputDialog, QLineEdit, QDialog from utilities.icon_utilities import geticon def grab_text_using_dialog( default = "", title = "title", label = "label", iconPath = "ui/border/MainWindow.png"): """ Get some text from the user by putting up a dialog with the supplied title, label, and default text. Return (ok, text) as described below. Replace @@@ with \n in the returned text (and convert it to a Python string). If it contains unicode characters, raise UnicodeEncodeError. @return: the 2-tuple (ok, text), which is (True, text) if we succeed, or (False, None) if the user cancels. """ # TODO: add an option to allow this to accept unicode, # and do something better if that's not provided and unicode is entered # (right now it just raises a UnicodeEncodeError). # modified from _set_test_from_dialog( ), # which was modified from debug_runpycode_from_a_dialog, # which does the "run py code" debug menu command # Qt4 version [070329; similar code in an exprs-module file] inputDialog = QDialog() # No parent inputDialog.setWindowIcon(geticon(iconPath)) text, ok = QInputDialog.getText(inputDialog, title, label, QLineEdit.Normal, default) # note: parent arg is needed in Qt4, not in Qt3 if ok: # fyi: type(text) == <class '__main__.qt.QString'> text = str(text) text = text.replace("@@@",'\n') else: pass # print "grab_text_using_dialog: cancelled" return ok, text # == # TODO: merge the features of the following grab_text_line_using_dialog # with the above grab_text_using_dialog by adding options to distinguish # them, and rewrite all calls to use the above grab_text_using_dialog. # Also improve it to permit unicode. def grab_text_line_using_dialog( default = "", title = "title", label = "label", iconPath = "ui/border/MainWindow.png"): #bruce 070531 """ Use a dialog to get one line of text from the user, with given default (initial) value, dialog window title, and label text inside the dialog. If successful, return (True, text); if not, return (False, "Reason why not"). Returned text is a python string (not unicode). """ # WARNING: several routines contain very similar code. # We should combine them into one (see comment before this function). # This function was modified from grab_text_line_using_dialog() (above) # which was modified from _set_test_from_dialog(), # which was modified from debug_runpycode_from_a_dialog(), # which does the "run py code" debug menu command. inputDialog = QDialog() # No parent inputDialog.setWindowIcon(geticon(iconPath)) text, ok = QInputDialog.getText(inputDialog, title, label, QLineEdit.Normal, default) # note: parent arg needed only in Qt4 if not ok: reason = "Cancelled" if ok: try: # fyi: type(text) == <class '__main__.qt.QString'> text = str(text) ###BUG: won't work for unicode except: ok = False reason = "Unicode is not yet supported" ## text = text.replace("@@@",'\n') if ok: return True, text else: return False, reason pass # end
NanoCAD-master
cad/src/widgets/simple_dialogs.py
""" GlobalDisplayStylesComboBox.py - Provides a combo box with all the global display styles. @author: Mark @version: $Id$ @copyright: 2004-2008 Nanorex, Inc. See LICENSE file for details. To do (for Mark): - Add tooltip and What's This text. - Change "Default Display Style" in the preferences dialog (Mode page) to "Global Display Style at start up" REVIEW: does this module belong in the ne1_ui package? [bruce 080711 comment] """ import os from PyQt4.Qt import SIGNAL, QComboBox import foundation.env as env from utilities.constants import diDEFAULT ,diTrueCPK, diLINES from utilities.constants import diBALL, diTUBES, diDNACYLINDER, diPROTEIN from utilities.prefs_constants import startupGlobalDisplayStyle_prefs_key from utilities.icon_utilities import geticon # Should DNA Cylinder be a global display style? Selecting it makes everything # except DNA invisible. If we leave it in the list, we must document this # confusing behavior in the "What's This" text. # --Mark 2008-03-16 # [note: this may have been fixed since then; not sure. [bruce 080711 comment]] displayIndexes = [diLINES, diTUBES, diBALL, diTrueCPK, diDNACYLINDER, diPROTEIN] displayNames = ["Lines", "Tubes", "Ball and Stick", "CPK", "DNA Cylinder", "Protein"] displayIcons = ["Lines", "Tubes", "Ball_and_Stick", "CPK", "DNACylinder", "Protein"] displayIconsDict = dict(zip(displayNames, displayIcons)) displayNamesDict = dict(zip(displayIndexes, displayNames)) class GlobalDisplayStylesComboBox(QComboBox): """ The GlobalDisplayStylesComboBox widget provides a combobox with all the standard NE1 display styles. """ def __init__(self, win): """ Constructs a combobox with all the display styles. @param win: The NE1 mainwindow. @type win: L{Ui_MainWindow} """ QComboBox.__init__(self, win) self.win = win self._setup(disconnect = False) def _setup(self, display_style = diDEFAULT, disconnect = True): """ Private method. Populates self and sets the current display style. """ from utilities.debug_prefs import debug_pref, Choice_boolean_False # Add a new experimental Protein display style # if the Enable proteins debug pref is set to True. # piotr 080710 from utilities.GlobalPreferences import ENABLE_PROTEINS if display_style == diDEFAULT: display_style = env.prefs[ startupGlobalDisplayStyle_prefs_key ] if disconnect: self.disconnect( self, SIGNAL("currentIndexChanged(int)"), self._setDisplayStyle ) self.clear() ADD_DEFAULT_TEXT = False for displayName in displayNames: # Experimental display style for Proteins. if displayName == "Protein" and \ not ENABLE_PROTEINS: # Skip the Proteins style. continue basename = displayIconsDict[displayName] + ".png" iconPath = os.path.join("ui/actions/View/Display/", basename) self.addItem(geticon(iconPath), displayName) self.setCurrentIndex(displayIndexes.index(display_style)) self.connect( self, SIGNAL("currentIndexChanged(int)"), self._setDisplayStyle ) def getDisplayStyleIndex(self): """ Returns the current global display style. @return: the current global display style (i.e. diDEFAULT, diTUBES, etc) @rtype: int """ return displayIndexes[self.currentIndex()] def _setDisplayStyle(self, index): """ Private slot method. Only called when self's index changes (i.e when the user selects a new global display style via self). @param index: the combobox index @type index: int """ assert index in range(self.count()) glpane = self.win.assy.glpane glpane.setGlobalDisplayStyle(displayIndexes[index]) glpane.gl_update() def setDisplayStyle(self, display_style): """ Public method. Sets the display style of self to I{display_style}. @param display_style: display style code (i.e. diTUBES, diLINES, etc.) @type display_style: int @note: does not directly call glpane.setGlobalDisplayStyle, but it's not documented whether it sometimes does this indirectly via a signal it causes to be sent from self. """ assert display_style in displayIndexes # If self is already set to display_style, return. if self.currentIndex() == displayIndexes.index(display_style): return self.setCurrentIndex(displayIndexes.index(display_style)) # Generates signal!
NanoCAD-master
cad/src/widgets/GlobalDisplayStylesComboBox.py
NanoCAD-master
cad/src/widgets/__init__.py
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. """ widget_controllers.py - miscellaneous widget-controller classes @author: bruce @version: $Id$ @copyright: 2006-2007 Nanorex, Inc. See LICENSE file for details. """ # a widget expr controller for a collapsible GroupBox # (different default style on Windows/Linux and Mac -- but most of the difference # is in an earlier setup layer which makes the Qt widgets passed to this) # wants access to 2 iconsets made from given imagenames in the "usual way for this env" # (can that just be the program env as a whole?) from PyQt4.Qt import QIcon, SIGNAL from utilities.qt4transition import qt4todo import foundation.env as env def _env_imagename_to_QIcon(imagename, _cache = {}): ### to be replaced with env.imagename_to_QIcon for global env or an arg env try: return _cache[imagename] except KeyError: pass ## pixmap_fname = imagename # stub from utilities.icon_utilities import imagename_to_pixmap pixmap = imagename_to_pixmap(imagename) pixmap_fname = pixmap # will this arg work too? res = QIcon() res.setPixmap(pixmap_fname, QIcon.Automatic) _cache[imagename] = res # memoize, and also keep permanent python reference return res class CollapsibleGroupController_Qt: open = True #k maybe not needed def __init__(self, parent, desc, header_refs, hidethese, groupbutton): ## print parent, header_refs ## print hidethese, groupbutton self.parent = parent # the QDialog subclass with full logic self.desc = desc # group_desc self.header_refs = header_refs # just keep python refs to these qt objects in the group header, or other objs related to the group self.hidethese = hidethese # what to hide and show (and python refs to other objects in the group) self.groupbutton = groupbutton # the QPushButton in the group header (used in two ways: signal, and change the icon) self.style = 'Mac' ### set from env ## self.env #e needs imagename_to_QIcon self.options = self.desc.options expanded = self.options.get('expanded', True) # these options were set when the desc was interpreted, e.g. "expanded = True" ##e ideally, actual default would come from env ### kluge for now: if expanded == 'false': expanded = False self.set_open(expanded) # signal for button self.parent.connect(groupbutton,SIGNAL("clicked()"),self.toggle_open) # was toggle_nt_parameters_grpbtn return # runtime logic def toggle_open(self): open = not self.open self.set_open(open) self.parent.update() # QWidget.update() #bruce - see if this speeds it up -- not much, but maybe a little, hard to say. #e would it work better to just change the height? try later. return def set_open(self, open): self.open = open #e someday, the state might be externally stored... let this be a property ref to self.stateref[self.openkey] self.set_openclose_icon( self.open ) self.set_children_shown( self.open ) return def set_openclose_icon(self, open): """ #doc @param open: @type open: boolean """ #e do we want to add a provision for not being collapsible at all? collapsed = not open if self.style == 'Mac': # on Mac, icon shows current state if collapsed: imagename = "mac_collapsed_icon.png" else: imagename = "mac_expanded_icon.png" else: # on Windows, it shows the state you can change it to if collapsed: imagename = "win_expand_icon.png" else: imagename = "win_collapse_icon.png" iconset = _env_imagename_to_QIcon(imagename) # memoized self.groupbutton.setIcon(iconset) return def set_children_shown(self, open): for child in self.hidethese: if open: child.show() else: child.hide() return pass class FloatLineeditController_Qt: def __init__(self, parent, desc, lineedit): self.parent = parent # the QDialog subclass with full logic (note: not the Group it's in -- we don't need to know that) self.desc = desc # param_desc self.lineedit = lineedit # a QLineEdit param = self.desc # has suffix, min, max, default ### needs a controller to handle the suffix, min, and max, maybe using keybindings; or needs to be floatspinbox ### may need a precision argument, at least to set format for default value # note: see Qt docs for inputMask property - lets you set up patterns it should look like precision = 1 format = "%0.1f" suffix = param.options.get('suffix', '') self.suffix = suffix #060601 printer = lambda val, format = format, suffix = suffix: format % val + suffix ##e store this default = param.options.get('default', 0.0) ### will be gotten through an env or state text = printer(default) self.lineedit.setText(self.parent._tr(text)) # was "20.0 A" -- btw i doubt it's right to pass it *all* thru __tr self.default = default def get_value(self): text = str(self.lineedit.text()) # remove suffix, or any initial part of it, or maybe any subsequence of it (except for numbers in it)... # ideal semantics are not very clear! removed_suffix = False text = text.strip() suffix = self.suffix.strip() if text.endswith(suffix): # this case is important to always get right removed_suffix = True text = text[:-len(suffix)] text = text.strip() # now it's either exactly right, or a lost cause -- forget about supporting partially-remaining suffix. #e should we visually indicate errors somehow? (yes, ideally by color of the text, and tooltip) try: return float(text) except: ### error message or indicator return self.default pass pass class realtime_update_controller: #bruce 060705, consolidate code from runSim.py, SimSetup.py, and soon MinimizeEnergyProp.py """ #doc """ def __init__(self, widgets, checkbox = None, checkbox_prefs_key = None): """ Set the data widgets, and if given, the checkbox widget and its prefs key, both optional. If checkbox and its prefs_key are both there, connect them. If neither is provided, always update. """ self.watch_motion_buttongroup, self.update_number_spinbox, self.update_units_combobox = widgets self.checkbox = checkbox self.checkbox_prefs_key = checkbox_prefs_key if checkbox and checkbox_prefs_key: from widgets.prefs_widgets import connect_checkbox_with_boolean_pref connect_checkbox_with_boolean_pref(checkbox , checkbox_prefs_key) def set_widgets_from_update_data(self, update_data): if update_data: update_number, update_units, update_as_fast_as_possible_data, enable = update_data if self.checkbox: self.checkbox.setChecked(enable) if self.checkbox_prefs_key: #k could be elif, if we connected them above env.prefs[self.checkbox_prefs_key] = enable qt4todo('self.watch_motion_buttongroup.setButton( update_as_fast_as_possible_data') self.update_number_spinbox.setValue( update_number) for i in range(self.update_units_combobox.count()): if self.update_units_combobox.itemText(i) == update_units: self.update_units_combobox.setCurrentIndex(i) return raise Exception("update_units_combobox has no such option: " + update_units) else: pass # rely on whatever is already in them (better than guessing here) return def get_update_data_from_widgets(self): update_as_fast_as_possible_data = self.watch_motion_buttongroup.checkedId() # 0 means yes, 1 means no (for now) # ( or -1 means neither, but that's prevented by how the button group is set up, at least when it's enabled) update_number = self.update_number_spinbox.value() # 1, 2, etc (or perhaps 0??) update_units = str(self.update_units_combobox.currentText()) # 'frames', 'seconds', 'minutes', 'hours' if self.checkbox: enable = self.checkbox.isChecked() elif self.checkbox_prefs_key: enable = env.prefs[self.checkbox_prefs_key] else: enable = True return update_number, update_units, update_as_fast_as_possible_data, enable def update_cond_from_update_data(self, update_data): #e could be a static method update_number, update_units, update_as_fast_as_possible_data, enable = update_data if not enable: return False #e someday we might do this at the end, if the subsequent code is extended to save some prefs update_as_fast_as_possible = (update_as_fast_as_possible_data != 1) if env.debug(): print "debug: using update_as_fast_as_possible = %r, update_number, update_units = %r, %r" % \ ( update_as_fast_as_possible, update_number, update_units ) pass if update_as_fast_as_possible: # This radiobutton might be misnamed; it really means "use the old code, # i.e. not worse than 20% slowdown, with threshholds". # It's also ambiguous -- does "fast" mean "fast progress" # or "often" (which are opposites)? It sort of means "often". update_cond = ( lambda simtime, pytime, nframes: simtime >= max(0.05, min(pytime * 4, 2.0)) ) elif update_units == 'frames': update_cond = ( lambda simtime, pytime, nframes, _nframes = update_number: nframes >= _nframes ) elif update_units == 'seconds': update_cond = ( lambda simtime, pytime, nframes, _timelimit = update_number: simtime + pytime >= _timelimit ) elif update_units == 'minutes': update_cond = ( lambda simtime, pytime, nframes, _timelimit = update_number * 60: simtime + pytime >= _timelimit ) elif update_units == 'hours': update_cond = ( lambda simtime, pytime, nframes, _timelimit = update_number * 3600: simtime + pytime >= _timelimit ) else: print "don't know how to set update_cond from (%r, %r)" % (update_number, update_units) update_cond = None # some callers can tolerate this, though it's always a reportable error return update_cond def get_update_cond_from_widgets(self): update_data = self.get_update_data_from_widgets() return self.update_cond_from_update_data(update_data) pass # end of class realtime_update_controller # end
NanoCAD-master
cad/src/widgets/widget_controllers.py
# Copyright 2004-2008 Nanorex, Inc. See LICENSE file for details. """ NE1_QToolBar.py - Main NE1 toolbar class, which subclasses Qt's QToolBar class. All NE1 main window toolbars should use this class (except for the Command Toolbar). @author: Mark Sims @version: $Id$ @copyright: 2004-2008 Nanorex, Inc. See LICENSE file for details. """ from PyQt4 import QtGui from PyQt4.Qt import Qt, QToolBar, SIGNAL from utilities.icon_utilities import getpixmap from utilities.debug import print_compact_stack _DEBUG = False # Do not commit with True class NE1_QToolBar(QToolBar): """ Main NE1 toolbar class. Its primary use is to reimplement addSeparator() so that we can create custom separators. @limitations: QToolBar's insertSeparator() method has been disabled. See docstring below for more information. """ # _separatorList is a list of all the QLabel widgets in this toolbar. # Each QLabel has either a horizontal or vertical separator pixmap. _separatorList = [] _separatorNumber = 0 def __init__(self, parent): """ Constructs an NE1 toolbar for the main window. """ QToolBar.__init__(self, parent) self._separatorList = [] # Attention: This signal-slot connection is not working and I'm not # sure why. As a workaround, I reimplemented QToolBar.moveEvent() # which does the job nicely. I'm leaving the connect() call here, # but commenting it out. I bet its a Qt bug and it might be fixed # in Qt 4.3 (or later). Mark 2008-03-01. #self.connect(self, # SIGNAL("orientationChanged()"), # self.updateSeparatorPixmaps) def updateSeparatorPixmaps(self): """ Updates the pixmap for all separators in this toolbar. @note: This is also supposed to be the slot for the orientationChanged() signal, but it doesn't work. """ for separator in self._separatorList: if _DEBUG: print separator.objectName() self.setSeparatorWidgetPixmap(separator, self.orientation()) def moveEvent(self, event): """ Reimplements QWidget.moveEvent(). It is used as a workaround for the orientationChanged() signal bug mentioned throughout. """ QToolBar.moveEvent(self, event) self.updateSeparatorPixmaps() def setSeparatorWidgetPixmap(self, widget, orientation): """ Sets either the horizontal or the vertical pixmap to widget, depending on orientation. @param widget: The separator widget. @type widget: U{B{QLabel}<http://doc.trolltech.com/4/qgroupbox.html>} @param orientation: The orientation of this separator. @type orientation: U{B{Qt.Orientation enum}<http://doc.trolltech.com/4.2/qtoolbar.html#orientation-prop>} """ if orientation == Qt.Horizontal: widget.setPixmap( getpixmap("ui/toolbars/h_separator.png")) else: widget.setPixmap( getpixmap("ui/toolbars/v_separator.png")) def addSeparator(self): """ Reimplements the addSeparator() method of QToolBar. """ _toolbarSeparator = QtGui.QLabel(self) if _DEBUG: _name = "%s-Separator%d" % (self.objectName(), self._separatorNumber) _toolbarSeparator.setObjectName(_name) self._separatorNumber += 1 self.setSeparatorWidgetPixmap(_toolbarSeparator, self.orientation()) _toolbarSeparator.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter) self.addWidget(_toolbarSeparator) self._separatorList.append(_toolbarSeparator) def insertSeparator(self): """ This method overrides QToolBar's method. It does nothing since the normal behavior will screw things up. @note: If you need this method, please code it! Mark 2008-02-29. """ print_compact_stack("insertSeparator() not supported. " \ "Use addSeparator() instead or implement insertSeparator()") return
NanoCAD-master
cad/src/widgets/NE1_QToolBar.py
# Copyright 2005-2008 Nanorex, Inc. See LICENSE file for details. """ prefs_widgets.py -- Utilities related to both user preferences and Qt widgets. Note: also includes some code related to "connect with state" which should be refiled. @author: Bruce @version: $Id$ @copyright: 2005-2008 Nanorex, Inc. See LICENSE file for details. History: Bruce 050805 started this module. Module classification, and refactoring needed: Needs splitting into at least two files. One of them is some widgets or widget helpers. The other is some "connect with state" facilities. Those might be used for pure model state someday (with at least some of them getting classified in foundation and used in model), but for now, they are probably only used with widgets, so we might get away with calling this a "ui/widgets" module without splitting it -- we'll see. [bruce 071215 comment] """ import foundation.env as env # for env.prefs from utilities.debug import print_compact_traceback, print_compact_stack from foundation.changes import Formula from widgets.widget_helpers import RGBf_to_QColor from PyQt4.Qt import QColorDialog from PyQt4.Qt import SIGNAL from PyQt4.Qt import QPalette from foundation.undo_manager import wrap_callable_for_undo # public helper functions def widget_destroyConnectionWithState(widget): """ """ conn = getattr(widget, '_ConnectionWithState__stored_connection', None) # warning: this is *not* name-mangled, since we're not inside a class. ### RENAME ATTR if conn is not None: # TODO: maybe assert it's of the expected class? or follows some api? conn.destroy() # this removes any subscriptions that object held widget._ConnectionWithState__stored_connection = None return def widget_setConnectionWithState( widget, connection): """ """ assert getattr(widget, '_ConnectionWithState__stored_connection', None) is None, \ "you must call widget_destroyConnectionWithState before making new connection on %r" % (widget,) widget._ConnectionWithState__stored_connection = connection ### TODO: arrange to destroy connection whenever widget gets destroyed. # Probably not needed except for widgets that get destroyed long before the app exits; # probably will be needed if we have any like that. return def widget_connectWithState(widget, state, connection_class, **options): """ Connect the given widget with the given state, using the given connection_class, which must be chosen to be correct for both the widget type and the state type / value format. @param widget: a QWidget of an appropriate type, or anything which works with the given connection_class. @type widget: QWidget (usually). @param state: bla @type state: bla @param connection_class: the constructor for the connection. Must be correct for both the widget type and state type / value format. @type connection_class: bla @param options: arbitrary options for connection_class. @type options: options dict, passed using ** """ widget_destroyConnectionWithState( widget) conn = connection_class( widget, state, **options) widget_setConnectionWithState( widget, conn) return def widget_setAction(widget, aCallable, connection_class, **options): """ """ # kluge: use widget_connectWithState as a helper function, # since no widgets need both and the behavior is identical. # (If we add a type assertion to that func, we'll have to pass in # an alternative one here.) # # Assume the connection_class is responsible for turning aCallable # into the right form, applying options, etc (even if that ends up # meaning all connection_classes share common code in a superclass). widget_connectWithState(widget, aCallable, connection_class, **options) return def set_metainfo_from_stateref( setter, stateref, attr, debug_metainfo = False): """ If stateref provides a value for attr (a stateref-metainfo attribute such as 'defaultValue' or 'minimum'), pass it to the given setter function. If debug_metainfo is true, print debug info saying what we do and why. """ if hasattr(stateref, attr): value = getattr( stateref, attr) if debug_metainfo: print "debug_metainfo: using %r.%s = %r" % (stateref, attr, value) setter(value) else: if debug_metainfo: print "debug_metainfo: %r has no value for %r" % (stateref, attr) return # == def colorpref_edit_dialog( parent, prefs_key, caption = "choose"): #bruce 050805; revised 070425 in Qt4 branch #bruce 050805: heavily modified this from some slot methods in UserPrefs.py. # Note that the new code for this knows the prefs key and that it's a color, # and nothing else that those old slot methods needed to know! # It no longer needs to know about the color swatch (if any) that shows this color in the UI, # or what/how to update anything when the color is changed, # or where the color is stored besides in env.prefs. # That knowledge now resides with the code that defines it, or in central places. old_color = RGBf_to_QColor( env.prefs[prefs_key] ) c = QColorDialog.getColor(old_color, parent) # In Qt3 this also had a caption argument if c.isValid(): new_color = (c.red()/255.0, c.green()/255.0, c.blue()/255.0) env.prefs[prefs_key] = new_color # this is change tracked, which permits the UI's color swatch # (as well as the glpane itself, or whatever else uses this prefs color) # to notice this and update its color return def connect_colorpref_to_colorframe( prefs_key, colorframe ): #bruce 050805; revised 070425/070430 in Qt4 branch """ Cause the bgcolor of the given Qt "color frame" to be set to each new legal color value stored in the given pref. """ # first destroy any prior connection trying to control the same colorframe widget widget_destroyConnectionWithState( colorframe) # For Qt4, to fix bug 2320, we need to give the colorframe a unique palette, in which we can modify the background color. # To get this to work, it was necessary to make a new palette each time the color changes, modify it, and re-save into colorframe # (done below). This probably relates to "implicit sharing" of QPalette (see Qt 4.2 online docs). # [bruce 070425] def colorframe_bgcolor_setter(color): #e no convenient/clean way for Formula API to permit but not require this function to receive the formula, # unless we store it temporarily in env._formula (which we might as well do if this feature is ever needed) try: # make sure errors here don't stop the formula from running: # (Need to protect against certain kinds of erroneous color values? RGBf_to_QColor does it well enough.) ## Qt3 code used: colorframe.setPaletteBackgroundColor(RGBf_to_QColor(color)) qcolor = RGBf_to_QColor(color) palette = QPalette() # QPalette(qcolor) would have window color set from qcolor, but that doesn't help us here qcolorrole = QPalette.Window ## http://doc.trolltech.com/4.2/qpalette.html#ColorRole-enum says: ## QPalette.Window 10 A general background color. palette.setColor(QPalette.Active, qcolorrole, qcolor) # used when window is in fg and has focus palette.setColor(QPalette.Inactive, qcolorrole, qcolor) # used when window is in bg or does not have focus palette.setColor(QPalette.Disabled, qcolorrole, qcolor) # used when widget is disabled colorframe.setPalette(palette) colorframe.setAutoFillBackground(True) # [Note: the above scheme was revised again by bruce 070430, for improved appearance # (now has thin black border around color patch), based on Ninad's change in UserPrefs.py.] ## no longer needed: set color for qcolorrole = QPalette.ColorRole(role) for role in range(14) ## no longer needed: colorframe.setLineWidth(500) # width of outline of frame (at least half max possible size) except: print "data for following exception: ", print "colorframe %r has palette %r" % (colorframe, colorframe.palette()) # fyi: in Qt4, like in Qt3, colorframe is a QFrame print_compact_traceback( "bug (ignored): exception in formula-setter: " ) #e include formula obj in this msg? pass conn = Formula( lambda: env.prefs.get( prefs_key) , colorframe_bgcolor_setter ) # this calls the setter now and whenever the lambda-value changes, until it's destroyed # or until there's any exception in either arg that it calls. widget_setConnectionWithState( colorframe, conn) return class destroyable_Qt_connection: """ holds a Qt signal/slot connection, but has a destroy method which disconnects it [#e no way to remain alive but discon/con it] """ def __init__(self, sender, signal, slot, owner = None): if owner is None: owner = sender # I hope that's ok -- not sure it is -- if not, put owner first in arglist, or, use topLevelWidget self.vars = owner, sender, signal, slot owner.connect(sender, signal, slot) def destroy(self): owner, sender, signal, slot = self.vars owner.disconnect(sender, signal, slot) self.vars = None # error to destroy self again pass class list_of_destroyables: """ hold 0 or more objects, so that when we're destroyed, so are they """ def __init__(self, *objs): self.objs = objs def destroy(self): for obj in self.objs: #e could let obj be a list and do this recursively obj.destroy() self.objs = None # error to destroy self again (if that's bad, set this to [] instead) pass def connect_checkbox_with_boolean_pref_OLD( qcheckbox, prefs_key ): #bruce 050810, slightly revised 070814, DEPRECATED since being replaced """ Cause the checkbox to track the value of the given boolean preference, and cause changes to the checkbox to change the preference. (Use of the word "with" in the function name, rather than "to" or "from", is meant to indicate that this connection is two-way.) First remove any prior connection of the same type on the same checkbox. Legal for more than one checkbox to track and control the same pref [but that might be untested]. """ # first destroy any prior connection trying to control the same thing widget_destroyConnectionWithState( qcheckbox) # make a one-way connection from prefs value to checkbox, using Formula (active as soon as made) setter = qcheckbox.setChecked #e or we might prefer a setter which wraps this with .blockSignals(True)/(False) conn1 = Formula( lambda: env.prefs.get( prefs_key) , setter ) # this calls the setter now and whenever the lambda-value changes, until it's destroyed # or until there's any exception in either arg that it calls. # make a one-way connection from Qt checkbox to preference (active as soon as made) def prefsetter(val): #e should we assert val is boolean? nah, just coerce it: val = not not val env.prefs[prefs_key] = val conn2 = destroyable_Qt_connection( qcheckbox, SIGNAL("toggled(bool)"), prefsetter ) # package up both connections as a single destroyable object, and store it conn = list_of_destroyables( conn1, conn2) widget_setConnectionWithState(qcheckbox, conn) return class StateRef_API(object): ### TODO: FILL THIS IN, rename some methods """ API for references to tracked state. """ #bruce 080930 added object superclass debug_name = "" def __repr__(self): #bruce 071002; 080930 revised, moved to superclass # assume self.debug_name includes class name, # as it does when made up by Preferences_StateRef.__init__ debug_name = self.debug_name or self.__class__.__name__.split('.')[-1] return "<%s at %#x>" % (debug_name, id(self)) # TODO: add support for queryable metainfo about type, whatsthis text, etc. # For example: # - self.defaultValue could be the default value (a constant value, # not an expr, though in a *type* it might be an expr), # and maybe some flag tells whether it's really known or just guessed. # TODO: add default implems of methods like set_value and get_value # (which raise NIM exceptions). But rename them as mentioned elsewhere pass class Preferences_StateRef(StateRef_API): # note: compare to exprs.staterefs.PrefsKey_StateRef. """ A state-reference object (conforming to StateRef_API), which represents the preferences value slot with the prefs_key and default value passed to our constructor. WARNING [071002]: this is not yet able to ask env.prefs for separately defined default values (in the table in preferences.py). For now, it is just for testing purposes when various kinds of staterefs should be tested, and should be used with newly made-up prefs keys. """ def __init__(self, prefs_key, defaultValue = None, debug_name = "", pref_name = ""): # TODO: also let a value-filter function be passed, for type checking/fixing. self.prefs_key = prefs_key self.defaultValue = defaultValue if defaultValue is not None: env.prefs.get(prefs_key, defaultValue) # set or check the default value # REVIEW: need to disambiguate, if None could be a legitimate default value -- pass _UNSET_ instead? # REVIEW: IIRC, env.prefs provides a way to ask for the centrally defined or already initialized # default value. We should use that here if defaultValue is not provided, and set self.defaultValue # to it, or verify consistency if both are provided (maybe the env.prefs.get call does that already). if not debug_name: debug_name = "Preferences_StateRef(%r)" % (pref_name or prefs_key,) # used by __repr__ in place of classname self.debug_name = debug_name return def set_value(self, value): # REVIEW: how can the caller tell that this is change-tracked? # Should StateRef_API define flags for client code queries about that? # e.g. self.tracked = true if set and get are fully tracked, false if not -- # I'm not sure if this can differ for set and get, or if so, if that difference # matters to clients. env.prefs[self.prefs_key] = value def get_value(self): # REVIEW: how can the caller tell that this is usage-tracked? # (see also the related comment for set_value) return env.prefs[self.prefs_key] pass def Preferences_StateRef_double( prefs_key, defaultValue = 0.0): # TODO: store metainfo about type, min, max, etc. return Preferences_StateRef( prefs_key, defaultValue) class Fallback_ObjAttr_StateRef(StateRef_API): #bruce 080930 experimental; useful when obj.attr is a property ### TODO: make property docstring available thru self for use in tooltips of UI elements def __init__(self, obj, attr, debug_name = None): self.obj = obj self.attr = attr self.defaultValue = self.get_value() ### review: always safe this soon? always wanted? if not debug_name: debug_name = "Fallback_ObjAttr_StateRef(%r, %r)" % (obj, attr) # used by __repr__ in place of classname self.debug_name = debug_name return def set_value(self, value): setattr( self.obj, self.attr, value) def get_value(self): return getattr( self.obj, self.attr) pass class Setter_StateRef(StateRef_API): #bruce 080930 experimental, not known to be useful since getter is required in practice """ A "write-mainly" stateref made from a setter/getter function pair, or (if getter is not supplied) a write-only stateref made from a setter function. """ # see also: call_with_new_value, ObjAttr_StateRef def __init__(self, setter, getter = None): self.setter = setter self.getter = getter # kluge (present of this attr of self affects semantics) ###review -- is that true? if getter is not None: self.defaultValue = getter() ### review: always safe this soon? always wanted? # todo: not always correct, should be overridable by option return def set_value(self, value): self.setter(value) def get_value(self): if not self.getter: assert 0, "can't get value from %r" % self return self.getter() pass def ObjAttr_StateRef( obj, attr, *moreattrs): #bruce 070815 experimental; plan: use it with connectWithState for mode tracked attrs ###e refile -- staterefs.py? StateRef_API.py? a staterefs package? """ Return a reference to tracked state obj.attr, as a StateRef_API-conforming object of an appropriate class, chosen based on obj's class and how obj stores its state. """ if moreattrs: assert 0, "a serial chain of attrs is not yet supported" ## ref1 = ObjAttr_StateRef( obj, attr) ## return ObjAttr_StateRef( ref1, *moreattrs) ### WRONG -- ref1 is a ref, not an obj which is its value! assert obj is not None #k might be redundant with checks below # Let's ask obj to do this. If it doesn't know how, use a fallback method. method = getattr(obj, '_StateRef__attr_ref', None) if method: stateref = method(attr) # REVIEW: pass moreattrs into here too? # print "ObjAttr_StateRef returning stateref %r" % (stateref,) if not getattr( stateref, 'debug_name', None): # TODO: do this below for other ways of finding a stateref # REVIEW: can we assume all kinds of staterefs have that attr, public for get and set? # This includes class Lval objects -- do they inherit stateref API? Not yet! ### FIX stateref.debug_name = "ObjAttr_StateRef(%r, %r)" % (obj, attr) return stateref # Use a fallback method. Note: this might produce a ref to a "delayed copy" of the state. # That's necessary if changes are tracked by polling and diff, # since otherwise the retval of get_value would change sooner than the change-track message was sent. # Alternatively, all get_value calls could cause it to be compared at that time... but I'm not sure that's a good idea -- # it might cause invals at the wrong times (inside update methods calling get_value). # For some purposes, it might be useful to produce a "write only" reference, # useable for changing the referred-to attribute, but not for subscribing to # other changes of it. Or better, able to get the value but not to subscribe # (i.e. it's not a change-trackable value). Let's try this now. # [bruce 080930 experiment] ## assert 0, "ObjAttr_StateRef fallback is nim -- needed for %r" % (obj,) return Fallback_ObjAttr_StateRef( obj, attr ) # == ### TODO: val = not not val before setting pref - ie val = boolean(val), or pass boolean as type coercer def connect_checkbox_with_boolean_pref( qcheckbox, prefs_key ): #bruce 050810, rewritten 070814 """ Cause the checkbox to track the value of the given boolean preference, and cause changes to the checkbox to change the preference. (Use of the word "with" in the function name, rather than "to" or "from", is meant to indicate that this connection is two-way.) First remove any prior connection of the same type on the same checkbox. Legal for more than one checkbox to track and control the same pref [but that might be untested]. """ stateref = Preferences_StateRef( prefs_key) # note: no default value specified widget_connectWithState( qcheckbox, stateref, QCheckBox_ConnectionWithState) return def connect_doubleSpinBox_with_pref(qDoubleSpinBox, prefs_key): # by Ninad """ Cause the QDoubleSpinbox to track the value of the given preference key AND causes changes to the Double spinbox to change the value of that prefs_key. @param qDoubleSpinBox: QDoublespinbox object which needs to be 'connected' to the given <prefs_key> (preference key) @type qDoubleSpinBox: B{QDoubleSpinBox} @param prefs_key: The preference key to be assocuated with <qDoubleSpinBox> @see: B{connect_checkbox_with_boolean_pref()} @see: B{QDoubleSpinBox_ConnectionWithState} @see: Preferences._setupPage_Dna() for an example use. @see: connect_spinBox_with_pref() """ stateref = Preferences_StateRef( prefs_key) # note: no default value specified widget_connectWithState( qDoubleSpinBox, stateref, QDoubleSpinBox_ConnectionWithState) return def connect_spinBox_with_pref(qSpinBox, prefs_key): # by Ninad """ Cause the QSpinbox to track the value of the given preference key AND causes changes to the Double spinbox to change the value of that prefs_key. @param qSpinBox: QSpinBox object which needs to be 'connected' to the given <prefs_key> (preference key) @type qSpinBox: B{QSpinBox} @param prefs_key: The preference key to be assocuated with <qSpinBox> @see: B{connect_checkbox_with_boolean_pref()} @see: B{QSpinBox_ConnectionWithState} @see: Preferences._setupPage_Dna() for an example use. @see: connect_doubleSpinBox_with_pref() """ stateref = Preferences_StateRef( prefs_key) # note: no default value specified widget_connectWithState( qSpinBox, stateref, QSpinBox_ConnectionWithState) return def connect_comboBox_with_pref(qComboBox, prefs_key): # by Ninad """ Cause the QComboBox to track the value of the given preference key AND causes changes to the combobox to change the value of that prefs_key. @param qComboBox: QComboBox object which needs to be 'connected' to the given <prefs_key> (preference key) @type qComboBox B{QComboBox} @param prefs_key: The preference key to be assocuated with <qSpinBox> @see: B{connect_checkbox_with_boolean_pref()} @see: B{QComboBox_ConnectionWithState} @see: connect_doubleSpinBox_with_pref() """ stateref = Preferences_StateRef( prefs_key) # note: no default value specified widget_connectWithState( qComboBox, stateref, QComboBox_ConnectionWithState) return # == class _twoway_Qt_connection(object): #bruce 080930 added object superclass #bruce 070814, experimental, modified from destroyable_Qt_connection ### TODO: RENAME; REVISE init arg order ### TODO: try to make destroyable_Qt_connection a super of this class """ Private helper class for various "connect widget with state" features (TBD). Holds a Qt signal/slot connection, with a destroy method which disconnects it, but also makes a connection in the other direction, using additional __init__ args, which disables the first connection during use. Only certified for use when nothing else is similarly connected to the same widget. Main experimental aspect of API is the StateRef_API used by the stateref arg... """ debug_name = "" connected = False #bruce 080930 conn1 = None def __init__(self, widget, signal, stateref, widget_setter, owner = None, debug_name = None): """ ...StateRef_API used by the stateref arg... """ sender = self.widget = widget self.stateref = stateref self.debug = getattr(self.stateref, '_changes__debug_print', False) change_tracked_setter = stateref.set_value ### is set_value public for all kinds of staterefs? VERIFY or MAKE TRUE usage_tracked_getter = stateref.get_value ### DITTO -- BTW also MUST rename these to imply desired user contract, # i.e. about how they're tracked, etc -- set_value_tracked, get_value_tracked, maybe. or setValue_tracked etc. slot = change_tracked_setter # function to take a new value and store it in, full invals/tracks -- value needs to be in same format # as comes with the widget signal in a single arg if owner is None: owner = sender # I hope that's ok -- not sure it is -- if not, put owner first in arglist, or, use topLevelWidget #e destroy self if owner is destroyed? self.vars = owner, sender, signal, slot # these two will become aspects of one state object, whose api provides them... self.usage_tracked_getter = usage_tracked_getter self.widget_setter = widget_setter # only after setting those instance vars is it safe to do the following: self.connect() self.connect_the_other_way() #e rename if self.debug: print "\n_changes__debug_print: finished _twoway_Qt_connection.__init__ for %r containing %r" % (self, stateref) ###REVIEW: what if subclass init is not done, and needed for %r to work? self.debug_name = debug_name or "" # used by __repr__ in place of classname, if provided return def __repr__(self): #bruce 080930 # assume self.debug_name includes class name, if that's needed debug_name = self.debug_name or \ self.stateref.debug_name or \ self.__class__.__name__.split('.')[-1] return "<%s at %#x>" % (debug_name, id(self)) def connect(self): owner, sender, signal, slot = self.vars owner.connect(sender, signal, slot) self.connected = True def disconnect(self): owner, sender, signal, slot = self.vars owner.disconnect(sender, signal, slot) self.connected = False def destroy(self): if self.vars: #bruce 080930 make destroy twice legal and a noop if self.connected: self.disconnect() if self.conn1: self.conn1.destroy() self.vars = None # error to use self after this, except for destroy return def connect_the_other_way(self): self.conn1 = Formula( self.usage_tracked_getter, self.careful_widget_setter, debug = self.debug ) if self.debug: print "\n_changes__debug_print: %r connected from %r to %r using %r with %r" % \ ( self, self.stateref, self.widget, self.conn1, self.usage_tracked_getter ) ## self.conn1._changes__debug_print = True # too late to tell Formula to notice initial stuff! Done with option instead. debug = False def careful_widget_setter(self, value): # Note: for some time we used self.widget_setter rather than this method, # by mistake, and it apparently worked fine. We'll still use this method # as a precaution; also it might be truly needed if the widget quantizes # the value, unless the widget refrains from sending signals when # programmatically set. [bruce 070815] if self.debug: print "\n_changes__debug_print: %r setting %r to %r using %r" % \ ( self, self.widget, value, self.widget_setter ) self.disconnect() # avoid possible recursion try: self.widget_setter(value) except: print_compact_traceback("bug: ignoring exception setting value of %r to %r: " % (self, value)) print_compact_stack(" fyi: prior exception came from: ") self.destroy() #bruce 080930 # this seems to be safe, but debug output implies it fails to stop formula # from continuing to call setter! but that seems unlikely... nevermind for now. # Review: do we want subsequent use of self # to be silently ok, smaller message, or error? If this destroy worked # then I think it should be silently ok, but might not be now, # depending on how refs to self continue to be used. pass else: self.connect() ### WARNING: .connect is slow, since it runs our Python code to set up an undo wrapper # around the slot! We should revise this to tell Qt to block the signals instead. # [We can use: bool QObject::blockSignals ( bool block ) ==> returns prior value of signalsBlocked, # now used in a helper function setValue_with_signals_blocked] # This will matter for performance when this is used for state which changes during a drag. # Note: avoiding the slot call is needed not only for recursion, but to avoid the # Undo checkpoint in the wrapper. # [bruce comments 071015; see also bug 2564 in other code] return pass class QCheckBox_ConnectionWithState( _twoway_Qt_connection): def __init__(self, qcheckbox, stateref): widget_setter = qcheckbox.setChecked _twoway_Qt_connection.__init__(self, qcheckbox, SIGNAL("toggled(bool)"), stateref, widget_setter) return pass class QDoubleSpinBox_ConnectionWithState( _twoway_Qt_connection): def __init__(self, qspinbox, stateref): widget_setter = qspinbox.setValue # note: requires bugfix in PM_DoubleSpinBox.setValue, # or this will also set default value when used with a PM_DoubleSpinBox object. self.qspinbox = qspinbox # review: is this reference needed? _twoway_Qt_connection.__init__(self, qspinbox, SIGNAL("valueChanged(double)"), stateref, widget_setter) return class QSpinBox_ConnectionWithState( _twoway_Qt_connection): # by Ninad # review: add a def connectWithState to a suitable PM class, which uses this? [bruce 080811 comment] def __init__(self, qspinbox, stateref): widget_setter = qspinbox.setValue self.qspinbox = qspinbox # review: is this reference needed? _twoway_Qt_connection.__init__(self, qspinbox, SIGNAL("valueChanged(int)"), stateref, widget_setter) return class QPushButton_ConnectionWithAction(destroyable_Qt_connection): def __init__(self, qpushbutton, aCallable, cmdname = None): sender = qpushbutton signal = SIGNAL("clicked()") slot = wrap_callable_for_undo( aCallable, cmdname = cmdname) # need to keep a ref to this destroyable_Qt_connection.__init__( self, sender, signal, slot) # this keeps a ref to slot return class QComboBox_ConnectionWithState( _twoway_Qt_connection): # by Ninad # review: add a def connectWithState to a suitable PM class, which uses this? [bruce 080811 comment] def __init__(self, qcombobox, stateref): widget_setter = qcombobox.setCurrentIndex self.qcombobox = qcombobox # review: is this reference needed? _twoway_Qt_connection.__init__(self, qcombobox, SIGNAL("currentIndexChanged(int)"), stateref, widget_setter) return pass # still needed: # - StateRef_API, in an appropriate file. # - state APIs, objects, maybe exprs... obj-with-state-attr apis... # - refactor above to take the widget with known signal/setter as its own class, maybe... not sure... # we know each widget needs special case, so maybe fine to do those as subclasses... or as new methods on existing widget subclasses... # review how to do that # - code to put at most one of these on one widget - can be grabbed from above - helper function, for use in methods # problem - might need two funcs, one to clear, one to add. since order should be clear (to deactivate), make (activates), add, # so never two active at once. #### REVIEW: should we rename connectWithState setStateConnection or something else with set, # to match setAction? # end
NanoCAD-master
cad/src/widgets/prefs_widgets.py
# Copyright 2007 Nanorex, Inc. See LICENSE file for details. """ NE1ToolBar.py - Variant of QToolBar in which the toolbar border is not rendered @author: Ninad @version: $Id$ @copyright: 2007 Nanorex, Inc. All rights reserved. History: File created on 20070507. There could be more than one NE1Toolbar classes (subclasses of QToolBar) in future depending upon the need. """ from PyQt4.Qt import QToolBar from PyQt4.Qt import QPainter from PyQt4.Qt import QStyleOptionToolBar from PyQt4.Qt import QPalette from PyQt4.Qt import QStyle class NE1ToolBar(QToolBar): """ Variant of QToolBar in which the toolbar border is not rendered. """ def paintEvent(self, event): """ reimplements the paintEvent of QToolBar """ #ninad20070507 : NE1ToolBar is used in Movie Prop mgr. # reimplementing paint event makes sure that the # unwanted toolbar border for the Movie control buttons # is not rendered. No other use at the moment. # [bruce 071214 guessed class docstring based on this comment. # I think the class should be renamed to be more descriptive.] painter = QPainter(self) option = QStyleOptionToolBar() option.initFrom(self) option.backgroundColor = self.palette().color(QPalette.Background) option.positionWithinLine = QStyleOptionToolBar.Middle option.positionOfLine = QStyleOptionToolBar.Middle self.style().drawPrimitive(QStyle.PE_PanelToolBar, option, painter, self) pass
NanoCAD-master
cad/src/widgets/NE1ToolBar.py
#!/usr/bin/python # Copyright 2005-2006 Nanorex, Inc. See LICENSE file for details. """runtest.py description.test [--generate] runs the described test and concatenates the results to stdout (after removing lines which vary inconsequentially (e.g. dates) if --generate is given, the results are written to $base.out, and the end structure is written to $base.xyzcmp (if the test type is "struct"). a description.test file looks like: comment lines, which start with a #, and are ignored blank lines, which are ignored lines containing one of the following directives: TYPE [ min | struct | dyn | fail ] Choose one of the given types of tests. The test type controls the defaults for the other directives. Test type "min" performs a minimization, and checks the program outputs, including the trace file and xyz file are identical. Test type "struct" also performs a minimization, but relies on a structure comparison to test for success, rather than the exact program output. Test type "dyn" performs a dynamics run, and requires that output be identical, as for "min". Default value for TYPE is "min". INPUT files... The listed files are copied to the temporary directory before the test is run. Defaults to the name of the description file with the .test replaced by .mmp ($base.mmp). OUTPUT files... The listed files contain significant data to be compared. They are concatenated together, run through a sed script to remove inconsequential lines, and the result goes to stdout. In addition to files explicitly generated by the program stdout and stderr are available. The file exitvalue contains the shell exit code $? resulting from executing the command. Defaults to "exitvalue stderr stdout $base.trc $base.xyz" for test types "min" and "dyn". Defaults to "exitvalue structurematch stderr" for test type "struct". PROGRAM command... This is the complete command line to run (excluding io redirection). Defaults to "/tmp/testsimulator -m -x $base.mmp" for test types "min" and "struct". Defaults to "/tmp/testsimulator -f100 -t300 -i10 -x $base.mmp" for test type "dyn". STRUCT file The listed file is compared against the $base.xyz file generated by PROGRAM. Defaults to "" for test types "min" and "dyn", and no structure comparison is performed. Defaults to "$base.xyzcmp" for test type "struct". # runtest.sh description.test [--generate] runs the described test and concatenates the results to stdout (after removing lines which vary inconsequentially (e.g. dates) if --generate is given, the results are written to $base.out, and the end structure is written to $base.xyzcmp (if the test type is "struct"). a description.test file looks like: comment lines, which start with a #, and are ignored blank lines, which are ignored lines containing one of the following directives: TYPE [ min | struct | dyn ] Choose one of the given types of tests. The test type controls the defaults for the other directives. Test type "min" performs a minimization, and checks the program outputs, including the trace file and xyz file are identical. Test type "struct" also performs a minimization, but relies on a structure comparison to test for success, rather than the exact program output. Test type "dyn" performs a dynamics run, and requires that output be identical, as for "min". Default value for TYPE is "min". INPUT files... The listed files are copied to the temporary directory before the test is run. Defaults to the name of the description file with the .test replaced by .mmp ($base.mmp). OUTPUT files... The listed files contain significant data to be compared. They are concatenated together, run through a sed script to remove inconsequential lines, and the result goes to stdout. In addition to files explicitly generated by the program stdout and stderr are available. The file exitvalue contains the shell exit code $? resulting from executing the command. Defaults to "exitvalue stderr stdout $base.trc $base.xyz" for test types "min" and "dyn". Defaults to "exitvalue structurematch stderr" for test type "struct". PROGRAM command... This is the complete command line to run (excluding io redirection). Defaults to "/tmp/testsimulator -m -x $base.mmp" for test types "min" and "struct". Defaults to "/tmp/testsimulator -f100 -t300 -i10 -x $base.mmp" for test type "dyn". STRUCT file The listed file is compared against the $base.xyz file generated by PROGRAM. Defaults to "" for test types "min" and "dyn", and no structure comparison is performed. Defaults to "$base.xyzcmp" for test type "struct". ################################################## NOTE: make sure you specify -x to generate a text file. Otherwise you'll end up with binary data in your output file for comparison, which is probably not what you wanted. ################################################## A minimizer test using the default command line and results can be performed with an empty description file. The other test types can often be performed with just a TYPE directive. """ import sys import os import re from os.path import join, dirname, basename, exists from shutil import copy, rmtree # I need this because I don't see a better way to get to findterms.py. sys.path.append("tests/scripts") import findterms # I've used os.linesep several places, assuming it would be the right # way to get cross-platform compatibility. When the time comes, we'll # need to check that I got that right. def appendFiles(flist, outfile, dtregexp = re.compile("Date and Time: ")): """for f in $flist; do echo ======= $f ======= cat $f done | sed '/Date and Time: /d' >> outfile""" outf = open(outfile, "a") for f in flist: outf.write("======= " + f + " =======" + os.linesep) for line in open(f).readlines(): if dtregexp.match(line) == None: line = line.rstrip() outf.write(line + os.linesep) outf.close() def run(prog, resultFile=None): # Redirect standard ouput to "stdout", appending # Redirect standard error to "stderr", appending # Will this work on Windows? prog += " >> stdout 2>> stderr" rc = os.system(prog) if resultFile != None: outf = open(resultFile, "w") # Exit status is shifted 8 bits left # http://www.python.org/search/hypermail/python-1994q2/0407.html # Does this apply to Windows? outf.write(repr(rc >> 8)) outf.close() def main(argv, myStdout=sys.stdout, generate=False): home = os.getcwd() testSpecFile = argv[0] assert testSpecFile[-5:] == ".test" if not exists("/tmp/testsimulator"): raise Exception, "Can't find /tmp/testsimulator" tmpDir = "/tmp/runtest%d" % os.getpid() rmtree(tmpDir, ignore_errors=True) os.mkdir(tmpDir) base = basename(testSpecFile[:-5]) here = os.getcwd() dir = dirname(testSpecFile) hereDir = join(here, dir) altoutFile = join(hereDir, base + ".altout") DEFAULT_INPUT = ["%s.mmp" % base] DEFAULT_OUTPUT_MIN = ["exitvalue", "stderr", "stdout", base+".trc", base + ".xyz"] DEFAULT_OUTPUT_STRUCT = ["exitvalue", "structurematch", "lengthsangles", "stderr"] DEFAULT_PROGRAM_MIN = "/tmp/testsimulator --minimize " + \ "--dump-as-text " + base + ".mmp" DEFAULT_PROGRAM_DYN = "/tmp/testsimulator --num-frames=100" + \ "--temperature=300 --iters-per-frame=10 " + \ "--dump-as-text " + base + ".mmp" DEFAULT_STRUCT_MIN = "" DEFAULT_STRUCT_STRUCT = base + ".xyzcmp" ALT_OUTPUT_FOR_STRUCT = ["exitvalue", "structurematch", "stderr", "stdout", base + ".trc", base + ".xyz"] userType = "min" userInput = [ ] userOutput = [ ] userProgram = "" userStruct = "" inf = open(testSpecFile) for line in inf.read().split(os.linesep): if line[:4] == "TYPE": userType = line[4:].strip() elif line[:5] == "INPUT": # This is a list, not a string userInput = line[5:].split() elif line[:6] == "OUTPUT": # This is a list, not a string userOutput = line[6:].split() elif line[:7] == "PROGRAM": userProgram = line[7:].strip() elif line[:6] == "STRUCT": userStruct = line[6:].strip() elif line[:1] == '#': pass elif len(line) > 0: raise Exception, \ "%s has unrecognied line:\n%s" % (testSpecFile, line) inf.close() if userType == "min": input = userInput or DEFAULT_INPUT output = userOutput or DEFAULT_OUTPUT_MIN program = userProgram or DEFAULT_PROGRAM_MIN struct = userStruct or DEFAULT_STRUCT_MIN elif userType == "struct": input = userInput or DEFAULT_INPUT output = userOutput or DEFAULT_OUTPUT_STRUCT program = userProgram or DEFAULT_PROGRAM_MIN struct = userStruct or DEFAULT_STRUCT_STRUCT elif userType == "dyn": input = userInput or DEFAULT_INPUT output = userOutput or DEFAULT_OUTPUT_MIN program = userProgram or DEFAULT_PROGRAM_DYN struct = userStruct or DEFAULT_STRUCT_MIN elif userType == "fail": input = userInput # might be None output = userOutput # will this work in Windows? program = userProgram or "echo fail" struct = userStruct else: raise Exception, \ "%s has unrecognied type:\n%s" % (testSpecFile, userType) if generate: outxyz = join(hereDir, struct) outstd = join(hereDir, base + ".out") outba = join(hereDir, base + ".ba") structCompare = (struct != "") for inputFile in input: copy(join(dir, inputFile), tmpDir) if structCompare and not generate: copy(join(dir, struct), tmpDir) copy(join(dir, base + ".ba"), tmpDir) results = open(join(tmpDir, "results"), "w") results.write("======= " + base + ".test =======" + os.linesep) results.write(open(testSpecFile).read()) results.close() os.chdir(tmpDir) run(program, "exitvalue") if structCompare: stdout = open("stdout", "a") stderr = open("stderr", "a") str = "== structure comparison ==" + os.linesep stdout.write(str) stderr.write(str) stdout.close() stderr.close() mmpFile = base + ".mmp" bondAngleFile = base + ".ba" if generate: # when generating a test case, assume the structure # comparison will succeed, therefore zero exit status sm = open("structurematch", "w") sm.write("0") sm.close() la = open("lengthsangles", "w") la.write("OK") la.close() findterms.main(mmpFile, outf=bondAngleFile, generateFlag=True) else: run("/tmp/testsimulator " + \ "--base-file=" + base + ".xyzcmp " + \ base + ".xyz", "structurematch") findterms.main(mmpFile, outf=open("lengthsangles", "w"), referenceInputFile=bondAngleFile) copy("results", altoutFile) appendFiles(ALT_OUTPUT_FOR_STRUCT, altoutFile) appendFiles(output, "results") if generate: copy("results", outstd) if structCompare: copy(base + ".xyz", outxyz) copy(base + ".ba", outba) else: myStdout.write(open("results").read()) os.chdir(home) return 0 if __name__ == "__main__": generate = False if len(sys.argv) > 2 and sys.argv[2] == "--generate": generate = True main(sys.argv[1:], generate=generate)
NanoCAD-master
sim/src/runtest.py
#!/usr/bin/python # Copyright 2006 Nanorex, Inc. See LICENSE file for details. # usage: # # mergemmpxyz.py file.mmp file.xyz > merged.mmp # import sys import re if len(sys.argv) != 3: print >>sys.stderr, "usage: mergemmpxyz.py file.mmp file.xyz > merged.mmp" sys.exit(1) atomLinePattern = re.compile(r"^(atom.*\(.*\).*\().*(\).*)$") xyzLinePattern = re.compile(r"^\S+\s+([-.0-9]+)\s+([-.0-9]+)\s+([-.0-9]+)\s*$") mmpInputFileName = sys.argv[1] xyzInputFileName = sys.argv[2] mmpInputFile = file(mmpInputFileName, "r") xyzInputFile = file(xyzInputFileName, "r") # skip the first two lines of xyz file xyzInput = xyzInputFile.readline() # number of atoms xyzInput = xyzInputFile.readline() # RMS=0.12345 mmpInput = mmpInputFile.readline() while mmpInput: mmpInput = mmpInput[:-1] # strip trailing newline m = atomLinePattern.match(mmpInput) if m: xyzInput = xyzInputFile.readline() if xyzInput: m2 = xyzLinePattern.match(xyzInput) if m2: x = int(float(m2.group(1)) * 1000.0) y = int(float(m2.group(2)) * 1000.0) z = int(float(m2.group(3)) * 1000.0) mmpInput = "%s%d, %d, %d%s" % (m.group(1), x, y, z, m.group(2)) else: print >>stderr, "xyz format error: " + xyzInput, sys.exit(1) else: print >>stderr, "not enough lines in xyz file" sys.exit(1) print mmpInput mmpInput = mmpInputFile.readline() mmpInputFile.close() xyzInputFile.close()
NanoCAD-master
sim/src/mergemmpxyz.py
#!/usr/bin/python # Copyright 2005-2006 Nanorex, Inc. See LICENSE file for details. """run regression tests how to make a regression test: Inside one of the directories listed below, you need to create three files. I'm going to call them test_000X.* here. Just number them sequentially although that doesn't really matter. The first file is the input data file for the test run. It will usually be called test_000X.mmp. If it's called something else, or there are more than one of them (or zero of them), you can specify that using the INPUT directive in the .test file. The second file is the test description file: test_000X.test. This file describes the inputs, outputs, and program arguments for the test. The default values should be fine for minimizer tests. For dynamics runs you'll need to specify the program arguments: PROGRAM simulator -f900 -x test_000X.mmp See runtest.sh for a complete description. The third file is the expected output. Generate this using runtest.sh like this (in the test directory): ../../runtest.sh test_000X.test > test_000X.out You can change the list of output files to be included using the OUTPUT directive in the .test file. Check this file to make sure the output looks reasonable, then rerun regression.sh before checking in the test_000X.* files. """ import os import sys import filecmp from shutil import copy from os.path import join, basename, exists from glob import glob import runtest testDirs = ["tests/minimize", "tests/dynamics", "tests/rigid_organics"] exitStatus = 0 generate = False try: if sys.argv[1] == "--generate": generate = True except IndexError: pass if exists("/tmp/testsimulator"): os.remove("/tmp/testsimulator") # Windows doesn't have symbolic links, so copy the file. copy("simulator", "/tmp/testsimulator") for dir in testDirs: for testFile in glob(join(dir, "*.test")): print "Running " + testFile base = basename(testFile[:-5]) out = join(dir, base + ".out") # Why do we not pass "--generate" to runtest??? outf = open(out + ".new", "w") #runtest.main((testFile,), myStdout=outf, generate=generate) runtest.main((testFile,), myStdout=outf) outf.close() if generate and not exists(out): copy(out + ".new", out) print "Generated new " + out if filecmp.cmp(out, out + ".new"): os.remove(out + ".new") else: print >> sys.__stderr__, "Test failed: " + testFile os.system("diff %s %s.new > %s.diff" % (out, out, out)) exitStatus = 1 os.remove("/tmp/testsimulator")
NanoCAD-master
sim/src/regression.py
#! /usr/bin/python # Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. from string import * import re import os import sys from math import sqrt findBondNamePattern = re.compile(r"^(\S+)\s+(.*)$") bondNamePattern = re.compile(r"(.*)([-=+@#])(.*)$") parameterPattern = re.compile(r"^([^=]+)\s*\=\s*(\S+)\s*(.*)") idPattern = re.compile(r"(\$Id\:.*\$)") commentPattern = re.compile("#") leadingWhitespacePattern = re.compile(r"^\s*") trailingWhitespacePattern = re.compile(r"\s*$") elmnts=[("H", 1, 1.6737), ("He", 2, 6.646), ("Li", 3, 11.525), ("Be", 4, 14.964), ("B", 5, 17.949), ("C", 6, 19.925), ("N", 7, 23.257), ("O", 8, 26.565), ("F", 9, 31.545), ("Ne", 10, 33.49), ("Na", 11, 38.1726), ("Mg", 12, 40.356), ("Al", 13, 44.7997), ("Si", 14, 46.6245), ("P", 15, 51.429), ("S", 16, 53.233), ("Cl", 17, 58.867), ("Ar", 18, 66.33), ("K", 19, 64.9256), ("Ca", 20, 66.5495), ("Sc", 21, 74.646), ("Ti", 22, 79.534), ("V", 23, 84.584), ("Cr", 24, 86.335), ("Mn", 25, 91.22), ("Fe", 26, 92.729), ("Co", 27, 97.854), ("Ni", 28, 97.483), ("Cu", 29, 105.513), ("Zn", 30, 108.541), ("Ga", 31, 115.764), ("Ge", 32, 120.53), ("As", 33, 124.401), ("Se", 34, 131.106), ("Br", 35, 132.674), ("Kr", 36, 134.429), ("Ax", 200, 0.000), ("Ss", 201, 0.000), ("Sp", 202, 0.000), ] sym2num={} for (sym, num, mass) in elmnts: sym2num[sym] = num bontyp = {'-':'1', '=':'2', '+':'3','@':'a', '#':'g'} def printBond(a1, bond, a2, parameters): ks = float(parameters['Ks']) r0 = float(parameters['R0']) de = float(parameters['De']) quality = int(parameters['Quality']) quadratic = int(parameters['Quadratic']) bt=sqrt(ks/(2.0*de))/10.0 r0=r0*100.0 r=r0; b = -1; while b < 0: a = (r * r - r0 * r0) b = a * a / r - 4000000 * de * r0 / ks r = r + 0.01 if sym2num[a1] > sym2num[a2]: e2 = a1 e1 = a2 else: e1 = a1 e2 = a2 print ' addInitialBondStretch(%7.2f,%7.2f,%7.4f,%7.4f,%7.2f,'%(ks,r0,de,bt,r), print '%5d, %3d, "%s-%s-%s");'%(quality, quadratic, e1, bontyp[bond], e2) if __name__ == "__main__": f=open(sys.argv[1]) headerPrinted = False for lin in f.readlines(): # remove leading and trailing whitespace lin = leadingWhitespacePattern.sub('', lin) lin = trailingWhitespacePattern.sub('', lin) # find RCSID m = idPattern.search(lin) if m: print '#define RCSID_BONDS_H "Generated from: ' + m.group(1) + '"' continue # ignore comments and blank lines if commentPattern.match(lin): continue if len(lin) == 0: continue m = findBondNamePattern.match(lin) if (m): bond = m.group(1) rest = m.group(2) parameters = {} parameters['bond'] = bond # default values for particular parameters: parameters['Quality'] = 9 parameters['Quadratic'] = 0 # extract parameters from rest of line into dictionary m = parameterPattern.match(rest) while m: key = m.group(1) value = m.group(2) rest = m.group(3) parameters[key] = value m = parameterPattern.match(rest) m = bondNamePattern.match(bond) if m: if not headerPrinted: headerPrinted = True print '// ks r0 de beta inflectionR qual quad bondName' printBond(m.group(1), m.group(2), m.group(3), parameters) else: print >> sys.stderr, 'malformed bond: ' + bond continue else: print >> sys.stderr, 'unrecognized line: "' + lin + '"'
NanoCAD-master
sim/src/stretch.py
# Copyright 2004-2006 Nanorex, Inc. See LICENSE file for details. """Vectors, Quaternions, and Trackballs Vectors are a simplified interface to the Numeric arrays. A relatively full implementation of Quaternions. Trackball produces incremental quaternions using a mapping of the screen onto a sphere, tracking the cursor on the sphere. """ import math, types from math import * from Numeric import * from LinearAlgebra import * intType = type(2) floType = type(2.0) numTypes = [intType, floType] def V(*v): return array(v, Float) def A(a): return array(a, Float) def cross(v1, v2): return V(v1[1]*v2[2] - v1[2]*v2[1], v1[2]*v2[0] - v1[0]*v2[2], v1[0]*v2[1] - v1[1]*v2[0]) def vlen(v1): return sqrt(dot(v1, v1)) def norm(v1): lng = vlen(v1) if lng: return v1 / lng # bruce 041012 optimized this by using lng instead of # recomputing vlen(v1) -- code was v1 / vlen(v1) else: return v1+0 # p1 and p2 are points, v1 is a direction vector from p1. # return (dist, wid) where dist is the distance from p1 to p2 # measured in the direction of v1, and wid is the orthogonal # distance from p2 to the p1-v1 line. # v1 should be a unit vector. def orthodist(p1, v1, p2): dist = dot(v1, p2-p1) wid = vlen(p1+dist*v1-p2) return (dist, wid) class Q: """Q(W, x, y, z) is the quaternion with axis vector x,y,z and sin(theta/2) = W (e.g. Q(1,0,0,0) is no rotation) Q(x, y, z) where x, y, and z are three orthonormal vectors is the quaternion that rotates the standard axes into that reference frame. (the frame has to be right handed, or there's no quaternion that can do it!) Q(V(x,y,z), theta) is what you probably want. Q(vector, vector) gives the quat that rotates between them """ def __init__(self, x, y=None, z=None, w=None): # 4 numbers if w != None: self.vec=V(x,y,z,w) elif z: # three axis vectors # Just use first two a100 = V(1,0,0) c1 = cross(a100,x) if vlen(c1)<0.000001: self.vec = Q(y,z).vec return ax1 = norm((a100+x)/2.0) x2 = cross(ax1,c1) a010 = V(0,1,0) c2 = cross(a010,y) if vlen(c2)<0.000001: self.vec = Q(x,z).vec return ay1 = norm((a010+y)/2.0) y2 = cross(ay1,c2) axis = cross(x2, y2) nw = sqrt(1.0 + x[0] + y[1] + z[2])/2.0 axis = norm(axis)*sqrt(1.0-nw**2) self.vec = V(nw, axis[0], axis[1], axis[2]) elif type(y) in numTypes: # axis vector and angle v = (x / vlen(x)) * sin(y*0.5) self.vec = V(cos(y*0.5), v[0], v[1], v[2]) elif y: # rotation between 2 vectors x = norm(x) y = norm(y) v = cross(x, y) theta = acos(min(1.0,max(-1.0,dot(x, y)))) if dot(y, cross(x, v)) > 0.0: theta = 2.0 * pi - theta w=cos(theta*0.5) vl = vlen(v) # null rotation if w==1.0: self.vec=V(1, 0, 0, 0) # opposite pole elif vl<0.000001: ax1 = cross(x,V(1,0,0)) ax2 = cross(x,V(0,1,0)) if vlen(ax1)>vlen(ax2): self.vec = norm(V(0, ax1[0],ax1[1],ax1[2])) else: self.vec = norm(V(0, ax2[0],ax2[1],ax2[2])) else: s=sqrt(1-w**2)/vl self.vec=V(w, v[0]*s, v[1]*s, v[2]*s) elif type(x) in numTypes: # just one number self.vec=V(1, 0, 0, 0) else: self.vec=V(x[0], x[1], x[2], x[3]) self.counter = 50 def __getattr__(self, name): if name == 'w': return self.vec[0] elif name in ('x', 'i'): return self.vec[1] elif name in ('y', 'j'): return self.vec[2] elif name in ('z', 'k'): return self.vec[3] elif name == 'angle': if -1.0<self.vec[0]<1.0: return 2.0*acos(self.vec[0]) else: return 0.0 elif name == 'axis': return V(self.vec[1], self.vec[2], self.vec[3]) elif name == 'matrix': # this the transpose of the normal form # so we can use it on matrices of row vectors self.__dict__['matrix'] = array([\ [1.0 - 2.0*(self.y**2 + self.z**2), 2.0*(self.x*self.y + self.z*self.w), 2.0*(self.z*self.x - self.y*self.w)], [2.0*(self.x*self.y - self.z*self.w), 1.0 - 2.0*(self.z**2 + self.x**2), 2.0*(self.y*self.z + self.x*self.w)], [2.0*(self.z*self.x + self.y*self.w), 2.0*(self.y*self.z - self.x*self.w), 1.0 - 2.0 * (self.y**2 + self.x**2)]]) return self.__dict__['matrix'] else: raise AttributeError, 'No "%s" in Quaternion' % name def __getitem__(self, num): return self.vec[num] def setangle(self, theta): """Set the quaternion's rotation to theta (destructive modification). (In the same direction as before.) """ theta = remainder(theta/2.0, pi) self.vec[1:] = norm(self.vec[1:]) * sin(theta) self.vec[0] = cos(theta) self.__reset() return self def __reset(self): if self.__dict__.has_key('matrix'): del self.__dict__['matrix'] def __setattr__(self, name, value): if name=="w": self.vec[0] = value elif name=="x": self.vec[1] = value elif name=="y": self.vec[2] = value elif name=="z": self.vec[3] = value else: self.__dict__[name] = value def __len__(self): return 4 def __add__(self, q1): """Q + Q1 is the quaternion representing the rotation achieved by doing Q and then Q1. """ return Q(q1.w*self.w - q1.x*self.x - q1.y*self.y - q1.z*self.z, q1.w*self.x + q1.x*self.w + q1.y*self.z - q1.z*self.y, q1.w*self.y - q1.x*self.z + q1.y*self.w + q1.z*self.x, q1.w*self.z + q1.x*self.y - q1.y*self.x + q1.z*self.w) def __iadd__(self, q1): """this is self += q1 """ temp=V(q1.w*self.w - q1.x*self.x - q1.y*self.y - q1.z*self.z, q1.w*self.x + q1.x*self.w + q1.y*self.z - q1.z*self.y, q1.w*self.y - q1.x*self.z + q1.y*self.w + q1.z*self.x, q1.w*self.z + q1.x*self.y - q1.y*self.x + q1.z*self.w) self.vec=temp self.counter -= 1 if self.counter <= 0: self.counter = 50 self.normalize() self.__reset() return self def __sub__(self, q1): return self + (-q1) def __isub__(self, q1): return __iadd__(self, -q1) def __mul__(self, n): """multiplication by a scalar, i.e. Q1 * 1.3, defined so that e.g. Q1 * 2 == Q1 + Q1, or Q1 = Q1*0.5 + Q1*0.5 Python syntax makes it hard to do n * Q, unfortunately. """ if type(n) in numTypes: nq = +self nq.setangle(n*self.angle) return nq else: raise MulQuat def __imul__(self, q2): if type(n) in numTypes: self.setangle(n*self.angle) self.__reset() return self else: raise MulQuat def __div__(self, q2): return self*q2.conj()*(1.0/(q2*q2.conj()).w) def __repr__(self): return 'Q(%g, %g, %g, %g)' % (self.w, self.x, self.y, self.z) def __str__(self): a= "<q:%6.2f @ " % (2.0*acos(self.w)*180/pi) l = sqrt(self.x**2 + self.y**2 + self.z**2) if l: z=V(self.x, self.y, self.z)/l a += "[%4.3f, %4.3f, %4.3f] " % (z[0], z[1], z[2]) else: a += "[%4.3f, %4.3f, %4.3f] " % (self.x, self.y, self.z) a += "|%8.6f|>" % vlen(self.vec) return a def __pos__(self): return Q(self.w, self.x, self.y, self.z) def __neg__(self): return Q(self.w, -self.x, -self.y, -self.z) def conj(self): return Q(self.w, -self.x, -self.y, -self.z) def normalize(self): w=self.vec[0] v=V(self.vec[1],self.vec[2],self.vec[3]) length = vlen(v) if length: s=sqrt(1.0-w**2)/length self.vec = V(w, v[0]*s, v[1]*s, v[2]*s) else: self.vec = V(1,0,0,0) return self def unrot(self,v): return matrixmultiply(self.matrix,v) def vunrot(self,v): # for use with row vectors return matrixmultiply(v,transpose(self.matrix)) def rot(self,v): return matrixmultiply(v,self.matrix) def twistor(axis, pt1, pt2): """return the quaternion that, rotating around axis, will bring pt1 closest to pt2. """ q = Q(axis, V(0,0,1)) pt1 = q.rot(pt1) pt2 = q.rot(pt2) a1 = atan2(pt1[1],pt1[0]) a2 = atan2(pt2[1],pt2[0]) theta = a2-a1 return Q(axis, theta) # project a point from a tangent plane onto a unit sphere def proj2sphere(x, y): d = sqrt(x*x + y*y) theta = pi * 0.5 * d s=sin(theta) if d>0.0001: return V(s*x/d, s*y/d, cos(theta)) else: return V(0.0, 0.0, 1.0) class Trackball: '''A trackball object. The current transformation matrix can be retrieved using the "matrix" attribute.''' def __init__(self, wide, high): '''Create a Trackball object. "size" is the radius of the inner trackball sphere. ''' self.w2=wide/2.0 self.h2=high/2.0 self.scale = 1.1 / min(wide/2.0, high/2.0) self.quat = Q(1,0,0,0) self.oldmouse = None def rescale(self, wide, high): self.w2=wide/2.0 self.h2=high/2.0 self.scale = 1.1 / min(wide/2.0, high/2.0) def start(self, px, py): self.oldmouse=proj2sphere((px-self.w2)*self.scale, (self.h2-py)*self.scale) def update(self, px, py, uq=None): newmouse = proj2sphere((px-self.w2)*self.scale, (self.h2-py)*self.scale) if self.oldmouse and not uq: quat = Q(self.oldmouse, newmouse) elif self.oldmouse and uq: quat = uq + Q(self.oldmouse, newmouse) - uq else: quat = Q(1,0,0,0) self.oldmouse = newmouse return quat def ptonline(xpt, lpt, ldr): """return the point on a line (point lpt, direction ldr) nearest to point xpt """ ldr = norm(ldr) return dot(xpt-lpt,ldr)*ldr + lpt def planeXline(ppt, pv, lpt, lv): """find the intersection of a line (point lpt, vector lv) with a plane (point ppt, normal pv) return None if (almost) parallel """ d=dot(lv,pv) if abs(d)<0.000001: return None return lpt+lv*(dot(ppt-lpt,pv)/d) def cat(a,b): """concatenate two arrays (the NumPy version is a mess) """ if not a: return b if not b: return a r1 = shape(a) r2 = shape(b) if len(r1) == len(r2): return concatenate((a,b)) if len(r1)<len(r2): return concatenate((reshape(a,(1,)+r1), b)) else: return concatenate((a,reshape(b,(1,)+r2))) def Veq(v1, v2): "tells if v1 is all equal to v2" return logical_and.reduce(v1==v2) __author__ = "Josh"
NanoCAD-master
sim/src/VQT.py
# Copyright 2005-2006 Nanorex, Inc. See LICENSE file for details. ''' setup.py (for sim code) Distutils setup file -- tells distutils how to rebuild our custom extension modules. NOTE: very similar to cad/src/setup.py in the cad cvs module. Some comments and docstrings (more relevant to cad than to sim) appear only in that file; others occur in both files. $Id$ One way to run this might be "make extensions" or "make pyx"; see Makefile in this directory. A more direct way is to ask your shell to do python setup.py build_ext --inplace For up to date info about how to do this (especially for Windows), see the wiki. Running this makes some output files and subdirectories, and prints lots of output. I think it only recompiles what needs to be recompiled (based on modtimes), but I\'m not sure. (I\'ve had a hard time finding any documentation about the internal workings of distutils, though it\'s easy to find basic instructions about how to use it.) This is based on the Pyrex example file Pyrex-0.9.3/Demos/Setup.py. ''' __author__ = ['bruce', 'will'] import sys from distutils.core import setup from distutils.extension import Extension try: from Pyrex.Distutils import build_ext except: print "Problem importing Pyrex. You need to install Pyrex before it makes sense to run this." print "For more info see cad/src/README-Pyrex and/or " print " http://www.nanoengineer-1.net/mediawiki/index.php?title=Integrating_Pyrex_into_the_Build_System" print "(If you already installed Pyrex, there's a bug in your Pyrex installation or in setup.py, " print " since the import should have worked.)" sys.exit(1) # Work around Mac compiler hang for -O3 with newtables.c # (and perhaps other files, though problem didn't occur for the ones compiled before newtables). # Ideally we'd do this only for that one file, but we don't yet know a non-klugy way to do that. # If we can't find one, we can always build newtables.o separately (perhaps also using distutils) # and then link newtables.o here by using the extra_objects distutils keyword, # which was used for most .o files in a prior cvs revision of this file. # [change by Will, commented by Bruce, 051230.] # Oops, now we've seen this on Linux, so back off optimization on all platforms # wware 060327, bug 1758 extra_compile_args = [ "-DDISTUTILS", "-O" ] setup(name = 'Simulator', ext_modules=[Extension("sim", ["sim.pyx", "allocate.c", "dynamics.c", "globals.c", "hashtable.c", "interpolate.c", "jigs.c", "lin-alg.c", "minimize.c", "minstructure.c", "newtables.c", "part.c", "potential.c", "printers.c", "readmmp.c", "readxyz.c", "structcompare.c", "writemovie.c"], depends = ["simhelp.c", "version.h", "bends.gen", "bonds.gen"], extra_compile_args = extra_compile_args ), ], cmdclass = {'build_ext': build_ext}) # this exit reminds people not to "import setup" from nE-1 itself! print "setup.py finished; exiting." sys.exit(0) #end
NanoCAD-master
sim/src/setup.py
#! /usr/bin/python # Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. from string import * import re import os import sys from math import sqrt findBondNamePattern = re.compile(r"^(\S+)\s+(.*)$") bondNamePattern = re.compile(r"(.*)([-=+@#])(.*)([-=+@#])(.*)$") parameterPattern = re.compile(r"^([^=]+)\s*\=\s*(\S+)\s*(.*)") idPattern = re.compile(r"(\$Id\:.*\$)") commentPattern = re.compile("#") leadingWhitespacePattern = re.compile(r"^\s*") trailingWhitespacePattern = re.compile(r"\s*$") elmnts=[("H", 1, 1.6737), ("He", 2, 6.646), ("Li", 3, 11.525), ("Be", 4, 14.964), ("B", 5, 17.949), ("C", 6, 19.925), ("N", 7, 23.257), ("O", 8, 26.565), ("F", 9, 31.545), ("Ne", 10, 33.49), ("Na", 11, 38.1726), ("Mg", 12, 40.356), ("Al", 13, 44.7997), ("Si", 14, 46.6245), ("P", 15, 51.429), ("S", 16, 53.233), ("Cl", 17, 58.867), ("Ar", 18, 66.33), ("K", 19, 64.9256), ("Ca", 20, 66.5495), ("Sc", 21, 74.646), ("Ti", 22, 79.534), ("V", 23, 84.584), ("Cr", 24, 86.335), ("Mn", 25, 91.22), ("Fe", 26, 92.729), ("Co", 27, 97.854), ("Ni", 28, 97.483), ("Cu", 29, 105.513), ("Zn", 30, 108.541), ("Ga", 31, 115.764), ("Ge", 32, 120.53), ("As", 33, 124.401), ("Se", 34, 131.106), ("Br", 35, 132.674), ("Kr", 36, 134.429), ("Ax", 200, 0.000), ("Ss", 201, 0.000), ("Sp", 202, 0.000), ] sym2num={} bends={} for (sym, num, mass) in elmnts: sym2num[sym] = num bontyp = {'-':'1', '=':'2', '+':'3','@':'a', '#':'g'} def printBond(a1, bond1, ac, bond2, a2, parameters): ktheta = parameters['Ktheta'] theta0 = parameters['theta0'] centerHybridization = parameters['CenterHybridization'] quality = int(parameters['Quality']) b1 = bontyp[bond1] b2 = bontyp[bond2] if sym2num[a1] > sym2num[a2] or (a1 == a2 and b1 > b2): a1, b1, b2, a2 = a2, b2, b1, a1 bendName = '%s-%s-%s.%s-%s-%s' % (a1, b1, ac, centerHybridization, b2, a2) bendLine = 'addInitialBendData(%-14s, %-13s, %2d, "%s");' % (ktheta, theta0, quality, bendName) if (bendName in bends): print '//' + bendLine else: print ' ' + bendLine bends[bendName] = 1 if __name__ == "__main__": f=open(sys.argv[1]) headerPrinted = False for lin in f.readlines(): # remove leading and trailing whitespace lin = leadingWhitespacePattern.sub('', lin) lin = trailingWhitespacePattern.sub('', lin) # find RCSID m = idPattern.search(lin) if m: print '#define RCSID_BENDS_H "Generated from: ' + m.group(1) + '"' continue # ignore comments and blank lines if commentPattern.match(lin): continue if len(lin) == 0: continue m = findBondNamePattern.match(lin) if (m): bond = m.group(1) rest = m.group(2) parameters = {} parameters['bond'] = bond # default values for particular parameters: parameters['Quality'] = 9 parameters['CenterHybridization'] = "sp3" # extract parameters from rest of line into dictionary m = parameterPattern.match(rest) while m: key = m.group(1) value = m.group(2) rest = m.group(3) parameters[key] = value m = parameterPattern.match(rest) m = bondNamePattern.match(bond) if m: if not headerPrinted: headerPrinted = True print '// ktheta theta0 quality bondName' printBond(m.group(1), m.group(2), m.group(3), m.group(4), m.group(5), parameters) else: print >> sys.stderr, 'malformed bond: ' + bond continue else: print >> sys.stderr, 'unrecognized line: "' + lin + '"'
NanoCAD-master
sim/src/bend.py
#!/usr/bin/env python # Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. """ Users place files into the INPUT directory and run batchsim. After a while, results appear in the OUTPUT directory. Each time batchsim is run, it scans the INPUT directory. Each .mmp file it finds is moved into a consecutively numbered subdirectory of QUEUE. The user is prompted for simulation parameters (temp, steps per frame, frames), which are used to build a command string. This command string is placed in the file 'run' in the same directory as the .mmp file. The batchsim script then starts the queue runner, and prints the status of all submitted jobs. It is safe to run batchsim as often as you like without providing any input files. This will just show you the status of job processing. It can be placed in a crontab with the --run-queue option to suppress the input scanning and status printing. This will restart the queue runner if it happens to have exited. The queue runner process is started with 'batchsim --run-queue'. It exits immediately if there is already a queue runner process. Otherwise, it scans the QUEUE directory and finds the first job. This is moved to the RUN directory, and the job's 'run' file is executed. When it exits, the job directory is moved to the OUTPUT directory, and the queue runner scans the QUEUE directory again. When it finds nothing in the QUEUE directory, it exits. """ import sys import os import time import fcntl baseDirectory = "/tmp/batchsim" INPUT = os.path.join(baseDirectory, "input") OUTPUT = os.path.join(baseDirectory, "output") QUEUE = os.path.join(baseDirectory, "queue") CURRENT = os.path.join(baseDirectory, "current") def nextJobNumber(): nextFileName = os.path.join(QUEUE, "next") try: f = open(nextFileName) n = int(f.readline()) f.close() except IOError: n = 0 f = open(nextFileName, 'w') print >>f, "%d" % (n + 1) return "%05d" % n def ask(question, default): """ Ask the user a question, presenting them with a default answer. Return their answer or the default if they just entered a blank line. """ print print "%s [%s]? " % (question, default), # suppress newline try: reply = sys.stdin.readline() except KeyboardInterrupt: print print "Aborted" sys.exit(1) if (reply.isspace()): return default return reply def askInt(question, default): while (True): reply = ask(question, default) try: result = int(reply) return result except ValueError: print print "reply was not an integer: " + reply.strip() def askFloat(question, default): while (True): reply = ask(question, default) try: result = float(reply) return result except ValueError: print print "reply was not a float: " + reply.strip() def runJob(jobNumber): queuePath = os.path.join(QUEUE, jobNumber) currentPath = os.path.join(CURRENT, jobNumber) outputPath = os.path.join(OUTPUT, jobNumber) os.rename(queuePath, currentPath) os.chdir(currentPath) childStdin = open("/dev/null") childStdout = open("stdout", 'w') childStderr = open("stderr", 'w') os.dup2(childStdin.fileno(), 0) childStdin.close() os.dup2(childStdout.fileno(), 1) childStdout.close() os.dup2(childStderr.fileno(), 2) childStderr.close() run = open("run") for command in run: status = os.system(command) if (status): print >>sys.stderr, "command: %s\nexited with status: %d" % (command, status) break os.close(0) os.close(1) os.close(2) os.chdir("/") os.rename(currentPath, outputPath) def processQueue(): # First, we move anything from the current directory into output, # and consider those jobs to have failed. The processQueue that # started these should have moved them to output itself, so # something must have gone wrong. We abort rather than retrying, # so we can make progress on other jobs. fileList = os.listdir(CURRENT) fileList.sort() for jobNumber in fileList: if (jobNumber.isdigit()): jobPath = os.path.join(CURRENT, jobNumber) failed = open(os.path.join(jobPath, "FAILED"), 'w') print >>failed, "The queue processor exited without completing this job." failed.close() os.rename(jobPath, os.path.join(OUTPUT, jobNumber)) # Now, we check to see if there's anything in the queue directory. # If so, we move the first job to current, and execute it's run # file. Move the results to the output directory and scan again # after the run file completes. while (True): gotOne = False fileList = os.listdir(QUEUE) fileList.sort() for jobNumber in fileList: if (jobNumber.isdigit()): gotOne = True runJob(jobNumber) break if (not gotOne): break def runQueue(): # fork and lock, exiting immediately if another process has the lock pid = os.fork() if (pid): # parent time.sleep(0.2) # seconds # by this time, a simulator sub-process should have been started else: # child lockFileName = os.path.join(QUEUE, "lock") lockFile = open(lockFileName, 'w') lockFD = lockFile.fileno() try: fcntl.flock(lockFD, fcntl.LOCK_EX | fcntl.LOCK_NB) except IOError: os._exit(0) processQueue() os._exit(0) def scanInput(): fileList = os.listdir(INPUT) fileList.sort() for fileName in fileList: if (fileName.endswith(".mmp")): baseName = fileName[:-4] print "processing " + baseName dirInQueue = os.path.join(QUEUE, nextJobNumber()) os.mkdir(dirInQueue) os.rename(os.path.join(INPUT, fileName), os.path.join(dirInQueue, fileName)) runFile = open(os.path.join(dirInQueue, "run"), 'w') minimize = ask("[M]inimize or [D]ynamics", "D").strip().lower() if (minimize.startswith("m")): end_rms = askFloat("Ending force threshold (pN)", 50.0) useGromacs = ask("Use [G]romacs (required for DNA) or [N]D-1 (required for double bonds)", "G").strip().lower() if (useGromacs.startswith("g")): hasPAM = ask("Does your model contain PAM atoms (DNA)? (Y/N)", "Y").strip().lower() hasPAM = hasPAM.startswith("y") if (hasPAM): vdwCutoffRadius = 2 else: vdwCutoffRadius = -1 doNS = ask("Enable neighbor searching? [Y]es (more accurate)/[N]o (faster)", "N").strip().lower() if (doNS.startswith("y")): neighborSearching = 1 else: neighborSearching = 0 print >>runFile, "simulator -m --min-threshold-end-rms=%f --trace-file %s-trace.txt --write-gromacs-topology %s --path-to-cpp /usr/bin/cpp --system-parameters %s/control/sim-params.txt --vdw-cutoff-radius %f --neighbor-searching %d %s" \ % (end_rms, baseName, baseName, baseDirectory, vdwCutoffRadius, neighborSearching, fileName) print >>runFile, "grompp -f %s.mdp -c %s.gro -p %s.top -n %s.ndx -o %s.tpr -po %s-out.mdp" \ % (baseName, baseName, baseName, baseName, baseName, baseName) if (hasPAM): tableFile = "%s/control/yukawa.xvg" % baseDirectory table = "-table %s -tablep %s" % (tableFile, tableFile) else: table = "" print >>runFile, "mdrun -s %s.tpr -o %s.trr -e %s.edr -c %s.xyz-out.gro -g %s.log %s" \ % (baseName, baseName, baseName, baseName, baseName, table) else: print >>runFile, "simulator -m --system-parameters %s/control/sim-params.txt --output-format-3 --min-threshold-end-rms=%f --trace-file %s-trace.txt %s" \ % (baseDirectory, end_rms, baseName, fileName) else: temp = askInt("Temperature in Kelvins", 300) stepsPerFrame = askInt("Steps per frame", 10) frames = askInt("Frames", 900) print print "temp %d steps %d frames %d" % (temp, stepsPerFrame, frames) print >>runFile, "simulator --system-parameters %s/control/sim-params.txt --temperature=%d --iters-per-frame=%d --num-frames=%d --trace-file %s-trace.txt %s" \ % (baseDirectory, temp, stepsPerFrame, frames, baseName, fileName) else: print "ignoring " + os.path.join(INPUT, fileName) def showOneJob(dirName, jobNumber): fileList = os.listdir(dirName) fileList.sort() for fileName in fileList: if (fileName.endswith(".mmp")): print " %s %s" % (jobNumber, fileName) def showJobsInDirectory(dirName, header): gotOne = False fileList = os.listdir(dirName) fileList.sort() for jobNumber in fileList: if (jobNumber.isdigit()): if (not gotOne): print header gotOne = True showOneJob(os.path.join(dirName, jobNumber), jobNumber) def showStatus(): showJobsInDirectory(QUEUE, "\nJobs queued for later processing:\n") showJobsInDirectory(CURRENT, "\nCurrently executing job:\n") showJobsInDirectory(OUTPUT, "\nCompleted jobs:\n") gotProcess = False ps = os.popen("ps ax") header = ps.readline() for process in ps: if (process.find("simulator") > 0 or process.find("grompp") > 0 or process.find("mdrun") > 0): if (not gotProcess): print print "Currently running simulator processes:" print print header.strip() gotProcess = True print process.strip() if (not gotProcess): print print "No simulator processes running." def makeDirectory(path): if (os.access(path, os.W_OK)): return os.makedirs(path) def main(): makeDirectory(INPUT) makeDirectory(QUEUE) makeDirectory(CURRENT) makeDirectory(OUTPUT) if (len(sys.argv) > 1 and sys.argv[1] == '--run-queue'): runQueue() else: print scanInput() runQueue() showStatus() print if (__name__ == '__main__'): main()
NanoCAD-master
sim/src/batchsim.py
#!/usr/bin/python # Copyright 2005-2006 Nanorex, Inc. See LICENSE file for details. # usage: # # onetest.py <test_name> [args for tests.py] # # runs a single regression test by name # import sys import tests class Main(tests.Main): def main(self, args): self.theTest = args[0] tests.Main.main(self, args[1:]) def getCasenames(self): return [ self.theTest ] if __name__ == "__main__": Main().main(sys.argv[1:])
NanoCAD-master
sim/src/onetest.py
#!/usr/bin/python # Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. # usage: # # merge.parameters.py existingParameterFile newParameterFiles... # # creates existingParameterFile.new # import sys import re leadingWhitespacePattern = re.compile(r"^\s*") trailingWhitespacePattern = re.compile(r"\s*$") idPattern = re.compile(r"(\$Id\:.*\$)") commentPattern = re.compile("#") firstField = re.compile(r"^(\S+)\s+(.*)") parameterPattern = re.compile(r"^([^=]+)\s*\=\s*(\S+)\s*(.*)") existing = sys.argv[1] allfiles = sys.argv[1:] print "existing parameter file: " + existing newfile = open(existing + ".new", 'w') # accumulates canonicalized lines for each unique "bond hybridization" pair results = {} for f in allfiles: print "processing " + f lines = open(f).readlines(); for l in lines: # remove leading and trailing whitespace l = leadingWhitespacePattern.sub('', l) l = trailingWhitespacePattern.sub('', l) # find RCSID if f == existing and idPattern.search(l): newfile.write("#\n" + l + "\n#\n\n") continue # ignore comments and blank lines if commentPattern.match(l): continue if len(l) == 0: continue m = firstField.match(l) if m: bond = m.group(1) rest = m.group(2) canonical = bond + " " hybrid = "sp3" m = parameterPattern.match(rest) while m: key = m.group(1) value = m.group(2) rest = m.group(3) if key == "CenterHybridization": hybrid = value canonical += key + "=" + value + " " m = parameterPattern.match(rest) sortfield = bond + " " + hybrid results[sortfield] = canonical bondkeys = results.keys() bondkeys.sort() for key in bondkeys: newfile.write(results[key] + "\n")
NanoCAD-master
sim/src/merge.parameters.py
#!/usr/bin/python # Copyright 2005-2006 Nanorex, Inc. See LICENSE file for details. """Regression and QA test script for the simulator $Id$ Test cases will generally arrive as MMP files with QM-minimized atom positions (or for QM dynamics simulations, sequences of atom positions). These should be translated into *.xyzcmp files, which are the references that the minimizer should be trying to approach. The positions from the QM data can be perturbed to provide starting points for minimization tests. For instance, from the QM-minimized file tests/rigid_organics/C3H6.mmp provided by Damian, we generate test_C3H6.xyzcmp as described above, then generate test_C3H6.mmp by perturbing those positions. Then we use test_C3H6.xyzcmp and test_C3H6.mmp for testing. """ __author__ = "Will" try: import Numeric except ImportError: import numpy as Numeric import math import md5 import os import os.path import random import re import shutil import string import sys import time import traceback import types import unittest if sys.platform == "win32": simulatorCmd = "simulator.exe" else: simulatorCmd = "simulator" if __name__ == "__main__": if not os.path.exists(simulatorCmd): print "simulator needs rebuilding" if not os.path.exists("sim.so"): print "sim.so needs rebuilding" # Global flags and variables set from command lines DEBUG = 0 MD5_CHECKS = False TIME_ONLY = False TIME_LIMIT = 1.e9 LENGTH_ANGLE_TEST, STRUCTCOMPARE_C_TEST = range(2) STRUCTURE_COMPARISON_TYPE = LENGTH_ANGLE_TEST GENERATE = False KEEP_RESULTS = False SHOW_TODO = False VERBOSE_FAILURES = False LOOSE_TOLERANCES = False MEDIUM_TOLERANCES = False TIGHT_TOLERANCES = False TEST_DIR = None LIST_EVERYTHING = False class Unimplemented(AssertionError): pass def todo(str): if SHOW_TODO: raise Unimplemented(str) def readlines(filename): return map(lambda x: x.rstrip(), open(filename).readlines()) testTimes = { } testsSkipped = 0 ################################################################## # How much variation do we permit in bond lengths and bond # angles before we think it's a problem? For now these are # wild guesses, to be later scrutinized by smart people. # default values, overridden by loose, medium, and tight options LENGTH_TOLERANCE = 0.139 # angstroms ANGLE_TOLERANCE = 14.1 # degrees #LENGTH_TOLERANCE = 0.05 # angstroms #ANGLE_TOLERANCE = 5 # degrees class WrongNumberOfAtoms(AssertionError): pass class PositionMismatch(AssertionError): pass class LengthAngleMismatch(AssertionError): pass def V(*v): return Numeric.array(v, Numeric.Float) def vlen(v1): return math.sqrt(Numeric.dot(v1, v1)) def angleBetween(vec1, vec2): TEENY = 1.0e-10 lensq1 = Numeric.dot(vec1, vec1) if lensq1 < TEENY: return 0.0 lensq2 = Numeric.dot(vec2, vec2) if lensq2 < TEENY: return 0.0 dprod = Numeric.dot(vec1 / lensq1**.5, vec2 / lensq2**.5) if dprod >= 1.0: return 0.0 if dprod <= -1.0: return 180.0 return (180/math.pi) * math.acos(dprod) def measureLength(xyz, first, second): """Returns the angle between two atoms (nuclei)""" p0 = apply(V, xyz[first]) p1 = apply(V, xyz[second]) return vlen(p0 - p1) def measureAngle(xyz, first, second, third): """Returns the angle between two atoms (nuclei)""" p0 = apply(V, xyz[first]) p1 = apply(V, xyz[second]) p2 = apply(V, xyz[third]) v01, v21 = p0 - p1, p2 - p1 return angleBetween(v01, v21) _PeriodicTable = [ "X", # our singlet has element number zero "H", "He", "Li", "Be", "B", "C", "N", "O", "F", "Ne", "Na", "Mg", "Al", "Si", "P", "S", "Cl", "Ar", "K", "Ca" #Sc,Ti,V,Cr,Mn,Fe.... ] _MmpAtomPattern = re.compile("^atom (\d+) \((\d+)\) " + "\((\-?\d+), (\-?\d+), (\-?\d+)\)") class Atom: def __init__(self): self.elem = 0 self.x = self.y = self.z = 0.0 self.bonds = [ ] def clone(self): "permit deep cloning of structure files" a = Atom() for key in self.__dict__.keys(): setattr(a, key, getattr(self, key)) return a def __repr__(self): element = _PeriodicTable[self.elem] return "%s %f %f %f" % (element, self.x, self.y, self.z) class XyzFile: """Python class to contain information from an XYZ file""" def __init__(self): self.atoms = [ ] def clone(self): other = XyzFile() other.atoms = [ ] for a in self.atoms: other.atoms.append(a.clone()) return other def getAtom(self, i): return self.atoms[i] def __getitem__(self, i): a = self.atoms[i] return (a.x, a.y, a.z) def __setitem__(self, i, xyz): a = self.atoms[i] a.x, a.y, a.z = xyz def __len__(self): return len(self.atoms) def read(self, filename): inf = open(filename) self.readstring(inf.read()) inf.close() def readstring(self, lines): lines = lines.split("\n") numAtoms = string.atoi(lines[0].strip()) lines = lines[2:] for i in range(numAtoms): a = Atom() element, x, y, z = lines[i].split() a.elem = _PeriodicTable.index(element) a.x, a.y, a.z = map(string.atof, (x, y, z)) self.atoms.append(a) def readFromList(self, lst): assert type(lst) == types.ListType for atminfo in lst: a = Atom() element, x, y, z = atminfo a.elem = _PeriodicTable.index(element) a.x, a.y, a.z = map(string.atof, (x, y, z)) self.atoms.append(a) def write(self, title, outf=None): if outf == None: outf = sys.stdout outf.write("%d\n%s\n" % (len(self.atoms), title)) for atm in self.atoms: element = _PeriodicTable[self.elem] outf.write("%s %f %f %f\n" % (element, self.x, self.y, self.z)) class MmpFile: """This is meant to be a Python class representing a MMP file. It is not intended to represent ALL the information in a MMP file, although it might do that in some distant-future version.""" class _AtomHolder: """Atom holders are indices into the MmpFile.atoms list, and that's done so that MmpFiles are easier to clone. """ def __init__(self, owner, match, rest): a = Atom() groups = match.groups() a.elem = elem = string.atoi(groups[1]) str = "atom %s" % groups[0] str += " (%s)" % groups[1] str += " (%d, %d, %d)" str += rest a._mmpstr = str a.x = 0.001 * string.atoi(groups[2]) a.y = 0.001 * string.atoi(groups[3]) a.z = 0.001 * string.atoi(groups[4]) self._owner = owner self._index = len(owner.atoms) owner.atoms.append(a) def mmpBonds(self, line): if hasattr(self, "_str") or not line.startswith("bond"): return False a = self._owner.atoms[self._index] for b in line.split()[1:]: a.bonds.append(string.atoi(b)) return True def __str__(self): if hasattr(self, "_str"): return self._str a = self._owner.atoms[self._index] return a._mmpstr % (int(a.x * 1000), int(a.y * 1000), int(a.z * 1000)) def __init__(self): self.atoms = [ ] self.lines = [ ] def clone(self): other = MmpFile() other.lines = self.lines[:] other.atoms = [ ] for a in self.atoms: other.atoms.append(a.clone()) return other def getAtom(self, i): return self.atoms[i] def __getitem__(self, i): a = self.atoms[i] return (a.x, a.y, a.z) def __setitem__(self, i, xyz): a = self.atoms[i] a.x, a.y, a.z = xyz def __len__(self): return len(self.atoms) def read(self, filename): inf = open(filename) self.readstring(inf.read()) inf.close() def readstring(self, lines): lines = lines.split("\n") i, n = 0, len(lines) while i < n: line = lines[i] m = _MmpAtomPattern.match(line) if m == None: self.lines.append(line) else: rest = line[m.span()[1]:] # anything after position atm = MmpFile._AtomHolder(self, m, rest) self.lines.append(atm) line = lines[i+1] if line.startswith("info atom"): self.lines.append(line) i += 1 elif atm.mmpBonds(line): self.lines.append(line) i += 1 i += 1 def write(self, outf=None): if outf == None: outf = sys.stdout for ln in self.lines: outf.write(str(ln) + "\n") def convertToXyz(self): import XyzFile xyz = XyzFile.XyzFile() for a in self.atoms: xyz.atoms.append(a) return xyz def perturb(self): """WARNING: Using this method will put some atoms in the dangerous high-Morse-potential region. """ A = 0.5 # some small number of angstroms A = A / (3 ** .5) # amount in one dimension for i in range(len(self)): x, y, z = self[i] x += random.normalvariate(0.0, A) y += random.normalvariate(0.0, A) z += random.normalvariate(0.0, A) self[i] = (x, y, z) def simplifiedMMP(mmp_in, mmp_out): # translate from a complete MMP file to one the simulator can # understand groups = [ ] lines = readlines(mmp_in) outf = open(mmp_out, "w") while True: L = lines.pop(0) if L.startswith("group "): lines.insert(0, L) break outf.write(L + "\n") # identify groups and put them into the groups list gotFirstGoodGroup = False while True: nextGroup = [ ] # we are either at the start of a group, or something that's # not a group L = lines.pop(0) if L.startswith("end1"): # throw this line away, and look for more groups L = lines.pop(0) if not L.startswith("group ("): lines.insert(0, L) break goodGroup = not (L.startswith("group (View") or L.startswith("group (Clipboard")) if goodGroup and not gotFirstGoodGroup: while True: if L.endswith(" def"): L = L[:-4] + " -" outf.write(L + "\n") L = lines.pop(0) if L.startswith("egroup "): outf.write(L + "\n") break gotFirstGoodGroup = True else: while True: L = lines.pop(0) if L.startswith("egroup "): break # whatever comes after the last group is still in 'lines' for L in lines: outf.write(L + "\n") outf.close() class LengthAngleComparison: def __init__(self, mmpFilename): self.bondLengthTerms = bondLengthTerms = { } self.bondAngleTerms = bondAngleTerms = { } def addBondLength(atm1, atm2): if atm1 == atm2: raise AssertionError("bond from atom to itself?") if atm2 < atm1: atm1, atm2 = atm2, atm1 if bondLengthTerms.has_key(atm1): if atm2 not in bondLengthTerms[atm1]: bondLengthTerms[atm1].append(atm2) else: bondLengthTerms[atm1] = [ atm2 ] def getBonds(atm1): lst = [ ] if bondLengthTerms.has_key(atm1): for x in bondLengthTerms[atm1]: lst.append(x) for key in bondLengthTerms.keys(): if atm1 in bondLengthTerms[key]: if key not in lst: lst.append(key) lst.sort() return lst def addBondAngle(atm1, atm2, atm3): if atm1 == atm3: return if atm3 < atm1: atm1, atm3 = atm3, atm1 value = (atm2, atm3) if bondAngleTerms.has_key(atm1): if value not in bondAngleTerms[atm1]: bondAngleTerms[atm1].append(value) else: bondAngleTerms[atm1] = [ value ] self.mmp = mmp = MmpFile() mmp.read(mmpFilename) # store all the bonds in bondLengthTerms for i in range(len(mmp)): a = mmp.atoms[i] for b in a.bonds: addBondLength(i, b - 1) # generate angles from chains of two bonds for first in range(len(mmp)): for second in getBonds(first): for third in getBonds(second): addBondAngle(first, second, third) self.numAtoms = len(mmp) class LengthMeasurement: def __init__(self, first, second, mmp, xyz): self.measure = length = measureLength(xyz, first, second) self.atoms = (first, second) # In MMP and PDB files, we count from 1, where Python list # elements start indexing at zero. e1 = _PeriodicTable[mmp.atoms[first].elem] e2 = _PeriodicTable[mmp.atoms[second].elem] self.reprstr = ("<Length %s%d %s%d %g>" % (e1, first + 1, e2, second + 1, length)) def __repr__(self): return self.reprstr def closeEnough(self, other): if self.__class__ != other.__class__: return 1e20 if self.atoms != other.atoms: return 1e20 return abs(self.measure - other.measure) class AngleMeasurement(LengthMeasurement): def __init__(self, first, second, third, mmp, xyz): self.measure = angle = measureAngle(xyz, first, second, third) self.atoms = (first, second, third) # In MMP and PDB files, we count from 1, where Python list # elements start indexing at zero. e1 = _PeriodicTable[mmp.atoms[first].elem] e2 = _PeriodicTable[mmp.atoms[second].elem] e3 = _PeriodicTable[mmp.atoms[third].elem] self.reprstr = ("<Angle %s%d %s%d %s%d %g>" % (e1, first + 1, e2, second + 1, e3, third + 1, angle)) def getLAfromXYZ(self, xyz): if len(xyz) != self.numAtoms: raise WrongNumberOfAtoms, \ "%d, expected %d" % (len(xyz), self.numAtoms) lengthList = [ ] for first in self.bondLengthTerms.keys(): for second in self.bondLengthTerms[first]: lengthList.append(self.LengthMeasurement(first, second, self.mmp, xyz)) angleList = [ ] for first in self.bondAngleTerms.keys(): for second, third in self.bondAngleTerms[first]: angleList.append(self.AngleMeasurement(first, second, third, self.mmp, xyz)) return (lengthList, angleList) def compare(self, questionableXyz, knownGoodXyzFile, lengthTolerance, angleTolerance): todo("handle multiple-frame xyz files from animations") xyz = XyzFile() if type(questionableXyz) == types.StringType: xyz.read(questionableXyz) elif type(questionableXyz) == types.ListType: xyz.readFromList(questionableXyz) else: raise Exception, type(questionableXyz) L1, A1 = self.getLAfromXYZ(xyz) xyz = XyzFile() xyz.read(knownGoodXyzFile) L2, A2 = self.getLAfromXYZ(xyz) mismatches="" maxangle=0 maxlen=0 for len1, len2 in map(None, L1, L2): diff = len1.closeEnough(len2) if diff > lengthTolerance: mismatches += "got %s\nexpected %s diff %f\n" %(repr(len1), repr(len2), diff) if diff > maxlen: maxlen = diff for ang1, ang2 in map(None, A1, A2): diff = ang1.closeEnough(ang2) if diff > angleTolerance: mismatches += "got %s\nexpected %s diff %f\n" %(repr(ang1), repr(ang2), diff) if diff > maxangle: maxangle = diff if mismatches: if maxlen > 0: mismatches += "max length difference: %f > %f\n" %(maxlen, lengthTolerance) if maxangle > 0: mismatches += "max angle difference: %f > %f\n" %(maxangle, angleTolerance) raise LengthAngleMismatch("\n" + mismatches) ################################################################## class EarlyTermination(Exception): pass def rmtreeSafe(dir): # platform-independent 'rm -rf' try: shutil.rmtree(dir) except OSError, e: pass lastRecordedTime = testStartTime = time.time() class TimedTest: def start(self): global testsSkipped if (not TIME_ONLY and not GENERATE and time.time() > testStartTime + TIME_LIMIT): testsSkipped += 1 raise EarlyTermination def finish(self): if TIME_ONLY: global testTimes, lastRecordedTime previous = lastRecordedTime lastRecordedTime = t = time.time() testTimes[self.methodname] = t - previous raise EarlyTermination class SandboxTest(TimedTest): DEFAULT_INPUTS = ( ) # in addition to xxx.mmp DEFAULT_SIMOPTS = ( ) DEFAULT_OUTPUTS = ( ) # in addition to stdout, stderr def md5sum(self, filename): hash = md5.new() inf = open(filename) for line in open(filename).readlines(): try: line.index("Date and Time") pass except ValueError: hash.update(line) inf.close() def hex2(ch): return "%02X" % ord(ch) return "".join(map(hex2, hash.digest())) class MD5SumMismatch(AssertionError): pass def __init__(self, dir=None, test=None, simopts=None, inputs=None, outputs=None, expectedExitStatus=0): global Tests self.dirname = dir # rigid_organics self.shortname = test # C2H4 self.testname = testname = "test_" + test # test_C2H4 # midname = tests/rigid_organics/test_C2H4 self.midname = midname = os.path.join("tests", dir, testname) # methodname = test_rigid_organics_C2H4 self.methodname = methodname = "_".join(["test", dir, test]) # basename = .../sim/src/tests/rigid_organics/test_C2H4 self.basename = os.path.join(os.getcwd(), midname) self.expectedExitStatus = expectedExitStatus try: TimedTest.start(self) except EarlyTermination: return if inputs == None: inputs = self.DEFAULT_INPUTS if simopts == None: simopts = self.DEFAULT_SIMOPTS if outputs == None: outputs = self.DEFAULT_OUTPUTS self.inputs = inputs self.simopts = simopts self.outputs = outputs if LIST_EVERYTHING: print print dir, testname self.runInSandbox() def runInSandbox(self): # Run the simulator in sim/src/tmp. here = os.getcwd() tmpdir = "tmp_" + self.dirname + "_" + self.shortname try: rmtreeSafe(tmpdir) os.mkdir(tmpdir) # Copy the input files into the tmp directory. shutil.copy(simulatorCmd, tmpdir) # We always have a .mmp file shutil.copy(self.basename + ".mmp", tmpdir) if not GENERATE: for ext in self.inputs: shutil.copy(self.basename + "." + ext, tmpdir) # Go into the tmp directory and run the simulator. os.chdir(tmpdir) exitStatus = self.runCommand(self.simopts) if self.expectedExitStatus != None: if exitStatus != self.expectedExitStatus: inf = open("stderr") sys.stderr.write(inf.read()) inf.close() str = ("simulator exit status was %d, expected %d" % (exitStatus, self.expectedExitStatus)) raise AssertionError(str) if GENERATE: self.generateOutputFiles() else: if DEBUG > 0: print os.listdir(".") if DEBUG > 2: print ("******** " + self.basename + " ********") for f in os.listdir("."): if f != simulatorCmd: # assume everything else is a text file print "---- " + f + " ----" sys.stdout.write(open(f).read()) try: self.finish() except EarlyTermination: return self.checkOutputFiles() return finally: os.chdir(here) if not KEEP_RESULTS: rmtreeSafe(tmpdir) def runCommandQt(self, opts): import qt def substFOO(str): if str.startswith("FOO"): return self.testname + str[3:] return str cmdline = [ "./" + simulatorCmd ] + map(substFOO, opts) if DEBUG > 0: print self.basename print cmdline simProcess = qt.QProcess() stdout = open("stdout", "a") stderr = open("stderr", "a") def blabout(): r = str(simProcess.readStdout()) if DEBUG > 1: print "STDOUT", r stdout.write(str(simProcess.readStdout())) def blaberr(): r = str(simProcess.readStderr()) if DEBUG > 1: print "STDERR", r stderr.write(str(simProcess.readStderr())) qt.QObject.connect(simProcess, qt.SIGNAL("readyReadStdout()"), blabout) qt.QObject.connect(simProcess, qt.SIGNAL("readyReadStderr()"), blaberr) args = qt.QStringList() for arg in cmdline: args.append(arg) simProcess.setArguments(args) simProcess.start() while simProcess.isRunning(): time.sleep(0.1) stdout.close() stderr.close() return simProcess.exitStatus() def runCommandSubprocess(self, opts): import subprocess def substFOO(str): if str.startswith("FOO"): return self.testname + str[3:] return str cmdline = [ "./" + simulatorCmd ] + map(substFOO, opts) stdout = open("stdout", "w") stderr = open("stderr", "w") p = subprocess.Popen(cmdline) r = p.wait() stdout.close() stderr.close() return r def runCommand(self, opts): usingQt = True try: import qt except ImportError: usingQt = False if usingQt: return self.runCommandQt(opts) else: return self.runCommandSubprocess(opts) def checkOutputFiles(self): if MD5_CHECKS: self.checkMd5Sums() else: if "xyzcmp" in self.inputs: if STRUCTURE_COMPARISON_TYPE == STRUCTCOMPARE_C_TEST: if self.runCommand(("--base-file", "FOO.xyzcmp", "FOO.xyz")) != 0: raise AssertionError("bad structure match") else: self.structureComparisonBondlengthsBondangles() todo("anything else we should be checking here?") # Generate MD5 checksums for all output files, store in # tests/rigid_organics/test_C4H8.md5sums (for example) def generateOutputFiles(self): outf = open(self.basename + ".md5sums", "w") outf.write("stdout %s\n" % self.md5sum("stdout")) outf.write("stderr %s\n" % self.md5sum("stderr")) for ext in self.outputs: fname = self.testname + "." + ext outf.write("%s %s\n" % (fname, self.md5sum(fname))) outf.close() def checkMd5Sums(self): inf = open(self.basename + ".md5sums") for line in inf.readlines(): fname, sum = line.split() realsum = self.md5sum(fname) if realsum != sum: raise self.MD5SumMismatch(self.midname + " " + fname) inf.close() def structureComparisonBondlengthsBondangles(self, lengthtol=None, angletol=None): if lengthtol == None: lengthtol = LENGTH_TOLERANCE if angletol == None: angletol = ANGLE_TOLERANCE todo("handle multiple-frame xyz files from animations") lac = LengthAngleComparison(self.testname + ".mmp") lac.compare(self.testname + ".xyz", self.testname + ".xyzcmp", lengthtol, angletol) ######################################### class TraceFile: def __init__(self, filename): f = open(filename) lines = [ ] for L in f.readlines(): lines.append(L.rstrip()) f.close() description = "" Ncolumns = re.compile('^(\d+) columns') i = 0 self.columnNames = [ ] while True: if lines[i][:1] != '#': break line = lines[i][2:] description += line + '\n' if line.startswith('uname -a: '): self.platform = line[10:] elif line.startswith('CFLAGS: '): self.cflags = line[8:] elif line.startswith('LDFLAGS: '): self.ldflags = line[9:] elif line.startswith('Command Line: '): self.commandLine = line[14:] elif line.startswith('Date and Time: '): self.dateAndTime = line[15:] elif line.startswith('Input File: '): self.inputFile = line[12:] elif line.startswith('Output File: '): self.outputFile = line[13:] elif line.startswith('Trace File: '): self.traceFile = line[12:] elif line.startswith('Number of Frames: '): self.numFrames = string.atoi(line[18:]) elif line.startswith('Steps per Frame: '): self.stepsPerFrame = string.atoi(line[17:]) elif line.startswith('Temperature: '): self.temperature = string.atof(line[13:]) elif line.startswith('Number of Atoms: '): self.numAtoms = string.atoi(line[17:]) else: m = Ncolumns.search(line) if m != None: N = string.atoi(m.group(1)) for j in range(N): self.columnNames.append(lines[i][2:]) i += 1 while i < len(lines) and lines[i][:1] == '#': i += 1 break i += 1 self.data = data = [ ] while i < len(lines) and lines[i][:1] != '#': data.append(map(string.atof, lines[i].split())) i += 1 def fuzzyMatch(self, other): def substr(haystack, needle): try: haystack.index(needle) except ValueError: return False return True assert self.columnNames == other.columnNames, "different column names" assert len(self.data) == len(other.data), "wrong number of data lines" tests = [ ] for name in self.columnNames: # here we can customize tests by the types of jigs if name.startswith('Thermo'): # ignore thermometers, they are way too noisy def alwaysPass(x, y): assert x == x, "not-a-number values in reference results" assert y == y, "not-a-number values in test results" tests.append(alwaysPass) elif name.startswith('Rotary Motor') and substr(name, "speed"): # rotary motor speeds seem to get a lot of variation def checkSpeed(x, y, name=name): assert x == x, "not-a-number values in reference results" assert y == y, "not-a-number values in test results" xdif = abs(x - y) assert xdif < 10.0 or (xdif / abs(x)) < 0.2, \ ("%s: expected %g, got %g" % (name, x, y)) tests.append(checkSpeed) elif name.startswith('Angle'): # angles seem to get a lot of variation def checkAngle(x, y, name=name): assert x == x, "not-a-number values in reference results" assert y == y, "not-a-number values in test results" xdif = abs(x - y) assert xdif < 10.0 or (xdif / abs(x)) < 0.2, \ ("%s: expected %g, got %g" % (name, x, y)) tests.append(checkAngle) elif name.startswith('Dihedral'): # dihedral angles vary a lot, and they flip sign if they # pass through 180 or -180 def checkDihedral(x, y, name=name): assert x == x, "not-a-number values in reference results" assert y == y, "not-a-number values in test results" # handle sign flips when angles jump -180 <-> +180 xdif = min(abs(x - y), min(abs(x + 360 - y), abs(x - y - 360))) assert xdif < 50.0 or (xdif / abs(x)) < 0.4, \ ("%s: expected %g, got %g" % (name, x, y)) tests.append(checkDihedral) else: def check(x, y, name=name): assert x == x, "not-a-number values in reference results" assert y == y, "not-a-number values in test results" xdif = abs(x - y) assert xdif < 1.0 or (xdif / abs(x)) < 0.1, \ ("%s: expected %g, got %g" % (name, x, y)) tests.append(check) n = len(self.columnNames) for d1, d2 in map(None, self.data, other.data): for i in range(n): tests[i](d1[i], d2[i]) ######################################### class NullTest(SandboxTest): def runInSandbox(self): global testTimes testTimes[self.methodname] = 0.0 class FailureExpectedTest(NullTest): """By default, the input for this kind of test is a MMP file, the command line is given explicitly in the test methods, and the outputs are stdout, stderr, and the exit value. We expect a failure here but I'm not sure exactly what kind of failure. Until I know exactly what kind of failure Eric wants here, just make it pass all the time. """ DEFAULT_SIMOPTS = None # force an explicit choice class MinimizeTest(SandboxTest): """Perform a minimization, starting with a MMP file. The results should be stdout, stderr, exit value, and an XYZ file. All these are checked for correctness. """ DEFAULT_SIMOPTS = ("--minimize", "--dump-as-text", "--trace-file", "FOO.trc", "FOO.mmp") DEFAULT_OUTPUTS = ("xyz",) class StructureTest(MinimizeTest): """Perform a minimization, starting with a MMP file. The results should be stdout, stderr, exit value, a TRC file, and an XYZ file. All these are checked for correctness. The XYZ file can be compared to an XYZCMP file for closeness of fit. """ DEFAULT_INPUTS = ("xyzcmp",) DEFAULT_SIMOPTS = ("--minimize", "--dump-as-text", "--trace-file", "FOO.trc", "FOO.mmp") DEFAULT_OUTPUTS = ( ) class DynamicsTest(MinimizeTest): """Make a dynamics movie, starting with a MMP file. The results should be stdout, stderr, exit value, a TRC file, and an XYZ file with multiple frames. All these are checked for correctness. """ DEFAULT_INPUTS = ( ) DEFAULT_SIMOPTS = ("--dump-as-text", "--trace-file", "FOO.trc", "FOO.mmp") DEFAULT_OUTPUTS = ("trc", "xyz") class PyrexTest(TimedTest): def __init__(self, methodname, base=None): self.methodname = methodname self.base = base try: self.start() except EarlyTermination: return self.run() try: self.finish() except EarlyTermination: pass def run(self): lac = LengthAngleComparison(self.base + ".mmp") import sim s = sim.theSimulator() s.reinitGlobals() inputfile = self.base + ".mmp" outputfile = self.base + ".xyz" s.InputFileName = inputfile s.OutputFileName = outputfile s.ToMinimize = 1 s.DumpAsText = 1 s.OutputFormat = 0 s.Temperature = 300 s.go(frame_callback=None, trace_callback=None) lac.compare(self.base + ".xyz", self.base + ".xyzcmp", LENGTH_TOLERANCE, ANGLE_TOLERANCE) class JigTest(SandboxTest): DEFAULT_INPUTS = ("trc", "xyzcmp") DEFAULT_SIMOPTS = ("-i100", "-f1", "--dump-as-text", "--trace-file", "FOO.trc", "FOO.mmp") DEFAULT_OUTPUTS = ("trc", "xyz") def generateOutputFiles(self): shutil.copy(self.testname + ".trc", self.basename + ".trc") shutil.copy(self.testname + ".xyz", self.basename + ".xyzcmp") def runInSandbox(self): if GENERATE: # If the simplified MMP doesn't already exist, generate it now mmpfile = self.midname + ".mmp" if not os.path.exists(mmpfile): mmp_orig = os.path.join("tests", self.dirname, self.shortname + ".mmp") simplifiedMMP(mmp_orig, mmpfile) SandboxTest.runInSandbox(self) def checkOutputFiles(self): # Given a trace file with several frames, and columns for various # jigs, make sure the jigs all have roughly the same numbers as they # had during a known-good run. def lastLineOfReadings(f): lines = readlines(f) n = None for i in range(len(lines)): if lines[i].startswith("# Done:"): n = i - 1 break if n == None: return None return map(string.atof, lines[n].split()) # add the following line to regenerate trace files when they fail to match? # shutil.copy(self.testname + ".trc", self.basename + ".trcnew") goodT = TraceFile(self.basename + ".trc") iffyT = TraceFile(self.testname + ".trc") goodT.fuzzyMatch(iffyT) # loosen up angles a little extra self.structureComparisonBondlengthsBondangles(LENGTH_TOLERANCE, 1.5 * ANGLE_TOLERANCE) #################################################### # Re-generate this with "python tests.py time_only" RANKED_BY_RUNTIME = [ 'test_dynamics_0001', 'test_minimize_0002', 'test_minimize_0003', 'test_minimize_0004', 'test_minimize_0006', 'test_minimize_0007', 'test_badCallback3', 'test_framecallback', 'test_badCallback1', 'test_pyrex_minH2', 'test_badCallback2', 'test_minimize_h2', 'test_temperature_tests_003_thermostat_test_3', 'test_singlebond_stretch_H_SH', 'test_singlebond_stretch_F_NH2', 'test_reordering_jigs_or_chunks_02_thermo_anchor_stat_reordering_7', 'test_singlebond_stretch_H_H', 'test_reordering_jigs_or_chunks_02_thermo_anchor_stat_reordering_6', 'test_rigid_organics_CH4', 'test_reordering_jigs_or_chunks_01_thermo_anchor_reordering_1', 'test_singlebond_stretch_Cl_F', 'test_reordering_jigs_or_chunks_03_thermo_anchor_reordering', 'test_enabled_disabled_jigs_003_one_thermometer_enabled_other_disabled', 'test_reordering_jigs_or_chunks_02_thermo_anchor_stat_reordering_8', 'test_reordering_jigs_or_chunks_02_thermo_anchor_stat_reordering_5', 'test_reordering_jigs_or_chunks_02_thermo_anchor_stat_reordering_2', 'test_singlebond_stretch_H_Cl', 'test_temperature_tests_003_thermostat_test_5', 'test_singlebond_stretch_Cl_OH', 'test_singlebond_stretch_H_NH2', 'test_singlebond_stretch_F_SH', 'test_singlebond_stretch_F_PH2', 'test_minimize_0013', 'test_singlebond_stretch_H_PH2', 'test_reordering_jigs_or_chunks_02_thermo_anchor_stat_reordering_1', 'test_motors_009_linearmotor_Methane_Molecule', 'test_singlebond_stretch_Cl_CH3', 'test_singlebond_stretch_HS_OH', 'test_enabled_disabled_jigs_001_disabled_anchors', 'test_reordering_jigs_or_chunks_02_thermo_anchor_stat_reordering_3', 'test_temperature_tests_003_thermostat_test_4', 'test_singlebond_stretch_Cl_PH2', 'test_reordering_jigs_or_chunks_01_thermo_anchor_reordering_2', 'test_temperature_tests_003_thermostat_test_2', 'test_reordering_jigs_or_chunks_02_thermo_anchor_stat_reordering_4', 'test_reordering_jigs_or_chunks_01_thermo_anchor_reordering_5', 'test_singlebond_stretch_Cl_NH2', 'test_singlebond_stretch_H_CH3', 'test_singlebond_stretch_F_SiH3', 'test_singlebond_stretch_Cl_AlH2', 'test_enabled_disabled_jigs_004_one_thermostat_enabled_other_disabled', 'test_singlebond_stretch_Cl_SH', 'test_reordering_jigs_or_chunks_01_thermo_anchor_reordering_4', 'test_temperature_tests_003_thermostat_test_1', 'test_singlebond_stretch_H_SiH3', 'test_singlebond_stretch_HS_NH2', 'test_singlebond_stretch_H_F', 'test_singlebond_stretch_HS_SH', 'test_singlebond_stretch_H_OH', 'test_floppy_organics_CH4', 'test_singlebond_stretch_F_CH3', 'test_singlebond_stretch_F_OH', 'test_reordering_jigs_or_chunks_01_thermo_anchor_reordering_3', 'test_singlebond_stretch_F_AlH2', 'test_singlebond_stretch_Cl_Cl', 'test_singlebond_stretch_HO_AlH2', 'test_singlebond_stretch_F_F', 'test_singlebond_stretch_Cl_SiH3', 'test_singlebond_stretch_H2N_PH2', 'test_singlebond_stretch_H3C_CH3', 'test_temperature_tests_003_thermostat_test', 'test_singlebond_stretch_HS_PH2', 'test_singlebond_stretch_H2P_CH3', 'test_singlebond_stretch_H2P_PH2', 'test_singlebond_stretch_H2P_AlH2', 'test_temperature_tests_002_two_methanes_10A_apart_vdw_6', 'test_singlebond_stretch_H2Al_SiH3', 'test_singlebond_stretch_HS_AlH2', 'test_singlebond_stretch_HS_CH3', 'test_singlebond_stretch_F_BH2', 'test_singlebond_stretch_HO_PH2', 'test_singlebond_stretch_H3C_SiH3', 'test_singlebond_stretch_H_BH2', 'test_singlebond_stretch_H2P_SiH3', 'test_singlebond_stretch_H3Si_SiH3', 'test_singlebond_stretch_H_AlH2', 'test_singlebond_stretch_HO_SiH3', 'test_singlebond_stretch_Cl_BH2', 'test_singlebond_stretch_H2N_AlH2', 'test_motors_014_rotarymotor_negative_torque_and_negative_speed', 'test_motors_013_rotarymotor_0_torque_and_positive_speed', 'test_singlebond_stretch_H2Al_AlH2', 'test_reordering_jigs_or_chunks_05_thermo_lmotor_anchor_measurement_jigs_reordering_5', 'test_enabled_disabled_jigs_002_one_anchor_enabled_other_disabled', 'test_motors_018_rotarymotor_positive_torque_and_0_speed', 'test_singlebond_stretch_H2B_BH2', 'test_enabled_disabled_jigs_005_disabled_measure_distance_jig', 'test_reordering_jigs_or_chunks_05_thermo_lmotor_anchor_measurement_jigs_reordering_4', 'test_enabled_disabled_jigs_007_one_linearmotor_enabled_and_other_disabled', 'test_motors_025_two_linearmotors_applying_equal_forces_normal_to_each_other', 'test_motors_028_bug1306_test2', 'test_reordering_jigs_or_chunks_05_thermo_lmotor_anchor_measurement_jigs_reordering_2', 'test_heteroatom_organics_C3H6O', 'test_reordering_jigs_or_chunks_05_thermo_lmotor_anchor_measurement_jigs_reordering_6', 'test_motors_019_rotarymotor_medium_torque_and_speed', 'test_motors_011_rotarymotor_0_torque_and_0_speed', 'test_temperature_tests_001_two_methanes_9A_apart_vdw_5', 'test_motors_015_rotarymotor_negative_torque_and_positive_speed', 'test_enabled_disabled_jigs_006_one_rotarymotor_enabled_and_other_disabled', 'test_motors_012_rotarymotor_0_torque_and_negative_speed', 'test_reordering_jigs_or_chunks_05_thermo_lmotor_anchor_measurement_jigs_reordering_1', 'test_motors_and_anchors_005_rotorymotor_against_anchor_3', 'test_singlebond_stretch_H2N_SiH3', 'test_reordering_jigs_or_chunks_05_thermo_lmotor_anchor_measurement_jigs_reordering_7', 'test_singlebond_stretch_H2B_SiH3', 'test_heteroatom_organics_C3H6NH', 'test_singlebond_stretch_H2B_CH3', 'test_singlebond_stretch_HO_CH3', 'test_motors_020_rotarymotor_high_torque_and_speed', 'test_motors_016_rotarymotor_negative_torque_and_0_speed', 'test_singlebond_stretch_H2B_AlH2', 'test_motors_017_rotarymotor_positive_torque_and_negative_speed', 'test_rigid_organics_C3H6', 'test_reordering_jigs_or_chunks_05_thermo_lmotor_anchor_measurement_jigs_reordering_8', 'test_minimize_0010', 'test_heteroatom_organics_CH3OH', 'test_heteroatom_organics_C3H6S', 'test_motors_026_two_linearmotors_applying_equal_and_opposite_forces', 'test_floppy_organics_C2H6', 'test_singlebond_stretch_H2Al_CH3', 'test_heteroatom_organics_C3H6BH', 'test_reordering_jigs_or_chunks_04_thermo_lmotor_anchor_stat_reordering_4', 'test_heteroatom_organics_C3H6PH', 'test_reordering_jigs_or_chunks_04_thermo_lmotor_anchor_stat_reordering_7', 'test_reordering_jigs_or_chunks_04_thermo_lmotor_anchor_stat_reordering_8', 'test_heteroatom_organics_CH3AlH2', 'test_reordering_jigs_or_chunks_03_thermo_rmotor_anchor_stat_reordering_4', 'test_reordering_jigs_or_chunks_05_thermo_lmotor_anchor_measurement_jigs_reordering_3', 'test_reordering_jigs_or_chunks_04_thermo_lmotor_anchor_stat_reordering_2', 'test_motors_030_rotarymotor_and_linear_motor_attached_to_same_atoms', 'test_floppy_organics_C4H8', 'test_reordering_jigs_or_chunks_03_thermo_rmotor_anchor_stat_reordering_6', 'test_reordering_jigs_or_chunks_04_thermo_lmotor_anchor_stat_reordering_1', 'test_singlebond_stretch_HO_NH2', 'test_heteroatom_organics_CH3BH2', 'test_reordering_jigs_or_chunks_04_thermo_lmotor_anchor_stat_reordering_6', 'test_reordering_jigs_or_chunks_03_thermo_rmotor_anchor_stat_reordering_2', 'test_motors_003_linearmotor_0_force_and_positive_stiffness', 'test_rigid_organics_C8H8', 'test_motors_004_linearmotor_negative_force_and_negative_stiffness', 'test_reordering_jigs_or_chunks_03_thermo_rmotor_anchor_stat_reordering_3', 'test_reordering_jigs_or_chunks_03_thermo_rmotor_anchor_stat_reordering_8', 'test_motors_006_linearmotor_negative_force_and_0_stiffness', 'test_reordering_jigs_or_chunks_03_thermo_rmotor_anchor_stat_reordering_1', 'test_singlebond_stretch_H2B_PH2', 'test_motors_007_linearmotor_positive_force_and_0_stiffness', 'test_frameAndTraceCallback', 'test_minimize_0009', 'test_reordering_jigs_or_chunks_04_thermo_lmotor_anchor_stat_reordering_3', 'test_reordering_jigs_or_chunks_03_thermo_rmotor_anchor_stat_reordering_7', 'test_motors_001_linearmotor_0_force_and_0_stiffness', 'test_reordering_jigs_or_chunks_03_thermo_rmotor_anchor_stat_reordering_5', 'test_heteroatom_organics_C3H6SiH2', 'test_heteroatom_organics_CH3OCH3', 'test_motors_021_rotarymotor_dyno_jig_test_to_same_chunk', 'test_rigid_organics_C4H8', 'test_singlebond_stretch_HO_OH', 'test_reordering_jigs_or_chunks_04_thermo_lmotor_anchor_stat_reordering_5', 'test_motors_023_rotarymotor_two_planet_gears', 'test_motors_002_linearmotor_0_force_and_negative_stiffness', 'test_motors_and_anchors_003_rotorymotor_against_anchor_1', 'test_floppy_organics_C6H12b', 'test_jigs_to_several_atoms_003_linearmotor_to_50_atoms', 'test_heteroatom_organics_ADAMframe_O_Cs', 'test_amino_acids_tyr_l_aminoacid', 'test_heteroatom_organics_ADAMframe_S_Cs', 'test_heteroatom_organics_ADAMframe_PH_Cs', 'test_heteroatom_organics_ADAM_Cl_c3v', 'test_rigid_organics_C10H12', 'test_motors_and_anchors_004_rotorymotor_against_anchor_2', 'test_floppy_organics_C4H10c', 'test_rigid_organics_C10H14', 'test_heteroatom_organics_C5H10PH', 'test_heteroatom_organics_CH3SH', 'test_motors_024_linearmotor_two_dodecahedranes', 'test_heteroatom_organics_CH3AlHCH3', 'test_heteroatom_organics_B_ADAM_C3v', 'test_heteroatom_organics_C5H10O', 'test_motors_and_anchors_002_linearmotor_pulling_against_anchor_2', 'test_heteroatom_organics_ADAMframe_SiH2_c2v', 'test_motors_027_two_rotarymotors_applying_equal_and_opposite_torque', 'test_heteroatom_organics_CH3NH2', 'test_heteroatom_organics_C5H10S', 'test_motors_and_anchors_001_linearmotor_pulling_against_anchor_1', 'test_floppy_organics_C6H12a', 'test_rigid_organics_C2H6', 'test_heteroatom_organics_ADAMframe_BH_Cs', 'test_heteroatom_organics_SiH_ADAM_C3v', 'test_rigid_organics_C3H8', 'test_heteroatom_organics_ADAM_SH_Cs', 'test_dpbFileShouldBeBinary', 'test_pyrex_dynamics', 'test_heteroatom_organics_ADAMframe_NH_Cs', 'test_motors_008_linearmotor_positive_force_and_positive_stiffness', 'test_traceCallbackWithMotor', 'test_heteroatom_organics_ADAM_F_c3v', 'test_heteroatom_organics_C4H8S', 'test_singlebond_stretch_H2N_NH2', 'test_heteroatom_organics_CH3PHCH3', 'test_heteroatom_organics_P_ADAM_C3v', 'test_singlebond_stretch_HO_BH2', 'test_heteroatom_organics_C4H8AlH', 'test_heteroatom_organics_C5H10NH', 'test_jigs_to_several_atoms_006_anchors_to_100_atoms', 'test_motors_005_linearmotor_negative_force_and_positive_stiffness', 'test_heteroatom_organics_Al_ADAM_C3v', 'test_heteroatom_organics_ADAMframe_AlH_Cs', 'test_minimize_0012', 'test_jigs_to_several_atoms_004_linearmotor_to_100_atoms', 'test_jigs_to_several_atoms_005_anchors_to_50_atoms', 'test_floppy_organics_C7H14c', 'test_singlebond_stretch_H2N_CH3', 'test_jigs_to_several_atoms_001_rotarymotor_to_50_atoms', 'test_heteroatom_organics_C_CH3_3_SiH3', 'test_heteroatom_organics_C3H6AlH', 'test_motors_010_linearmotor_box_of_helium', 'test_heteroatom_organics_CH3PH2', 'test_pyrex_minimize0001', 'test_heteroatom_organics_N_ADAM_C3v', 'test_motors_029_bug_1331', 'test_rigid_organics_C14H20', 'test_floppy_organics_C4H10a', 'test_heteroatom_organics_C4H8NH', 'test_floppy_organics_C3H8', 'test_heteroatom_organics_C4H8BH', 'test_rigid_organics_C6H10', 'test_minimize_0011', 'test_minimize_0005', 'test_singlebond_stretch_HS_SiH3', 'test_heteroatom_organics_CH3SiH2CH3', 'test_floppy_organics_C5H12b', 'test_heteroatom_organics_C_CH3_3_SH', 'test_heteroatom_organics_C_CH3_3_OH', 'test_minimize_0001', 'test_heteroatom_organics_C5H10SiH2', 'test_heteroatom_organics_C4H8SiH2', 'test_singlebond_stretch_HS_BH2', 'test_heteroatom_organics_ADAM_BH2', 'test_heteroatom_organics_C5H10AlH', 'test_heteroatom_organics_C_CH3_3_BH2', 'test_heteroatom_organics_CH3SiH3', 'test_heteroatom_organics_CH3NHCH3', 'test_heteroatom_organics_ADAM_OH_Cs', 'test_heteroatom_organics_C_CH3_3_NH2', 'test_heteroatom_organics_C4H8PH', 'test_floppy_organics_C7H14a', 'test_rigid_organics_C8H14', 'test_floppy_organics_C5H12d', 'test_heteroatom_organics_C_CH3_3_PH2', 'test_heteroatom_organics_ADAM_AlH2_Cs', 'test_jigs_to_several_atoms_007_rotarymotor_and_anchors_to_100_atoms', 'test_jigs_to_several_atoms_002_rotarymotor_to_100_atoms', 'test_heteroatom_organics_ADAM_PH2_Cs', 'test_heteroatom_organics_ADAM_NH2_Cs', 'test_heteroatom_organics_CH3SCH3', 'test_floppy_organics_C5H10', 'test_floppy_organics_C5H12e', 'test_singlebond_stretch_H2B_NH2', 'test_heteroatom_organics_C4H8O', 'test_motors_022_rotary_motor_small_bearing_test', 'test_amino_acids_ala_l_aminoacid', 'test_heteroatom_organics_C5H10BH', 'test_floppy_organics_C6H14a', 'test_floppy_organics_C6H14c', 'test_minimize_0008', 'test_heteroatom_organics_CH3BHCH3', 'test_floppy_organics_C7H14b', 'test_amino_acids_asp_l_aminoacid', 'test_floppy_organics_C6H14b', 'test_floppy_organics_C5H12c', 'test_floppy_organics_C5H12a', 'test_floppy_organics_C6H14d', 'test_floppy_organics_C6H14e', 'test_floppy_organics_C4H10b', 'test_heteroatom_organics_C_CH3_3_AlH2', 'test_rigid_organics_C14H24', 'test_amino_acids_ser_l_aminoacid', 'test_amino_acids_pro_l_aminoacid', 'test_heteroatom_organics_ADAM_SiH3_C3v', 'test_amino_acids_ile_l_aminoacid', 'test_amino_acids_cys_l_aminoacid', 'test_floppy_organics_C6H14f', 'test_amino_acids_thr_l_aminoacid', 'test_amino_acids_glu_l_aminoacid', 'test_amino_acids_val_l_aminoacid', 'test_amino_acids_asn_l_aminoacid', 'test_amino_acids_gly_l_aminoacid', 'test_amino_acids_his_l_aminoacid', 'test_amino_acids_met_l_aminoacid', 'test_amino_acids_arg_l_aminoacid', 'test_dynamics_small_bearing_01', 'test_amino_acids_gln_l_aminoacid', 'test_amino_acids_lys_l_aminoacid', 'test_amino_acids_leu_l_aminoacid', 'test_amino_acids_phe_l_aminoacid' ] try: import sim class PyrexUnitTests(sim.Tests, TimedTest): def test_framecallback(self): self.methodname = "test_framecallback" try: TimedTest.start(self) except EarlyTermination: return try: sim.Tests.test_framecallback(self) finally: try: TimedTest.finish(self) except EarlyTermination: pass def test_frameAndTraceCallback(self): self.methodname = "test_frameAndTraceCallback" try: TimedTest.start(self) except EarlyTermination: return try: sim.Tests.test_frameAndTraceCallback(self) finally: try: TimedTest.finish(self) except EarlyTermination: pass def test_traceCallbackWithMotor(self): self.methodname = "test_traceCallbackWithMotor" try: TimedTest.start(self) except EarlyTermination: return try: sim.Tests.test_traceCallbackWithMotor(self) finally: try: TimedTest.finish(self) except EarlyTermination: pass def test_dpbFileShouldBeBinary(self): self.methodname = "test_dpbFileShouldBeBinary" try: TimedTest.start(self) except EarlyTermination: return try: sim.Tests.test_dpbFileShouldBeBinary(self) finally: try: TimedTest.finish(self) except EarlyTermination: pass def test_badCallback1(self): self.methodname = "test_badCallback1" try: TimedTest.start(self) except EarlyTermination: return try: sim.Tests.test_badCallback1(self) finally: try: TimedTest.finish(self) except EarlyTermination: pass def test_badCallback2(self): self.methodname = "test_badCallback2" try: TimedTest.start(self) except EarlyTermination: return try: sim.Tests.test_badCallback2(self) finally: try: TimedTest.finish(self) except EarlyTermination: pass def test_badCallback3(self): self.methodname = "test_badCallback3" try: TimedTest.start(self) except EarlyTermination: return try: sim.Tests.test_badCallback3(self) finally: try: TimedTest.finish(self) except EarlyTermination: pass baseClass = PyrexUnitTests except ImportError: baseClass = unittest.TestCase class Tests(baseClass): def test_minimize_h2(self): StructureTest(dir="minimize", test="h2") def test_dynamics_0001(self): # rotary motor test FailureExpectedTest(dir="dynamics", test="0001", simopts=("--num-frames=30", "--temperature=0", "--iters-per-frame=10000", "--dump-as-text", "FOO.mmp")) #def test_dynamics_0002(self): # # ground, thermostat, and thermometer test # DynamicsTest(dir="dynamics", test="0002", # simopts=("--num-frames=100", # "--temperature=300", # "--iters-per-frame=10", # "--dump-as-text", # "FOO.mmp")) def test_dynamics_small_bearing_01(self): # rotary motor test DynamicsTest(dir="dynamics", test="small_bearing_01", simopts=("--num-frames=100", "--temperature=300", "--iters-per-frame=10", "--dump-as-text", "--trace-file", "FOO.trc", "FOO.mmp")) def test_minimize_0002(self): FailureExpectedTest(dir="minimize", test="0002", simopts=("--num-frames=500", "--minimize", "--dump-as-text", "FOO.mmp")) def test_minimize_0003(self): FailureExpectedTest(dir="minimize", test="0003", simopts=("--num-frames=300", "--minimize", "--dump-intermediate-text", "--dump-as-text", "FOO.mmp")) def test_minimize_0004(self): FailureExpectedTest(dir="minimize", test="0004", simopts=("--num-frames=600", "--minimize", "--dump-as-text", "FOO.mmp")) def test_minimize_0006(self): FailureExpectedTest(dir="minimize", test="0006", simopts=("--num-frames=300", "--minimize", "--dump-intermediate-text", "--dump-as-text", "FOO.mmp")) def test_minimize_0007(self): FailureExpectedTest(dir="minimize", test="0007", simopts=("--num-frames=300", "--minimize", "--dump-intermediate-text", "--dump-as-text", "FOO.mmp")) # In Emacs, do "sort-lines" to keep things organized def test_amino_acids_ala_l_aminoacid(self): StructureTest(dir="amino_acids", test="ala_l_aminoacid") def test_amino_acids_arg_l_aminoacid(self): StructureTest(dir="amino_acids", test="arg_l_aminoacid") def test_amino_acids_asn_l_aminoacid(self): StructureTest(dir="amino_acids", test="asn_l_aminoacid") def test_amino_acids_asp_l_aminoacid(self): StructureTest(dir="amino_acids", test="asp_l_aminoacid") def test_amino_acids_cys_l_aminoacid(self): StructureTest(dir="amino_acids", test="cys_l_aminoacid") def test_amino_acids_gln_l_aminoacid(self): StructureTest(dir="amino_acids", test="gln_l_aminoacid") def test_amino_acids_glu_l_aminoacid(self): StructureTest(dir="amino_acids", test="glu_l_aminoacid") def test_amino_acids_gly_l_aminoacid(self): StructureTest(dir="amino_acids", test="gly_l_aminoacid") def test_amino_acids_his_l_aminoacid(self): StructureTest(dir="amino_acids", test="his_l_aminoacid") def test_amino_acids_ile_l_aminoacid(self): StructureTest(dir="amino_acids", test="ile_l_aminoacid") def test_amino_acids_leu_l_aminoacid(self): StructureTest(dir="amino_acids", test="leu_l_aminoacid") def test_amino_acids_lys_l_aminoacid(self): StructureTest(dir="amino_acids", test="lys_l_aminoacid") def test_amino_acids_met_l_aminoacid(self): StructureTest(dir="amino_acids", test="met_l_aminoacid") def test_amino_acids_phe_l_aminoacid(self): StructureTest(dir="amino_acids", test="phe_l_aminoacid") def test_amino_acids_pro_l_aminoacid(self): StructureTest(dir="amino_acids", test="pro_l_aminoacid") def test_amino_acids_ser_l_aminoacid(self): StructureTest(dir="amino_acids", test="ser_l_aminoacid") def test_amino_acids_thr_l_aminoacid(self): StructureTest(dir="amino_acids", test="thr_l_aminoacid") def test_amino_acids_tyr_l_aminoacid(self): StructureTest(dir="amino_acids", test="tyr_l_aminoacid") def test_amino_acids_val_l_aminoacid(self): StructureTest(dir="amino_acids", test="val_l_aminoacid") def test_floppy_organics_C2H6(self): StructureTest(dir="floppy_organics", test="C2H6") def test_floppy_organics_C3H8(self): StructureTest(dir="floppy_organics", test="C3H8") def test_floppy_organics_C4H10a(self): StructureTest(dir="floppy_organics", test="C4H10a") def test_floppy_organics_C4H10b(self): StructureTest(dir="floppy_organics", test="C4H10b") def test_floppy_organics_C4H10c(self): StructureTest(dir="floppy_organics", test="C4H10c") def test_floppy_organics_C4H8(self): StructureTest(dir="floppy_organics", test="C4H8") def test_floppy_organics_C5H10(self): StructureTest(dir="floppy_organics", test="C5H10") def test_floppy_organics_C5H12a(self): StructureTest(dir="floppy_organics", test="C5H12a") def test_floppy_organics_C5H12b(self): StructureTest(dir="floppy_organics", test="C5H12b") def test_floppy_organics_C5H12c(self): StructureTest(dir="floppy_organics", test="C5H12c") def test_floppy_organics_C5H12d(self): StructureTest(dir="floppy_organics", test="C5H12d") def test_floppy_organics_C5H12e(self): StructureTest(dir="floppy_organics", test="C5H12e") def test_floppy_organics_C6H12a(self): StructureTest(dir="floppy_organics", test="C6H12a") def test_floppy_organics_C6H12b(self): StructureTest(dir="floppy_organics", test="C6H12b") def test_floppy_organics_C6H14a(self): StructureTest(dir="floppy_organics", test="C6H14a") def test_floppy_organics_C6H14b(self): StructureTest(dir="floppy_organics", test="C6H14b") def test_floppy_organics_C6H14c(self): StructureTest(dir="floppy_organics", test="C6H14c") def test_floppy_organics_C6H14d(self): StructureTest(dir="floppy_organics", test="C6H14d") def test_floppy_organics_C6H14e(self): StructureTest(dir="floppy_organics", test="C6H14e") def test_floppy_organics_C6H14f(self): StructureTest(dir="floppy_organics", test="C6H14f") def test_floppy_organics_C7H14a(self): StructureTest(dir="floppy_organics", test="C7H14a") def test_floppy_organics_C7H14b(self): StructureTest(dir="floppy_organics", test="C7H14b") def test_floppy_organics_C7H14c(self): StructureTest(dir="floppy_organics", test="C7H14c") def test_floppy_organics_CH4(self): StructureTest(dir="floppy_organics", test="CH4") def test_heteroatom_organics_ADAM_AlH2_Cs(self): StructureTest(dir="heteroatom_organics", test="ADAM_AlH2_Cs") def test_heteroatom_organics_ADAM_BH2(self): StructureTest(dir="heteroatom_organics", test="ADAM_BH2") def test_heteroatom_organics_ADAM_Cl_c3v(self): StructureTest(dir="heteroatom_organics", test="ADAM_Cl_c3v") def test_heteroatom_organics_ADAM_F_c3v(self): StructureTest(dir="heteroatom_organics", test="ADAM_F_c3v") def test_heteroatom_organics_ADAM_NH2_Cs(self): StructureTest(dir="heteroatom_organics", test="ADAM_NH2_Cs") def test_heteroatom_organics_ADAM_OH_Cs(self): StructureTest(dir="heteroatom_organics", test="ADAM_OH_Cs") def test_heteroatom_organics_ADAM_PH2_Cs(self): StructureTest(dir="heteroatom_organics", test="ADAM_PH2_Cs") def test_heteroatom_organics_ADAM_SH_Cs(self): StructureTest(dir="heteroatom_organics", test="ADAM_SH_Cs") def test_heteroatom_organics_ADAM_SiH3_C3v(self): StructureTest(dir="heteroatom_organics", test="ADAM_SiH3_C3v") def test_heteroatom_organics_ADAMframe_AlH_Cs(self): StructureTest(dir="heteroatom_organics", test="ADAMframe_AlH_Cs") def test_heteroatom_organics_ADAMframe_BH_Cs(self): StructureTest(dir="heteroatom_organics", test="ADAMframe_BH_Cs") def test_heteroatom_organics_ADAMframe_NH_Cs(self): StructureTest(dir="heteroatom_organics", test="ADAMframe_NH_Cs") def test_heteroatom_organics_ADAMframe_O_Cs(self): StructureTest(dir="heteroatom_organics", test="ADAMframe_O_Cs") def test_heteroatom_organics_ADAMframe_PH_Cs(self): StructureTest(dir="heteroatom_organics", test="ADAMframe_PH_Cs") def test_heteroatom_organics_ADAMframe_S_Cs(self): StructureTest(dir="heteroatom_organics", test="ADAMframe_S_Cs") def test_heteroatom_organics_ADAMframe_SiH2_c2v(self): StructureTest(dir="heteroatom_organics", test="ADAMframe_SiH2_c2v") def test_heteroatom_organics_Al_ADAM_C3v(self): StructureTest(dir="heteroatom_organics", test="Al_ADAM_C3v") def test_heteroatom_organics_B_ADAM_C3v(self): StructureTest(dir="heteroatom_organics", test="B_ADAM_C3v") def test_heteroatom_organics_C3H6AlH(self): StructureTest(dir="heteroatom_organics", test="C3H6AlH") def test_heteroatom_organics_C3H6BH(self): StructureTest(dir="heteroatom_organics", test="C3H6BH") def test_heteroatom_organics_C3H6NH(self): StructureTest(dir="heteroatom_organics", test="C3H6NH") def test_heteroatom_organics_C3H6O(self): StructureTest(dir="heteroatom_organics", test="C3H6O") def test_heteroatom_organics_C3H6PH(self): StructureTest(dir="heteroatom_organics", test="C3H6PH") def test_heteroatom_organics_C3H6S(self): StructureTest(dir="heteroatom_organics", test="C3H6S") def test_heteroatom_organics_C3H6SiH2(self): StructureTest(dir="heteroatom_organics", test="C3H6SiH2") def test_heteroatom_organics_C4H8AlH(self): StructureTest(dir="heteroatom_organics", test="C4H8AlH") def test_heteroatom_organics_C4H8BH(self): StructureTest(dir="heteroatom_organics", test="C4H8BH") def test_heteroatom_organics_C4H8NH(self): StructureTest(dir="heteroatom_organics", test="C4H8NH") def test_heteroatom_organics_C4H8O(self): StructureTest(dir="heteroatom_organics", test="C4H8O") def test_heteroatom_organics_C4H8PH(self): StructureTest(dir="heteroatom_organics", test="C4H8PH") def test_heteroatom_organics_C4H8S(self): StructureTest(dir="heteroatom_organics", test="C4H8S") def test_heteroatom_organics_C4H8SiH2(self): StructureTest(dir="heteroatom_organics", test="C4H8SiH2") def test_heteroatom_organics_C5H10AlH(self): StructureTest(dir="heteroatom_organics", test="C5H10AlH") def test_heteroatom_organics_C5H10BH(self): StructureTest(dir="heteroatom_organics", test="C5H10BH") def test_heteroatom_organics_C5H10NH(self): StructureTest(dir="heteroatom_organics", test="C5H10NH") def test_heteroatom_organics_C5H10O(self): StructureTest(dir="heteroatom_organics", test="C5H10O") def test_heteroatom_organics_C5H10PH(self): StructureTest(dir="heteroatom_organics", test="C5H10PH") def test_heteroatom_organics_C5H10S(self): StructureTest(dir="heteroatom_organics", test="C5H10S") def test_heteroatom_organics_C5H10SiH2(self): StructureTest(dir="heteroatom_organics", test="C5H10SiH2") def test_heteroatom_organics_CH3AlH2(self): StructureTest(dir="heteroatom_organics", test="CH3AlH2") def test_heteroatom_organics_CH3AlHCH3(self): StructureTest(dir="heteroatom_organics", test="CH3AlHCH3") def test_heteroatom_organics_CH3BH2(self): StructureTest(dir="heteroatom_organics", test="CH3BH2") def test_heteroatom_organics_CH3BHCH3(self): StructureTest(dir="heteroatom_organics", test="CH3BHCH3") def test_heteroatom_organics_CH3NH2(self): StructureTest(dir="heteroatom_organics", test="CH3NH2") def test_heteroatom_organics_CH3NHCH3(self): StructureTest(dir="heteroatom_organics", test="CH3NHCH3") def test_heteroatom_organics_CH3OCH3(self): StructureTest(dir="heteroatom_organics", test="CH3OCH3") def test_heteroatom_organics_CH3OH(self): StructureTest(dir="heteroatom_organics", test="CH3OH") def test_heteroatom_organics_CH3PH2(self): StructureTest(dir="heteroatom_organics", test="CH3PH2") def test_heteroatom_organics_CH3PHCH3(self): StructureTest(dir="heteroatom_organics", test="CH3PHCH3") def test_heteroatom_organics_CH3SCH3(self): StructureTest(dir="heteroatom_organics", test="CH3SCH3") def test_heteroatom_organics_CH3SH(self): StructureTest(dir="heteroatom_organics", test="CH3SH") def test_heteroatom_organics_CH3SiH2CH3(self): StructureTest(dir="heteroatom_organics", test="CH3SiH2CH3") def test_heteroatom_organics_CH3SiH3(self): StructureTest(dir="heteroatom_organics", test="CH3SiH3") def test_heteroatom_organics_C_CH3_3_AlH2(self): StructureTest(dir="heteroatom_organics", test="C_CH3_3_AlH2") def test_heteroatom_organics_C_CH3_3_BH2(self): StructureTest(dir="heteroatom_organics", test="C_CH3_3_BH2") def test_heteroatom_organics_C_CH3_3_NH2(self): StructureTest(dir="heteroatom_organics", test="C_CH3_3_NH2") def test_heteroatom_organics_C_CH3_3_OH(self): StructureTest(dir="heteroatom_organics", test="C_CH3_3_OH") def test_heteroatom_organics_C_CH3_3_PH2(self): StructureTest(dir="heteroatom_organics", test="C_CH3_3_PH2") def test_heteroatom_organics_C_CH3_3_SH(self): StructureTest(dir="heteroatom_organics", test="C_CH3_3_SH") def test_heteroatom_organics_C_CH3_3_SiH3(self): StructureTest(dir="heteroatom_organics", test="C_CH3_3_SiH3") def test_heteroatom_organics_N_ADAM_C3v(self): StructureTest(dir="heteroatom_organics", test="N_ADAM_C3v") def test_heteroatom_organics_P_ADAM_C3v(self): StructureTest(dir="heteroatom_organics", test="P_ADAM_C3v") def test_heteroatom_organics_SiH_ADAM_C3v(self): StructureTest(dir="heteroatom_organics", test="SiH_ADAM_C3v") def test_minimize_0001(self): StructureTest(dir="minimize", test="0001") def test_minimize_0005(self): StructureTest(dir="minimize", test="0005") def test_minimize_0008(self): MinimizeTest(dir="minimize", test="0008") def test_minimize_0009(self): StructureTest(dir="minimize", test="0009") def test_minimize_0010(self): MinimizeTest(dir="minimize", test="0010") def test_minimize_0011(self): MinimizeTest(dir="minimize", test="0011") def test_minimize_0012(self): MinimizeTest(dir="minimize", test="0012") def test_minimize_0013(self): StructureTest(dir="minimize", test="0013") def test_rigid_organics_C10H12(self): StructureTest(dir="rigid_organics", test="C10H12") def test_rigid_organics_C10H14(self): StructureTest(dir="rigid_organics", test="C10H14") def test_rigid_organics_C14H20(self): StructureTest(dir="rigid_organics", test="C14H20") def test_rigid_organics_C14H24(self): StructureTest(dir="rigid_organics", test="C14H24") def test_rigid_organics_C2H6(self): StructureTest(dir="rigid_organics", test="C2H6") def test_rigid_organics_C3H6(self): StructureTest(dir="rigid_organics", test="C3H6") def test_rigid_organics_C3H8(self): StructureTest(dir="rigid_organics", test="C3H8") def test_rigid_organics_C4H8(self): StructureTest(dir="rigid_organics", test="C4H8") def test_rigid_organics_C6H10(self): StructureTest(dir="rigid_organics", test="C6H10") def test_rigid_organics_C8H14(self): StructureTest(dir="rigid_organics", test="C8H14") def test_rigid_organics_C8H8(self): StructureTest(dir="rigid_organics", test="C8H8") def test_rigid_organics_CH4(self): StructureTest(dir="rigid_organics", test="CH4") def test_singlebond_stretch_Cl_AlH2(self): StructureTest(dir="singlebond_stretch", test="Cl_AlH2") def test_singlebond_stretch_Cl_BH2(self): StructureTest(dir="singlebond_stretch", test="Cl_BH2") def test_singlebond_stretch_Cl_CH3(self): StructureTest(dir="singlebond_stretch", test="Cl_CH3") def test_singlebond_stretch_Cl_Cl(self): StructureTest(dir="singlebond_stretch", test="Cl_Cl") def test_singlebond_stretch_Cl_F(self): StructureTest(dir="singlebond_stretch", test="Cl_F") def test_singlebond_stretch_Cl_NH2(self): StructureTest(dir="singlebond_stretch", test="Cl_NH2") def test_singlebond_stretch_Cl_OH(self): StructureTest(dir="singlebond_stretch", test="Cl_OH") def test_singlebond_stretch_Cl_PH2(self): StructureTest(dir="singlebond_stretch", test="Cl_PH2") def test_singlebond_stretch_Cl_SH(self): StructureTest(dir="singlebond_stretch", test="Cl_SH") def test_singlebond_stretch_Cl_SiH3(self): StructureTest(dir="singlebond_stretch", test="Cl_SiH3") def test_singlebond_stretch_F_AlH2(self): StructureTest(dir="singlebond_stretch", test="F_AlH2") def test_singlebond_stretch_F_BH2(self): StructureTest(dir="singlebond_stretch", test="F_BH2") def test_singlebond_stretch_F_CH3(self): StructureTest(dir="singlebond_stretch", test="F_CH3") def test_singlebond_stretch_F_F(self): StructureTest(dir="singlebond_stretch", test="F_F") def test_singlebond_stretch_F_NH2(self): StructureTest(dir="singlebond_stretch", test="F_NH2") def test_singlebond_stretch_F_OH(self): StructureTest(dir="singlebond_stretch", test="F_OH") def test_singlebond_stretch_F_PH2(self): StructureTest(dir="singlebond_stretch", test="F_PH2") def test_singlebond_stretch_F_SH(self): StructureTest(dir="singlebond_stretch", test="F_SH") def test_singlebond_stretch_F_SiH3(self): StructureTest(dir="singlebond_stretch", test="F_SiH3") def test_singlebond_stretch_H2Al_AlH2(self): StructureTest(dir="singlebond_stretch", test="H2Al_AlH2") def test_singlebond_stretch_H2Al_CH3(self): StructureTest(dir="singlebond_stretch", test="H2Al_CH3") def test_singlebond_stretch_H2Al_SiH3(self): StructureTest(dir="singlebond_stretch", test="H2Al_SiH3") def test_singlebond_stretch_H2B_AlH2(self): StructureTest(dir="singlebond_stretch", test="H2B_AlH2") def test_singlebond_stretch_H2B_BH2(self): StructureTest(dir="singlebond_stretch", test="H2B_BH2") def test_singlebond_stretch_H2B_CH3(self): StructureTest(dir="singlebond_stretch", test="H2B_CH3") def test_singlebond_stretch_H2B_NH2(self): StructureTest(dir="singlebond_stretch", test="H2B_NH2") def test_singlebond_stretch_H2B_PH2(self): StructureTest(dir="singlebond_stretch", test="H2B_PH2") def test_singlebond_stretch_H2B_SiH3(self): StructureTest(dir="singlebond_stretch", test="H2B_SiH3") def test_singlebond_stretch_H2N_AlH2(self): StructureTest(dir="singlebond_stretch", test="H2N_AlH2") def test_singlebond_stretch_H2N_CH3(self): StructureTest(dir="singlebond_stretch", test="H2N_CH3") def test_singlebond_stretch_H2N_NH2(self): StructureTest(dir="singlebond_stretch", test="H2N_NH2") def test_singlebond_stretch_H2N_PH2(self): StructureTest(dir="singlebond_stretch", test="H2N_PH2") def test_singlebond_stretch_H2N_SiH3(self): StructureTest(dir="singlebond_stretch", test="H2N_SiH3") def test_singlebond_stretch_H2P_AlH2(self): StructureTest(dir="singlebond_stretch", test="H2P_AlH2") def test_singlebond_stretch_H2P_CH3(self): StructureTest(dir="singlebond_stretch", test="H2P_CH3") def test_singlebond_stretch_H2P_PH2(self): StructureTest(dir="singlebond_stretch", test="H2P_PH2") def test_singlebond_stretch_H2P_SiH3(self): StructureTest(dir="singlebond_stretch", test="H2P_SiH3") def test_singlebond_stretch_H3C_CH3(self): StructureTest(dir="singlebond_stretch", test="H3C_CH3") def test_singlebond_stretch_H3C_SiH3(self): StructureTest(dir="singlebond_stretch", test="H3C_SiH3") def test_singlebond_stretch_H3Si_SiH3(self): StructureTest(dir="singlebond_stretch", test="H3Si_SiH3") def test_singlebond_stretch_H_AlH2(self): StructureTest(dir="singlebond_stretch", test="H_AlH2") def test_singlebond_stretch_H_BH2(self): StructureTest(dir="singlebond_stretch", test="H_BH2") def test_singlebond_stretch_H_CH3(self): StructureTest(dir="singlebond_stretch", test="H_CH3") def test_singlebond_stretch_H_Cl(self): StructureTest(dir="singlebond_stretch", test="H_Cl") def test_singlebond_stretch_H_F(self): StructureTest(dir="singlebond_stretch", test="H_F") def test_singlebond_stretch_H_H(self): StructureTest(dir="singlebond_stretch", test="H_H") def test_singlebond_stretch_H_NH2(self): StructureTest(dir="singlebond_stretch", test="H_NH2") def test_singlebond_stretch_HO_AlH2(self): StructureTest(dir="singlebond_stretch", test="HO_AlH2") def test_singlebond_stretch_HO_BH2(self): StructureTest(dir="singlebond_stretch", test="HO_BH2") def test_singlebond_stretch_HO_CH3(self): StructureTest(dir="singlebond_stretch", test="HO_CH3") def test_singlebond_stretch_H_OH(self): StructureTest(dir="singlebond_stretch", test="H_OH") def test_singlebond_stretch_HO_NH2(self): StructureTest(dir="singlebond_stretch", test="HO_NH2") def test_singlebond_stretch_HO_OH(self): StructureTest(dir="singlebond_stretch", test="HO_OH") def test_singlebond_stretch_HO_PH2(self): StructureTest(dir="singlebond_stretch", test="HO_PH2") def test_singlebond_stretch_HO_SiH3(self): StructureTest(dir="singlebond_stretch", test="HO_SiH3") def test_singlebond_stretch_H_PH2(self): StructureTest(dir="singlebond_stretch", test="H_PH2") def test_singlebond_stretch_HS_AlH2(self): StructureTest(dir="singlebond_stretch", test="HS_AlH2") def test_singlebond_stretch_HS_BH2(self): StructureTest(dir="singlebond_stretch", test="HS_BH2") def test_singlebond_stretch_HS_CH3(self): StructureTest(dir="singlebond_stretch", test="HS_CH3") def test_singlebond_stretch_H_SH(self): StructureTest(dir="singlebond_stretch", test="H_SH") def test_singlebond_stretch_H_SiH3(self): StructureTest(dir="singlebond_stretch", test="H_SiH3") def test_singlebond_stretch_HS_NH2(self): StructureTest(dir="singlebond_stretch", test="HS_NH2") def test_singlebond_stretch_HS_OH(self): StructureTest(dir="singlebond_stretch", test="HS_OH") def test_singlebond_stretch_HS_PH2(self): StructureTest(dir="singlebond_stretch", test="HS_PH2") def test_singlebond_stretch_HS_SH(self): StructureTest(dir="singlebond_stretch", test="HS_SH") def test_singlebond_stretch_HS_SiH3(self): StructureTest(dir="singlebond_stretch", test="HS_SiH3") def test_singlebond_stretch_test_Cl_AlH2(self): StructureTest(dir="singlebond_stretch", test="Cl_AlH2") def test_singlebond_stretch_test_Cl_BH2(self): StructureTest(dir="singlebond_stretch", test="Cl_BH2") def test_singlebond_stretch_test_Cl_CH3(self): StructureTest(dir="singlebond_stretch", test="Cl_CH3") def test_singlebond_stretch_test_Cl_Cl(self): StructureTest(dir="singlebond_stretch", test="Cl_Cl") def test_singlebond_stretch_test_Cl_F(self): StructureTest(dir="singlebond_stretch", test="Cl_F") def test_singlebond_stretch_test_Cl_NH2(self): StructureTest(dir="singlebond_stretch", test="Cl_NH2") def test_singlebond_stretch_test_Cl_OH(self): StructureTest(dir="singlebond_stretch", test="Cl_OH") def test_singlebond_stretch_test_Cl_PH2(self): StructureTest(dir="singlebond_stretch", test="Cl_PH2") def test_singlebond_stretch_test_Cl_SH(self): StructureTest(dir="singlebond_stretch", test="Cl_SH") def test_singlebond_stretch_test_Cl_SiH3(self): StructureTest(dir="singlebond_stretch", test="Cl_SiH3") def test_singlebond_stretch_test_F_AlH2(self): StructureTest(dir="singlebond_stretch", test="F_AlH2") def test_singlebond_stretch_test_F_BH2(self): StructureTest(dir="singlebond_stretch", test="F_BH2") def test_singlebond_stretch_test_F_CH3(self): StructureTest(dir="singlebond_stretch", test="F_CH3") def test_singlebond_stretch_test_F_F(self): StructureTest(dir="singlebond_stretch", test="F_F") def test_singlebond_stretch_test_F_NH2(self): StructureTest(dir="singlebond_stretch", test="F_NH2") def test_singlebond_stretch_test_F_OH(self): StructureTest(dir="singlebond_stretch", test="F_OH") def test_singlebond_stretch_test_F_PH2(self): StructureTest(dir="singlebond_stretch", test="F_PH2") def test_singlebond_stretch_test_F_SH(self): StructureTest(dir="singlebond_stretch", test="F_SH") def test_singlebond_stretch_test_F_SiH3(self): StructureTest(dir="singlebond_stretch", test="F_SiH3") def test_singlebond_stretch_test_H2Al_AlH2(self): StructureTest(dir="singlebond_stretch", test="H2Al_AlH2") def test_singlebond_stretch_test_H2Al_CH3(self): StructureTest(dir="singlebond_stretch", test="H2Al_CH3") def test_singlebond_stretch_test_H2Al_SiH3(self): StructureTest(dir="singlebond_stretch", test="H2Al_SiH3") def test_singlebond_stretch_test_H2B_AlH2(self): StructureTest(dir="singlebond_stretch", test="H2B_AlH2") def test_singlebond_stretch_test_H2B_BH2(self): StructureTest(dir="singlebond_stretch", test="H2B_BH2") def test_singlebond_stretch_test_H2B_CH3(self): StructureTest(dir="singlebond_stretch", test="H2B_CH3") def test_singlebond_stretch_test_H2B_NH2(self): StructureTest(dir="singlebond_stretch", test="H2B_NH2") def test_singlebond_stretch_test_H2B_PH2(self): StructureTest(dir="singlebond_stretch", test="H2B_PH2") def test_singlebond_stretch_test_H2B_SiH3(self): StructureTest(dir="singlebond_stretch", test="H2B_SiH3") def test_singlebond_stretch_test_H2N_AlH2(self): StructureTest(dir="singlebond_stretch", test="H2N_AlH2") def test_singlebond_stretch_test_H2N_CH3(self): StructureTest(dir="singlebond_stretch", test="H2N_CH3") def test_singlebond_stretch_test_H2N_NH2(self): StructureTest(dir="singlebond_stretch", test="H2N_NH2") def test_singlebond_stretch_test_H2N_PH2(self): StructureTest(dir="singlebond_stretch", test="H2N_PH2") def test_singlebond_stretch_test_H2N_SiH3(self): StructureTest(dir="singlebond_stretch", test="H2N_SiH3") def test_singlebond_stretch_test_H2P_AlH2(self): StructureTest(dir="singlebond_stretch", test="H2P_AlH2") def test_singlebond_stretch_test_H2P_CH3(self): StructureTest(dir="singlebond_stretch", test="H2P_CH3") def test_singlebond_stretch_test_H2P_PH2(self): StructureTest(dir="singlebond_stretch", test="H2P_PH2") def test_singlebond_stretch_test_H2P_SiH3(self): StructureTest(dir="singlebond_stretch", test="H2P_SiH3") def test_singlebond_stretch_test_H3C_CH3(self): StructureTest(dir="singlebond_stretch", test="H3C_CH3") def test_singlebond_stretch_test_H3C_SiH3(self): StructureTest(dir="singlebond_stretch", test="H3C_SiH3") def test_singlebond_stretch_test_H3Si_SiH3(self): StructureTest(dir="singlebond_stretch", test="H3Si_SiH3") def test_singlebond_stretch_test_H_AlH2(self): StructureTest(dir="singlebond_stretch", test="H_AlH2") def test_singlebond_stretch_test_H_BH2(self): StructureTest(dir="singlebond_stretch", test="H_BH2") def test_singlebond_stretch_test_H_CH3(self): StructureTest(dir="singlebond_stretch", test="H_CH3") def test_singlebond_stretch_test_H_Cl(self): StructureTest(dir="singlebond_stretch", test="H_Cl") def test_singlebond_stretch_test_H_F(self): StructureTest(dir="singlebond_stretch", test="H_F") def test_singlebond_stretch_test_H_H(self): StructureTest(dir="singlebond_stretch", test="H_H") def test_singlebond_stretch_test_H_NH2(self): StructureTest(dir="singlebond_stretch", test="H_NH2") def test_singlebond_stretch_test_HO_AlH2(self): StructureTest(dir="singlebond_stretch", test="HO_AlH2") def test_singlebond_stretch_test_HO_BH2(self): StructureTest(dir="singlebond_stretch", test="HO_BH2") def test_singlebond_stretch_test_HO_CH3(self): StructureTest(dir="singlebond_stretch", test="HO_CH3") def test_singlebond_stretch_test_H_OH(self): StructureTest(dir="singlebond_stretch", test="H_OH") def test_singlebond_stretch_test_HO_NH2(self): StructureTest(dir="singlebond_stretch", test="HO_NH2") def test_singlebond_stretch_test_HO_OH(self): StructureTest(dir="singlebond_stretch", test="HO_OH") def test_singlebond_stretch_test_HO_PH2(self): StructureTest(dir="singlebond_stretch", test="HO_PH2") def test_singlebond_stretch_test_HO_SiH3(self): StructureTest(dir="singlebond_stretch", test="HO_SiH3") def test_singlebond_stretch_test_H_PH2(self): StructureTest(dir="singlebond_stretch", test="H_PH2") def test_singlebond_stretch_test_HS_AlH2(self): StructureTest(dir="singlebond_stretch", test="HS_AlH2") def test_singlebond_stretch_test_HS_BH2(self): StructureTest(dir="singlebond_stretch", test="HS_BH2") def test_singlebond_stretch_test_HS_CH3(self): StructureTest(dir="singlebond_stretch", test="HS_CH3") def test_singlebond_stretch_test_H_SH(self): StructureTest(dir="singlebond_stretch", test="H_SH") def test_singlebond_stretch_test_H_SiH3(self): StructureTest(dir="singlebond_stretch", test="H_SiH3") def test_singlebond_stretch_test_HS_NH2(self): StructureTest(dir="singlebond_stretch", test="HS_NH2") def test_singlebond_stretch_test_HS_OH(self): StructureTest(dir="singlebond_stretch", test="HS_OH") def test_singlebond_stretch_test_HS_PH2(self): StructureTest(dir="singlebond_stretch", test="HS_PH2") def test_singlebond_stretch_test_HS_SH(self): StructureTest(dir="singlebond_stretch", test="HS_SH") def test_singlebond_stretch_test_HS_SiH3(self): StructureTest(dir="singlebond_stretch", test="HS_SiH3") ### Pyrex tests def test_pyrex_minH2(self): PyrexTest("test_pyrex_minH2", "tests/minimize/test_h2") def test_pyrex_minimize0001(self): PyrexTest("test_pyrex_minimize0001", "tests/minimize/test_0001") def test_pyrex_dynamics(self): class Foo(PyrexTest): def run(self): import sim s = sim.theSimulator() s.reinitGlobals() s.InputFileName = "tests/dynamics/test_0002.mmp" s.OutputFileName = "tests/dynamics/test_0002.dpb" s.ToMinimize = 0 s.DumpAsText = 0 s.OutputFormat = 1 s.NumFrames = 100 s.PrintFrameNums = 0 s.IterPerFrame = 10 s.Temperature = 300 s.go() assert not sim.isFileAscii("tests/dynamics/test_0002.dpb") Foo("test_pyrex_dynamics") # Jig tests def test_enabled_disabled_jigs_001_disabled_anchors(self): JigTest(dir="enabled_disabled_jigs", test="001_disabled_anchors") def test_enabled_disabled_jigs_002_one_anchor_enabled_other_disabled(self): JigTest(dir="enabled_disabled_jigs", test="002_one_anchor_enabled_other_disabled") def test_enabled_disabled_jigs_003_one_thermometer_enabled_other_disabled(self): JigTest(dir="enabled_disabled_jigs", test="003_one_thermometer_enabled_other_disabled") def test_enabled_disabled_jigs_004_one_thermostat_enabled_other_disabled(self): JigTest(dir="enabled_disabled_jigs", test="004_one_thermostat_enabled_other_disabled") def test_enabled_disabled_jigs_005_disabled_measure_distance_jig(self): JigTest(dir="enabled_disabled_jigs", test="005_disabled_measure_distance_jig") def test_enabled_disabled_jigs_006_one_rotarymotor_enabled_and_other_disabled(self): JigTest(dir="enabled_disabled_jigs", test="006_one_rotarymotor_enabled_and_other_disabled") def test_enabled_disabled_jigs_007_one_linearmotor_enabled_and_other_disabled(self): JigTest(dir="enabled_disabled_jigs", test="007_one_linearmotor_enabled_and_other_disabled") def test_jigs_to_several_atoms_001_rotarymotor_to_50_atoms(self): JigTest(dir="jigs_to_several_atoms", test="001_rotarymotor_to_50_atoms") def test_jigs_to_several_atoms_002_rotarymotor_to_100_atoms(self): JigTest(dir="jigs_to_several_atoms", test="002_rotarymotor_to_100_atoms") def test_jigs_to_several_atoms_003_linearmotor_to_50_atoms(self): JigTest(dir="jigs_to_several_atoms", test="003_linearmotor_to_50_atoms") def test_jigs_to_several_atoms_004_linearmotor_to_100_atoms(self): JigTest(dir="jigs_to_several_atoms", test="004_linearmotor_to_100_atoms") def test_jigs_to_several_atoms_005_anchors_to_50_atoms(self): JigTest(dir="jigs_to_several_atoms", test="005_anchors_to_50_atoms") def test_jigs_to_several_atoms_006_anchors_to_100_atoms(self): JigTest(dir="jigs_to_several_atoms", test="006_anchors_to_100_atoms") def test_jigs_to_several_atoms_007_rotarymotor_and_anchors_to_100_atoms(self): JigTest(dir="jigs_to_several_atoms", test="007_rotarymotor_and_anchors_to_100_atoms") def test_motors_001_linearmotor_0_force_and_0_stiffness(self): JigTest(dir="motors", test="001_linearmotor_0_force_and_0_stiffness") def test_motors_002_linearmotor_0_force_and_negative_stiffness(self): JigTest(dir="motors", test="002_linearmotor_0_force_and_negative_stiffness") def test_motors_003_linearmotor_0_force_and_positive_stiffness(self): JigTest(dir="motors", test="003_linearmotor_0_force_and_positive_stiffness") def test_motors_004_linearmotor_negative_force_and_negative_stiffness(self): JigTest(dir="motors", test="004_linearmotor_negative_force_and_negative_stiffness") def test_motors_005_linearmotor_negative_force_and_positive_stiffness(self): JigTest(dir="motors", test="005_linearmotor_negative_force_and_positive_stiffness") def test_motors_006_linearmotor_negative_force_and_0_stiffness(self): JigTest(dir="motors", test="006_linearmotor_negative_force_and_0_stiffness") def test_motors_007_linearmotor_positive_force_and_0_stiffness(self): JigTest(dir="motors", test="007_linearmotor_positive_force_and_0_stiffness") def test_motors_008_linearmotor_positive_force_and_positive_stiffness(self): JigTest(dir="motors", test="008_linearmotor_positive_force_and_positive_stiffness") def test_motors_009_linearmotor_Methane_Molecule(self): JigTest(dir="motors", test="009_linearmotor_Methane_Molecule") def test_motors_010_linearmotor_box_of_helium(self): JigTest(dir="motors", test="010_linearmotor_box_of_helium") def test_motors_011_rotarymotor_0_torque_and_0_speed(self): JigTest(dir="motors", test="011_rotarymotor_0_torque_and_0_speed") def test_motors_012_rotarymotor_0_torque_and_negative_speed(self): JigTest(dir="motors", test="012_rotarymotor_0_torque_and_negative_speed") def test_motors_013_rotarymotor_0_torque_and_positive_speed(self): JigTest(dir="motors", test="013_rotarymotor_0_torque_and_positive_speed") def test_motors_014_rotarymotor_negative_torque_and_negative_speed(self): JigTest(dir="motors", test="014_rotarymotor_negative_torque_and_negative_speed") def test_motors_015_rotarymotor_negative_torque_and_positive_speed(self): JigTest(dir="motors", test="015_rotarymotor_negative_torque_and_positive_speed") def test_motors_016_rotarymotor_negative_torque_and_0_speed(self): JigTest(dir="motors", test="016_rotarymotor_negative_torque_and_0_speed") def test_motors_017_rotarymotor_positive_torque_and_negative_speed(self): JigTest(dir="motors", test="017_rotarymotor_positive_torque_and_negative_speed") def test_motors_018_rotarymotor_positive_torque_and_0_speed(self): JigTest(dir="motors", test="018_rotarymotor_positive_torque_and_0_speed") def test_motors_019_rotarymotor_medium_torque_and_speed(self): JigTest(dir="motors", test="019_rotarymotor_medium_torque_and_speed") def test_motors_020_rotarymotor_high_torque_and_speed(self): JigTest(dir="motors", test="020_rotarymotor_high_torque_and_speed") def test_motors_021_rotarymotor_dyno_jig_test_to_same_chunk(self): JigTest(dir="motors", test="021_rotarymotor_dyno_jig_test_to_same_chunk") def test_motors_022_rotary_motor_small_bearing_test(self): JigTest(dir="motors", test="022_rotary_motor_small_bearing_test") def test_motors_023_rotarymotor_two_planet_gears(self): JigTest(dir="motors", test="023_rotarymotor_two_planet_gears") def test_motors_024_linearmotor_two_dodecahedranes(self): JigTest(dir="motors", test="024_linearmotor_two_dodecahedranes") def test_motors_025_two_linearmotors_applying_equal_forces_normal_to_each_other(self): JigTest(dir="motors", test="025_two_linearmotors_applying_equal_forces_normal_to_each_other") def test_motors_026_two_linearmotors_applying_equal_and_opposite_forces(self): JigTest(dir="motors", test="026_two_linearmotors_applying_equal_and_opposite_forces") def test_motors_027_two_rotarymotors_applying_equal_and_opposite_torque(self): JigTest(dir="motors", test="027_two_rotarymotors_applying_equal_and_opposite_torque") def test_motors_028_bug1306_test2(self): JigTest(dir="motors", test="028_bug1306_test2") def test_motors_029_bug_1331(self): JigTest(dir="motors", test="029_bug_1331") def test_motors_030_rotarymotor_and_linear_motor_attached_to_same_atoms(self): JigTest(dir="motors", test="030_rotarymotor_and_linear_motor_attached_to_same_atoms") def test_motors_and_anchors_001_linearmotor_pulling_against_anchor_1(self): JigTest(dir="motors_and_anchors", test="001_linearmotor_pulling_against_anchor_1") def test_motors_and_anchors_002_linearmotor_pulling_against_anchor_2(self): JigTest(dir="motors_and_anchors", test="002_linearmotor_pulling_against_anchor_2") def test_motors_and_anchors_003_rotorymotor_against_anchor_1(self): JigTest(dir="motors_and_anchors", test="003_rotorymotor_against_anchor_1") def test_motors_and_anchors_004_rotorymotor_against_anchor_2(self): JigTest(dir="motors_and_anchors", test="004_rotorymotor_against_anchor_2") def test_motors_and_anchors_005_rotorymotor_against_anchor_3(self): JigTest(dir="motors_and_anchors", test="005_rotorymotor_against_anchor_3") def test_reordering_jigs_or_chunks_01_thermo_anchor_reordering_1(self): JigTest(dir="reordering_jigs_or_chunks", test="01_thermo_anchor_reordering_1") def test_reordering_jigs_or_chunks_01_thermo_anchor_reordering_2(self): JigTest(dir="reordering_jigs_or_chunks", test="01_thermo_anchor_reordering_2") def test_reordering_jigs_or_chunks_01_thermo_anchor_reordering_3(self): JigTest(dir="reordering_jigs_or_chunks", test="01_thermo_anchor_reordering_3") def test_reordering_jigs_or_chunks_01_thermo_anchor_reordering_4(self): JigTest(dir="reordering_jigs_or_chunks", test="01_thermo_anchor_reordering_4") def test_reordering_jigs_or_chunks_01_thermo_anchor_reordering_5(self): JigTest(dir="reordering_jigs_or_chunks", test="01_thermo_anchor_reordering_5") def test_reordering_jigs_or_chunks_02_thermo_anchor_stat_reordering_1(self): JigTest(dir="reordering_jigs_or_chunks", test="02_thermo_anchor_stat_reordering_1") def test_reordering_jigs_or_chunks_02_thermo_anchor_stat_reordering_2(self): JigTest(dir="reordering_jigs_or_chunks", test="02_thermo_anchor_stat_reordering_2") def test_reordering_jigs_or_chunks_02_thermo_anchor_stat_reordering_3(self): JigTest(dir="reordering_jigs_or_chunks", test="02_thermo_anchor_stat_reordering_3") def test_reordering_jigs_or_chunks_02_thermo_anchor_stat_reordering_4(self): JigTest(dir="reordering_jigs_or_chunks", test="02_thermo_anchor_stat_reordering_4") def test_reordering_jigs_or_chunks_02_thermo_anchor_stat_reordering_5(self): JigTest(dir="reordering_jigs_or_chunks", test="02_thermo_anchor_stat_reordering_5") def test_reordering_jigs_or_chunks_02_thermo_anchor_stat_reordering_6(self): JigTest(dir="reordering_jigs_or_chunks", test="02_thermo_anchor_stat_reordering_6") def test_reordering_jigs_or_chunks_02_thermo_anchor_stat_reordering_7(self): JigTest(dir="reordering_jigs_or_chunks", test="02_thermo_anchor_stat_reordering_7") def test_reordering_jigs_or_chunks_02_thermo_anchor_stat_reordering_8(self): JigTest(dir="reordering_jigs_or_chunks", test="02_thermo_anchor_stat_reordering_8") def test_reordering_jigs_or_chunks_03_thermo_anchor_reordering(self): JigTest(dir="reordering_jigs_or_chunks", test="03_thermo_anchor_reordering") def test_reordering_jigs_or_chunks_03_thermo_rmotor_anchor_stat_reordering_1(self): JigTest(dir="reordering_jigs_or_chunks", test="03_thermo_rmotor_anchor_stat_reordering_1") def test_reordering_jigs_or_chunks_03_thermo_rmotor_anchor_stat_reordering_2(self): JigTest(dir="reordering_jigs_or_chunks", test="03_thermo_rmotor_anchor_stat_reordering_2") def test_reordering_jigs_or_chunks_03_thermo_rmotor_anchor_stat_reordering_3(self): JigTest(dir="reordering_jigs_or_chunks", test="03_thermo_rmotor_anchor_stat_reordering_3") def test_reordering_jigs_or_chunks_03_thermo_rmotor_anchor_stat_reordering_4(self): JigTest(dir="reordering_jigs_or_chunks", test="03_thermo_rmotor_anchor_stat_reordering_4") def test_reordering_jigs_or_chunks_03_thermo_rmotor_anchor_stat_reordering_5(self): JigTest(dir="reordering_jigs_or_chunks", test="03_thermo_rmotor_anchor_stat_reordering_5") def test_reordering_jigs_or_chunks_03_thermo_rmotor_anchor_stat_reordering_6(self): JigTest(dir="reordering_jigs_or_chunks", test="03_thermo_rmotor_anchor_stat_reordering_6") def test_reordering_jigs_or_chunks_03_thermo_rmotor_anchor_stat_reordering_7(self): JigTest(dir="reordering_jigs_or_chunks", test="03_thermo_rmotor_anchor_stat_reordering_7") def test_reordering_jigs_or_chunks_03_thermo_rmotor_anchor_stat_reordering_8(self): JigTest(dir="reordering_jigs_or_chunks", test="03_thermo_rmotor_anchor_stat_reordering_8") def test_reordering_jigs_or_chunks_04_thermo_lmotor_anchor_stat_reordering_1(self): JigTest(dir="reordering_jigs_or_chunks", test="04_thermo_lmotor_anchor_stat_reordering_1") def test_reordering_jigs_or_chunks_04_thermo_lmotor_anchor_stat_reordering_2(self): JigTest(dir="reordering_jigs_or_chunks", test="04_thermo_lmotor_anchor_stat_reordering_2") def test_reordering_jigs_or_chunks_04_thermo_lmotor_anchor_stat_reordering_3(self): JigTest(dir="reordering_jigs_or_chunks", test="04_thermo_lmotor_anchor_stat_reordering_3") def test_reordering_jigs_or_chunks_04_thermo_lmotor_anchor_stat_reordering_4(self): JigTest(dir="reordering_jigs_or_chunks", test="04_thermo_lmotor_anchor_stat_reordering_4") def test_reordering_jigs_or_chunks_04_thermo_lmotor_anchor_stat_reordering_5(self): JigTest(dir="reordering_jigs_or_chunks", test="04_thermo_lmotor_anchor_stat_reordering_5") def test_reordering_jigs_or_chunks_04_thermo_lmotor_anchor_stat_reordering_6(self): JigTest(dir="reordering_jigs_or_chunks", test="04_thermo_lmotor_anchor_stat_reordering_6") def test_reordering_jigs_or_chunks_04_thermo_lmotor_anchor_stat_reordering_7(self): JigTest(dir="reordering_jigs_or_chunks", test="04_thermo_lmotor_anchor_stat_reordering_7") def test_reordering_jigs_or_chunks_04_thermo_lmotor_anchor_stat_reordering_8(self): JigTest(dir="reordering_jigs_or_chunks", test="04_thermo_lmotor_anchor_stat_reordering_8") def test_reordering_jigs_or_chunks_05_thermo_lmotor_anchor_measurement_jigs_reordering_1(self): JigTest(dir="reordering_jigs_or_chunks", test="05_thermo_lmotor_anchor_measurement_jigs_reordering_1") def test_reordering_jigs_or_chunks_05_thermo_lmotor_anchor_measurement_jigs_reordering_2(self): JigTest(dir="reordering_jigs_or_chunks", test="05_thermo_lmotor_anchor_measurement_jigs_reordering_2") def test_reordering_jigs_or_chunks_05_thermo_lmotor_anchor_measurement_jigs_reordering_3(self): JigTest(dir="reordering_jigs_or_chunks", test="05_thermo_lmotor_anchor_measurement_jigs_reordering_3") def test_reordering_jigs_or_chunks_05_thermo_lmotor_anchor_measurement_jigs_reordering_4(self): JigTest(dir="reordering_jigs_or_chunks", test="05_thermo_lmotor_anchor_measurement_jigs_reordering_4") def test_reordering_jigs_or_chunks_05_thermo_lmotor_anchor_measurement_jigs_reordering_5(self): JigTest(dir="reordering_jigs_or_chunks", test="05_thermo_lmotor_anchor_measurement_jigs_reordering_5") def test_reordering_jigs_or_chunks_05_thermo_lmotor_anchor_measurement_jigs_reordering_6(self): JigTest(dir="reordering_jigs_or_chunks", test="05_thermo_lmotor_anchor_measurement_jigs_reordering_6") def test_reordering_jigs_or_chunks_05_thermo_lmotor_anchor_measurement_jigs_reordering_7(self): JigTest(dir="reordering_jigs_or_chunks", test="05_thermo_lmotor_anchor_measurement_jigs_reordering_7") def test_reordering_jigs_or_chunks_05_thermo_lmotor_anchor_measurement_jigs_reordering_8(self): JigTest(dir="reordering_jigs_or_chunks", test="05_thermo_lmotor_anchor_measurement_jigs_reordering_8") def test_temperature_tests_001_two_methanes_9A_apart_vdw_5(self): JigTest(dir="temperature_tests", test="001_two_methanes_9A_apart_vdw_5") def test_temperature_tests_002_two_methanes_10A_apart_vdw_6(self): JigTest(dir="temperature_tests", test="002_two_methanes_10A_apart_vdw_6") def test_temperature_tests_003_thermostat_test_1(self): JigTest(dir="temperature_tests", test="003_thermostat_test_1") def test_temperature_tests_003_thermostat_test_2(self): JigTest(dir="temperature_tests", test="003_thermostat_test_2") def test_temperature_tests_003_thermostat_test_3(self): JigTest(dir="temperature_tests", test="003_thermostat_test_3") def test_temperature_tests_003_thermostat_test_4(self): JigTest(dir="temperature_tests", test="003_thermostat_test_4") def test_temperature_tests_003_thermostat_test_5(self): JigTest(dir="temperature_tests", test="003_thermostat_test_5") def test_temperature_tests_003_thermostat_test(self): JigTest(dir="temperature_tests", test="003_thermostat_test") class TwoStreamTextTestResult(unittest._TextTestResult): def __init__(self, progressStream, resultStream, descriptions, verbosity): unittest._TextTestResult.__init__(self, unittest._WritelnDecorator(progressStream), descriptions, verbosity) self.resultStream = unittest._WritelnDecorator(resultStream) def printErrorList(self, flavour, errors): for test, err in errors: self.resultStream.writeln(self.separator1) self.resultStream.writeln("%s: %s" % (flavour,self.getDescription(test))) self.resultStream.writeln(self.separator2) self.resultStream.writeln("%s" % err) class Main(unittest.TextTestRunner): def main(self, args): options = None # Process command line arguments def generate(x): """update md5sums files according to current simulator behavior """ global GENERATE GENERATE = True def md5check(x): """perform MD5 checksum comparisons; useful for simulator development """ global MD5_CHECKS if sys.platform != "linux2": raise SystemExit("MD5 checks supported only on Linux") MD5_CHECKS = True def lengths_angles(x): """perform structure comparisons with known-good structures computed by QM minimizations, comparing bond lengths and bond angles """ global STRUCTURE_COMPARISON_TYPE STRUCTURE_COMPARISON_TYPE = LENGTH_ANGLE_TEST def structcompare(x): """perform structure comparisons with known-good structures computed by QM minimizations, using code in structcompare.c """ global STRUCTURE_COMPARISON_TYPE STRUCTURE_COMPARISON_TYPE = STRUCTCOMPARE_C_TEST def time_limit(x): """do as many tests as possible in this many seconds """ assert x[:1] == "=" global TIME_LIMIT TIME_LIMIT = string.atof(x[1:]) def pyrex(x): """Perform the Pyrex tests """ for nm in dir(Tests): if nm.startswith("test_") and not nm.startswith("test_pyrex"): try: delattr(Tests, nm) except AttributeError: pass def loose(x): """Loose tolerances on length and angle comparisons. """ global LOOSE_TOLERANCES LOOSE_TOLERANCES = True def medium(x): """Moderate tolerances on length and angle comparisons. """ global MEDIUM_TOLERANCES MEDIUM_TOLERANCES = True def tight(x): """Tight tolerances on length and angle comparisons. """ global TIGHT_TOLERANCES TIGHT_TOLERANCES = True def test_dir(x): """which directory should we test """ assert x[:1] == "=" x = x[1:] assert x in ("minimize", "dynamics", "rigid_organics", "amino_acids", "floppy_organics", "heteroatom_organics") global TEST_DIR TEST_DIR = x def list_everything(x): """Instead of just showing the first failure for each test case, show every non-compliant energy term """ global LIST_EVERYTHING LIST_EVERYTHING = True def debug(x): """debug this script """ global DEBUG if x[:1] == "=": DEBUG = string.atoi(x[1:]) else: DEBUG = 1 def time_only(x): """measure the time each test takes, ignore any results """ global TIME_ONLY, Tests TIME_ONLY = True def keep(x): """when a test is finished, don't delete its temporary directory (useful for debug) """ global KEEP_RESULTS KEEP_RESULTS = True def todo_tasks(x): """reminders of what work still needs doing """ global SHOW_TODO, MD5_CHECKS SHOW_TODO = True # catch all the TODOs everywhere MD5_CHECKS = True def verbose_failures(x): """print non-abbreviated assertion statements (useful for debug) """ global VERBOSE_FAILURES VERBOSE_FAILURES = True def verbose_progress(x): """print verbose test names as progress indicator instead of dots. """ self.verbosity = 2 def help(x): """print help information """ print __doc__ for opt in options: print opt.__name__ + "\n " + opt.__doc__ sys.exit(0) options = (md5check, lengths_angles, structcompare, time_limit, pyrex, loose, medium, tight, test_dir, list_everything, generate, debug, time_only, keep, todo_tasks, verbose_failures, verbose_progress, help) # Default behavior is to do all the tests, including the slow ones, # with loose tolerances, so things pass defaultArgs = () if len(args) < 1: args = defaultArgs for arg in args: found = False for opt in options: nm = opt.__name__ if arg.startswith(nm): found = True arg = arg[len(nm):] opt(arg) break if not found: print "Don't understand command line arg:", arg print "Try typing: python tests.py help" sys.exit(1) # For failures, don't usually bother with complete tracebacks, # it's more information than we need. def addFailure(self, test, err): self.failures.append((test, traceback.format_exception(*err)[-1])) if not VERBOSE_FAILURES: unittest.TestResult.addFailure = addFailure global LENGTH_TOLERANCE, ANGLE_TOLERANCE if TIGHT_TOLERANCES: LENGTH_TOLERANCE = 0.03 # angstroms ANGLE_TOLERANCE = 3 # degrees if MEDIUM_TOLERANCES: LENGTH_TOLERANCE = 0.11 # angstroms ANGLE_TOLERANCE = 12 # degrees if LOOSE_TOLERANCES: LENGTH_TOLERANCE = 0.138 # angstroms ANGLE_TOLERANCE = 14.1 # degrees casenames = self.getCasenames() self.run(unittest.TestSuite(map(Tests, casenames))) if TIME_ONLY: lst = [ ] for name in testTimes.keys(): t = testTimes[name] lst.append([t, name]) lst.sort() import pprint pprint.pprint(map(lambda x: x[1], lst)) else: print len(casenames) - testsSkipped, "tests really done,", print testsSkipped, "tests skipped" def getCasenames(self): # Start with tests that appear both as entries in RANKED_BY_RUNTIME # and _also_ as test cases in Tests. casenames = filter(lambda x: hasattr(Tests, x), RANKED_BY_RUNTIME) if TIME_ONLY or GENERATE: # Add any test cases in Tests that did not appear in RANKED_BY_RUNTIME. for attr in dir(Tests): if attr.startswith("test_") and attr not in casenames: casenames.append(attr) elif TEST_DIR != None: # filter the results to only what we want def filt(name): return name.startswith("test_" + TEST_DIR) casenames = filter(filt, casenames) return casenames def _getCasenames(self): return [ 'test_dynamics_small_bearing_01', ] # send progress indicators to stderr (usually a terminal) def _makeResult(self): return TwoStreamTextTestResult(sys.stderr, sys.stdout, self.descriptions, self.verbosity) # send test results to stdout (can be easily redirected) def __init__(self, stream=sys.stdout, descriptions=1, verbosity=1): self.stream = unittest._WritelnDecorator(stream) self.descriptions = descriptions self.verbosity = verbosity """ If you want some special selection of cases, you can do it like this: import sys import tests class Main(tests.Main): def getCasenames(self): return [ 'test_motors_011_rotarymotor_0_torque_and_0_speed', 'test_motors_016_rotarymotor_negative_torque_and_0_speed', 'test_motors_018_rotarymotor_positive_torque_and_0_speed', 'test_motors_021_rotarymotor_dyno_jig_test_to_same_chunk', ] Main().main(sys.argv[1:]) """ ########################################### if __name__ == "__main__": Main().main(sys.argv[1:])
NanoCAD-master
sim/src/tests.py
# Copyright 2006 Nanorex, Inc. See LICENSE file for details. import sys import distutils.sysconfig import distutils.ccompiler class FakeCompiler: def __init__(self): self.compiler_type = distutils.ccompiler.get_default_compiler() def set_executables(self, **kw): for k in kw: setattr(self, k, kw[k]) mcc = FakeCompiler() distutils.sysconfig.customize_compiler(mcc) if len(sys.argv) < 2: import pprint pprint.pprint(mcc.__dict__) else: for arg in sys.argv[1:]: cmd = getattr(mcc, arg) if cmd.startswith("gcc ") or cmd.startswith("g++ "): cmd = cmd[4:] print cmd
NanoCAD-master
sim/src/distutils_compile_options.py
# Copyright 2006 Nanorex, Inc. See LICENSE file for details. __author__ = "Will" import sys, os, Pyrex def find_pyrexc(): if sys.platform == 'darwin': # MacOS x = os.path.dirname(Pyrex.__file__).split('/') y = '/'.join(x[:-4] + ['bin', 'pyrexc']) if os.path.exists(y): return y elif os.path.exists('/usr/local/bin/pyrexc'): return '/usr/local/bin/pyrexc' raise Exception('cannot find Mac pyrexc') elif sys.platform == 'linux2': if os.path.exists('/usr/bin/pyrexc'): return '/usr/bin/pyrexc' if os.path.exists('/usr/local/bin/pyrexc'): return '/usr/local/bin/pyrexc' raise Exception('cannot find Linux pyrexc') else: # windows return 'python c:/Python' + sys.version[:3] + '/Scripts/pyrexc.py'
NanoCAD-master
sim/src/findpyrex.py
# Copyright 2006 Nanorex, Inc. See LICENSE file for details. import sys import time import os.path if sys.platform == "darwin": extra_compile_args = [ "-O" ] else: extra_compile_args = [ ] DISTUTILS_FLAGS = None if sys.platform != "win32": from distutils.core import setup from distutils.extension import Extension import Pyrex.Distutils class local_build_ext(Pyrex.Distutils.build_ext): def __init__(self, dist): Pyrex.Distutils.build_ext.__init__(self, dist) self.distn = dist def run(self): # Pieces of the distutils.command.build_ext.run() method global DISTUTILS_FLAGS from distutils.ccompiler import new_compiler from distutils.sysconfig import customize_compiler compiler = new_compiler(compiler=None, verbose=self.verbose, dry_run=self.dry_run, force=self.force) customize_compiler(compiler) DISTUTILS_FLAGS = (compiler.compiler_so + self.distn.ext_modules[0].extra_compile_args) sys_argv = sys.argv sys.argv = ["setup.py", "build_ext"] setup(name = 'Simulator', ext_modules=[Extension("sim", [ ], extra_compile_args = extra_compile_args)], cmdclass = {'build_ext': local_build_ext}) sys.argv = sys_argv def hString(name, s, prefix=""): import string retval = "#define " + name + " \\\n\"" + prefix # replace double-quote with escaped-double-quote s = string.replace(s, "\"", "\\\"") # replace line terminations with end-of-last-line plus start-of-next-line s = string.replace(s, "\n", ("\\n\"\\\n\"") + prefix) return retval + s + "\\n\"\n" #def cString(name, s, prefix=""): # import string # retval = "char " + name + "[] = \"\\\n" + prefix # # replace double-quote with escaped-double-quote # s = string.replace(s, "\"", "\\\"") # # replace line terminations with end-of-last-line plus start-of-next-line # s = string.replace(s, "\n", ("\\n\\\n") + prefix) # return retval + s + "\\n\";\n" ###################################### print hString("TRACE_PREFIX", "uname -a: " + sys.argv[3] + "\n", "# ") print hString("TRACE_PREFIX_NON_DISTUTILS", "CFLAGS: " + sys.argv[1] + "\n" + "LDFLAGS: " + sys.argv[2] + "\n", "# ") if DISTUTILS_FLAGS != None: distutils = " ".join(DISTUTILS_FLAGS) else: distutils = "None" print hString("TRACE_PREFIX_DISTUTILS", "Python " + sys.version.replace("\n", " ") + "\n" + distutils + "\n", "# ")
NanoCAD-master
sim/src/makehelp.py
# Copyright 2005 Nanorex, Inc. See LICENSE file for details. """Physical units for calculations Physical quantities are represented here as dictionaries. One key is 'coefficient', the other keys are metric units like 'm', 'sec', 'kg'. The value for each dimension key is the power to which that unit is raised. For instance, the representation for a newton is {'sec': -2, 'kg': 1, 'm': 1, 'coefficient': 1.0}. When quantities are multiplied or divided, the powers of units are correctly maintained. If one unit ends up being raised to a zeroth power, that unit is discarded in the product or ratio. If a result is dimensionless, just return a float. There are also some handy units and conversions at the bottom of the file. """ import types coeff = 'coefficient' class UnitsMismatch(Exception): pass class Quantity: def __init__(self,stuff,units=None): if units == None: stuff = stuff.copy() c = stuff[coeff] del stuff[coeff] self.stuff = stuff else: c = 1. * stuff self.stuff = units.copy() for k in self.stuff.keys(): if self.stuff[k] == 0: del self.stuff[k] self.stuff[coeff] = c def __repr__(self): str = '<%g' % self.stuff[coeff] for k in self.stuff.keys(): if k != coeff: str = str + ' ' + k if self.stuff[k] != 1: str = str + '^' + `self.stuff[k]` return str + '>' def __add__(self, other): self.testUnitsMatch(other) stuff = self.stuff.copy() stuff[coeff] += other.stuff[coeff] return Quantity(stuff) def __neg__(self): stuff = self.stuff.copy() stuff[coeff] = -stuff[coeff] return Quantity(stuff) def __sub__(self, other): return self + (-other) def __cmp__(self, other): self.testUnitsMatch(other) return cmp(self.stuff[coeff], other.stuff[coeff]) def __mul__(self, other): if type(other) in (types.IntType, types.FloatType, types.ComplexType): stuff = self.stuff.copy() stuff[coeff] = other * stuff[coeff] return Quantity(stuff) if not isinstance(other, Quantity): raise UnitsMismatch, repr(self) + " * " + repr(other) stuff = self.stuff.copy() for k in other.stuff.keys(): if k != coeff: if stuff.has_key(k): stuff[k] += other.stuff[k] if abs(stuff[k]) < 1.0e-8: del stuff[k] else: stuff[k] = other.stuff[k] stuff[coeff] *= other.stuff[coeff] if len(stuff.keys()) == 1: return stuff[coeff] else: return Quantity(stuff) def __rmul__(self, other): return self * other def __div__(self, other): return self * (other ** -1) def __rdiv__(self, other): return (self ** -1) * other def __pow__(self, z): stuff = self.stuff.copy() for k in stuff.keys(): if k != coeff: stuff[k] = z * stuff[k] stuff[coeff] = stuff[coeff] ** z return Quantity(stuff) def coefficient(self): return self.stuff[coeff] def unitsMatch(self, other): if not isinstance(other, Quantity): return False otherkeys = other.stuff.keys() for k in self.stuff.keys(): if k not in otherkeys: return False if k != coeff and self.stuff[k] != other.stuff[k]: return False return True def testUnitsMatch(self, other): if not self.unitsMatch(other): raise UnitsMismatch, repr(self) + " mismatch " + repr(other) # Lotsa good stuff on units and measures at: # http://aurora.rg.iupui.edu/UCUM/UCUM-tab.html ### Fundamental units meter = Quantity(1,{'m':1}) kilogram = Quantity(1,{'kg':1}) second = Quantity(1,{'sec':1}) coulomb = Quantity(1,{'C':1}) radian = Quantity(1,{'rad':1}) Kilo = 1.e3 Mega = 1.e6 Giga = 1.e9 Tera = 1.e12 Centi = 1.e-2 Milli = 1.e-3 Micro = 1.e-6 Nano = 1.e-9 Pico = 1.e-12 Femto = 1.e-15 Atto = 1.e-18 ### Conveniences and metric prefixes meter2 = meter * meter meter3 = meter2 * meter # don't know the official metric names for these, if such exist speed = meter / second acceleration = speed / second density = kilogram / meter3 liter = Milli * meter3 newton = kilogram * acceleration joule = newton * meter watt = joule / second ampere = coulomb / second volt = joule / coulomb ohm = volt / ampere farad = coulomb / volt weber = volt * second tesla = weber / meter2 pascal = newton / meter2 henry = weber / ampere km = Kilo * meter cm = Centi * meter mm = Milli * meter um = Micro * meter nm = Nano * meter gram = Milli * kilogram mgram = Micro * kilogram ugram = Nano * kilogram msec = Milli * second usec = Micro * second nsec = Nano * second psec = Pico * second fsec = Femto * second uF = Micro * farad nF = Nano * farad pF = Pico * farad mH = Milli * henry uH = Micro * henry nH = Nano * henry Kohm = Kilo * ohm Mohm = Mega * ohm ### Some English measures inch = .0254 * meter foot = 12 * inch yard = 3 * foot furlong = 660 * foot mile = 5280 * foot gallon = 3.79 * liter quart = .25 * gallon pint = .5 * quart cup = .5 * pint fluid_ounce = .125 * cup tablespoon = .5 * fluid_ounce teaspoon = tablespoon / 3. minute = 60 * second hour = 60 * minute day = 24 * hour year = 365.25 * day # There is some disagreement on years. There are Julian years (this is # that), Gregorian years (365.2425), and tropical years (365.24219). angstrom = 1.e-10 * meter protonMass = 1.672621e-27 * kilogram MomentOfInertiaUnit = kilogram * meter2 TorqueUnit = radian * newton * meter AngularVelocityUnit = radian / second class Vector: def __init__(self, x, y, z): self.x, self.y, self.z = x, y, z def __repr__(self): return "[%s %s %s]" % (repr(self.x), repr(self.y), repr(self.z)) def __add__(self, other): return Vector(self.x + other.x, self.y + other.y, self.z + other.z) def __sub__(self, other): return Vector(self.x - other.x, self.y - other.y, self.z - other.z) def __neg__(self, other): return Vector(-self.x, -self.y, -self.z) def scale(self, m): return Vector(self.x * m, self.y * m, self.z * m) def dot(self, other): return self.x * other.x + self.y * other.y + self.z * other.z def cross(self, other): return Vector(self.y * other.z - self.z * other.y, self.z * other.x - self.x * other.z, self.x * other.y - self.y * other.x) def length(self): return self.dot(self) ** .5 def normalize(self): return self.scale(1. / self.length()) ZERO_POSITION = Vector(0. * meter, 0. * meter, 0. * meter) ZERO_VELOCITY = Vector(0. * meter / second, 0. * meter / second, 0. * meter / second) ZERO_FORCE = Vector(0. * newton, 0. * newton, 0. * newton) ZERO_TORQUE = Vector(0. * TorqueUnit, 0. * TorqueUnit, 0. * TorqueUnit)
NanoCAD-master
sim/src/experimental/units.py
#!/usr/bin/python # Copyright 2005 Nanorex, Inc. See LICENSE file for details. # Refer to http://tinyurl.com/8zl86, the 22 Dec discussion about # rotary motors. from math import pi, cos, sin import random import units import sys DEBUG = False DT = 1.e-16 * units.second SPRING_STIFFNESS = 10 * units.newton / units.meter # Sw(x) goes from 0 to 1, use 1-Sw(x) to go from 1 to 0 def Sw(x, a=.5/pi, b=2*pi): if x < 0: return 0 elif x > 1: return 1 else: return x - a * cos(b * (x - .25)) class Atom: def __init__(self, mass, x, y, z): self.mass = mass self.position = units.Vector(x, y, z) self.velocity = units.ZERO_VELOCITY self.zeroForce() def zeroForce(self): self.force = units.ZERO_FORCE def __repr__(self): pos = self.position return "<%s %s>" % (repr(self.mass), repr(self.position)) def timeStep(self): self.position += self.velocity.scale(DT) self.velocity += self.force.scale(DT / self.mass) class Spring: def __init__(self, stiffness, atom1, atom2): self.stiffness = stiffness self.atom1 = atom1 self.atom2 = atom2 self.length = (atom1.position - atom2.position).length() def timeStep(self): x = self.atom1.position - self.atom2.position f = x.normalize().scale(self.stiffness * (x.length() - self.length)) self.atom1.force -= f self.atom2.force += f class RotaryController: def __init__(self, atomlist): self.atoms = atomlist center = units.ZERO_POSITION for atm in atomlist: center += atm.position self.center = center = center.scale(1./len(atomlist)) # Determine the direction of the axis. If the atoms are all # lying in a plane, this should be normal to the plane. axis = units.ZERO_POSITION extended = atomlist + [ atomlist[0], ] for i in range(len(atomlist)): u = extended[i].position - center v = extended[i+1].position - center axis += u.cross(v).scale(1./units.meter) self.axis = axis = axis.normalize() # at this point, axis is dimensionless and unit-length self.anchors = anchors = [ ] amoi = 0. * units.MomentOfInertiaUnit for atom in atomlist: x = atom.position - center u = axis.scale(x.dot(axis)) v = x - u # component perpendicular to motor axis w = axis.cross(v) def getAnchor(theta, u=u, v=v, w=w): # be able to rotate the anchor around the axis theta /= units.radian return u + v.scale(cos(theta)) + w.scale(sin(theta)) anchors.append(getAnchor) amoi = atom.mass * v.length() ** 2 self.atomsMomentOfInertia = amoi self.omega = 0. * units.radian / units.second self.theta = 0. * units.radian def nudgeAtomsTowardTheta(self): # this is called during the controller's time step function # assume that any interatomic forces have already been computed # and are represented in the "force" attribute of each atom # calculate positions of each anchor, and spring force to atom atoms, anchors, center = self.atoms, self.anchors, self.center atomDragTorque = 0. * units.TorqueUnit for i in range(len(atoms)): atom = atoms[i] anchor = anchors[i](self.theta) # compute force between atom and anchor springForce = (atom.position - anchor).scale(SPRING_STIFFNESS) atom.force -= springForce r = atom.position - center T = r.cross(springForce).scale(units.radian) atomDragTorque += self.axis.dot(T) return atomDragTorque class BoschMotor(RotaryController): def __init__(self, atomlist, torque, gigahertz): RotaryController.__init__(self, atomlist) speed = (2 * pi * 1.e9 * units.AngularVelocityUnit) * gigahertz if DEBUG: print "target speed", speed assert units.TorqueUnit.unitsMatch(torque) assert units.AngularVelocityUnit.unitsMatch(speed) self.stallTorque = torque self.speed = speed amoi = self.atomsMomentOfInertia flywheelMomentOfInertia = 10 * amoi self.momentOfInertia = amoi + flywheelMomentOfInertia # # There REALLY IS a criterion for numerical stability! # ratio = (DT * torque) / (self.momentOfInertia * speed) #if False: if abs(ratio) > 0.3: # The C code must also throw an exception or do whatever is # the equivalent thing at this point. raise Exception, "torque-to-speed ratio is too high" def timeStep(self): # assume that any interatomic forces have already been computed # and are represented in the "force" attribute of each atom # calculate positions of each anchor, and spring force to atom atomDragTorque = self.nudgeAtomsTowardTheta() controlTorque = self.torqueFunction() self.torque = torque = controlTorque + atomDragTorque # iterate equations of motion self.theta += DT * self.omega self.omega += DT * torque / self.momentOfInertia def torqueFunction(self): # The Bosch model return (1.0 - self.omega / self.speed) * self.stallTorque class ThermostatMotor(BoschMotor): def torqueFunction(self): # bang-bang control if self.omega < self.speed: return self.stallTorque else: return -self.stallTorque class RotarySpeedController(RotaryController): def __init__(self, atomlist, rampupTime, gigahertz): RotaryController.__init__(self, atomlist) speed = (2 * pi * 1.e9 * units.AngularVelocityUnit) * gigahertz if DEBUG: print "target speed", speed assert units.second.unitsMatch(rampupTime) assert units.AngularVelocityUnit.unitsMatch(speed) self.time = 0. * units.second self.rampupTime = rampupTime self.speed = speed def timeStep(self): self.nudgeAtomsTowardTheta() # iterate equations of motion self.theta += DT * self.omega self.omega = self.speed * Sw(self.time / self.rampupTime) self.time += DT ################################################ N = 6 alst = [ ] for i in range(N): def rand(): #return 0.1 * (1. - 2. * random.random()) return 0. a = 3 * units.angstrom x = a * (rand() + cos(2 * pi * i / N)) y = a * (rand() + sin(2 * pi * i / N)) z = a * rand() atm = Atom(12 * units.protonMass, x, y, z) alst.append(atm) springs = [ ] extended = alst + [ alst[0], ] for i in range(N): atom1 = extended[i] atom2 = extended[i+1] stiffness = 400 * units.newton / units.meter springs.append(Spring(stiffness, atom1, atom2)) type = "S" ghz = 2000 if type == "B": Motor = BoschMotor m = Motor(alst, 1.0e-16 * units.TorqueUnit, ghz) elif type == "T": Motor = ThermostatMotor m = Motor(alst, 1.0e-16 * units.TorqueUnit, ghz) elif type == "S": Motor = RotarySpeedController m = Motor(alst, 10000 * DT, ghz) yyy = open("yyy", "w") zzz = open("zzz", "w") for i in range(10000): for a in alst: a.zeroForce() for s in springs: s.timeStep() m.timeStep() for a in alst: a.timeStep() if (i % 100) == 0: #print m.theta, m.omega, alst[0] p = alst[0].position yyy.write("%g %g\n" % (p.x.coefficient(), p.y.coefficient())) p = alst[N/2].position zzz.write("%g %g\n" % (p.x.coefficient(), p.y.coefficient())) yyy.close() zzz.close() print "Gnuplot command: plot \"yyy\" with lines, \"zzz\" with lines"
NanoCAD-master
sim/src/experimental/rotaryMotor.py
# Copyright 2005 Nanorex, Inc. See LICENSE file for details. """Usage: Type 'python interp.py c' to generate C code. Type 'python interp.py gnuplot' to see graphs of the approximations. Type 'python interp.py quadratic c' to generate C code for a quadratic interpolator. Type 'python interp.py linear c' to generate C code for a linear interpolator. 'quadratic' and 'linear' also work for the 'gnuplot' mode. The default behavior is 'quadratic' but the behavioral difference appears to be negligible. Type 'python interp.py discontinuity' to investigate any discontinuities in potential or force near r=r0. ------------------ In order to apply this to each of the types of bond length terms, we need to call this script with each (Ks, R0, De, Beta) set and use it to generate a C function for that term. In each case, we should visually inspect the left-of-r0 and right-of-r0 gnuplot graphs to make sure they look reasonable (and possibly discuss what 'reasonable' means here). We will probably want to generate the 'points' list based on the values of R0 and R1; that can probably be done in some automated way. The result would be one or more automatically generated C files that go into the source code, and the Makefile would generate those files from text files containing the (Ks, R0, De, Beta) sets. """ import os import sys from math import exp, log, sqrt # Use 1 if the input to the interpolator is r. # Use 2 if the input to the interpolator is r**2. # The default is 2. TABLE_INPUT_ORDER = 2 if "quadratic" in sys.argv[1:]: TABLE_INPUT_ORDER = 2 if "linear" in sys.argv[1:]: TABLE_INPUT_ORDER = 1 name = "Csp3_Csp3" Ks = 440.0 # newtons per meter R0 = 152.3 # picometers De = 0.556 # attojoules Beta = 1.989 # beta if "nitrogen" in sys.argv[1:]: name = "Nsp3_Nsp3" Ks = 560.0 R0 = 138.1 De = 0.417 Beta = 2.592 def lippincottPotential(r): return De * (1 - exp(-1e-6 * Ks * R0 * (r - R0) * (r - R0) / (2 * De * r))) def lippincottDerivative(r): if r < 0.001: r = 0.001 a = 5.0e-7 b = a * Ks * (r - R0)**2 * R0 c = 2 * a * Ks * (r - R0) * R0 return -De * (b / (De * r**2) - c / (De * r)) * exp(-b / (De * r)) def morsePotential(r): return De * (1 - exp(-Beta * (r - R0))) ** 2 def morseDerivative(r): expFoo = exp(-Beta * (r - R0)) return 2 * Beta * De * (1 - expFoo) * expFoo #################################################### # Do the V1-r1 trick for putting a bound on Morse potential. V1 = 10.0 * De R1 = R0 - log(sqrt(V1/De) + 1) / Beta D1 = 2.0 * Beta * De * (1 - exp(-Beta * (R1 - R0))) * exp(-Beta * (R1 - R0)) def boundedMorsePotential(r, oldMorse=morsePotential): if r < R1: return D1 * (r - R1) + V1 else: return oldMorse(r) def boundedMorseDerivative(r, oldDeriv=morseDerivative): if r < R1: return D1 else: return oldDeriv(r) morsePotential = boundedMorsePotential morseDerivative = boundedMorseDerivative ################################################## # Josh wanted to switch from Morse to Lippincott abruptly. # This gives a discontinuity in the force, and we might want # something a little smoother. if "smooth" in sys.argv[1:]: def blend(r): "zero for r << R0, one for r >> R0, smooth everywhere" width = 1.0e-9 * R0 # needed empirical tinkering x = (r - R0) / width return 0.5 * (1 + x / sqrt(x**2 + 1)) def compositePotential(r): b = blend(r) return (b * lippincottPotential(r) + (1 - b) * morsePotential(r)) def compositeDerivative(r): b = blend(r) return (b * lippincottDerivative(r) + (1 - b) * morseDerivative(r)) else: def compositePotential(r): if r >= R0: return lippincottPotential(r) else: return morsePotential(r) def compositeDerivative(r): if r >= R0: return lippincottDerivative(r) else: return morseDerivative(r) ############################################################### if "discontinuity" in sys.argv[1:]: # Check for continuity when we switch from Lippincott to Morse h = 1.0e-10 * R0 sys.stderr.write("%f %f\n" % (compositePotential(R0 - h), compositePotential(R0 + h))) # 5.1035893951e-08 -5.10296338518e-12 for abrupt switch sys.stderr.write("%f %f\n" % (compositeDerivative(R0 - h), compositeDerivative(R0 + h))) # -0.000670303668534 6.70118994284e-08 for abrupt switch # Alternatively, allowing for round-off error, do asserts diff = compositePotential(R0 - h) - compositePotential(R0 + h) assert abs(diff) < 1.0e-6 * De # this one is OK diff = compositeDerivative(R0 - h) - compositeDerivative(R0 + h) assert abs(diff) < 1.0e-4 * De / R0 # Is this OK? GNUPLOT_PAUSE = 5 class Gnuplot: def __init__(self, enable=True): if enable: self.outf = open("/tmp/results", "w") else: self.outf = None def add(self, x, *y): if self.outf != None: if hasattr(self, "graphs"): assert len(y) == self.graphs else: self.graphs = len(y) format = "%.16e " + (self.graphs * " %.16e") + "\n" self.outf.write(format % ((x,) + y)) def plot(self): if self.outf != None: self.outf.close() g = os.popen("gnuplot", "w") if hasattr(self, "ylimits"): cmd = "plot [] [%.16e:%.16e] " % self.ylimits else: cmd = "plot " for i in range(self.graphs): cmd += "\"/tmp/results\" using 1:%d with lines" % (i + 2) if i < self.graphs - 1: cmd += "," cmd += " " cmd += "; pause %f\n" % GNUPLOT_PAUSE g.write(cmd) g.close() #os.system("rm -f /tmp/results") if False: gp = Gnuplot() r = R0 + 0.0001 while r < 3 * R0: gp.add(r, compositePotential(r)) r += 0.01 gp.plot() sys.exit(0) # Does r0 need to be in this list? points = [ 0, 0.99 * R1, R1, 0.8 * R1 + 0.2 * R0, 0.6 * R1 + 0.4 * R0, 0.4 * R1 + 0.6 * R0, 0.2 * R1 + 0.8 * R0, 0.05 * R1 + 0.95 * R0, R0, R0 * 1.05, R0 * 1.2, R0 * 1.3, R0 * 1.5, R0 * 1.8, R0 * 2.0, R0 * 2.2 ] points.sort() # in case I messed up if "static_inline" in sys.argv[1:]: STATIC_INLINE = "static inline" else: STATIC_INLINE = "" # We will instantiate an Interpolator for each bond type. # Note that the tables used by Interpolators are pretty small, # typically about 512 bytes (~64 doubles). class Interpolator: def __init__(self, name, func, points): self.name = name self.intervals = intervals = [ ] # Generate a cubic spline for each interpolation interval. for u, v in map(None, points[:-1], points[1:]): FU, FV = func(u), func(v) h = 0.01 # picometers? # I know I said we shouldn't do numerical integration, # and yet here I am, doing it anyway. Shame on me. DU = (func(u + h) - FU) / h DV = (func(v + h) - FV) / h denom = (u - v)**3 A = ((-DV - DU) * v + (DV + DU) * u + 2 * FV - 2 * FU) / denom B = -((-DV - 2 * DU) * v**2 + u * ((DU - DV) * v + 3 * FV - 3 * FU) + 3 * FV * v - 3 * FU * v + (2 * DV + DU) * u**2) / denom C = (- DU * v**3 + u * ((- 2 * DV - DU) * v**2 + 6 * FV * v - 6 * FU * v) + (DV + 2 * DU) * u**2 * v + DV * u**3) / denom D = -(u *(-DU * v**3 - 3 * FU * v**2) + FU * v**3 + u**2 * ((DU - DV) * v**2 + 3 * FV * v) + u**3 * (DV * v - FV)) / denom intervals.append((u, A, B, C, D)) def __call__(self, x): def getInterval(x, intervalList): # run-time proportional to the log of the length # of the interval list n = len(intervalList) if n < 2: return intervalList[0] n2 = n / 2 if x < intervalList[n2][0]: return getInterval(x, intervalList[:n2]) else: return getInterval(x, intervalList[n2:]) # Tree-search the intervals to get coefficients. u, A, B, C, D = getInterval(x, self.intervals) # Plug coefficients into polynomial. return ((A * x + B) * x + C) * x + D def c_code(self): """Generate C code to efficiently implement this interpolator.""" def codeChoice(intervalList): n = len(intervalList) if n < 2: return ("A=%.16e;B=%.16e;C=%.16e;D=%.16e;" % intervalList[0][1:]) n2 = n / 2 return ("if (x < %.16e) {%s} else {%s}" % (intervalList[n2][0], codeChoice(intervalList[:n2]), codeChoice(intervalList[n2:]))) return (STATIC_INLINE + " double interpolator_%s(double x) {" % self.name + "double A,B,C,D;%s" % codeChoice(self.intervals) + "return ((A * x + B) * x + C) * x + D;}") DISCRETIZE_POINTS = ("discretize" in sys.argv[1:]) NUM_SLOTS = 10000 class EvenOrderInterpolator: def __init__(self, name, func, points): self.name = name self.intervals = intervals = [ ] if DISCRETIZE_POINTS: self.startPoint = start = 1. * points[0] ** 2 self.finishPoint = finish = 1. * points[-1] ** 2 self.xstep = xstep = (finish - start) / NUM_SLOTS intpoints = [ ] newpoints = [ ] for p in points: index = int((p**2 - start) / xstep) newvalue = (start + index * xstep) ** 0.5 intpoints.append(index) newpoints.append(newvalue) points = newpoints j = 0 for u, v in map(None, points[:-1], points[1:]): s0 = s2 = s4 = s6 = s8 = 0.0 P = Q = R = 0.0 N = 2 x = 1. * u dx = (1. * v - u) / N for i in range(N+1): y = func(x) s0 += dx s2 += dx * x**2 s4 += dx * x**4 s6 += dx * x**6 s8 += dx * x**8 P += dx * y * x**4 Q += dx * y * x**2 R += dx * y x += dx denom = ((s0*s4 - s2**2) * s8 + (s2*s6 - s4**2) * s4 + (s2*s4 - s0*s6) * s6) a11 = (s0 * s4 - s2**2) / denom a12 = (s2 * s4 - s0 * s6) / denom a13 = (s2 * s6 - s4**2) / denom a21 = a12 a22 = (s0 * s8 - s4**2) / denom a23 = (s4 * s6 - s2 * s8) / denom a31 = a13 a32 = a23 a33 = (s4 * s8 - s6**2) / denom A = a11 * P + a12 * Q + a13 * R B = a21 * P + a22 * Q + a23 * R C = a31 * P + a32 * Q + a33 * R if DISCRETIZE_POINTS: intervals.append((intpoints[j], A, B, C)) else: intervals.append((u**2, A, B, C)) j += 1 def __call__(self, xsq): def getInterval(xsq, intervalList): # run-time proportional to the log of the length # of the interval list n = len(intervalList) if n < 2: return intervalList[0] n2 = n / 2 if xsq < intervalList[n2][0]: return getInterval(xsq, intervalList[:n2]) else: return getInterval(xsq, intervalList[n2:]) # Tree-search the intervals to get coefficients. if DISCRETIZE_POINTS: j = (xsq - self.startPoint) / self.xstep u, A, B, C = getInterval(j, self.intervals) else: u, A, B, C = getInterval(xsq, self.intervals) # Plug coefficients into polynomial. return (A * xsq + B) * xsq + C def c_code(self): """Generate C code to efficiently implement this interpolator.""" def codeChoice(intervalList): n = len(intervalList) if n < 2: return ("return (%.16e * xsq + %.16e) * xsq + %.16e;" % intervalList[0][1:]) n2 = n / 2 if DISCRETIZE_POINTS: return ("if (j < %d) {%s} else {%s}" % (intervalList[n2][0], codeChoice(intervalList[:n2]), codeChoice(intervalList[n2:]))) else: return ("if (xsq < %.16e) {%s} else {%s}" % (intervalList[n2][0], codeChoice(intervalList[:n2]), codeChoice(intervalList[n2:]))) if DISCRETIZE_POINTS: return (STATIC_INLINE + " double interpolator_%s(double xsq) {\n" % self.name + "int j = (int) (%.16e * (xsq - %.16e));" % (1.0 / self.xstep, self.startPoint) + codeChoice(self.intervals) + "}") else: return (STATIC_INLINE + " double interpolator_%s(double xsq) {\n" % self.name + codeChoice(self.intervals) + "}") class MaybeFasterEvenOrderInterpolator(EvenOrderInterpolator): def c_code(self): assert DISCRETIZE_POINTS """Generate C code to efficiently implement this interpolator.""" ccode = "double A[] = {" for ivl in self.intervals: ccode += "%.16e," % ivl[1] ccode += "};\n" ccode += "double B[] = {" for ivl in self.intervals: ccode += "%.16e," % ivl[2] ccode += "};\n" ccode += "double C[] = {" for ivl in self.intervals: ccode += "%.16e," % ivl[3] ccode += "};\n" ccode += "int slots[] = {\n" j = 0 for i in range(NUM_SLOTS): ccode += "%d," % j if j < len(self.intervals) and i >= self.intervals[j][0]: j += 1 ccode += "};\n" ccode += STATIC_INLINE + " double interpolator_%s(double xsq) {\n" % self.name ccode += "int j = (int) (%.16e * (xsq - %.16e));\n" % (1.0 / self.xstep, self.startPoint) ccode += "j = j[slots];" ccode += "return (A[j] * xsq + B[j]) * xsq + C[j];}" return ccode if "sqrt" in sys.argv[1:]: points = [1, 1.5, 2, 2.5, 3, 3.5, 4, 5, 6, 8, 10, 12, 14, 17, 20, 25, 30, 35, 40, 50, 60, 80, 100] def myFunction(x): return x ** 0.5 name = "sqrt" else: myFunction = compositeDerivative if TABLE_INPUT_ORDER == 2: interp = EvenOrderInterpolator(name, myFunction, points) else: interp = Interpolator(name, myFunction, points) def graphRegion(start, finish): gp = Gnuplot() N = 10000 rstep = (1.0 * finish - start) / N r = 1.0 * start errsq = 0.0 for i in range(N): f_real = myFunction(r) f_approx = interp(r ** TABLE_INPUT_ORDER) errsq += (f_real - f_approx) ** 2 gp.add(r, f_real, f_approx) r += rstep sys.stderr.write("Total square error is %g\n" % errsq) sys.stderr.write("Mean square error is %g\n"% (errsq / N)) gp.plot() if "c" in sys.argv[1:]: # crank it thru 'indent' so it's not so ugly outf = open("interp_ugly.c", "w") outf.write(interp.c_code()) outf.close() if "graph" in sys.argv[1:]: # Because the Morse potential is so huge, we need # to graph Morse and Lippincott separately. if "sqrt" in sys.argv[1:]: graphRegion(points[0], points[-1]) else: if True: GNUPLOT_PAUSE = 10 #graphRegion(0, R0) graphRegion(.5*(R0+R1), R0) #graphRegion(R0, points[-1]) else: graphRegion(R1, R0) graphRegion(R0, points[-1])
NanoCAD-master
sim/src/experimental/interp.py
# Copyright 2004-2005 Nanorex, Inc. See LICENSE file for details. """ VQT.py Vectors, Quaternions, and Trackballs Vectors are a simplified interface to the Numeric arrays. A relatively full implementation of Quaternions. Trackball produces incremental quaternions using a mapping of the screen onto a sphere, tracking the cursor on the sphere. $Id$ """ __author__ = "Josh" import math, types from math import * from Numeric import * from LinearAlgebra import * import platform debug_quats = 1 #bruce 050518; I'll leave this turned on in the main sources for awhile intType = type(2) floType = type(2.0) numTypes = [intType, floType] def V(*v): return array(v, Float) def A(a): return array(a, Float) def cross(v1, v2): #bruce 050518 comment: for int vectors, this presumably gives an int vector result # (which is correct, and unlikely to cause bugs even in calling code unaware of it, # but ideally all calling code would be checked). return V(v1[1]*v2[2] - v1[2]*v2[1], v1[2]*v2[0] - v1[0]*v2[2], v1[0]*v2[1] - v1[1]*v2[0]) def vlen(v1): #bruce 050518 question: is vlen correct for int vectors, not only float ones? # In theory it should be, since sqrt works for int args and always gives float answers. # And is it correct for Numeric arrays of vectors? I don't know; norm is definitely not. return sqrt(dot(v1, v1)) def norm(v1): #bruce 050518 questions: # - Is this correct for int vectors, not only float ones? # In theory it should be, since vlen is always a float (see above). # - Is it correct for Numeric arrays of vectors (doing norm on each one alone)? # No... clearly the "if" makes the same choice for all of them, but even ignoring that, # it gives an alignment exception for any vector-array rather than working at all. # I don't know how hard that would be to fix. lng = vlen(v1) if lng: return v1 / lng # bruce 041012 optimized this by using lng instead of # recomputing vlen(v1) -- code was v1 / vlen(v1) else: return v1+0 # p1 and p2 are points, v1 is a direction vector from p1. # return (dist, wid) where dist is the distance from p1 to p2 # measured in the direction of v1, and wid is the orthogonal # distance from p2 to the p1-v1 line. # v1 should be a unit vector. def orthodist(p1, v1, p2): dist = dot(v1, p2-p1) wid = vlen(p1+dist*v1-p2) return (dist, wid) #bruce 050518 added these: X_AXIS = V(1,0,0) Y_AXIS = V(0,1,0) Z_AXIS = V(0,0,1) class Q: # by Josh; some comments and docstring revised by bruce 050518 """Q(W, x, y, z) is the quaternion with axis vector x,y,z and sin(theta/2) = W (e.g. Q(1,0,0,0) is no rotation [used a lot]) [Warning: the python argument names are not in the same order as in the usage-form above! This is not a bug, just possibly confusing.] Q(x, y, z) where x, y, and z are three orthonormal vectors is the quaternion that rotates the standard axes into that reference frame [this was first used, and first made correct, by bruce 050518] (the frame has to be right handed, or there's no quaternion that can do it!) Q(V(x,y,z), theta) is what you probably want [axis vector and angle]. [used widely] Q(vector, vector) gives the quat that rotates between them [used widely] [bruce 050518 asks: which such quat? presumably the one that does the least rotation in all] [undocumented until 050518: Q(number) gives Q(1,0,0,0) [perhaps never used, not sure]; Q(quat) gives a copy of that quat [used fairly often]; Q([W,x,y,z]) (for any sequence type) gives the same quat as Q(W, x, y, z) [used for parsing csys records, maybe in other places].] """ counter = 50 # initial value of instance variable # [bruce 050518 moved it here, fixing bug in which it sometimes didn't get inited] def __init__(self, x, y=None, z=None, w=None): if w is not None: # 4 numbers # [bruce comment 050518: note than ints are not turned to floats, # and no checking (of types or values) or normalization is done, # and that these arg names don't correspond to their meanings, # which are W,x,y,z (as documented) rather than x,y,z,w.] self.vec = V(x,y,z,w) elif z is not None: # three axis vectors # Just use first two # [bruce comments 050518: # - bugfix/optim: test z for None, not for truth value # (only fixes z = V(0,0,0) which is not allowed here anyway, so not very important) # - This case was not used until now, and was wrong for some or all inputs # (not just returning the inverse quat as I initially thought); # so I fixed it. # - The old code sometimes used 'z' but the new code never does # (except to decide to use this case, and when debug_quats to check the results). # Q(x, y, z) where x, y, and z are three orthonormal vectors # is the quaternion that rotates the standard axes into that # reference frame ##e could have a debug check for vlen(x), y,z, and ortho and right-handed... # but when this is false (due to caller bugs), the check_posns_near below should catch it. xfixer = Q( X_AXIS, x) y_axis_2 = xfixer.rot(Y_AXIS) yfixer = twistor( x, y_axis_2, y) res = xfixer res += yfixer # warning: modifies res -- xfixer is no longer what it was if debug_quats: check_posns_near( res.rot(X_AXIS), x, "x" ) check_posns_near( res.rot(Y_AXIS), y, "y" ) check_posns_near( res.rot(Z_AXIS), z, "z" ) self.vec = res.vec if debug_quats: res = self # sanity check check_posns_near( res.rot(X_AXIS), x, "sx" ) check_posns_near( res.rot(Y_AXIS), y, "sy" ) check_posns_near( res.rot(Z_AXIS), z, "sz" ) return ## # the old code (incorrect, and was not used): ## a100 = V(1,0,0) ## c1 = cross(a100,x) ## if vlen(c1)<0.000001: ## if debug_quats or platform.atom_debug: #bruce 050518 ## # i suspect it's wrong, always giving a 90 degree rotation, and not setting self.counter ## print "debug_quats: using Q(y,z).vec case" ## self.vec = Q(y,z).vec ## return ## ax1 = norm((a100+x)/2.0) ## x2 = cross(ax1,c1) ## a010 = V(0,1,0) ## c2 = cross(a010,y) ## if vlen(c2)<0.000001: ## if debug_quats or platform.atom_debug: #bruce 050518 -- same comment as above ## print "debug_quats: using Q(x,z).vec case" ## self.vec = Q(x,z).vec ## return ## ay1 = norm((a010+y)/2.0) ## y2 = cross(ay1,c2) ## axis = cross(x2, y2) ## nw = sqrt(1.0 + x[0] + y[1] + z[2])/2.0 ## axis = norm(axis)*sqrt(1.0-nw**2) ## self.vec = V(nw, axis[0], axis[1], axis[2]) elif type(y) in numTypes: # axis vector and angle [used often] v = (x / vlen(x)) * sin(y*0.5) self.vec = V(cos(y*0.5), v[0], v[1], v[2]) elif y is not None: # rotation between 2 vectors [used often] #bruce 050518 bugfix/optim: test y for None, not for truth value # (only fixes y = V(0,0,0) which is not allowed here anyway, so not very important) # [I didn't yet verify it does this in correct order; could do that from its use # in bonds.py or maybe the new indirect use in jigs.py (if I checked iadd too). ###@@@] #bruce 050730 bugfix: when x and y are very close to equal, original code treats them as opposite. # Rewriting it to fix that, though not yet in an ideal way (just returns identity). # Also, when they're close but not that close, original code might be numerically unstable. # I didn't fix that problem. x = norm(x) y = norm(y) dotxy = dot(x, y) v = cross(x, y) vl = vlen(v) if vl<0.000001: # x,y are very close, or very close to opposite, or one of them is zero if dotxy < 0: # close to opposite; treat as actually opposite (same as pre-050730 code) ax1 = cross(x,V(1,0,0)) ax2 = cross(x,V(0,1,0)) if vlen(ax1)>vlen(ax2): self.vec = norm(V(0, ax1[0],ax1[1],ax1[2])) else: self.vec = norm(V(0, ax2[0],ax2[1],ax2[2])) else: # very close, or one is zero -- we could pretend they're equal, but let's be a little # more accurate than that -- vl is sin of desired theta, so vl/2 is approximately sin(theta/2) # (##e could improve this further by using a better formula to relate sin(theta/2) to sin(theta)), # so formula for xyz part is v/vl * vl/2 == v/2 [bruce 050730] xyz = v/2.0 sintheta2 = vl/2.0 # sin(theta/2) costheta2 = sqrt(1-sintheta2**2) # cos(theta/2) self.vec = V(costheta2, xyz[0], xyz[1], xyz[2]) else: # old code's method is numerically unstable if abs(dotxy) is close to 1. I didn't fix this. # I also didn't review this code (unchanged from old code) for correctness. [bruce 050730] theta = acos(min(1.0,max(-1.0,dotxy))) if dot(y, cross(x, v)) > 0.0: theta = 2.0 * pi - theta w=cos(theta*0.5) s=sqrt(1-w**2)/vl self.vec=V(w, v[0]*s, v[1]*s, v[2]*s) pass elif type(x) in numTypes: # just one number [#k is this ever used?] self.vec=V(1, 0, 0, 0) else: #bruce 050518 comment: a copy of the quat x, or of any length-4 sequence [both forms are used] self.vec=V(x[0], x[1], x[2], x[3]) return # from Q.__init__ def __getattr__(self, name): if name == 'w': return self.vec[0] elif name in ('x', 'i'): return self.vec[1] elif name in ('y', 'j'): return self.vec[2] elif name in ('z', 'k'): return self.vec[3] elif name == 'angle': if -1.0<self.vec[0]<1.0: return 2.0*acos(self.vec[0]) else: return 0.0 elif name == 'axis': return V(self.vec[1], self.vec[2], self.vec[3]) elif name == 'matrix': # this the transpose of the normal form # so we can use it on matrices of row vectors # [bruce comment 050518: there is a comment on self.vunrot() # which seems to contradict the above old comment by Josh. # Josh says he revised the transpose situation later than he wrote the rest, # so he's not surprised if some comments (or perhaps even rarely-used # code cases?? not sure) are out of date. # I didn't yet investigate the true situation. # To clarify the code, I'll introduce local vars w,x,y,z, mat. # This will optimize it too (avoiding 42 __getattr__ calls!). # ] w, x, y, z = self.vec self.__dict__['matrix'] = mat = array([\ [1.0 - 2.0*(y**2 + z**2), 2.0*(x*y + z*w), 2.0*(z*x - y*w)], [2.0*(x*y - z*w), 1.0 - 2.0*(z**2 + x**2), 2.0*(y*z + x*w)], [2.0*(z*x + y*w), 2.0*(y*z - x*w), 1.0 - 2.0 * (y**2 + x**2)]]) return mat else: raise AttributeError, 'No "%s" in Quaternion' % name def __getitem__(self, num): return self.vec[num] def setangle(self, theta): """Set the quaternion's rotation to theta (destructive modification). (In the same direction as before.) """ theta = remainder(theta/2.0, pi) self.vec[1:] = norm(self.vec[1:]) * sin(theta) self.vec[0] = cos(theta) self.__reset() return self def __reset(self): if self.__dict__.has_key('matrix'): del self.__dict__['matrix'] def __setattr__(self, name, value): #bruce comment 050518: possible bug (depends on usage, unknown): this doesn't call __reset if name=="w": self.vec[0] = value elif name=="x": self.vec[1] = value elif name=="y": self.vec[2] = value elif name=="z": self.vec[3] = value else: self.__dict__[name] = value def __len__(self): return 4 def __add__(self, q1): """Q + Q1 is the quaternion representing the rotation achieved by doing Q and then Q1. """ return Q(q1.w*self.w - q1.x*self.x - q1.y*self.y - q1.z*self.z, q1.w*self.x + q1.x*self.w + q1.y*self.z - q1.z*self.y, q1.w*self.y - q1.x*self.z + q1.y*self.w + q1.z*self.x, q1.w*self.z + q1.x*self.y - q1.y*self.x + q1.z*self.w) def __iadd__(self, q1): """this is self += q1 """ temp=V(q1.w*self.w - q1.x*self.x - q1.y*self.y - q1.z*self.z, q1.w*self.x + q1.x*self.w + q1.y*self.z - q1.z*self.y, q1.w*self.y - q1.x*self.z + q1.y*self.w + q1.z*self.x, q1.w*self.z + q1.x*self.y - q1.y*self.x + q1.z*self.w) self.vec=temp self.counter -= 1 if self.counter <= 0: self.counter = 50 self.normalize() self.__reset() return self def __sub__(self, q1): return self + (-q1) def __isub__(self, q1): return __iadd__(self, -q1) def __mul__(self, n): """multiplication by a scalar, i.e. Q1 * 1.3, defined so that e.g. Q1 * 2 == Q1 + Q1, or Q1 = Q1*0.5 + Q1*0.5 Python syntax makes it hard to do n * Q, unfortunately. """ if type(n) in numTypes: nq = +self nq.setangle(n*self.angle) return nq else: raise MulQuat def __imul__(self, q2): if type(n) in numTypes: self.setangle(n*self.angle) self.__reset() return self else: raise MulQuat def __div__(self, q2): return self*q2.conj()*(1.0/(q2*q2.conj()).w) def __repr__(self): return 'Q(%g, %g, %g, %g)' % (self.w, self.x, self.y, self.z) def __str__(self): a= "<q:%6.2f @ " % (2.0*acos(self.w)*180/pi) l = sqrt(self.x**2 + self.y**2 + self.z**2) if l: z=V(self.x, self.y, self.z)/l a += "[%4.3f, %4.3f, %4.3f] " % (z[0], z[1], z[2]) else: a += "[%4.3f, %4.3f, %4.3f] " % (self.x, self.y, self.z) a += "|%8.6f|>" % vlen(self.vec) return a def __pos__(self): return Q(self.w, self.x, self.y, self.z) def __neg__(self): return Q(self.w, -self.x, -self.y, -self.z) def conj(self): return Q(self.w, -self.x, -self.y, -self.z) def normalize(self): w=self.vec[0] v=V(self.vec[1],self.vec[2],self.vec[3]) length = vlen(v) if length: s=sqrt(1.0-w**2)/length self.vec = V(w, v[0]*s, v[1]*s, v[2]*s) else: self.vec = V(1,0,0,0) return self def unrot(self,v): return matrixmultiply(self.matrix,v) def vunrot(self,v): # for use with row vectors # [bruce comment 050518: the above old comment by Josh seems to contradict # the comment about 'matrix' in __getattr__ (also old and by Josh) # that it's the transpose of the normal form so it can be used for row vectors. # See the other comment for more info.] return matrixmultiply(v,transpose(self.matrix)) def rot(self,v): return matrixmultiply(v,self.matrix) def twistor(axis, pt1, pt2): #bruce 050724 revised code (should not change the result) """return the quaternion that, rotating around axis, will bring pt1 closest to pt2. """ #bruce 050518 comment: now using this in some cases of Q.__init__; not the ones this uses! theta = twistor_angle(axis, pt1, pt2) return Q(axis, theta) def twistor_angle(axis, pt1, pt2): #bruce 050724 split this out of twistor() q = Q(axis, V(0,0,1)) pt1 = q.rot(pt1) pt2 = q.rot(pt2) a1 = atan2(pt1[1],pt1[0]) a2 = atan2(pt2[1],pt2[0]) theta = a2-a1 return theta # project a point from a tangent plane onto a unit sphere def proj2sphere(x, y): d = sqrt(x*x + y*y) theta = pi * 0.5 * d s=sin(theta) if d>0.0001: return V(s*x/d, s*y/d, cos(theta)) else: return V(0.0, 0.0, 1.0) class Trackball: '''A trackball object. The current transformation matrix can be retrieved using the "matrix" attribute.''' def __init__(self, wide, high): '''Create a Trackball object. "size" is the radius of the inner trackball sphere. ''' self.w2=wide/2.0 self.h2=high/2.0 self.scale = 1.1 / min(wide/2.0, high/2.0) self.quat = Q(1,0,0,0) self.oldmouse = None def rescale(self, wide, high): self.w2=wide/2.0 self.h2=high/2.0 self.scale = 1.1 / min(wide/2.0, high/2.0) def start(self, px, py): self.oldmouse=proj2sphere((px-self.w2)*self.scale, (self.h2-py)*self.scale) def update(self, px, py, uq=None): newmouse = proj2sphere((px-self.w2)*self.scale, (self.h2-py)*self.scale) if self.oldmouse and not uq: quat = Q(self.oldmouse, newmouse) elif self.oldmouse and uq: quat = uq + Q(self.oldmouse, newmouse) - uq else: quat = Q(1,0,0,0) self.oldmouse = newmouse return quat def ptonline(xpt, lpt, ldr): """return the point on a line (point lpt, direction ldr) nearest to point xpt """ ldr = norm(ldr) return dot(xpt-lpt,ldr)*ldr + lpt def planeXline(ppt, pv, lpt, lv): """find the intersection of a line (point lpt, vector lv) with a plane (point ppt, normal pv) return None if (almost) parallel (warning to callers: retvals other than None might still be false, e.g. V(0,0,0) -- untested, but likely; so don't use retval as boolean) """ d=dot(lv,pv) if abs(d)<0.000001: return None return lpt+lv*(dot(ppt-lpt,pv)/d) def cat(a,b): """concatenate two arrays (the NumPy version is a mess) """ #bruce comment 050518: these boolean tests look like bugs! # I bet they should be testing the number of entries being 0, or so. # So I added some debug code to warn us if this happens. if not a: if (debug_quats or platform.atom_debug): print "debug_quats: cat(a,b) with false a -- is it right?",a return b if not b: if (debug_quats or platform.atom_debug): print "debug_quats: cat(a,b) with false b -- is it right?",b return a r1 = shape(a) r2 = shape(b) if len(r1) == len(r2): return concatenate((a,b)) if len(r1)<len(r2): return concatenate((reshape(a,(1,)+r1), b)) else: return concatenate((a,reshape(b,(1,)+r2))) def Veq(v1, v2): "tells if v1 is all equal to v2" return logical_and.reduce(v1==v2) #bruce comment 050518: I guess that not (v1 != v2) would also work (and be slightly faster) # (in principle it would work, based on my current understanding of Numeric...) # == bruce 050518 moved the following here from extrudeMode.py (and bugfixed/docstringed them) def floats_near(f1,f2): #bruce, circa 040924, revised 050518 to be relative, 050520 to be absolute for small numbers. """Say whether two floats are "near" in value (just for use in sanity-check assertions). """ ## return abs( f1-f2 ) <= 0.0000001 ## return abs( f1-f2 ) <= 0.000001 * max(abs(f1),abs(f2)) return abs( f1-f2 ) <= 0.000001 * max( abs(f1), abs(f2), 0.1) #e maybe let callers pass a different "scale" than 0.1? def check_floats_near(f1,f2,msg = ""): #bruce, circa 040924 "Complain to stdout if two floats are not near; return whether they are." if floats_near(f1,f2): return True # means good (they were near) if msg: fmt = "not near (%s):" % msg else: fmt = "not near:" # fmt is not a format but a prefix print fmt,f1,f2 return False # means bad def check_posns_near(p1,p2,msg=""): #bruce, circa 040924 "Complain to stdout if two length-3 float vectors are not near; return whether they are." res = True #bruce 050518 bugfix -- was False (which totally disabled this) for i in [0,1,2]: res = res and check_floats_near(p1[i],p2[i],msg+"[%d]"%i) return res def check_quats_near(q1,q2,msg=""): #bruce, circa 040924 "Complain to stdout if two quats are not near; return whether they are." res = True #bruce 050518 bugfix -- was False (which totally disabled this) for i in [0,1,2,3]: res = res and check_floats_near(q1[i],q2[i],msg+"[%d]"%i) return res # end
NanoCAD-master
sim/src/experimental/josh_dev/VQT.py
# Copyright 2005 Nanorex, Inc. See LICENSE file for details. from bondage import * e,p,b = readmmp('ethane.mmp') bondsetup(b) dt=1e-16 massacc=array([dt*dt/elmass[x] for x in e]) n=p+massacc*force(p) x= os.times() ## print 'running...', ## for i in xrange(100000): ## o=p ## p=n ## n=2*p-o+massacc*force(p) ## print os.times()[0]-x[0]
NanoCAD-master
sim/src/experimental/josh_dev/test.py
# Copyright 2005 Nanorex, Inc. See LICENSE file for details. from Numeric import * from VQT import * from string import * import re keypat = re.compile("(\S+)") molpat = re.compile("mol \(.*\) (\S\S\S)") atompat = re.compile("atom (\d+) \((\d+)\) \((-?\d+), (-?\d+), (-?\d+)\)") def readmmp(fname): pos = [] elt = [] atnum = -1 atnos = {} bonds = [] for card in open(fname).readlines(): key = keypat.match(card).group(1) if key == 'atom': atnum += 1 m = atompat.match(card) atnos[int(m.group(1))] = atnum elt += [int(m.group(2))] pos += [map(float, [m.group(3),m.group(4),m.group(5)])] if key[:4] == 'bond': order = ['1','2','3','a','g'].index(key[4]) bonds += [(atnum,atnos[int(x)],order) for x in re.findall("\d+",card[5:])] pos = array(pos)/1000.0 return elt, pos, array(bonds)
NanoCAD-master
sim/src/experimental/josh_dev/readmmp.py
#! /usr/bin/python # Copyright 2005 Nanorex, Inc. See LICENSE file for details. from Numeric import * from VQT import * from string import * import re import os import sys keypat = re.compile("(\S+)") molpat = re.compile("mol \(.*\) (\S\S\S)") atompat = re.compile("atom (\d+) \((\d+)\) \((-?\d+), (-?\d+), (-?\d+)\)") def readmmp(fname): global atnum, elt, poshape pos = [] elt = [] atnum = -1 atnos = {} bonds = [(0,0,0)] for card in open(fname).readlines(): key = keypat.match(card).group(1) if key == 'atom': atnum += 1 m = atompat.match(card) atnos[int(m.group(1))] = atnum elt += [int(m.group(2))] pos += [[float(m.group(n)) for n in [3,4,5]]] if key[:4] == 'bond': order = ['1','2','3','a','g'].index(key[4]) bonds += [(atnum,atnos[int(x)],order) for x in re.findall("\d+",card[5:])] pos = transpose(array(pos)/1000.0) # gives angstroms poshape = shape(pos) return elt, pos, array(bonds) parmpat = re.compile("([A-Z][a-z]?)([\+=\-@#])([A-Z][a-z]?) +Ks= *([\d\.]+) +R0= *([\d\.]+) +De= *([\d\.]+)") commpat = re.compile("#") bendpat = re.compile("([A-Z][a-z]?)([\+=\-@#])([A-Z][a-z]?)([\+=\-@#])([A-Z][a-z]?) +theta0= *([\d\.]+) +Ktheta= *([\d\.]+)") # masses in 1e-27kg elmnts=[("H", 1, 1.6737), ("He", 2, 6.646), ("Li", 3, 11.525), ("Be", 4, 14.964), ("B", 5, 17.949), ("C", 6, 19.925), ("N", 7, 23.257), ("O", 8, 26.565), ("F", 9, 31.545), ("Ne", 10, 33.49), ("Na", 11, 38.1726), ("Mg", 12, 40.356), ("Al", 13, 44.7997), ("Si", 14, 46.6245), ("P", 15, 51.429), ("S", 16, 53.233), ("Cl", 17, 58.867), ("Ar", 18, 66.33), ("K", 19, 64.9256), ("Ca", 20, 66.5495), ("Sc", 21, 74.646), ("Ti", 22, 79.534), ("V", 23, 84.584), ("Cr", 24, 86.335), ("Mn", 25, 91.22), ("Fe", 26, 92.729), ("Co", 27, 97.854), ("Ni", 28, 97.483), ("Cu", 29, 105.513), ("Zn", 30, 108.541), ("Ga", 31, 115.764), ("Ge", 32, 120.53), ("As", 33, 124.401), ("Se", 34, 131.106), ("Br", 35, 132.674), ("Kr", 36, 134.429)] elmass=array([0.0]+[1e-27*x[2] for x in elmnts]) enames=['X']+[x[0] for x in elmnts] btypes = ['-', '=', '+','@', '#'] def bondstr(elts,triple): return enames[elts[triple[0]]]+btypes[triple[2]]+enames[elts[triple[1]]] def bendstr(elts,quint): return (enames[elts[quint[0]]]+btypes[quint[1]]+enames[elts[quint[2]]] +btypes[quint[1]]+enames[elts[quint[2]]]) # ks -- N/m # R0 -- 1e-10 m # De -- aJ stretchtable={} f=open("stretch.parms") for lin in f.readlines(): if commpat.match(lin): continue m = parmpat.match(lin) which = m.group(1)+m.group(2)+m.group(3) which1 = m.group(3)+m.group(2)+m.group(1) ks,r0,de = [float(m.group(p)) for p in [4,5,6]] bt=sqrt(ks/(2.0*de))/10.0 stretchtable[which] = (ks,r0,de, bt) stretchtable[which1] = (ks,r0,de, bt) # Theta - radians # Ktheta - aJ/radian^2 bendtable={} f=open("bending.parms") for lin in f.readlines(): if commpat.match(lin): continue m = bendpat.match(lin) which = m.group(1)+m.group(2)+m.group(3)+m.group(4)+m.group(5) which1 = m.group(5)+m.group(4)+m.group(3)+m.group(2)+m.group(1) th0, kth = [float(m.group(p)) for p in [6,7]] kth *= 100.0 bendtable[which] = (th0, kth) bendtable[which1] = (th0, kth) # given a set of stretch bonds, return the bend quintuples def bondsetup(bonds): global bond0, bond1, KS, R0 global sort0,mash0,spred0, sort1,mash1,spred1 global bends, Theta0, Ktheta, bba, bbb, bbc global bbsorta, bbmasha, bbputa global bbsortb, bbmashb, bbputb global bbsortc, bbmashc, bbputc n = atnum+1 bond0 = bonds[:,0] bond1 = bonds[:,1] sort0 = argsort(bond0) x0=take(bond0,sort0) x=x0[1:]!=x0[:-1] x[0]=1 x=compress(x,arange(len(x))) mash0=concatenate((array([0]),x+1)) spred0=zeros(n) x=take(x0,mash0[1:]) put(spred0,x,1+arange(len(x))) sort1 = argsort(bond1) x1=take(bond1,sort1) x=x1[1:]!=x1[:-1] x[0]=1 x=compress(x,arange(len(x))) mash1=concatenate((array([0]),x+1)) spred1=zeros(n) x=take(x1,mash1[1:]) put(spred1,x,1+arange(len(x))) btlis = [bondstr(elt,x) for x in bonds] KS = array([stretchtable[x][0] for x in btlis]) KS[0]=0.0 R0 = array([stretchtable[x][1] for x in btlis]) R0[0]=0.0 bondict = {} bends = [] for (a,b,o) in bonds[1:]: bondict[a] = bondict.get(a,[]) + [(o,b)] bondict[b] = bondict.get(b,[]) + [(o,a)] for (a,lis) in bondict.iteritems(): for i in range(len(lis)-1): (ob,b) = lis[i] for (oc,c) in lis[i+1:]: bends += [(b,ob,a,oc,c)] bends = array(bends) bba = bends[:,0] bbb = bends[:,4] bbc = bends[:,2] bnlis = [bendstr(elt,x) for x in bends] Theta0 = array([bendtable[b][0] for b in bnlis]) Ktheta = array([bendtable[b][1] for b in bnlis]) n=len(elt) bbsorta = argsort(bba) x1=take(bba,bbsorta) x2=x1[1:]!=x1[:-1] x=compress(x2,arange(len(x2))) bbmasha=concatenate((array([0]),x+1)) bbputa = compress(concatenate((array([1]),x2)),x1) bbputa = concatenate((bbputa, n+bbputa, 2*n+bbputa)) bbsortb = argsort(bbb) x1=take(bbb,bbsortb) x2=x1[1:]!=x1[:-1] x=compress(x2,arange(len(x2))) bbmashb=concatenate((array([0]),x+1)) bbputb = compress(concatenate((array([1]),x2)),x1) bbputb = concatenate((bbputb, n+bbputb, 2*n+bbputb)) bbsortc = argsort(bbc) x1=take(bbc,bbsortc) x2=x1[1:]!=x1[:-1] x=compress(x2,arange(len(x2))) bbmashc=concatenate((array([0]),x+1)) bbputc = compress(concatenate((array([1]),x2)),x1) bbputc = concatenate((bbputc, n+bbputc, 2*n+bbputc)) return bends # aa means stretch bond (atom-atom) # bb means bend (bond-bond) # bba, bbb, bbc are the three atoms in a bend, bbc the center # #globals: bond0, bond1: atom #'s; R0s; KSs def force(pos): aavx = take(pos,bond0,1) - take(pos,bond1,1) aax = sqrt(add.reduce(aavx*aavx)) aax[0]=1.0 aavu = aavx/aax aavf = aavu * KS * (R0 - aax) avf0 = add.reduceat(take(aavf,sort0,1),mash0) avf1 = add.reduceat(take(aavf,sort1,1),mash1) f = take(avf0,spred0,1) - take(avf1,spred1,1) bbva = take(pos,bba,1) - take(pos,bbc,1) bbvb = take(pos,bbb,1) - take(pos,bbc,1) bbla = sqrt(add.reduce(bbva*bbva)) bblb = sqrt(add.reduce(bbvb*bbvb)) bbau = bbva/bbla bbbu = bbvb/bblb bbadb = add.reduce(bbau*bbbu) angle = arccos(bbadb) torq = Ktheta*(angle-Theta0) bbaf = bbbu-bbadb*bbau bbaf = bbaf/sqrt(add.reduce(bbaf*bbaf)) bbaf = bbaf*torq/bbla bbbf = bbau-bbadb*bbbu bbbf = bbbf/sqrt(add.reduce(bbbf*bbbf)) bbbf = bbbf*torq/bblb fa = zeros(poshape,Float) put(fa,bbputa,add.reduceat(take(bbaf,bbsorta,1),bbmasha)) fc1 = zeros(poshape,Float) put(fc1,bbputc,add.reduceat(take(bbaf,bbsortc,1),bbmashc)) fb = zeros(poshape,Float) put(fb,bbputb,add.reduceat(take(bbbf,bbsortb,1),bbmashb)) fc2 = zeros(poshape,Float) put(fc2,bbputc,add.reduceat(take(bbbf,bbsortc,1),bbmashc)) return f+fa+fb-fc1-fc2
NanoCAD-master
sim/src/experimental/josh_dev/bondage.py
#!/usr/bin/python import sys import string import Atom class XyzFile: """Python class to contain information from an XYZ file""" def __init__(self): self.atoms = [ ] def clone(self): other = XyzFile() other.atoms = [ ] for a in self.atoms: other.atoms.append(a.clone()) return other def getAtom(self, i): return self.atoms[i] def __getitem__(self, i): a = self.atoms[i] return (a.x, a.y, a.z) def __setitem__(self, i, xyz): a = self.atoms[i] a.x, a.y, a.z = xyz def __len__(self): return len(self.atoms) def read(self, filename): inf = open(filename) self.readstring(inf.read()) inf.close() def readstring(self, lines): lines = lines.split("\n") numAtoms = string.atoi(lines[0]) lines = lines[2:] for i in range(numAtoms): element, x, y, z = lines[i].split() x, y, z = map(string.atof, (x, y, z)) a = Atom.Atom() a.fromXyz(element, x, y, z) self.atoms.append(a) def write(self, title, outf=None): if outf == None: outf = sys.stdout outf.write("%d\n%s\n" % (len(self.atoms), title)) for atm in self.atoms: outf.write(atm.toXyzString() + "\n") if __name__ == "__main__": # do a little test class StringCollector: def __init__(self): self.contents = "" def write(self, x): self.contents += x import sys example_xyz_file = """15 RMS=0.994508 C -0.193641 2.900593 -0.026523 X 0.093601 3.502437 0.394872 X -0.623522 3.154064 -0.637458 C -1.079249 2.005273 0.890906 X -1.803795 1.958430 0.584626 X -1.090331 2.310792 1.617200 C 0.986482 2.029986 -0.552402 X 0.945121 1.985940 -1.338110 X 1.667645 2.347089 -0.314849 C -0.443634 0.583852 0.936816 X -0.955793 0.061908 0.643109 X -0.248030 0.411844 1.680547 C 0.839719 0.603152 0.054672 X 1.466374 0.446893 0.504740 X 0.762053 0.079748 -0.528147 """ xyz = XyzFile() xyz.readstring(example_xyz_file) # test 1 sc = StringCollector() ss, sys.stdout = sys.stdout, sc xyz.write("RMS=0.994508") sys.stdout = ss assert sc.contents == example_xyz_file # test 2 for i in range(len(xyz)): print xyz.getAtom(i) print for i in range(8): xyz[i] = (1.0, 2.0, 3.0) for i in range(len(xyz)): print xyz.getAtom(i)
NanoCAD-master
sim/src/tests/heteroatom_organics/XyzFile.py
#!/usr/bin/python import os import sys import MmpFile import XyzFile damianFiles = map(lambda x: x.strip(), open("damianFiles").readlines()) for df in damianFiles: prefix = df[:df.index(".")] testPrefix = "test_" + prefix damianMmp = MmpFile.MmpFile() damianMmp.read(df) # Generate the xyzcmp file xyzcmpFilename = testPrefix + ".xyzcmp" outf = open(xyzcmpFilename, "w") xyzcmp = damianMmp.convertToXyz() xyzcmp.write(df, outf) outf.close() # Make a perturbed copy of the MMP, use it for test_{foo}.mmp dmClone = damianMmp.clone() dmClone.perturb() testMmpFilename = testPrefix + ".mmp" outf = open(testMmpFilename, "w") dmClone.write(outf) outf.close() # Create test_{foo}.test testTestFilename = testPrefix + ".test" outf = open(testTestFilename, "w") outf.write("TYPE struct\n") outf.close() print "Test input files generated for " + testPrefix
NanoCAD-master
sim/src/tests/heteroatom_organics/CreateTests.py
#!/usr/bin/python """Grab one of Damian's minimized MMP files, perturb each atom's position by some fraction of an angstrom, write out the result as another MMP file, which becomes an input file for the test. $Id$ """ __author__ = "Will" import re import os import sys import string import Atom class MmpFile: """This is meant to be a Python class representing a MMP file. It is not intended to represent ALL the information in a MMP file, although it might do that in some distant-future version. Right now, its biggest strength is that it allows us to easily modify the positions of the atoms in an MMP file, and write out the resulting modified MMP file.""" class _Line: def fromMmp(self, line): self._str = line def str(self): return self._str def clone(self, owner): ln = MmpFile._Line() ln._str = self._str return ln class _AtomHolder: """Atom holders are indices into the MmpFile.atoms list, 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 __init__(self, owner): self._owner = owner def fromMmp(self, line): atoms = self._owner.atoms self._index = len(atoms) a = Atom.Atom() a.fromMmp(line) atoms.append(a) def str(self): a = self._owner.atoms[self._index] return a.toMmpString() def clone(self, newowner): other = MmpFile._AtomHolder(newowner) other._index = self._index return other def __init__(self): self.atoms = [ ] self.lines = [ ] def clone(self): other = MmpFile() for x in self.lines: other.lines.append(x.clone(other)) for a in self.atoms: other.atoms.append(a.clone()) return other def getAtom(self, i): return self.atoms[i] def __getitem__(self, i): a = self.atoms[i] return (a.x, a.y, a.z) def __setitem__(self, i, xyz): a = self.atoms[i] a.x, a.y, a.z = xyz def __len__(self): return len(self.atoms) def read(self, filename): inf = open(filename) self.readstring(inf.read()) inf.close() def readstring(self, lines): for line in lines.split("\n"): try: atm = MmpFile._AtomHolder(self) atm.fromMmp(line) except Atom.NotAtomException: atm = MmpFile._Line() atm.fromMmp(line) self.lines.append(atm) def write(self, outf=None): if outf == None: outf = sys.stdout for ln in self.lines: outf.write(ln.str() + "\n") def convertToXyz(self): import XyzFile xyz = XyzFile.XyzFile() for a in self.atoms: xyz.atoms.append(a) return xyz def perturb(self): import random A = 0.5 # some small number of angstroms A = A / (3 ** .5) # amount in one dimension for i in range(len(self)): x, y, z = self[i] x += random.normalvariate(0.0, A) y += random.normalvariate(0.0, A) z += random.normalvariate(0.0, A) self[i] = (x, y, z) if __name__ == "__main__": """What follows is a specific usage of the MmpFile class. It's not the only way it could be used, but it demonstrates something we're going to want to do very soon as we generate test cases from Damian's MMP files.""" m = MmpFile() #input = "C14H20.mmp" input = "C3H8.mmp" m.read(input) m.perturb() #outf = os.popen("diff -u - %s | less" % input, "w") outf = os.popen("diff -u - %s" % input, "w") m.write(outf) outf.close()
NanoCAD-master
sim/src/tests/heteroatom_organics/MmpFile.py
#!/usr/bin/python """MMP and XYZ files share a common Atom definition. This will make it easy to move information back and forth between the two formats. $Id$ """ __author__ = "Will" import re import os import sys import string import random _PeriodicTable = [ "X", # our singlet has element number zero "H", "He", "Li", "Be", "B", "C", "N", "O", "F", "Ne", "Na", "Mg", "Al", "Si", "P", "S", "Cl", "Ar", "K", "Ca" #Sc,Ti,V,Cr,Mn,Fe.... ] _MmpAtomPattern = re.compile("^atom (\d+) \((\d+)\) " + "\((\-?\d+), (\-?\d+), (\-?\d+)\)") class NotAtomException(Exception): pass class Atom: def fromMmp(self, line): m = _MmpAtomPattern.match(line) if m == None: raise NotAtomException groups = m.groups() self.elem = elem = string.atoi(groups[1]) str = "atom %s" % groups[0] str += " (%s)" % groups[1] str += " (%d, %d, %d)" str += line[m.span()[1]:] # anything after position self._mmpstr = str self.x = 0.001 * string.atoi(groups[2]) self.y = 0.001 * string.atoi(groups[3]) self.z = 0.001 * string.atoi(groups[4]) def clone(self): "permit deep cloning of structure files" a = Atom() for key in self.__dict__.keys(): setattr(a, key, getattr(self, key)) return a def fromXyz(self, element, x, y, z): self.elem = _PeriodicTable.index(element) self.x = x self.y = y self.z = z def toMmpString(self): return self._mmpstr % (int(self.x * 1000), int(self.y * 1000), int(self.z * 1000)) def toXyzString(self): element = _PeriodicTable[self.elem] return "%s %f %f %f" % (element, self.x, self.y, self.z) def __repr__(self): return "<" + self.toXyzString() + ">"
NanoCAD-master
sim/src/tests/heteroatom_organics/Atom.py
#!/usr/bin/python import sys import string import Atom class XyzFile: """Python class to contain information from an XYZ file""" def __init__(self): self.atoms = [ ] def clone(self): other = XyzFile() other.atoms = [ ] for a in self.atoms: other.atoms.append(a.clone()) return other def getAtom(self, i): return self.atoms[i] def __getitem__(self, i): a = self.atoms[i] return (a.x, a.y, a.z) def __setitem__(self, i, xyz): a = self.atoms[i] a.x, a.y, a.z = xyz def __len__(self): return len(self.atoms) def read(self, filename): inf = open(filename) self.readstring(inf.read()) inf.close() def readstring(self, lines): lines = lines.split("\n") numAtoms = string.atoi(lines[0]) lines = lines[2:] for i in range(numAtoms): element, x, y, z = lines[i].split() x, y, z = map(string.atof, (x, y, z)) a = Atom.Atom() a.fromXyz(element, x, y, z) self.atoms.append(a) def write(self, title, outf=None): if outf == None: outf = sys.stdout outf.write("%d\n%s\n" % (len(self.atoms), title)) for atm in self.atoms: outf.write(atm.toXyzString() + "\n") if __name__ == "__main__": # do a little test class StringCollector: def __init__(self): self.contents = "" def write(self, x): self.contents += x import sys example_xyz_file = """15 RMS=0.994508 C -0.193641 2.900593 -0.026523 X 0.093601 3.502437 0.394872 X -0.623522 3.154064 -0.637458 C -1.079249 2.005273 0.890906 X -1.803795 1.958430 0.584626 X -1.090331 2.310792 1.617200 C 0.986482 2.029986 -0.552402 X 0.945121 1.985940 -1.338110 X 1.667645 2.347089 -0.314849 C -0.443634 0.583852 0.936816 X -0.955793 0.061908 0.643109 X -0.248030 0.411844 1.680547 C 0.839719 0.603152 0.054672 X 1.466374 0.446893 0.504740 X 0.762053 0.079748 -0.528147 """ xyz = XyzFile() xyz.readstring(example_xyz_file) # test 1 sc = StringCollector() ss, sys.stdout = sys.stdout, sc xyz.write("RMS=0.994508") sys.stdout = ss assert sc.contents == example_xyz_file # test 2 for i in range(len(xyz)): print xyz.getAtom(i) print for i in range(8): xyz[i] = (1.0, 2.0, 3.0) for i in range(len(xyz)): print xyz.getAtom(i)
NanoCAD-master
sim/src/tests/amino_acids/XyzFile.py
#!/usr/bin/python import os import sys import MmpFile import XyzFile damianFiles = ("ala_l_aminoacid.mmp", "arg_l_aminoacid.mmp", "asn_l_aminoacid.mmp", "asp_l_aminoacid.mmp", "cys_l_aminoacid.mmp", "gln_l_aminoacid.mmp", "glu_l_aminoacid.mmp", "gly_l_aminoacid.mmp", "his_l_aminoacid.mmp", "ile_l_aminoacid.mmp", "leu_l_aminoacid.mmp", "lys_l_aminoacid.mmp", "met_l_aminoacid.mmp", "phe_l_aminoacid.mmp", "pro_l_aminoacid.mmp", "ser_l_aminoacid.mmp", "thr_l_aminoacid.mmp", "tyr_l_aminoacid.mmp", "val_l_aminoacid.mmp") for df in damianFiles: prefix = df[:df.index(".")] testPrefix = "test_" + prefix damianMmp = MmpFile.MmpFile() damianMmp.read(df) # Generate the xyzcmp file xyzcmpFilename = testPrefix + ".xyzcmp" outf = open(xyzcmpFilename, "w") xyzcmp = damianMmp.convertToXyz() xyzcmp.write(df, outf) outf.close() # Make a perturbed copy of the MMP, use it for test_{foo}.mmp dmClone = damianMmp.clone() dmClone.perturb() testMmpFilename = testPrefix + ".mmp" outf = open(testMmpFilename, "w") dmClone.write(outf) outf.close() # Create test_{foo}.test testTestFilename = testPrefix + ".test" outf = open(testTestFilename, "w") outf.write("TYPE struct\n") outf.close() print "Test input files generated for " + testPrefix
NanoCAD-master
sim/src/tests/amino_acids/CreateTests.py
#!/usr/bin/python """Grab one of Damian's minimized MMP files, perturb each atom's position by some fraction of an angstrom, write out the result as another MMP file, which becomes an input file for the test. $Id$ """ __author__ = "Will" import re import os import sys import string import Atom class MmpFile: """This is meant to be a Python class representing a MMP file. It is not intended to represent ALL the information in a MMP file, although it might do that in some distant-future version. Right now, its biggest strength is that it allows us to easily modify the positions of the atoms in an MMP file, and write out the resulting modified MMP file.""" class _Line: def fromMmp(self, line): self._str = line def str(self): return self._str def clone(self, owner): ln = MmpFile._Line() ln._str = self._str return ln class _AtomHolder: """Atom holders are indices into the MmpFile.atoms list, 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 __init__(self, owner): self._owner = owner def fromMmp(self, line): atoms = self._owner.atoms self._index = len(atoms) a = Atom.Atom() a.fromMmp(line) atoms.append(a) def str(self): a = self._owner.atoms[self._index] return a.toMmpString() def clone(self, newowner): other = MmpFile._AtomHolder(newowner) other._index = self._index return other def __init__(self): self.atoms = [ ] self.lines = [ ] def clone(self): other = MmpFile() for x in self.lines: other.lines.append(x.clone(other)) for a in self.atoms: other.atoms.append(a.clone()) return other def getAtom(self, i): return self.atoms[i] def __getitem__(self, i): a = self.atoms[i] return (a.x, a.y, a.z) def __setitem__(self, i, xyz): a = self.atoms[i] a.x, a.y, a.z = xyz def __len__(self): return len(self.atoms) def read(self, filename): inf = open(filename) self.readstring(inf.read()) inf.close() def readstring(self, lines): for line in lines.split("\n"): try: atm = MmpFile._AtomHolder(self) atm.fromMmp(line) except Atom.NotAtomException: atm = MmpFile._Line() atm.fromMmp(line) self.lines.append(atm) def write(self, outf=None): if outf == None: outf = sys.stdout for ln in self.lines: outf.write(ln.str() + "\n") def convertToXyz(self): import XyzFile xyz = XyzFile.XyzFile() for a in self.atoms: xyz.atoms.append(a) return xyz def perturb(self): import random A = 0.5 # some small number of angstroms A = A / (3 ** .5) # amount in one dimension for i in range(len(self)): x, y, z = self[i] x += random.normalvariate(0.0, A) y += random.normalvariate(0.0, A) z += random.normalvariate(0.0, A) self[i] = (x, y, z) if __name__ == "__main__": """What follows is a specific usage of the MmpFile class. It's not the only way it could be used, but it demonstrates something we're going to want to do very soon as we generate test cases from Damian's MMP files.""" m = MmpFile() #input = "C14H20.mmp" input = "C3H8.mmp" m.read(input) m.perturb() #outf = os.popen("diff -u - %s | less" % input, "w") outf = os.popen("diff -u - %s" % input, "w") m.write(outf) outf.close()
NanoCAD-master
sim/src/tests/amino_acids/MmpFile.py
#!/usr/bin/python """MMP and XYZ files share a common Atom definition. This will make it easy to move information back and forth between the two formats. $Id$ """ __author__ = "Will" import re import os import sys import string import random _PeriodicTable = [ "X", # our singlet has element number zero "H", "He", "Li", "Be", "B", "C", "N", "O", "F", "Ne", "Na", "Mg", "Al", "Si", "P", "S", "Cl", "Ar", "K", "Ca" #Sc,Ti,V,Cr,Mn,Fe.... ] _MmpAtomPattern = re.compile("^atom (\d+) \((\d+)\) " + "\((\-?\d+), (\-?\d+), (\-?\d+)\)") class NotAtomException(Exception): pass class Atom: def fromMmp(self, line): m = _MmpAtomPattern.match(line) if m == None: raise NotAtomException groups = m.groups() self.elem = elem = string.atoi(groups[1]) str = "atom %s" % groups[0] str += " (%s)" % groups[1] str += " (%d, %d, %d)" str += line[m.span()[1]:] # anything after position self._mmpstr = str self.x = 0.001 * string.atoi(groups[2]) self.y = 0.001 * string.atoi(groups[3]) self.z = 0.001 * string.atoi(groups[4]) def clone(self): "permit deep cloning of structure files" a = Atom() for key in self.__dict__.keys(): setattr(a, key, getattr(self, key)) return a def fromXyz(self, element, x, y, z): self.elem = _PeriodicTable.index(element) self.x = x self.y = y self.z = z def toMmpString(self): return self._mmpstr % (int(self.x * 1000), int(self.y * 1000), int(self.z * 1000)) def toXyzString(self): element = _PeriodicTable[self.elem] return "%s %f %f %f" % (element, self.x, self.y, self.z) def __repr__(self): return "<" + self.toXyzString() + ">"
NanoCAD-master
sim/src/tests/amino_acids/Atom.py
#!/usr/bin/python """This script merges an MMP file with an XYZ file, by replacing the MMP file's atom positions with the positions from the XYZ file, producing a new MMP file with the XYZ positions. The merged MMP file is written to standard output. Usage: xyzmerge.py input1.mmp input2.xyz > output.mmp $Id$ """ __author__ = "Will" import sys from MmpFile import MmpFile from XyzFile import XyzFile try: mmpInputFile = sys.argv[1] xyzInputFile = sys.argv[2] xyz = XyzFile() xyz.read(xyzInputFile) mmp = MmpFile() mmp.read(mmpInputFile) assert len(xyz) != 0 assert len(xyz) == len(mmp) for i in range(len(xyz)): xa = xyz.atoms[i] ma = mmp.atoms[i] assert xa.elem == ma.elem ma.x, ma.y, ma.z = xa.x, xa.y, xa.z mmp.write() except Exception, e: if e: sys.stderr.write(sys.argv[0] + ": " + e.args[0] + "\n\n") sys.stderr.write(__doc__) sys.exit(1)
NanoCAD-master
sim/src/tests/scripts/xyzmerge.py
#!/usr/bin/python """MMP and XYZ files share a common Atom definition. This will make it easy to move information back and forth between the two formats. $Id$ """ __author__ = "Will" import os import sys import string import Atom class XyzFile: """Python class to contain information from an XYZ file""" def __init__(self): self.atoms = [ ] def clone(self): other = XyzFile() other.atoms = [ ] for a in self.atoms: other.atoms.append(a.clone()) return other def getAtom(self, i): return self.atoms[i] def __getitem__(self, i): a = self.atoms[i] return (a.x, a.y, a.z) def __setitem__(self, i, xyz): a = self.atoms[i] a.x, a.y, a.z = xyz def __len__(self): return len(self.atoms) def read(self, filename): inf = open(filename) self.readstring(inf.read()) inf.close() def readstring(self, lines): lines = lines.split(os.linesep) numAtoms = string.atoi(lines[0]) lines = lines[2:] for i in range(numAtoms): element, x, y, z = lines[i].split() x, y, z = map(string.atof, (x, y, z)) a = Atom.Atom() a.fromXyz(element, x, y, z) self.atoms.append(a) def write(self, title, outf=None): if outf == None: outf = sys.stdout outf.write("%d\n%s\n" % (len(self.atoms), title)) for atm in self.atoms: outf.write(atm.toXyzString() + "\n") if __name__ == "__main__": # do a little test class StringCollector: def __init__(self): self.contents = "" def write(self, x): self.contents += x import sys example_xyz_file = """15 RMS=0.994508 C -0.193641 2.900593 -0.026523 X 0.093601 3.502437 0.394872 X -0.623522 3.154064 -0.637458 C -1.079249 2.005273 0.890906 X -1.803795 1.958430 0.584626 X -1.090331 2.310792 1.617200 C 0.986482 2.029986 -0.552402 X 0.945121 1.985940 -1.338110 X 1.667645 2.347089 -0.314849 C -0.443634 0.583852 0.936816 X -0.955793 0.061908 0.643109 X -0.248030 0.411844 1.680547 C 0.839719 0.603152 0.054672 X 1.466374 0.446893 0.504740 X 0.762053 0.079748 -0.528147 """ xyz = XyzFile() xyz.readstring(example_xyz_file) # test 1 sc = StringCollector() ss, sys.stdout = sys.stdout, sc xyz.write("RMS=0.994508") sys.stdout = ss assert sc.contents == example_xyz_file # test 2 for i in range(len(xyz)): print xyz.getAtom(i) print for i in range(8): xyz[i] = (1.0, 2.0, 3.0) for i in range(len(xyz)): print xyz.getAtom(i)
NanoCAD-master
sim/src/tests/scripts/XyzFile.py
#!/usr/bin/python """This script examines the structure in an MMP file to enumerate all the bond length terms and bond angle terms for the structure. If an XYZ file is given, use the position information from the XYZ file, otherwise use position information from the MMP file. Bond lengths are in angstroms, bond angles are in degrees. Usage: findterms.py input.mmp > output.txt findterms.py input1.mmp input2.xyz > output.txt Example output: LENGTH 0 1 1.53077692692 LENGTH 0 3 1.09477166569 .... ANGLE 0 1 2 112.961986081 ANGLE 0 1 6 109.491950915 .... ------------------------------------------------- To generate the bond-angle information from the sim/src directory type: for x in tests/*/*.test; do ./runtest.py $x --generate; done This will generate a bunch of *.ba files (ba='bond,angle'). Those are actually already checked into CVS so that's unnecessary. To really use this stuff, we need to clear out the *.out files and replace them, like this: rm -f tests/*/*altout tests/*/*.diff tests/*/*.new rm -f tests/rigid_organics/test_*.out # other directories? ./regression.py --generate I don't dare do that on the head (the main CVS tree with the duple rev numbers) because Eric M needs the *.out files for his regression testing. So I'll plan to attempt this on a branch at some point. $Id$ """ __author__ = "Will" import os import sys import string import getopt from MmpFile import MmpFile from XyzFile import XyzFile import math import Numeric # How much variation do we permit in bond lengths and bond # angles before we think it's a problem? For now these are # wild guesses, to be later scrutinized by smart people. LENGTH_TOLERANCE = 0.2 # angstroms ANGLE_TOLERANCE = 10 # degrees ######################################## # Borrow stuff from VQT.py def V(*v): return Numeric.array(v, Numeric.Float) def vlen(v1): return math.sqrt(Numeric.dot(v1, v1)) def angleBetween(vec1, vec2): TEENY = 1.0e-10 lensq1 = Numeric.dot(vec1, vec1) if lensq1 < TEENY: return 0.0 lensq2 = Numeric.dot(vec2, vec2) if lensq2 < TEENY: return 0.0 dprod = Numeric.dot(vec1 / lensq1**.5, vec2 / lensq2**.5) if dprod >= 1.0: return 0.0 if dprod <= -1.0: return 180.0 return (180/math.pi) * math.acos(dprod) def measureLength(xyz, first, second): '''Returns the angle between two atoms (nuclei)''' p0 = apply(V, xyz[first]) p1 = apply(V, xyz[second]) return vlen(p0 - p1) def measureAngle(xyz, first, second, third): '''Returns the angle between two atoms (nuclei)''' p0 = apply(V, xyz[first]) p1 = apply(V, xyz[second]) p2 = apply(V, xyz[third]) v01, v21 = p0 - p1, p2 - p1 return angleBetween(v01, v21) ################################# def main(mmpInputFile, xyzInputFile=None, outf=None, referenceInputFile=None, generateFlag=False): bondLengthTerms = { } bondAngleTerms = { } def addBondLength(atm1, atm2): assert atm1 != atm2 if atm2 < atm1: atm1, atm2 = atm2, atm1 if bondLengthTerms.has_key(atm1): if atm2 not in bondLengthTerms[atm1]: bondLengthTerms[atm1].append(atm2) else: bondLengthTerms[atm1] = [ atm2 ] def getBonds(atm1): lst = [ ] if bondLengthTerms.has_key(atm1): for x in bondLengthTerms[atm1]: lst.append(x) for key in bondLengthTerms.keys(): if atm1 in bondLengthTerms[key]: if key not in lst: lst.append(key) lst.sort() return lst def addBondAngle(atm1, atm2, atm3): if atm3 < atm1: atm1, atm3 = atm3, atm1 value = (atm2, atm3) if bondAngleTerms.has_key(atm1): if value not in bondAngleTerms[atm1]: bondAngleTerms[atm1].append(value) else: bondAngleTerms[atm1] = [ value ] if outf != None: ss, sys.stdout = sys.stdout, outf mmp = MmpFile() mmp.read(mmpInputFile) xyz = XyzFile() if xyzInputFile != None: xyz.read(xyzInputFile) else: # copy xyz file from mmp file import Atom for i in range(len(mmp)): ma = mmp.atoms[i] element = Atom._PeriodicTable[ma.elem] x, y, z = ma.x, ma.y, ma.z a = Atom.Atom() a.fromXyz(element, x, y, z) xyz.atoms.append(a) assert len(xyz) != 0 assert len(xyz) == len(mmp) # store all the bonds in bondLengthTerms for i in range(len(mmp)): a = mmp.atoms[i] for b in a.bonds: addBondLength(i, b - 1) # generate angles from chains of two bonds for first in range(len(mmp)): for second in getBonds(first): for third in getBonds(second): if first != third: addBondAngle(first, second, third) lengthList = [ ] for first in bondLengthTerms.keys(): for second in bondLengthTerms[first]: lengthList.append((first, second, measureLength(xyz, first, second))) angleList = [ ] for first in bondAngleTerms.keys(): for second, third in bondAngleTerms[first]: angleList.append((first, second, third, measureAngle(xyz, first, second, third))) if generateFlag: for a1, a2, L in lengthList: print "LENGTH", a1, a2, L for a1, a2, a3, A in angleList: print "ANGLE", a1, a2, a3, A if referenceInputFile != None: badness = False # read in LENGTH lines, compare them to this guy inf = open(referenceInputFile) lp = ap = 0 for line in inf.readlines(): if line.startswith("LENGTH "): fields = line[7:].split() a1, a2, L = (string.atoi(fields[0]), string.atoi(fields[1]), string.atof(fields[2])) a11, a22, LL = lengthList[lp] lp += 1 if a1 != a11 or a2 != a22: print ("Wrong length term (%d, %d), should be (%d, %d)" % (a11, a22, a1, a2)) badness = True break if abs(L - LL) > LENGTH_TOLERANCE: print ("Wrong bond length at (%d, %d), it's %f, should be %f" % (a1, a2, LL, L)) badness = True break elif line.startswith("ANGLE "): fields = line[6:].split() a1, a2, a3, A = (string.atoi(fields[0]), string.atoi(fields[1]), string.atoi(fields[2]), string.atof(fields[3])) a11, a22, a33, AA = angleList[ap] ap += 1 if a1 != a11 or a2 != a22 or a3 != a33: print ("Wrong angle term (%d, %d, %d), should be (%d, %d, %d)" % (a11, a22, a33, a1, a2, a3)) badness = True break if abs(L - LL) > ANGLE_TOLERANCE: print ("Wrong bond angle at (%d, %d, %d), it's %f, should be %f" % (a1, a2, a3, AA, A)) badness = True break else: print "Unknown line in reference file:", line badness = True break if not badness: print "OK" if outf != None: outf.close() sys.stdout = ss ############################################################ if __name__ == "__main__": try: mmpInputFile = None xyzInputFile = None outputFile = None referenceInputFile = None generateFlag = False try: opts, args = getopt.getopt(sys.argv[1:], "m:x:o:r:g", ["mmp=", "xyz=", "output=", "reference=", "generate"]) except getopt.error, msg: errprint(msg) sys.exit(1) for o, a in opts: if o in ('-m', '--mmp'): mmpInputFile = a elif o in ('-x', '--xyz'): xyzInputFile = a elif o in ('-o', '--output'): outputFile = a elif o in ('-r', '--reference'): referenceInputFile = a elif o in ('-g', '--generate'): generateFlag = True else: print "Bad command line option:", o if mmpInputFile == None: mmpInputFile = args.pop(0) if xyzInputFile == None and len(args) > 1: xyzInputFile = args.pop(0) outf = None if outputFile != None: outf = open(outputFile, "w") main(mmpInputFile, xyzInputFile=xyzInputFile, outf=outf, referenceInputFile=referenceInputFile, generateFlag=generateFlag) except Exception, e: if e: sys.stderr.write(sys.argv[0] + ": " + repr(e.args[0]) + "\n") import traceback traceback.print_tb(sys.exc_traceback, sys.stderr) sys.stderr.write("\n") sys.stderr.write(__doc__) sys.exit(1)
NanoCAD-master
sim/src/tests/scripts/findterms.py
#!/usr/bin/python """Grab one of Damian's minimized MMP files, perturb each atom's position by some fraction of an angstrom, write out the result as another MMP file, which becomes an input file for the test. $Id$ """ __author__ = "Will" import re import os import sys import string import Atom class MmpFile: """This is meant to be a Python class representing a MMP file. It is not intended to represent ALL the information in a MMP file, although it might do that in some distant-future version. Right now, its biggest strength is that it allows us to easily modify the positions of the atoms in an MMP file, and write out the resulting modified MMP file.""" class _Line: def fromMmp(self, line): self._str = line def str(self): return self._str class _AtomHolder: """Atom holders are indices into the MmpFile.atoms list, and that's done so that MmpFiles are easier to clone. """ def __init__(self, owner): self._owner = owner def fromMmp(self, line): atoms = self._owner.atoms n = len(atoms) a = Atom.Atom() try: a.fromMmp(line) except Atom.NotAtomException: del a return False self._index = n atoms.append(a) return True def mmpBonds(self, line): return self._owner.atoms[self._index].mmpBonds(line) def str(self): a = self._owner.atoms[self._index] return a.toMmpString() def __init__(self): self.atoms = [ ] self.lines = [ ] def clone(self): other = MmpFile() other.lines = self.lines[:] other.atoms = [ ] for a in self.atoms: other.atoms.append(a.clone()) return other def getAtom(self, i): return self.atoms[i] def __getitem__(self, i): a = self.atoms[i] return (a.x, a.y, a.z) def __setitem__(self, i, xyz): a = self.atoms[i] a.x, a.y, a.z = xyz def __len__(self): return len(self.atoms) def read(self, filename): inf = open(filename) self.readstring(inf.read()) inf.close() def readstring(self, lines): lines = Atom.FileLineIterator(lines.split(os.linesep)) try: while True: line = lines.next() atm = MmpFile._AtomHolder(self) if atm.fromMmp(line): self.lines.append(atm) line = lines.next() if atm.mmpBonds(line): x = MmpFile._Line() x.fromMmp(line) self.lines.append(x) else: lines.backup() else: x = MmpFile._Line() x.fromMmp(line) self.lines.append(x) except StopIteration: pass def write(self, outf=None): if outf == None: outf = sys.stdout for ln in self.lines: outf.write(ln.str() + "\n") def convertToXyz(self): import XyzFile xyz = XyzFile.XyzFile() for a in self.atoms: xyz.atoms.append(a) return xyz def perturb(self): import random A = 0.5 # some small number of angstroms A = A / (3 ** .5) # amount in one dimension for i in range(len(self)): x, y, z = self[i] x += random.normalvariate(0.0, A) y += random.normalvariate(0.0, A) z += random.normalvariate(0.0, A) self[i] = (x, y, z) if __name__ == "__main__": """What follows is a specific usage of the MmpFile class. It's not the only way it could be used, but it demonstrates something we're going to want to do very soon as we generate test cases from Damian's MMP files.""" m = MmpFile() #input = "C14H20.mmp" input = "C3H8.mmp" m.read(input) m.perturb() if False: outf = open("results", "w") m.write(outf) outf.close() if False: for a in m.atoms: print a.bonds outf = os.popen("diff -u - %s" % input, "w") m.write(outf) outf.close()
NanoCAD-master
sim/src/tests/scripts/MmpFile.py
#!/usr/bin/python """This script translates an MMP file to an XYZ file. Usage: mmp2xyz.py input.mmp > output.xyz $Id$ """ __author__ = "Will" import sys from MmpFile import MmpFile from XyzFile import XyzFile import Atom try: mmpInputFile = sys.argv[1] xyz = XyzFile() mmp = MmpFile() mmp.read(mmpInputFile) for i in range(len(mmp)): ma = mmp.atoms[i] element = Atom._PeriodicTable[ma.elem] x, y, z = ma.x, ma.y, ma.z a = Atom.Atom() a.fromXyz(element, x, y, z) xyz.atoms.append(a) xyz.write(mmpInputFile) except Exception, e: if e: sys.stderr.write(sys.argv[0] + ": " + e.args[0] + "\n") import traceback traceback.print_tb(sys.exc_traceback, sys.stderr) sys.stderr.write("\n") sys.stderr.write(__doc__) sys.exit(1)
NanoCAD-master
sim/src/tests/scripts/mmp2xyz.py
#!/usr/bin/python """A common Atom definition to be shared by the classes for various molecule file formats including MMP and XYZ. This will make it easy to move information back and forth between formats. $Id$ """ __author__ = "Will" import re import os import sys import string import random _PeriodicTable = [ "X", # our singlet has element number zero "H", "He", "Li", "Be", "B", "C", "N", "O", "F", "Ne", "Na", "Mg", "Al", "Si", "P", "S", "Cl", "Ar", "K", "Ca" #Sc,Ti,V,Cr,Mn,Fe.... ] _MmpAtomPattern = re.compile("^atom (\d+) \((\d+)\) " + "\((\-?\d+), (\-?\d+), (\-?\d+)\)") class NotAtomException(Exception): pass class Atom: def fromMmp(self, line): m = _MmpAtomPattern.match(line) if m == None: raise NotAtomException groups = m.groups() self.elem = elem = string.atoi(groups[1]) str = "atom %s" % groups[0] str += " (%s)" % groups[1] str += " (%d, %d, %d)" str += line[m.span()[1]:] # anything after position self._mmpstr = str self.x = 0.001 * string.atoi(groups[2]) self.y = 0.001 * string.atoi(groups[3]) self.z = 0.001 * string.atoi(groups[4]) self.bonds = [ ] def clone(self): "permit deep cloning of structure files" a = Atom() for key in self.__dict__.keys(): setattr(a, key, getattr(self, key)) return a def mmpBonds(self, line): if line.startswith("bond"): for b in line.split()[1:]: self.bonds.append(string.atoi(b)) return True return False def fromXyz(self, element, x, y, z): self.elem = _PeriodicTable.index(element) self.x = x self.y = y self.z = z def toMmpString(self): return self._mmpstr % (int(self.x * 1000), int(self.y * 1000), int(self.z * 1000)) def toXyzString(self): element = _PeriodicTable[self.elem] return "%s %f %f %f" % (element, self.x, self.y, self.z) def __repr__(self): return "<" + self.toXyzString() + ">" class FileLineIterator: def __init__(self, lines): self.lines = lines self.pointer = 0 def next(self): pointer = self.pointer lines = self.lines if pointer >= len(lines): raise StopIteration self.pointer = pointer + 1 return lines[pointer] def backup(self): pointer = self.pointer if pointer <= 0: raise Exception, "can't back up" self.pointer = pointer - 1
NanoCAD-master
sim/src/tests/scripts/Atom.py
#!/usr/bin/python import sys import string import Atom class XyzFile: """Python class to contain information from an XYZ file""" def __init__(self): self.atoms = [ ] def clone(self): other = XyzFile() other.atoms = [ ] for a in self.atoms: other.atoms.append(a.clone()) return other def getAtom(self, i): return self.atoms[i] def __getitem__(self, i): a = self.atoms[i] return (a.x, a.y, a.z) def __setitem__(self, i, xyz): a = self.atoms[i] a.x, a.y, a.z = xyz def __len__(self): return len(self.atoms) def read(self, filename): inf = open(filename) self.readstring(inf.read()) inf.close() def readstring(self, lines): lines = lines.split("\n") numAtoms = string.atoi(lines[0]) lines = lines[2:] for i in range(numAtoms): element, x, y, z = lines[i].split() x, y, z = map(string.atof, (x, y, z)) a = Atom.Atom() a.fromXyz(element, x, y, z) self.atoms.append(a) def write(self, title, outf=None): if outf == None: outf = sys.stdout outf.write("%d\n%s\n" % (len(self.atoms), title)) for atm in self.atoms: outf.write(atm.toXyzString() + "\n") if __name__ == "__main__": # do a little test class StringCollector: def __init__(self): self.contents = "" def write(self, x): self.contents += x import sys example_xyz_file = """15 RMS=0.994508 C -0.193641 2.900593 -0.026523 X 0.093601 3.502437 0.394872 X -0.623522 3.154064 -0.637458 C -1.079249 2.005273 0.890906 X -1.803795 1.958430 0.584626 X -1.090331 2.310792 1.617200 C 0.986482 2.029986 -0.552402 X 0.945121 1.985940 -1.338110 X 1.667645 2.347089 -0.314849 C -0.443634 0.583852 0.936816 X -0.955793 0.061908 0.643109 X -0.248030 0.411844 1.680547 C 0.839719 0.603152 0.054672 X 1.466374 0.446893 0.504740 X 0.762053 0.079748 -0.528147 """ xyz = XyzFile() xyz.readstring(example_xyz_file) # test 1 sc = StringCollector() ss, sys.stdout = sys.stdout, sc xyz.write("RMS=0.994508") sys.stdout = ss assert sc.contents == example_xyz_file # test 2 for i in range(len(xyz)): print xyz.getAtom(i) print for i in range(8): xyz[i] = (1.0, 2.0, 3.0) for i in range(len(xyz)): print xyz.getAtom(i)
NanoCAD-master
sim/src/tests/floppy_organics/XyzFile.py
#!/usr/bin/python import os import sys import MmpFile import XyzFile damianFiles = filter(lambda x: x, os.popen("ls C*.mmp").read().split("\n")) for df in damianFiles: prefix = df[:df.index(".")] testPrefix = "test_" + prefix damianMmp = MmpFile.MmpFile() damianMmp.read(df) # Generate the xyzcmp file xyzcmpFilename = testPrefix + ".xyzcmp" outf = open(xyzcmpFilename, "w") xyzcmp = damianMmp.convertToXyz() xyzcmp.write(df, outf) outf.close() # Make a perturbed copy of the MMP, use it for test_{foo}.mmp dmClone = damianMmp.clone() dmClone.perturb() testMmpFilename = testPrefix + ".mmp" outf = open(testMmpFilename, "w") dmClone.write(outf) outf.close() # Create test_{foo}.test testTestFilename = testPrefix + ".test" outf = open(testTestFilename, "w") outf.write("TYPE struct\n") outf.close() print "Test input files generated for " + testPrefix
NanoCAD-master
sim/src/tests/floppy_organics/CreateTests.py
#!/usr/bin/python """Grab one of Damian's minimized MMP files, perturb each atom's position by some fraction of an angstrom, write out the result as another MMP file, which becomes an input file for the test. $Id$ """ __author__ = "Will" import re import os import sys import string import Atom class MmpFile: """This is meant to be a Python class representing a MMP file. It is not intended to represent ALL the information in a MMP file, although it might do that in some distant-future version. Right now, its biggest strength is that it allows us to easily modify the positions of the atoms in an MMP file, and write out the resulting modified MMP file.""" class _Line: def fromMmp(self, line): self._str = line def str(self): return self._str def clone(self, owner): ln = MmpFile._Line() ln._str = self._str return ln class _AtomHolder: """Atom holders are indices into the MmpFile.atoms list, 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 __init__(self, owner): self._owner = owner def fromMmp(self, line): atoms = self._owner.atoms self._index = len(atoms) a = Atom.Atom() a.fromMmp(line) atoms.append(a) def str(self): a = self._owner.atoms[self._index] return a.toMmpString() def clone(self, newowner): other = MmpFile._AtomHolder(newowner) other._index = self._index return other def __init__(self): self.atoms = [ ] self.lines = [ ] def clone(self): other = MmpFile() for x in self.lines: other.lines.append(x.clone(other)) for a in self.atoms: other.atoms.append(a.clone()) return other def getAtom(self, i): return self.atoms[i] def __getitem__(self, i): a = self.atoms[i] return (a.x, a.y, a.z) def __setitem__(self, i, xyz): a = self.atoms[i] a.x, a.y, a.z = xyz def __len__(self): return len(self.atoms) def read(self, filename): inf = open(filename) self.readstring(inf.read()) inf.close() def readstring(self, lines): for line in lines.split("\n"): try: atm = MmpFile._AtomHolder(self) atm.fromMmp(line) except Atom.NotAtomException: atm = MmpFile._Line() atm.fromMmp(line) self.lines.append(atm) def write(self, outf=None): if outf == None: outf = sys.stdout for ln in self.lines: outf.write(ln.str() + "\n") def convertToXyz(self): import XyzFile xyz = XyzFile.XyzFile() for a in self.atoms: xyz.atoms.append(a) return xyz def perturb(self): import random A = 0.5 # some small number of angstroms A = A / (3 ** .5) # amount in one dimension for i in range(len(self)): x, y, z = self[i] x += random.normalvariate(0.0, A) y += random.normalvariate(0.0, A) z += random.normalvariate(0.0, A) self[i] = (x, y, z) if __name__ == "__main__": """What follows is a specific usage of the MmpFile class. It's not the only way it could be used, but it demonstrates something we're going to want to do very soon as we generate test cases from Damian's MMP files.""" m = MmpFile() #input = "C14H20.mmp" input = "C3H8.mmp" m.read(input) m.perturb() #outf = os.popen("diff -u - %s | less" % input, "w") outf = os.popen("diff -u - %s" % input, "w") m.write(outf) outf.close()
NanoCAD-master
sim/src/tests/floppy_organics/MmpFile.py
#!/usr/bin/python """MMP and XYZ files share a common Atom definition. This will make it easy to move information back and forth between the two formats. $Id$ """ __author__ = "Will" import re import os import sys import string import random _PeriodicTable = [ "X", # our singlet has element number zero "H", "He", "Li", "Be", "B", "C", "N", "O", "F", "Ne", "Na", "Mg", "Al", "Si", "P", "S", "Cl", "Ar", "K", "Ca" #Sc,Ti,V,Cr,Mn,Fe.... ] _MmpAtomPattern = re.compile("^atom (\d+) \((\d+)\) " + "\((\-?\d+), (\-?\d+), (\-?\d+)\)") class NotAtomException(Exception): pass class Atom: def fromMmp(self, line): m = _MmpAtomPattern.match(line) if m == None: raise NotAtomException groups = m.groups() self.elem = elem = string.atoi(groups[1]) str = "atom %s" % groups[0] str += " (%s)" % groups[1] str += " (%d, %d, %d)" str += line[m.span()[1]:] # anything after position self._mmpstr = str self.x = 0.001 * string.atoi(groups[2]) self.y = 0.001 * string.atoi(groups[3]) self.z = 0.001 * string.atoi(groups[4]) def clone(self): "permit deep cloning of structure files" a = Atom() for key in self.__dict__.keys(): setattr(a, key, getattr(self, key)) return a def fromXyz(self, element, x, y, z): self.elem = _PeriodicTable.index(element) self.x = x self.y = y self.z = z def toMmpString(self): return self._mmpstr % (int(self.x * 1000), int(self.y * 1000), int(self.z * 1000)) def toXyzString(self): element = _PeriodicTable[self.elem] return "%s %f %f %f" % (element, self.x, self.y, self.z) def __repr__(self): return "<" + self.toXyzString() + ">"
NanoCAD-master
sim/src/tests/floppy_organics/Atom.py
#!/usr/bin/python import sys import string import Atom class XyzFile: """Python class to contain information from an XYZ file""" def __init__(self): self.atoms = [ ] def clone(self): other = XyzFile() other.atoms = [ ] for a in self.atoms: other.atoms.append(a.clone()) return other def getAtom(self, i): return self.atoms[i] def __getitem__(self, i): a = self.atoms[i] return (a.x, a.y, a.z) def __setitem__(self, i, xyz): a = self.atoms[i] a.x, a.y, a.z = xyz def __len__(self): return len(self.atoms) def read(self, filename): inf = open(filename) self.readstring(inf.read()) inf.close() def readstring(self, lines): lines = lines.split("\n") numAtoms = string.atoi(lines[0]) lines = lines[2:] for i in range(numAtoms): element, x, y, z = lines[i].split() x, y, z = map(string.atof, (x, y, z)) a = Atom.Atom() a.fromXyz(element, x, y, z) self.atoms.append(a) def write(self, title, outf=None): if outf == None: outf = sys.stdout outf.write("%d\n%s\n" % (len(self.atoms), title)) for atm in self.atoms: outf.write(atm.toXyzString() + "\n") if __name__ == "__main__": # do a little test class StringCollector: def __init__(self): self.contents = "" def write(self, x): self.contents += x import sys example_xyz_file = """15 RMS=0.994508 C -0.193641 2.900593 -0.026523 X 0.093601 3.502437 0.394872 X -0.623522 3.154064 -0.637458 C -1.079249 2.005273 0.890906 X -1.803795 1.958430 0.584626 X -1.090331 2.310792 1.617200 C 0.986482 2.029986 -0.552402 X 0.945121 1.985940 -1.338110 X 1.667645 2.347089 -0.314849 C -0.443634 0.583852 0.936816 X -0.955793 0.061908 0.643109 X -0.248030 0.411844 1.680547 C 0.839719 0.603152 0.054672 X 1.466374 0.446893 0.504740 X 0.762053 0.079748 -0.528147 """ xyz = XyzFile() xyz.readstring(example_xyz_file) # test 1 sc = StringCollector() ss, sys.stdout = sys.stdout, sc xyz.write("RMS=0.994508") sys.stdout = ss assert sc.contents == example_xyz_file # test 2 for i in range(len(xyz)): print xyz.getAtom(i) print for i in range(8): xyz[i] = (1.0, 2.0, 3.0) for i in range(len(xyz)): print xyz.getAtom(i)
NanoCAD-master
sim/src/tests/rigid_organics/XyzFile.py
#!/usr/bin/python import os import sys import MmpFile import XyzFile damianFiles = filter(lambda x: x, os.popen("ls C*.mmp").read().split("\n")) for df in damianFiles: prefix = df[:df.index(".")] testPrefix = "test_" + prefix damianMmp = MmpFile.MmpFile() damianMmp.read(df) # Generate the xyzcmp file xyzcmpFilename = testPrefix + ".xyzcmp" outf = open(xyzcmpFilename, "w") xyzcmp = damianMmp.convertToXyz() xyzcmp.write(df, outf) outf.close() # Make a perturbed copy of the MMP, use it for test_{foo}.mmp dmClone = damianMmp.clone() dmClone.perturb() testMmpFilename = testPrefix + ".mmp" outf = open(testMmpFilename, "w") dmClone.write(outf) outf.close() # Create test_{foo}.test testTestFilename = testPrefix + ".test" outf = open(testTestFilename, "w") outf.write("TYPE struct\n") outf.close() print "Test input files generated for " + testPrefix
NanoCAD-master
sim/src/tests/rigid_organics/CreateTests.py
#!/usr/bin/python """Grab one of Damian's minimized MMP files, perturb each atom's position by some fraction of an angstrom, write out the result as another MMP file, which becomes an input file for the test. $Id$ """ __author__ = "Will" import re import os import sys import string import Atom class MmpFile: """This is meant to be a Python class representing a MMP file. It is not intended to represent ALL the information in a MMP file, although it might do that in some distant-future version. Right now, its biggest strength is that it allows us to easily modify the positions of the atoms in an MMP file, and write out the resulting modified MMP file.""" class _Line: def fromMmp(self, line): self._str = line def str(self): return self._str def clone(self, owner): ln = MmpFile._Line() ln._str = self._str return ln class _AtomHolder: """Atom holders are indices into the MmpFile.atoms list, 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 __init__(self, owner): self._owner = owner def fromMmp(self, line): atoms = self._owner.atoms self._index = len(atoms) a = Atom.Atom() a.fromMmp(line) atoms.append(a) def str(self): a = self._owner.atoms[self._index] return a.toMmpString() def clone(self, newowner): other = MmpFile._AtomHolder(newowner) other._index = self._index return other def __init__(self): self.atoms = [ ] self.lines = [ ] def clone(self): other = MmpFile() for x in self.lines: other.lines.append(x.clone(other)) for a in self.atoms: other.atoms.append(a.clone()) return other def getAtom(self, i): return self.atoms[i] def __getitem__(self, i): a = self.atoms[i] return (a.x, a.y, a.z) def __setitem__(self, i, xyz): a = self.atoms[i] a.x, a.y, a.z = xyz def __len__(self): return len(self.atoms) def read(self, filename): inf = open(filename) self.readstring(inf.read()) inf.close() def readstring(self, lines): for line in lines.split("\n"): try: atm = MmpFile._AtomHolder(self) atm.fromMmp(line) except Atom.NotAtomException: atm = MmpFile._Line() atm.fromMmp(line) self.lines.append(atm) def write(self, outf=None): if outf == None: outf = sys.stdout for ln in self.lines: outf.write(ln.str() + "\n") def convertToXyz(self): import XyzFile xyz = XyzFile.XyzFile() for a in self.atoms: xyz.atoms.append(a) return xyz def perturb(self): import random A = 0.5 # some small number of angstroms A = A / (3 ** .5) # amount in one dimension for i in range(len(self)): x, y, z = self[i] x += random.normalvariate(0.0, A) y += random.normalvariate(0.0, A) z += random.normalvariate(0.0, A) self[i] = (x, y, z) if __name__ == "__main__": """What follows is a specific usage of the MmpFile class. It's not the only way it could be used, but it demonstrates something we're going to want to do very soon as we generate test cases from Damian's MMP files.""" m = MmpFile() #input = "C14H20.mmp" input = "C3H8.mmp" m.read(input) m.perturb() #outf = os.popen("diff -u - %s | less" % input, "w") outf = os.popen("diff -u - %s" % input, "w") m.write(outf) outf.close()
NanoCAD-master
sim/src/tests/rigid_organics/MmpFile.py
#!/usr/bin/python """MMP and XYZ files share a common Atom definition. This will make it easy to move information back and forth between the two formats. $Id$ """ __author__ = "Will" import re import os import sys import string import random _PeriodicTable = [ "X", # our singlet has element number zero "H", "He", "Li", "Be", "B", "C", "N", "O", "F", "Ne", "Na", "Mg", "Al", "Si", "P", "S", "Cl", "Ar", "K", "Ca" #Sc,Ti,V,Cr,Mn,Fe.... ] _MmpAtomPattern = re.compile("^atom (\d+) \((\d+)\) " + "\((\-?\d+), (\-?\d+), (\-?\d+)\)") class NotAtomException(Exception): pass class Atom: def fromMmp(self, line): m = _MmpAtomPattern.match(line) if m == None: raise NotAtomException groups = m.groups() self.elem = elem = string.atoi(groups[1]) str = "atom %s" % groups[0] str += " (%s)" % groups[1] str += " (%d, %d, %d)" str += line[m.span()[1]:] # anything after position self._mmpstr = str self.x = 0.001 * string.atoi(groups[2]) self.y = 0.001 * string.atoi(groups[3]) self.z = 0.001 * string.atoi(groups[4]) def clone(self): "permit deep cloning of structure files" a = Atom() for key in self.__dict__.keys(): setattr(a, key, getattr(self, key)) return a def fromXyz(self, element, x, y, z): self.elem = _PeriodicTable.index(element) self.x = x self.y = y self.z = z def toMmpString(self): return self._mmpstr % (int(self.x * 1000), int(self.y * 1000), int(self.z * 1000)) def toXyzString(self): element = _PeriodicTable[self.elem] return "%s %f %f %f" % (element, self.x, self.y, self.z) def __repr__(self): return "<" + self.toXyzString() + ">"
NanoCAD-master
sim/src/tests/rigid_organics/Atom.py
#!/usr/bin/python import sys import string import Atom class XyzFile: """Python class to contain information from an XYZ file""" def __init__(self): self.atoms = [ ] def clone(self): other = XyzFile() other.atoms = [ ] for a in self.atoms: other.atoms.append(a.clone()) return other def getAtom(self, i): return self.atoms[i] def __getitem__(self, i): a = self.atoms[i] return (a.x, a.y, a.z) def __setitem__(self, i, xyz): a = self.atoms[i] a.x, a.y, a.z = xyz def __len__(self): return len(self.atoms) def read(self, filename): inf = open(filename) self.readstring(inf.read()) inf.close() def readstring(self, lines): lines = lines.split("\n") numAtoms = string.atoi(lines[0]) lines = lines[2:] for i in range(numAtoms): element, x, y, z = lines[i].split() x, y, z = map(string.atof, (x, y, z)) a = Atom.Atom() a.fromXyz(element, x, y, z) self.atoms.append(a) def write(self, title, outf=None): if outf == None: outf = sys.stdout outf.write("%d\n%s\n" % (len(self.atoms), title)) for atm in self.atoms: outf.write(atm.toXyzString() + "\n") if __name__ == "__main__": # do a little test class StringCollector: def __init__(self): self.contents = "" def write(self, x): self.contents += x import sys example_xyz_file = """15 RMS=0.994508 C -0.193641 2.900593 -0.026523 X 0.093601 3.502437 0.394872 X -0.623522 3.154064 -0.637458 C -1.079249 2.005273 0.890906 X -1.803795 1.958430 0.584626 X -1.090331 2.310792 1.617200 C 0.986482 2.029986 -0.552402 X 0.945121 1.985940 -1.338110 X 1.667645 2.347089 -0.314849 C -0.443634 0.583852 0.936816 X -0.955793 0.061908 0.643109 X -0.248030 0.411844 1.680547 C 0.839719 0.603152 0.054672 X 1.466374 0.446893 0.504740 X 0.762053 0.079748 -0.528147 """ xyz = XyzFile() xyz.readstring(example_xyz_file) # test 1 sc = StringCollector() ss, sys.stdout = sys.stdout, sc xyz.write("RMS=0.994508") sys.stdout = ss assert sc.contents == example_xyz_file # test 2 for i in range(len(xyz)): print xyz.getAtom(i) print for i in range(8): xyz[i] = (1.0, 2.0, 3.0) for i in range(len(xyz)): print xyz.getAtom(i)
NanoCAD-master
sim/src/tests/singlebond_stretch/XyzFile.py
#!/usr/bin/python import os import sys import MmpFile import XyzFile damianFiles = map(lambda x: x.strip(), open("damianFiles").readlines()) for df in damianFiles: prefix = df[:df.index(".")] testPrefix = "test_" + prefix damianMmp = MmpFile.MmpFile() damianMmp.read(df) # Generate the xyzcmp file xyzcmpFilename = testPrefix + ".xyzcmp" outf = open(xyzcmpFilename, "w") xyzcmp = damianMmp.convertToXyz() xyzcmp.write(df, outf) outf.close() # Make a perturbed copy of the MMP, use it for test_{foo}.mmp dmClone = damianMmp.clone() dmClone.perturb() testMmpFilename = testPrefix + ".mmp" outf = open(testMmpFilename, "w") dmClone.write(outf) outf.close() # Create test_{foo}.test testTestFilename = testPrefix + ".test" outf = open(testTestFilename, "w") outf.write("TYPE struct\n") outf.close() print "Test input files generated for " + testPrefix
NanoCAD-master
sim/src/tests/singlebond_stretch/CreateTests.py
#!/usr/bin/python """Grab one of Damian's minimized MMP files, perturb each atom's position by some fraction of an angstrom, write out the result as another MMP file, which becomes an input file for the test. $Id$ """ __author__ = "Will" import re import os import sys import string import Atom class MmpFile: """This is meant to be a Python class representing a MMP file. It is not intended to represent ALL the information in a MMP file, although it might do that in some distant-future version. Right now, its biggest strength is that it allows us to easily modify the positions of the atoms in an MMP file, and write out the resulting modified MMP file.""" class _Line: def fromMmp(self, line): self._str = line def str(self): return self._str def clone(self, owner): ln = MmpFile._Line() ln._str = self._str return ln class _AtomHolder: """Atom holders are indices into the MmpFile.atoms list, 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 __init__(self, owner): self._owner = owner def fromMmp(self, line): atoms = self._owner.atoms self._index = len(atoms) a = Atom.Atom() a.fromMmp(line) atoms.append(a) def str(self): a = self._owner.atoms[self._index] return a.toMmpString() def clone(self, newowner): other = MmpFile._AtomHolder(newowner) other._index = self._index return other def __init__(self): self.atoms = [ ] self.lines = [ ] def clone(self): other = MmpFile() for x in self.lines: other.lines.append(x.clone(other)) for a in self.atoms: other.atoms.append(a.clone()) return other def getAtom(self, i): return self.atoms[i] def __getitem__(self, i): a = self.atoms[i] return (a.x, a.y, a.z) def __setitem__(self, i, xyz): a = self.atoms[i] a.x, a.y, a.z = xyz def __len__(self): return len(self.atoms) def read(self, filename): inf = open(filename) self.readstring(inf.read()) inf.close() def readstring(self, lines): for line in lines.split("\n"): try: atm = MmpFile._AtomHolder(self) atm.fromMmp(line) except Atom.NotAtomException: atm = MmpFile._Line() atm.fromMmp(line) self.lines.append(atm) def write(self, outf=None): if outf == None: outf = sys.stdout for ln in self.lines: outf.write(ln.str() + "\n") def convertToXyz(self): import XyzFile xyz = XyzFile.XyzFile() for a in self.atoms: xyz.atoms.append(a) return xyz def perturb(self): import random A = 0.5 # some small number of angstroms A = A / (3 ** .5) # amount in one dimension for i in range(len(self)): x, y, z = self[i] x += random.normalvariate(0.0, A) y += random.normalvariate(0.0, A) z += random.normalvariate(0.0, A) self[i] = (x, y, z) if __name__ == "__main__": """What follows is a specific usage of the MmpFile class. It's not the only way it could be used, but it demonstrates something we're going to want to do very soon as we generate test cases from Damian's MMP files.""" m = MmpFile() #input = "C14H20.mmp" input = "C3H8.mmp" m.read(input) m.perturb() #outf = os.popen("diff -u - %s | less" % input, "w") outf = os.popen("diff -u - %s" % input, "w") m.write(outf) outf.close()
NanoCAD-master
sim/src/tests/singlebond_stretch/MmpFile.py
#!/usr/bin/python """MMP and XYZ files share a common Atom definition. This will make it easy to move information back and forth between the two formats. $Id$ """ __author__ = "Will" import re import os import sys import string import random _PeriodicTable = [ "X", # our singlet has element number zero "H", "He", "Li", "Be", "B", "C", "N", "O", "F", "Ne", "Na", "Mg", "Al", "Si", "P", "S", "Cl", "Ar", "K", "Ca" #Sc,Ti,V,Cr,Mn,Fe.... ] _MmpAtomPattern = re.compile("^atom (\d+) \((\d+)\) " + "\((\-?\d+), (\-?\d+), (\-?\d+)\)") class NotAtomException(Exception): pass class Atom: def fromMmp(self, line): m = _MmpAtomPattern.match(line) if m == None: raise NotAtomException groups = m.groups() self.elem = elem = string.atoi(groups[1]) str = "atom %s" % groups[0] str += " (%s)" % groups[1] str += " (%d, %d, %d)" str += line[m.span()[1]:] # anything after position self._mmpstr = str self.x = 0.001 * string.atoi(groups[2]) self.y = 0.001 * string.atoi(groups[3]) self.z = 0.001 * string.atoi(groups[4]) def clone(self): "permit deep cloning of structure files" a = Atom() for key in self.__dict__.keys(): setattr(a, key, getattr(self, key)) return a def fromXyz(self, element, x, y, z): self.elem = _PeriodicTable.index(element) self.x = x self.y = y self.z = z def toMmpString(self): return self._mmpstr % (int(self.x * 1000), int(self.y * 1000), int(self.z * 1000)) def toXyzString(self): element = _PeriodicTable[self.elem] return "%s %f %f %f" % (element, self.x, self.y, self.z) def __repr__(self): return "<" + self.toXyzString() + ">"
NanoCAD-master
sim/src/tests/singlebond_stretch/Atom.py
#! /usr/bin/python import os import sys import re from Numeric import * from LinearAlgebra import * nampat = re.compile("([A-Z][a-z]?[+=-][A-Z][a-z]?[+=-][A-Z][a-z]?)\.1\.log") thetapat = re.compile(" INPUT CARD\> *theta *= *([\d\.-]+)") engpat = re.compile(" FINAL U-B3LYP ENERGY IS +([\d\.-]+)") hobond = re.compile("[A-Z+=]+\.") Hartree = 4.3597482 # attoJoules Bohr = 0.5291772083 # Angstroms def fexist(fname): try: os.stat(fname) except OSError: return False return True def findnext(f,pat): while 1: card = f.readline() if not card: return None m = pat.match(card) if m: return m def ending(nam,suf): if suf==nam[-len(suf):]: return nam else: return nam+suf def readangle(name): b=zeros((0,2),Float) for num in "123456789": fn='angles/'+name+'.'+num+'.log' if not fexist(fn): continue f=open(fn) theta = 2*(180-float(findnext(f,thetapat).group(1)))*pi/180.0 try: e = float(findnext(f,engpat).group(1))*Hartree except AttributeError: # print '# bad energy in',name+'.'+num e=0.0 if e != 0.0: b=concatenate((b,array(((theta,e),))),axis=0) return b # return a function that evals a polynomial def poly(c): def ep(x): b=0.0 for q in c: b = q+x*b return b return ep # The derivative of a polynomial def dif(p): a=arange(len(p))[::-1] return (a*p)[:-1] def newton(f,df,g): fg=f(g) while abs(fg)>1e-8: dfg=df(g) g=g-fg/dfg fg=f(g) return g def quadmin(a,fa,b,fb,c,fc): num = (b-a)**2 * (fb-fc) - (b-c)**2 * (fb-fa) den = (b-a) * (fb-fc) - (b-c) * (fb-fa) if den == 0.0: return b return b - num / (2*den) def golden(f,a,fa,b,fb,c,fc, tol=1e-2): if c-a<tol: return quadmin(a,fa,b,fb,c,fc) if c-b > b-a: new = b+0.38197*(c-b) fnew = f(new) if fnew < fb: return golden(f, b,fb, new,fnew, c,fc) else: return golden(f, a,fa, b,fb, new, fnew) else: new = a+0.61803*(b-a) fnew = f(new) if fnew < fb: return golden(f, a, fa, new,fnew, b,fb) else: return golden(f, new, fnew, b,fb, c,fc) def ak(m): # find lowest point lo=m[0][1] ix=0 for i in range(shape(m)[0]): if m[i][1] < lo: lo=m[i][1] ix=i # take it and its neighbors for parabolic interpolation a = m[ix-1][0] fa= m[ix-1][1] b = m[ix][0] fb= m[ix][1] c = m[ix+1][0] fc= m[ix+1][1] # the lowest point on the parabola th0 = quadmin(a,fa,b,fb,c,fc) # its value via Lagrange's formula eth0 = (fa*((th0-b)*(th0-c))/((a-b)*(a-c)) + fb*((th0-a)*(th0-c))/((b-a)*(b-c)) + fc*((th0-a)*(th0-b))/((c-a)*(c-b))) # adjust points to min of 0 m=m-array([0.0,eth0]) fa= m[ix-1][1] fb= m[ix][1] fc= m[ix+1][1] # stiffness, interpolated between two triples of points # this assumes equally spaced abcissas num = (b - a)*fc + (a - c)*fb + (c - b)*fa den = (b - a)* c**2 + (a**2 - b**2 )*c + a*b**2 - a**2 * b Kth1 = 200.0 * num / den ob = b if th0>b: ix += 1 else: ix -= 1 a = m[ix-1][0] fa= m[ix-1][1] b = m[ix][0] fb= m[ix][1] c = m[ix+1][0] fc= m[ix+1][1] num = (b - a)*fc + (a - c)*fb + (c - b)*fa den = (b - a)* c**2 + (a**2 - b**2 )*c + a*b**2 - a**2 * b Kth2 = 200.0 * num / den Kth = Kth1 + (Kth2-Kth1)*(th0-ob)/(b-ob) return th0, Kth for fn in os.listdir('angles'): m=nampat.match(fn) if not m: continue name=m.group(1) m=readangle(name) ## x=m[:,0] ## xn=1.0 ## a=zeros((shape(m)[0],5),Float) ## for i in range(5): ## a[:,4-i]=xn ## xn=x*xn ## b=m[:,1] ## coef, sosr, rank, svs = linear_least_squares(a,b) ## d2f=poly(dif(dif(coef))) ## nx = newton(poly(dif(coef)), d2f, 1.5) ## print name, 'theta0=', nx, 'Ktheta=', d2f(nx) # find lowest point lo=m[0][1] ix=0 for i in range(shape(m)[0]): if m[i][1] < lo: lo=m[i][1] ix=i # take it and its neighbors for parabolic interpolation if ix==0: ix=1 if ix>len(m)-2: ix=len(m)-2 m2=m[ix-1:ix+2] x=m2[:,0] xn=1.0 a=zeros((3,3),Float) for i in [2,1,0]: a[:,i]=xn xn=x*xn b=m2[:,1] coef, sosr, rank, svs = linear_least_squares(a,b) d2f=poly(dif(dif(coef))) nx = newton(poly(dif(coef)), d2f, m2[1,0]) print name, 'theta0=', nx, 'Ktheta=', d2f(nx)
NanoCAD-master
sim/src/parameters/collang.py
#! /usr/bin/python from Numeric import * from VQT import * from LinearAlgebra import * from string import * import re import os import sys from struct import pack from stat import * datapat = re.compile("\ \$DATA") gradpat = re.compile("\ \$GRAD") hesspat = re.compile(" \$HESS") vecpat = re.compile(" \$VEC") endpat = re.compile("\ \$END") failpat = re.compile("-ABNORMALLY-") blankpat = re.compile("\s*$") equilpat = re.compile("1 \*\*\*\*\* EQUILIBRIUM GEOMETRY LOCATED \*\*\*\*\*") coordpat = re.compile(" COORDINATES") erecpat = re.compile("E\=\ +([\d\.-]+)\ +GMAX\=\ +([\d\.-]+)\ +GRMS\=\ +([\d\.-]+)") frecpat = re.compile(".+\ +\d+\.\ +([\d\.E+-]+)\ +([\d\.E+-]+)\ +([\d\.E+-]+)") irecpat = re.compile(" (\w+) +\d+\.\d* +([\d\.E+-]+) +([\d\.E+-]+) +([\d\.E+-]+)") xyzpat = re.compile("(\w+) +([\d\.E+-]+) +([\d\.E+-]+) +([\d\.E+-]+)") pdbname= re.compile("([^\.]+)\.pdb") xyzname= re.compile("([^\.]+)\.xyz") inpname= re.compile("([^\.]+)\.inp") am1p = re.compile("GBASIS=AM1") preface=["""! Gamess control file $CONTRL SCFTYP=RHF MAXIT=200 RUNTYP=optimize MULT=1 ICHARG=0 ICUT=9 ITOL=20 INTTYP=best NPRINT=-5 $END $SCF NCONV=8 dirscf=.t. DAMP=.t. SHIFT=.t. DIIS=.T. SOSCF=.T. npunch=0 $END $STATPT NSTEP=50 OPTTOL=0.0001 $END $FORCE VIBANL=.f. PRTIFC=.f. METHOD=analytic $END $SYSTEM TIMLIM=10000 MWORDS=250 $END """, """! Gamess control file $CONTRL SCFTYP=RHF MAXIT=500 RUNTYP=energy MULT=1 ICHARG=0 ICUT=9 ITOL=20 INTTYP=best NPRINT=-5 $END $SCF NCONV=8 dirscf=.t. DAMP=.t. SHIFT=.t. DIIS=.T. SOSCF=.T. npunch=0 $END $FORCE VIBANL=.f. PRTIFC=.f. METHOD=analytic $END $SYSTEM TIMLIM=10000 MWORDS=250 $END """, """! Gamess control file $CONTRL SCFTYP=RHF MAXIT=500 RUNTYP=optimize MULT=1 ICHARG=0 ICUT=9 ITOL=20 INTTYP=best NPRINT=-5 $END $SCF NCONV=8 dirscf=.t. DAMP=.t. SHIFT=.t. DIIS=.T. SOSCF=.T. npunch=0 $END $STATPT NSTEP=50 OPTTOL=0.0001 HSSEND=.true. $END $FORCE VIBANL=.f. PRTIFC=.f. METHOD=seminum $END $SYSTEM TIMLIM=10000 MWORDS=250 $END """] preface2=" $DATA\nGamess theory ladder: " preface3="\nC1\n" postface=""" $END """ dftface=""" $DFT DFTTYP=B3LYP $END """ levels=[" $BASIS GBASIS=AM1 $END\n", " $BASIS GBASIS=N21 NGAUSS=3 $END\n", " $BASIS GBASIS=N31 NGAUSS=6 $END\n", " $BASIS GBASIS=N31 NGAUSS=6 NDFUNC=1 NPFUNC=1 $END\n", " $BASIS GBASIS=N31 NGAUSS=6 NDFUNC=1 NPFUNC=1 DIFFSP=.t. $END\n", " $BASIS GBASIS=N311 NGAUSS=6 NDFUNC=2 NPFUNC=2 DIFFSP=.t. $END\n" ] schedule=[#[0, 0, 0, " am1, no dft"], [2, 0, 0, " am1, hessian"], [0, 1, 1, " 3-21G, b3lyp"]] ## [0, 2, 1, " 6-31G, b3lyp"], ## [0, 3, 1, " 6-31G(d,p), b3lyp"], ## [0, 3, 1, " 6-31G(d,p), b3lyp"], ## [0, 4, 1, " 6-31+G(d,p), b3lyp"], ## [1, 5, 1, " 6-31+G(2d,2p), b3lyp, single point energy"]] # distances are in angstroms, and delta T is 1e-16 seconds # gradients from Gamess are given in Hartrees/Bohr. To convert to N: gradU = 82.38729477e-9 # given in 1e-27 kg elmnts=[("H", 1, 1.6737), ("He", 2, 6.646), ("Li", 3, 11.525), ("Be", 4, 14.964), ("B", 5, 17.949), ("C", 6, 19.925), ("N", 7, 23.257), ("O", 8, 26.565), ("F", 9, 31.545), ("Ne", 10, 33.49), ("Na", 11, 38.1726), ("Mg", 12, 40.356), ("Al", 13, 44.7997), ("Si", 14, 46.6245), ("P", 15, 51.429), ("S", 16, 53.233), ("Cl", 17, 58.867), ("Ar", 18, 66.33), ("K", 19, 64.9256), ("Ca", 20, 66.5495), ("Sc", 21, 74.646), ("Ti", 22, 79.534), ("V", 23, 84.584), ("Cr", 24, 86.335), ("Mn", 25, 91.22), ("Fe", 26, 92.729), ("Co", 27, 97.854), ("Ni", 28, 97.483), ("Cu", 29, 105.513), ("Zn", 30, 108.541), ("Ga", 31, 115.764), ("Ge", 32, 120.53), ("As", 33, 124.401), ("Se", 34, 131.106), ("Br", 35, 132.674), ("Kr", 36, 134.429)] sym2num={} num2mass=[0] for (sym, num, mass) in elmnts: sym2num[sym] = num num2mass += [mass] def datread(fname): f=open(fname,"r") grads=zeros((0,3),Float) while 1: card = f.readline() if gradpat.match(card): break f.readline() # R= ... while 1: card = f.readline() if endpat.match(card): break m=frecpat.match(card) v=A([map(float,(m.group(1),m.group(2), m.group(3)))]) grads = concatenate((grads,v),axis=0) f.close() return grads def inpread(fname): f=open(fname+'.inp',"r") atoms = zeros((0,3),Float) elem = [] preface=" $DATA\n" postface="" while 1: card = f.readline() if datapat.match(card): break preface += f.readline() # the comment line preface += f.readline() # the symmetry line while 1: card = f.readline() if blankpat.match(card): preface += card # if non-C1 sym continue if endpat.match(card): break m=irecpat.match(card) elem += [m.group(1)] v=A([map(float,(m.group(2),m.group(3), m.group(4)))]) atoms = concatenate((atoms,v),axis=0) postface = card f.close() return elem, atoms, preface def inpwrite(fname, elem, pos, pref=" $DATA\ncomment\nC1\n"): f=open(fname+'.inp',"w") f.write(pref) for i in range(len(elem)): f.write(" %-10s %2d." % (elem[i], sym2num[elem[i]]) + " %12.7f %12.7f %12.7f" % tuple(pos[i]) + "\n") f.write(" $END\n") f.close() def xyzread(f): n=int(f.readline()) elems=[] atoms = zeros((n,3),Float) f.readline() # skip comment line for i in range(n): m=xyzpat.match(f.readline()) elems += [capitalize(m.group(1))] atoms[i]=A(map(float,(m.group(2),m.group(3), m.group(4)))) return elems, atoms def xyzwrite(f, elem, pos): f.write(str(len(elem))+"\n--comment line--\n") for i in range(len(elem)): f.write(elem[i] + " %12.7f %12.7f %12.7f" % tuple(pos[i]) + "\n") def logread(name): f=open(name+'.log',"r") while 1: card = f.readline() if failpat.search(card): print 'GAMESS bombs in',name return None, None if card == "1 ***** EQUILIBRIUM GEOMETRY LOCATED *****\n": break if card == " **** THE GEOMETRY SEARCH IS NOT CONVERGED! ****": print 'GAMESS bombs in',name return None, None f.readline() # COORDINATES ... f.readline() # ATOM CHARGE X Y Z f.readline() # ------------------------------------------------------------ atoms = zeros((0,3),Float) elem = [] while 1: card = f.readline() if len(card)<10: break if coordpat.match(card): break m=irecpat.match(card) elem += [capitalize(m.group(1))] v=A([map(float,(m.group(2),m.group(3), m.group(4)))]) atoms = concatenate((atoms,v),axis=0) return elem, atoms def dpbwrite(f, pos): global ipos npos=floor(pos*100) delta=npos-ipos ipos = npos for line in delta: f.write(pack("bbb",int(line[0]),int(line[1]),int(line[2]))) def rungms(name, elem, pos, pref): print "***** running",name," *****" inpwrite(name, elem, pos, pref) if am1p.search(pref): os.system("rungms "+name+" 1 > "+name+".log") else: os.system("rcp "+name+".inp cluster:/home/josh/working.inp") os.system("rsh cluster /home/gamess32/rungms working Nov222004R1 4 >"+name+".log") return name def makexyz(): print "making xyz files:" xyzs = {} files = os.listdir('level0') for file in files: x = xyzname.match(file) if x: xyzs[x.group(1)] = True for file in files: x = pdbname.match(file) if x and not x.group(1) in xyzs: print 'Making',x.group(1)+'.xyz' os.system("pdb2xyz " + 'level0/'+x.group(1)) def fexist(fname): try: os.stat(fname) except OSError: return False return True def dirsetup(): print "making input files:" files = os.listdir('level0') for file in files: x = xyzname.match(file) if x: name = x.group(1) if fexist('level0/'+name+'.inp'): continue elems, atoms = xyzread(open('level0/'+name+'.xyz')) inpwrite('level0/'+name, elems, atoms) def dorunrun(n): print "\nrunning Gamess at level",n fd = 'level'+str(n-1) td = 'level'+str(n) header = open(td+'/theory').read() files = os.listdir(fd) for file in files: x = inpname.match(file) if not x: continue name = x.group(1) fname = fd+'/'+name tname = td+'/'+name if fexist(tname+'.log'): continue elem, atoms, pref = inpread(fname) if fexist(fname+'.log'): elem, atoms = logread(fname) if elem: rungms(tname, elem, atoms, header+pref) if __name__ == "__main__": makexyz() dirsetup() n=1 while 1: dorunrun(n) n += 1 if not fexist('level'+str(n)): break
NanoCAD-master
sim/src/parameters/minimize.py
# Copyright (c) 2004 Nanorex, Inc. All rights reserved. """ VQT.py Vectors, Quaternions, and Trackballs Vectors are a simplified interface to the Numeric arrays. A relatively full implementation of Quaternions. Trackball produces incremental quaternions using a mapping of the screen onto a sphere, tracking the cursor on the sphere. $Id$ """ import math, types from math import * from Numeric import * from LinearAlgebra import * intType = type(2) floType = type(2.0) numTypes = [intType, floType] def V(*v): return array(v, Float) def A(a): return array(a, Float) def cross(v1, v2): return V(v1[1]*v2[2] - v1[2]*v2[1], v1[2]*v2[0] - v1[0]*v2[2], v1[0]*v2[1] - v1[1]*v2[0]) def vlen(v1): return sqrt(dot(v1, v1)) def norm(v1): lng = vlen(v1) if lng: return v1 / lng # bruce 041012 optimized this by using lng instead of # recomputing vlen(v1) -- code was v1 / vlen(v1) else: return v1+0 # p1 and p2 are points, v1 is a direction vector from p1. # return (dist, wid) where dist is the distance from p1 to p2 # measured in the direction of v1, and wid is the orthogonal # distance from p2 to the p1-v1 line. # v1 should be a unit vector. def orthodist(p1, v1, p2): dist = dot(v1, p2-p1) wid = vlen(p1+dist*v1-p2) return (dist, wid) class Q: """Q(W, x, y, z) is the quaternion with axis vector x,y,z and sin(theta/2) = W (e.g. Q(1,0,0,0) is no rotation) Q(x, y, z) where x, y, and z are three orthonormal vectors is the quaternion that rotates the standard axes into that reference frame. (the frame has to be right handed, or there's no quaternion that can do it!) Q(V(x,y,z), theta) is what you probably want. Q(vector, vector) gives the quat that rotates between them """ def __init__(self, x, y=None, z=None, w=None): # 4 numbers if w != None: self.vec=V(x,y,z,w) elif z: # three axis vectors # Just use first two a100 = V(1,0,0) c1 = cross(a100,x) if vlen(c1)<0.000001: self.vec = Q(y,z).vec return ax1 = norm((a100+x)/2.0) x2 = cross(ax1,c1) a010 = V(0,1,0) c2 = cross(a010,y) if vlen(c2)<0.000001: self.vec = Q(x,z).vec return ay1 = norm((a010+y)/2.0) y2 = cross(ay1,c2) axis = cross(x2, y2) nw = sqrt(1.0 + x[0] + y[1] + z[2])/2.0 axis = norm(axis)*sqrt(1.0-nw**2) self.vec = V(nw, axis[0], axis[1], axis[2]) elif type(y) in numTypes: # axis vector and angle v = (x / vlen(x)) * sin(y*0.5) self.vec = V(cos(y*0.5), v[0], v[1], v[2]) elif y: # rotation between 2 vectors x = norm(x) y = norm(y) v = cross(x, y) theta = acos(min(1.0,max(-1.0,dot(x, y)))) if dot(y, cross(x, v)) > 0.0: theta = 2.0 * pi - theta w=cos(theta*0.5) vl = vlen(v) # null rotation if w==1.0: self.vec=V(1, 0, 0, 0) # opposite pole elif vl<0.000001: ax1 = cross(x,V(1,0,0)) ax2 = cross(x,V(0,1,0)) if vlen(ax1)>vlen(ax2): self.vec = norm(V(0, ax1[0],ax1[1],ax1[2])) else: self.vec = norm(V(0, ax2[0],ax2[1],ax2[2])) else: s=sqrt(1-w**2)/vl self.vec=V(w, v[0]*s, v[1]*s, v[2]*s) elif type(x) in numTypes: # just one number self.vec=V(1, 0, 0, 0) else: self.vec=V(x[0], x[1], x[2], x[3]) self.counter = 50 def __getattr__(self, name): if name == 'w': return self.vec[0] elif name in ('x', 'i'): return self.vec[1] elif name in ('y', 'j'): return self.vec[2] elif name in ('z', 'k'): return self.vec[3] elif name == 'angle': if -1.0<self.vec[0]<1.0: return 2.0*acos(self.vec[0]) else: return 0.0 elif name == 'axis': return V(self.vec[1], self.vec[2], self.vec[3]) elif name == 'matrix': # this the transpose of the normal form # so we can use it on matrices of row vectors self.__dict__['matrix'] = array([\ [1.0 - 2.0*(self.y**2 + self.z**2), 2.0*(self.x*self.y + self.z*self.w), 2.0*(self.z*self.x - self.y*self.w)], [2.0*(self.x*self.y - self.z*self.w), 1.0 - 2.0*(self.z**2 + self.x**2), 2.0*(self.y*self.z + self.x*self.w)], [2.0*(self.z*self.x + self.y*self.w), 2.0*(self.y*self.z - self.x*self.w), 1.0 - 2.0 * (self.y**2 + self.x**2)]]) return self.__dict__['matrix'] else: raise AttributeError, 'No "%s" in Quaternion' % name def __getitem__(self, num): return self.vec[num] def setangle(self, theta): """Set the quaternion's rotation to theta (destructive modification). (In the same direction as before.) """ theta = remainder(theta/2.0, pi) self.vec[1:] = norm(self.vec[1:]) * sin(theta) self.vec[0] = cos(theta) self.__reset() return self def __reset(self): if self.__dict__.has_key('matrix'): del self.__dict__['matrix'] def __setattr__(self, name, value): if name=="w": self.vec[0] = value elif name=="x": self.vec[1] = value elif name=="y": self.vec[2] = value elif name=="z": self.vec[3] = value else: self.__dict__[name] = value def __len__(self): return 4 def __add__(self, q1): """Q + Q1 is the quaternion representing the rotation achieved by doing Q and then Q1. """ return Q(q1.w*self.w - q1.x*self.x - q1.y*self.y - q1.z*self.z, q1.w*self.x + q1.x*self.w + q1.y*self.z - q1.z*self.y, q1.w*self.y - q1.x*self.z + q1.y*self.w + q1.z*self.x, q1.w*self.z + q1.x*self.y - q1.y*self.x + q1.z*self.w) def __iadd__(self, q1): """this is self += q1 """ temp=V(q1.w*self.w - q1.x*self.x - q1.y*self.y - q1.z*self.z, q1.w*self.x + q1.x*self.w + q1.y*self.z - q1.z*self.y, q1.w*self.y - q1.x*self.z + q1.y*self.w + q1.z*self.x, q1.w*self.z + q1.x*self.y - q1.y*self.x + q1.z*self.w) self.vec=temp self.counter -= 1 if self.counter <= 0: self.counter = 50 self.normalize() self.__reset() return self def __sub__(self, q1): return self + (-q1) def __isub__(self, q1): return __iadd__(self, -q1) def __mul__(self, n): """multiplication by a scalar, i.e. Q1 * 1.3, defined so that e.g. Q1 * 2 == Q1 + Q1, or Q1 = Q1*0.5 + Q1*0.5 Python syntax makes it hard to do n * Q, unfortunately. """ if type(n) in numTypes: nq = +self nq.setangle(n*self.angle) return nq else: raise MulQuat def __imul__(self, q2): if type(n) in numTypes: self.setangle(n*self.angle) self.__reset() return self else: raise MulQuat def __div__(self, q2): return self*q2.conj()*(1.0/(q2*q2.conj()).w) def __repr__(self): return 'Q(%g, %g, %g, %g)' % (self.w, self.x, self.y, self.z) def __str__(self): a= "<q:%6.2f @ " % (2.0*acos(self.w)*180/pi) l = sqrt(self.x**2 + self.y**2 + self.z**2) if l: z=V(self.x, self.y, self.z)/l a += "[%4.3f, %4.3f, %4.3f] " % (z[0], z[1], z[2]) else: a += "[%4.3f, %4.3f, %4.3f] " % (self.x, self.y, self.z) a += "|%8.6f|>" % vlen(self.vec) return a def __pos__(self): return Q(self.w, self.x, self.y, self.z) def __neg__(self): return Q(self.w, -self.x, -self.y, -self.z) def conj(self): return Q(self.w, -self.x, -self.y, -self.z) def normalize(self): w=self.vec[0] v=V(self.vec[1],self.vec[2],self.vec[3]) length = vlen(v) if length: s=sqrt(1.0-w**2)/length self.vec = V(w, v[0]*s, v[1]*s, v[2]*s) else: self.vec = V(1,0,0,0) return self def unrot(self,v): return matrixmultiply(self.matrix,v) def vunrot(self,v): # for use with row vectors return matrixmultiply(v,transpose(self.matrix)) def rot(self,v): return matrixmultiply(v,self.matrix) def twistor(axis, pt1, pt2): """return the quaternion that, rotating around axis, will bring pt1 closest to pt2. """ q = Q(axis, V(0,0,1)) pt1 = q.rot(pt1) pt2 = q.rot(pt2) a1 = atan2(pt1[1],pt1[0]) a2 = atan2(pt2[1],pt2[0]) theta = a2-a1 return Q(axis, theta) # project a point from a tangent plane onto a unit sphere def proj2sphere(x, y): d = sqrt(x*x + y*y) theta = pi * 0.5 * d s=sin(theta) if d>0.0001: return V(s*x/d, s*y/d, cos(theta)) else: return V(0.0, 0.0, 1.0) class Trackball: '''A trackball object. The current transformation matrix can be retrieved using the "matrix" attribute.''' def __init__(self, wide, high): '''Create a Trackball object. "size" is the radius of the inner trackball sphere. ''' self.w2=wide/2.0 self.h2=high/2.0 self.scale = 1.1 / min(wide/2.0, high/2.0) self.quat = Q(1,0,0,0) self.oldmouse = None def rescale(self, wide, high): self.w2=wide/2.0 self.h2=high/2.0 self.scale = 1.1 / min(wide/2.0, high/2.0) def start(self, px, py): self.oldmouse=proj2sphere((px-self.w2)*self.scale, (self.h2-py)*self.scale) def update(self, px, py, uq=None): newmouse = proj2sphere((px-self.w2)*self.scale, (self.h2-py)*self.scale) if self.oldmouse and not uq: quat = Q(self.oldmouse, newmouse) elif self.oldmouse and uq: quat = uq + Q(self.oldmouse, newmouse) - uq else: quat = Q(1,0,0,0) self.oldmouse = newmouse return quat def ptonline(xpt, lpt, ldr): """return the point on a line (point lpt, direction ldr) nearest to point xpt """ ldr = norm(ldr) return dot(xpt-lpt,ldr)*ldr + lpt def planeXline(ppt, pv, lpt, lv): """find the intersection of a line (point lpt, vector lv) with a plane (point ppt, normal pv) return None if (almost) parallel (warning to callers: retvals other than None might still be false, e.g. V(0,0,0) -- untested, but likely; so don't use retval as boolean) """ d=dot(lv,pv) if abs(d)<0.000001: return None return lpt+lv*(dot(ppt-lpt,pv)/d) def cat(a,b): """concatenate two arrays (the NumPy version is a mess) """ if not a: return b if not b: return a r1 = shape(a) r2 = shape(b) if len(r1) == len(r2): return concatenate((a,b)) if len(r1)<len(r2): return concatenate((reshape(a,(1,)+r1), b)) else: return concatenate((a,reshape(b,(1,)+r2))) def Veq(v1, v2): "tells if v1 is all equal to v2" return logical_and.reduce(v1==v2) __author__ = "Josh"
NanoCAD-master
sim/src/parameters/VQT.py
#! /usr/bin/python from string import * import re import os import sys from math import sqrt parmpat = re.compile("([A-Z][a-z]?)([\+=\-@#])([A-Z][a-z]?) +Ks= *([\d\.]+) +R0= *([\d\.]+) +De= *([\d\.]+)") commpat = re.compile("#") elmnts=[("H", 1, 1.6737), ("He", 2, 6.646), ("Li", 3, 11.525), ("Be", 4, 14.964), ("B", 5, 17.949), ("C", 6, 19.925), ("N", 7, 23.257), ("O", 8, 26.565), ("F", 9, 31.545), ("Ne", 10, 33.49), ("Na", 11, 38.1726), ("Mg", 12, 40.356), ("Al", 13, 44.7997), ("Si", 14, 46.6245), ("P", 15, 51.429), ("S", 16, 53.233), ("Cl", 17, 58.867), ("Ar", 18, 66.33), ("K", 19, 64.9256), ("Ca", 20, 66.5495), ("Sc", 21, 74.646), ("Ti", 22, 79.534), ("V", 23, 84.584), ("Cr", 24, 86.335), ("Mn", 25, 91.22), ("Fe", 26, 92.729), ("Co", 27, 97.854), ("Ni", 28, 97.483), ("Cu", 29, 105.513), ("Zn", 30, 108.541), ("Ga", 31, 115.764), ("Ge", 32, 120.53), ("As", 33, 124.401), ("Se", 34, 131.106), ("Br", 35, 132.674), ("Kr", 36, 134.429)] sym2num={} for (sym, num, mass) in elmnts: sym2num[sym] = num bontyp = {'-':'1', '=':'2', '+':'3','@':'a', '#':'g'} if __name__ == "__main__": f=open(sys.argv[1]) for lin in f.readlines(): if commpat.match(lin): continue m = parmpat.match(lin) which = m.group(1),m.group(2),m.group(3) ks,r0,de = map(lambda p: float(m.group(p)),[4,5,6]) bt=sqrt(ks/(2.0*de))/10.0 r0=r0*100.0 print ' addInitialBondStretch(', print '%2d,'%sym2num[which[0]], print '%2d,'%sym2num[which[2]], print "'%s',"%bontyp[which[1]], print '%6.1f,%6.1f,%7.4f,%7.4f); //'%(ks,r0,de,bt), print which[0]+which[1]+which[2]
NanoCAD-master
sim/src/parameters/parmlist.py
#! /usr/bin/python from Numeric import * import sys import re recpat = re.compile(" *([\d\.E+-]+) +([\d\.E+-]+) +([\d\.E+-]+)") f=open(sys.argv[1]) card = f.readline() m=recpat.match(card) v=array(map(float,(m.group(1),m.group(2), m.group(3)))) while 1: card = f.readline() if len(card)<3: break m=recpat.match(card) w=array(map(float,(m.group(1),m.group(2), m.group(3)))) print (w-v)[0], (w-v)[1], (w-v)[2] v=w
NanoCAD-master
sim/src/parameters/dx.py
#! /usr/bin/python from math import * r0=1 De=1 ks=100 beta = sqrt(ks/(2*De)) def morse(r): return De*(1-exp(-sqrt(ks/(2*De))*(r-r0)))**2 def lipp(r): return De*(1-exp(-ks*r0*(r-r0)**2/(2*De*r))) def lippmor(r): if r<r0: return morse(r) - De else: return lipp(r) - De def flp(x): k1 = 4.55328 k2 = -8.24688 k3 = 4.7872 c = 4.00777 return c*(1/(k1*x**2+k2*x+k3)**16-1/(k1*x**2+k2*x+k3)**8) def fmo(x): k1 = 2303.27 k2 = 1.12845 k3 = 1.45109 c = 59.1548 k1 = 95.1566 k2 = 1.3563 k3 = 0.416429 c = 46234.9 return k1*(c/(k2+x**2)**16-1/(k3+x**2)**8) def flipmor(r): if r<1.03946: return fmo(r) else: return flp(r) for i in range(600): x=i*0.001 + .9 print x, flp(x), fmo(x) # print x, lippmor(x) # print x, flipmor(x),(flipmor(x+0.001)-flipmor(x-0.001))*1e3 ## r<0, quartic ## a = 2689.48 +/- 12.49 (0.4645%) ## b = -11027.6 +/- 48.73 (0.4419%) ## c = 16997.7 +/- 71.21 (0.419%) ## d = -11670.6 +/- 46.22 (0.396%) ## e = 3009.98 +/- 11.24 (0.3734%) ## r>0 ## a = 274.58 +/- 6.785 (2.471%) ## b = -1349 +/- 29.58 (2.193%) ## c = 2459.39 +/- 48.31 (1.964%) ## d = -1970.22 +/- 35.02 (1.777%) ## e = 584.236 +/- 9.506 (1.627%) ## for r>r0, using +/ a[i]/x^i ## a = 214.69 +/- 1.915 (0.8918%) ## b = -1092.98 +/- 9.376 (0.8578%) ## c = 2068.38 +/- 17.13 (0.8281%) ## d = -1721.46 +/- 13.83 (0.8036%) ## e = 530.38 +/- 4.168 (0.7859%)
NanoCAD-master
sim/src/parameters/lippmor.py
#! /usr/bin/python from Numeric import * from VQT import * from LinearAlgebra import * from string import * import re import os import sys from struct import pack from stat import * datapat = re.compile("\ \$DATA") gradpat = re.compile("\ \$GRAD") hesspat = re.compile(" \$HESS") vecpat = re.compile(" \$VEC") endpat = re.compile("\ \$END") termpat = re.compile(" EXECUTION OF GAMESS TERMINATED") failpat = re.compile("-ABNORMALLY-") blankpat = re.compile("\s*$") potpat = re.compile(" POTENTIAL SURFACE MAP INPUT") hevpat = re.compile(" HAS ENERGY VALUE +([\d\.-]+)") smgpat = re.compile(" ---- SURFACE MAPPING GEOMETRY ----") alphpat = re.compile(" *ALPH *[\d\.-]+ *[\d\.-]+ *([\d\.-]+)") betapat = re.compile(" +\d+ +BETA +([\d\.]+)") c1pat = re.compile(" \d C +([\d\.]+)") b3pat = re.compile(" FINAL U-B3LYP ENERGY IS +([\d\.-]+)") equilpat = re.compile("1 \*\*\*\*\* EQUILIBRIUM GEOMETRY LOCATED \*\*\*\*\*") erecpat = re.compile("E\=\ +([\d\.-]+)\ +GMAX\=\ +([\d\.-]+)\ +GRMS\=\ +([\d\.-]+)") frecpat = re.compile(".+\ +\d+\.\ +([\d\.E+-]+)\ +([\d\.E+-]+)\ +([\d\.E+-]+)") irecpat = re.compile(" (\w+) +\d+\.\d* +([\d\.E+-]+) +([\d\.E+-]+) +([\d\.E+-]+)") grecpat = re.compile("\w+ +\d+\.\d* +([\d\.E+-]+) +([\d\.E+-]+) +([\d\.E+-]+)") xyzpat = re.compile("(\w+) +([\d\.E+-]+) +([\d\.E+-]+) +([\d\.E+-]+)") pdbname= re.compile("([^\.]+)\.pdb") xyzname= re.compile("([^\.]+)\.xyz") inpname= re.compile("([^\.]+)\.inp") moiname= re.compile("(\w+)([=\-\+])\.moi$") am1p = re.compile("GBASIS=AM1") preface="""! Gamess control file $CONTRL SCFTYP=UHF MAXIT=200 RUNTYP=surface MULT=1 ICHARG=0 ICUT=9 ITOL=20 INTTYP=best NPRINT=-5 $END $SCF NCONV=8 dirscf=.t. DAMP=.t. SHIFT=.t. DIIS=.T. SOSCF=.T. npunch=0 $END $STATPT NSTEP=50 OPTTOL=0.0001 $END $FORCE VIBANL=.f. PRTIFC=.f. $END $SYSTEM TIMLIM=10000 MWORDS=250 $END $BASIS GBASIS=N31 NGAUSS=6 NDFUNC=1 NPFUNC=1 DIFFSP=.t. $END $DFT DFTTYP=B3LYP $END """ triplet="""! Gamess control file $CONTRL SCFTYP=UHF MAXIT=200 RUNTYP=energy MULT=3 ICHARG=0 ICUT=9 ITOL=20 INTTYP=best NPRINT=-5 $END $SCF NCONV=5 dirscf=.t. DAMP=.t. SHIFT=.t. DIIS=.T. SOSCF=.T. npunch=0 $END $STATPT NSTEP=50 OPTTOL=0.0001 $END $FORCE VIBANL=.f. PRTIFC=.f. $END $SYSTEM TIMLIM=10000 MWORDS=250 $END $BASIS GBASIS=N31 NGAUSS=6 NDFUNC=1 NPFUNC=1 DIFFSP=.t. $END $DFT DFTTYP=B3LYP $END """ # distances are in angstroms, and delta T is 1e-16 seconds # gradients from Gamess are given in Hartrees/Bohr. To convert to N: gradU = 82.38729477e-9 Hartree = 4.3597482 # attoJoules Bohr = 0.5291772083 # Angstroms # given in 1e-27 kg elmnts=[("H", 1, 1.6737), ("He", 2, 6.646), ("Li", 3, 11.525), ("Be", 4, 14.964), ("B", 5, 17.949), ("C", 6, 19.925), ("N", 7, 23.257), ("O", 8, 26.565), ("F", 9, 31.545), ("Ne", 10, 33.49), ("Na", 11, 38.1726), ("Mg", 12, 40.356), ("Al", 13, 44.7997), ("Si", 14, 46.6245), ("P", 15, 51.429), ("S", 16, 53.233), ("Cl", 17, 58.867), ("Ar", 18, 66.33), ("K", 19, 64.9256), ("Ca", 20, 66.5495), ("Sc", 21, 74.646), ("Ti", 22, 79.534), ("V", 23, 84.584), ("Cr", 24, 86.335), ("Mn", 25, 91.22), ("Fe", 26, 92.729), ("Co", 27, 97.854), ("Ni", 28, 97.483), ("Cu", 29, 105.513), ("Zn", 30, 108.541), ("Ga", 31, 115.764), ("Ge", 32, 120.53), ("As", 33, 124.401), ("Se", 34, 131.106), ("Br", 35, 132.674), ("Kr", 36, 134.429)] sym2num={} num2mass=[0] for (sym, num, mass) in elmnts: sym2num[sym] = num num2mass += [mass] def findnext(f,pat): while 1: card = f.readline() if not card: return None m = pat.match(card) if m: return m def datread(fname): f=open(fname,"r") grads=zeros((0,3),Float) while 1: card = f.readline() if gradpat.match(card): break f.readline() # R= ... while 1: card = f.readline() if endpat.match(card): break m=frecpat.match(card) v=A([map(float,(m.group(1),m.group(2), m.group(3)))]) grads = concatenate((grads,v),axis=0) f.close() return grads # read a moiety, consisting of a chunk of a $data section only def moiread(fname): f=open(fname+'.moi',"r") atoms = zeros((0,3),Float) elem = [] while 1: card = f.readline() if blankpat.match(card): break m=irecpat.match(card) elem += [capitalize(m.group(1))] v=A([map(float,(m.group(2),m.group(3), m.group(4)))]) atoms = concatenate((atoms,v),axis=0) f.close() return elem, atoms def inpread(fname): f=open(fname+'.inp',"r") atoms = zeros((0,3),Float) elem = [] preface="" postface="" while 1: card = f.readline() preface += card if datapat.match(card): break preface += f.readline() # the comment line preface += f.readline() # the C1 line while 1: card = f.readline() if endpat.match(card): break m=irecpat.match(card) elem += [capitalize(m.group(1))] v=A([map(float,(m.group(2),m.group(3), m.group(4)))]) atoms = concatenate((atoms,v),axis=0) postface = card f.close() return elem, atoms def absetup(e1, e2): sym2num['ALPH']= sym2num[e1[0]] sym2num['BETA']= sym2num[e2[0]] e1[0] = 'ALPH' e2[0] = 'BETA' return e1, e2 def inpwrite(fname, elem, pos, pref=" $DATA\nComment\nC1\n"): f=open(fname+'.inp',"w") f.write(pref) for i in range(len(elem)): f.write(" %-10s %2d." % (elem[i], sym2num[elem[i]]) + " %12.7f %12.7f %12.7f" % tuple(pos[i]) + "\n") f.write(" $END\n") f.close() def xyzread(f): n=int(f.readline()) elems=[] atoms = zeros((n,3),Float) f.readline() # skip comment line for i in range(n): m=xyzpat.match(f.readline()) elems += [capitalize(m.group(1))] atoms[i]=A(map(float,(m.group(2),m.group(3), m.group(4)))) return elems, atoms def xyzwrite(f, elem, pos): f.write(str(len(elem))+"\n--comment line--\n") for i in range(len(elem)): f.write(elem[i] + " %12.7f %12.7f %12.7f" % tuple(pos[i]) + "\n") def xeread(name): f=open(name+'.log',"r") x = [] e= [] t = False findnext(f, potpat) while 1: m = findnext(f, betapat) m1 = findnext(f,hevpat) if not (m and m1): break x += [float(m.group(1))] e += [float(m1.group(1))*Hartree] f.close() return x,e def logread(name): f=open(name+'.log',"r") while 1: card = f.readline() if failpat.search(card): print card sys.exit(1) if card == "1 ***** EQUILIBRIUM GEOMETRY LOCATED *****\n": break if card == " **** THE GEOMETRY SEARCH IS NOT CONVERGED! ****": print card sys.exit(1) f.readline() # COORDINATES OF ALL ATOMS ARE (ANGS) f.readline() # ATOM CHARGE X Y Z f.readline() # ------------------------------------------------------------ atoms = zeros((0,3),Float) elem = [] while 1: card = f.readline() if len(card)<10: break m=irecpat.match(card) elem += [capitalize(m.group(1))] v=A([map(float,(m.group(2),m.group(3), m.group(4)))]) atoms = concatenate((atoms,v),axis=0) return elem, atoms def dpbwrite(f, pos): global ipos npos=floor(pos*100) delta=npos-ipos ipos = npos for line in delta: f.write(pack("bbb",int(line[0]),int(line[1]),int(line[2]))) def rungms(name, elem, pos, pref): print "***** running",name," *****" inpwrite(name, elem, pos, pref) if am1p.search(pref): os.system("rungms "+name+" 1 > "+name+".log") else: os.system("rcp "+name+".inp cluster:/home/josh/working.inp") os.system("rsh cluster /home/gamess32/rungms working Nov222004R1 4 >"+name+".log") return name def makexyz(): print "making xyz files:" xyzs = {} files = os.listdir('.') for file in files: x = xyzname.match(file) if x: xyzs[x.group(1)] = True for file in files: x = pdbname.match(file) if x and not x.group(1) in xyzs: print 'Making',x.group(1)+'.xyz' os.system("pdb2xyz " + x.group(1)) def fexist(fname): try: os.stat(fname) except OSError: return False return True def dirsetup(): print "making input files:" files = os.listdir('.') for file in files: x = xyzname.match(file) if x: name = x.group(1) if fexist('level0/'+name+'.inp'): continue elems, atoms = xyzread(open(name+'.xyz')) inpwrite('level0/'+name, elems, atoms) def dorunrun(n): print "running Gamess at level",n fd = 'level'+str(n-1) td = 'level'+str(n) header = open(td+'/theory').read() files = os.listdir(fd) for file in files: x = inpname.match(file) if not x: continue name = x.group(1) fname = fd+'/'+name tname = td+'/'+name if fexist(tname+'.inp'): continue if fexist(fname+'.log'): elem, atoms = logread(fname) else: elem, atoms = inpread(fname) rungms(tname, elem, atoms, header) De=0.556 # R0=1.523 Beta=1.989 def morse(r,de,beta, R0): return de*(1-exp(-beta*(r-R0)))**2 def diff(de, e, x, ix, Ks, R0): sum = 0.0 beta = sqrt(Ks/(2.0*de)) /10.0 for i in range(ix): sum += (e[i]-morse(x[i],de,beta, R0))**2 return sum def quadmin(a,fa,b,fb,c,fc): num = (b-a)**2 * (fb-fc) - (b-c)**2 * (fb-fa) den = (b-a) * (fb-fc) - (b-c) * (fb-fa) if den == 0.0: return b return b - num / (2*den) def golden(f,a,fa,b,fb,c,fc, tol=1e-2): ## print 'Searching:',a,b,c ## print '[',fa, fb, fc,']' if c-a<tol: return quadmin(a,fa,b,fb,c,fc) if c-b > b-a: new = b+0.38197*(c-b) fnew = f(new) if fnew < fb: return golden(f, b,fb, new,fnew, c,fc) else: return golden(f, a,fa, b,fb, new, fnew) else: new = a+0.61803*(b-a) fnew = f(new) if fnew < fb: return golden(f, a, fa, new,fnew, b,fb) else: return golden(f, new, fnew, b,fb, c,fc) def texvec(v): if len(v)>1: return str(v[0])+','+texvec(v[1:]) if v: return str(v[0]) return '' def surfgen(fqbn, x1, x2): b = " $SURF ivec1(1)=1,"+str(1+len(x1)) b += " igrp1(1)="+texvec(map(lambda x: 1+len(x1)+x, range(len(x2)))) dx = x1[0][2]+x2[0][2] b += "\n orig1="+str(-0.33*dx) b += " disp1="+str(dx*0.01)+" ndisp1=50 $END\n" b += " $DATA\n *** Parm Gen for "+fqbn+"\nC1\n" return b def enggen(fqbn): return " $DATA\n *** Separated energy for "+fqbn+"\nC1\n" def surfread(filnam, zero): x,e = xeread('bonds/'+filnam) # find lowest point lo=e[0] ix=0 for i in range(len(x)): if e[i] < lo: lo=e[i] ix=i # take it and its neighbors for parabolic interpolation a = x[ix-1] fa= e[ix-1] b = x[ix] fb= e[ix] c = x[ix+1] fc= e[ix+1] # the lowest point on the parabola R0 = quadmin(a,fa,b,fb,c,fc) # its value via Lagrange's formula fR0 = (fa*((R0-b)*(R0-c))/((a-b)*(a-c)) + fb*((R0-a)*(R0-c))/((b-a)*(b-c)) + fc*((R0-a)*(R0-b))/((c-a)*(c-b))) # adjust points to min of 0 for i in range(len(x)): e[i]=e[i]-fR0 fa= e[ix-1] fb= e[ix] fc= e[ix+1] # stiffness, interpolated between two triples of points # this assumes equally spaced abcissas num = (b - a)*fc + (a - c)*fb + (c - b)*fa den = (b - a)* c**2 + (a**2 - b**2 )*c + a*b**2 - a**2 * b Ks1 = 200.0 * num / den ob = b if R0>b: ix += 1 else: ix -= 1 a = x[ix-1] fa= e[ix-1] b = x[ix] fb= e[ix] c = x[ix+1] fc= e[ix+1] num = (b - a)*fc + (a - c)*fb + (c - b)*fa den = (b - a)* c**2 + (a**2 - b**2 )*c + a*b**2 - a**2 * b Ks2 = 200.0 * num / den Ks = Ks1 + (Ks2-Ks1)*(R0-ob)/(b-ob) # now search for De by fitting a morse curve to the points delo = 0.2 dehi = 1.7 demd = delo + 0.61803*(dehi-delo) De = golden(lambda d: diff(d, e, x, ix, Ks, R0), delo, diff(delo, e, x, ix, Ks, R0), demd, diff(demd, e, x, ix, Ks, R0), dehi, diff(dehi, e, x, ix, Ks, R0)) if zero != 0.0: De = zero-fR0 Beta=sqrt(Ks/(2.0*De))/10.0 return Ks, R0, De def deread(nam): f=open('bonds/'+nam+'.De.log','r') z=0.0 while 1: m=findnext(f, b3pat) if not m: break q=float(m.group(1)) if q != 0.0: z=q*Hartree return z ## if __name__ == "__main__": ## files = os.listdir('moieties') ## for i in range(len(files)): ## f1 = moiname.match(files[i]) ## if f1: ## f1el, f1bn = f1.groups() ## for f2 in files[i:]: ## m = moiname.match(f2) ## if not m: continue ## f2el, f2bn = m.groups() ## if f1bn != f2bn: continue ## fqbn=f1el+f1bn+f2el ## #if fexist('bonds/'+fqbn+'.parms'): continue ## print 'Doing',fqbn ## el, pos = moiread('moieties/'+f1el+f1bn) ## el2, pos2 = moiread('moieties/'+f2el+f2bn) ## #el, el2 = absetup(el, el2) ## rungms('bonds/'+fqbn+'.De', ## el+el2, ## concatenate((pos+V(0,0,4), -pos2),axis=0), ## triplet+enggen(fqbn)) if __name__ == "__main__": files = os.listdir('bonds') logfiles = filter(lambda x: x[-4:]=='.log', files) defiles = filter(lambda x: x[-7:]=='.De.log', logfiles) logfiles = filter(lambda x: x not in defiles, logfiles) fn = map(lambda x: x[:-4], logfiles) for f in fn: if fexist('bonds/'+f+'.De.log'): zero = deread(f) else: zero=0.0 if zero==0.0: print '###',f,'-- no energy zero' print f,'Ks=%7.2f R0=%7.4f De=%7.4f' % surfread(f,zero)
NanoCAD-master
sim/src/parameters/morgames.py
#! /usr/bin/python import os import sys import re from string import * from math import sqrt leftpat=re.compile('([A-Z][a-z]?)([=+#@-])\.moi$') rightpat=re.compile('([=+#@-])([A-Z][a-z]?)\.moi$') centerpat=re.compile('([=+#@-])([A-Z][a-z]?)([=+#@-])\.moi$') thetapat=re.compile(" *theta *= *([\d\.]+)") parmpat = re.compile("([A-Z][a-z]?)([\+=\-@#])([A-Z][a-z]?) +Ks= *([\d\.]+) +R0= *([\d\.]+) +De= *([\d\.]+)") commpat = re.compile("#") pref="""! Gamess control file $CONTRL SCFTYP=UHF MAXIT=200 RUNTYP=energy MULT=1 ICHARG=0 ICUT=9 ITOL=20 INTTYP=best COORD=zmt nprint=-5 $END $SCF NCONV=5 dirscf=.t. DAMP=.t. SHIFT=.t. DIIS=.T. npunch=0 $END $STATPT NSTEP=50 OPTTOL=0.0001 IFREEZ(1)=1,2,3 $END $FORCE VIBANL=.f. PRTIFC=.f. $END $SYSTEM TIMLIM=10000 MWORDS=250 $END ! $BASIS GBASIS=AM1 $END $BASIS GBASIS=N31 NGAUSS=6 NDFUNC=1 NPFUNC=1 DIFFSP=.t. $END $DFT DFTTYP=B3LYP $END $DATA *** bending for %s C1 """ angs=[('.1',-30),('.2',-20),('.3',-15),('.4',-7),('.5',0), ('.6',7),('.7',15),('.8',20),('.9',30)] bontyp = {'-':'1', '=':'2', '+':'3','@':'a', '#':'g'} Rzeros={} f=open('stretch.parms') for lin in f.readlines(): if commpat.match(lin): continue m = parmpat.match(lin) l,b,r = m.group(1),m.group(2),m.group(3) ks,r0,de = map(lambda p: float(m.group(p)),[4,5,6]) Rzeros[l+b+r]=r0 Rzeros[r+b+l]=r0 lefts = [] rights = [] centers = [] for fn in os.listdir('moieties'): if leftpat.match(fn): lefts += [fn] if rightpat.match(fn): rights += [fn] if centerpat.match(fn): centers += [fn] ### hack rights = ['-B.moi'] for c in centers: m=centerpat.match(c) ce=m.group(2) clb=m.group(1) crb=m.group(3) # print c for l in lefts: m=leftpat.match(l) le=m.group(1) lb=m.group(2) if lb != clb: continue # print l for r in rights: m=rightpat.match(r) re=m.group(2) rb=m.group(1) if rb != crb: continue # print r name = le+lb+ce+rb+re print name for nmx,dth in angs: of = open(name+nmx+'.inp','w') of.write(pref % name) cf = open('moieties/'+c) thetlin=cf.readline() theta = float(thetapat.match(thetlin).group(1)) + dth for ln in cf.readlines(): of.write(ln) for ln in open('moieties/'+l).readlines(): of.write(ln) for ln in open('moieties/'+r).readlines(): of.write(ln) of.write('\n') of.write(' theta = %f\n' % theta) of.write(' dxl = %f\n' % Rzeros[le+lb+ce]) of.write(' dxr = %f\n' % Rzeros[ce+rb+re]) of.write(' $END\n') of.close()
NanoCAD-master
sim/src/parameters/genang.py
#!/usr/bin/env python3 import argparse import random import os import numpy as np import torch from habitat import logger from habitat_baselines.common.baseline_registry import baseline_registry import habitat_extensions # noqa: F401 import vlnce_baselines # noqa: F401 from vlnce_baselines.config.default import get_config # from vlnce_baselines.nonlearning_agents import ( # evaluate_agent, # nonlearning_inference, # ) def main(): parser = argparse.ArgumentParser() parser.add_argument( "--exp_name", type=str, default="test", required=True, help="experiment id that matches to exp-id in Notion log", ) parser.add_argument( "--run-type", choices=["train", "eval", "inference"], required=True, help="run type of the experiment (train, eval, inference)", ) parser.add_argument( "--exp-config", type=str, required=True, help="path to config yaml containing info about experiment", ) parser.add_argument( "opts", default=None, nargs=argparse.REMAINDER, help="Modify config options from command line", ) parser.add_argument('--local_rank', type=int, default=0, help="local gpu id") args = parser.parse_args() run_exp(**vars(args)) def run_exp(exp_name: str, exp_config: str, run_type: str, opts=None, local_rank=None) -> None: r"""Runs experiment given mode and config Args: exp_config: path to config file. run_type: "train" or "eval. opts: list of strings of additional config options. Returns: None. """ config = get_config(exp_config, opts) config.defrost() if run_type != 'train': config.IL.resume = False config.TENSORBOARD_DIR += exp_name config.CHECKPOINT_FOLDER += exp_name config.CEPH_URL += exp_name if os.path.isdir(config.EVAL_CKPT_PATH_DIR): config.EVAL_CKPT_PATH_DIR += exp_name config.RESULTS_DIR += exp_name config.VIDEO_DIR += exp_name # config.TASK_CONFIG.TASK.RXR_INSTRUCTION_SENSOR.max_text_len = config.IL.max_text_len config.LOG_FILE = exp_name + '_' + config.LOG_FILE if 'CMA' in config.MODEL.policy_name and 'r2r' in config.BASE_TASK_CONFIG_PATH: config.TASK_CONFIG.DATASET.DATA_PATH = 'data/datasets/R2R_VLNCE_v1-2_preprocessed/{split}/{split}.json.gz' config.local_rank = local_rank config.freeze() os.system("mkdir -p data/logs/running_log") logger.add_filehandler('data/logs/running_log/'+config.LOG_FILE) random.seed(config.TASK_CONFIG.SEED) np.random.seed(config.TASK_CONFIG.SEED) torch.manual_seed(config.TASK_CONFIG.SEED) torch.backends.cudnn.benchmark = False torch.backends.cudnn.deterministic = False if torch.cuda.is_available(): torch.set_num_threads(1) # if run_type == "eval" and config.EVAL.EVAL_NONLEARNING: # evaluate_agent(config) # return # if run_type == "inference" and config.INFERENCE.INFERENCE_NONLEARNING: # nonlearning_inference(config) # return trainer_init = baseline_registry.get_trainer(config.TRAINER_NAME) assert trainer_init is not None, f"{config.TRAINER_NAME} is not supported" trainer = trainer_init(config) # import pdb; pdb.set_trace() if run_type == "train": trainer.train() elif run_type == "eval": trainer.eval() elif run_type == "inference": trainer.inference() if __name__ == "__main__": main()
InternVideo-main
Downstream/Visual-Language-Navigation/run.py