示例#1
0
 def update(self):
     """
     Update the image object.
     """
     # Without saving/opening, 'tostring()' is not working right.
     # [bruce guess 061127 about the cause: maybe related to ops that don't
     #  work before or after image is loaded. The docs mentioned elsewhere
     #  are not very clear about this.]
     import os
     from platform_dependent.PlatformDependent import find_or_make_Nanorex_subdir
     nhdir = find_or_make_Nanorex_subdir("Nano-Hive")
     basename = os.path.basename(self.imageName)
     if self._tmpmode:
         # change file extension of tmp file to correspond with the format we'll store in it
         # [this is not needed (I think) except to not fool people who stumble upon the temporary file]
         basename, extjunk = os.path.splitext(basename)
         basename = "%s.%s" % (basename, self._tmpmode)
     newName = os.path.join(nhdir, 'temp_' + basename)
         ###e change file extension to one that always supports self.DESIRED_MODE? (or specify it in save command)
     oldmode = self.img.mode #bruce 061127
     if self._tmpmode:
         self.img.save(newName, self._tmpmode) #bruce 061128 experimental, hopefully a temporary kluge
     else:
         self.img.save(newName)
         # if we use self.convert to convert PNG RGBA to RGBX, this can raise an exception:
         ## IOError: cannot write mode RGBX as PNG
     self.img = Image.open(newName)
     newmode = self.img.mode
     if oldmode != newmode and debug_flags.atom_debug and self.debug: #k does this ever happen??
         print "debug warning: oldmode != newmode (%r != %r) in %r.update" % (oldmode, newmode, self)
示例#2
0
    def viewDnaOrderFile(self, openFileInEditor = True):
        """
        Opens a text editor and loads a temporary text file containing all the 
        DNA strand names and their sequences in the current DNA object. It will
        look something like this: 

        Strand1,ATCAGCTACGCATCGCT
        Strand2,TAGTCGATGCGTAGCGA
        ...
        Strandn, ...

        The user can then save the file to a permanent location using the 
        text editor the file is loaded (and displayed) in.

        @see: Ui_DnaFlyout.orderDnaCommand
        @see: writeDnaOrderFile()
        @TODO: assy.getAllDnaObjects(). 
        """
        dnaSequence = self.getDnaSequence(format = 'CSV')

        if dnaSequence: 
            tmpdir = find_or_make_Nanorex_subdir('temp')
            fileBaseName = 'DnaOrder'
            temporaryFile = os.path.join(tmpdir, "%s.csv" % fileBaseName)            
            writeDnaOrderFile(temporaryFile, 
                              self.assy,
                              dnaSequence)      

            if openFileInEditor:
                open_file_in_editor(temporaryFile)
示例#3
0
 def update(self):
     """
     Update the image object.
     """
     # Without saving/opening, 'tostring()' is not working right.
     # [bruce guess 061127 about the cause: maybe related to ops that don't
     #  work before or after image is loaded. The docs mentioned elsewhere
     #  are not very clear about this.]
     import os
     from platform_dependent.PlatformDependent import find_or_make_Nanorex_subdir
     nhdir = find_or_make_Nanorex_subdir("Nano-Hive")
     basename = os.path.basename(self.imageName)
     if self._tmpmode:
         # change file extension of tmp file to correspond with the format we'll store in it
         # [this is not needed (I think) except to not fool people who stumble upon the temporary file]
         basename, extjunk = os.path.splitext(basename)
         basename = "%s.%s" % (basename, self._tmpmode)
     newName = os.path.join(nhdir, 'temp_' + basename)
     ###e change file extension to one that always supports self.DESIRED_MODE? (or specify it in save command)
     oldmode = self.img.mode  #bruce 061127
     if self._tmpmode:
         self.img.save(
             newName, self._tmpmode
         )  #bruce 061128 experimental, hopefully a temporary kluge
     else:
         self.img.save(newName)
         # if we use self.convert to convert PNG RGBA to RGBX, this can raise an exception:
         ## IOError: cannot write mode RGBX as PNG
     self.img = Image.open(newName)
     newmode = self.img.mode
     if oldmode != newmode and debug_flags.atom_debug and self.debug:  #k does this ever happen??
         print "debug warning: oldmode != newmode (%r != %r) in %r.update" % (
             oldmode, newmode, self)
    def viewDnaOrderFile(self, openFileInEditor=True):
        """
        Writes a DNA Order file in comma-separated values (CSV) format 
        and opens it in a text editor.

        The user must save the file to a permanent location using the 
        text editor.

        @see: Ui_DnaFlyout.orderDnaCommand
        @see: writeDnaOrderFile()
        @TODO: assy.getAllDnaObjects(). 
        """
        dnaSequence = self.getDnaSequence(format='CSV')

        if dnaSequence:
            tmpdir = find_or_make_Nanorex_subdir('temp')
            fileBaseName = 'DnaOrder'
            temporaryFile = os.path.join(tmpdir, "%s.csv" % fileBaseName)
            writeDnaOrderFile(temporaryFile, self.assy,
                              self.getNumberOfBases(),
                              self.getNumberOfBases(unassignedOnly=True),
                              dnaSequence)

            if openFileInEditor:
                open_file_in_editor(temporaryFile)

        return
示例#5
0
def _tempfilename(basename):  # todo: rename, refile
    """
    @warning: does not check whether file already exists.
    """
    tmpdir = find_or_make_Nanorex_subdir(
        "TemporaryFiles")  # also hardcoded elsewhere
    return os.path.join(tmpdir, basename)
    def viewDnaOrderFile(self, openFileInEditor = True):
        """
        Writes a DNA Order file in comma-separated values (CSV) format 
        and opens it in a text editor.

        The user must save the file to a permanent location using the 
        text editor.

        @see: Ui_DnaFlyout.orderDnaCommand
        @see: writeDnaOrderFile()
        @TODO: assy.getAllDnaObjects(). 
        """
        dnaSequence = self.getDnaSequence(format = 'CSV')

        if dnaSequence: 
            tmpdir = find_or_make_Nanorex_subdir('temp')
            fileBaseName = 'DnaOrder'
            temporaryFile = os.path.join(tmpdir, "%s.csv" % fileBaseName)            
            writeDnaOrderFile(temporaryFile, 
                              self.assy,
                              self.getNumberOfBases(),
                              self.getNumberOfBases(unassignedOnly = True),
                              dnaSequence)      

            if openFileInEditor:
                open_file_in_editor(temporaryFile)
                
        return
示例#7
0
    def calculate_esp(self):

        cmd = greenmsg("Calculate ESP: ")

        errmsgs = [ # warning: their indices in this list matter.
            "Error: Nano-Hive plug-in not enabled.",
            "Error: Nano-Hive Plug-in path is empty.",
            "Error: Nano-Hive plug-in path points to a file that does not exist.",
            "Error: Nano-Hive plug-in is not Version 1.2b.",
            "Error: Couldn't connect to Nano-Hive instance.",
            "Error: Load command failed.",
            "Error: Run command failed.",
            "Simulation Aborted"
         ]

        sim_parms = self.get_sim_parms()
        sims_to_run = ["MPQC_ESP"]
        results_to_save = [] # Results info included in write_nh_mpqc_esp_rec()

        # Temporary file name of ESP image file.
        nhdir = find_or_make_Nanorex_subdir("Nano-Hive")
        tmp_espimage_file = os.path.join(nhdir, "%s.png" % (self.name))

        # Destination (permanent) file name of ESP image file.
        espimage_file = get_nh_espimage_filename(self.assy, self.name)

        msg = "Running ESP calculation on [%s]. " \
              "Results will be written to: [%s]" % (self.name, espimage_file)
        env.history.message( cmd + msg ) 

        r = run_nh_simulation(self.assy, 'CalcESP', 
                              sim_parms, sims_to_run, results_to_save)

        if r:
            msg = redmsg(errmsgs[r - 1])
            env.history.message( cmd + msg )
            return

        msg = "ESP calculation on [%s] finished." % (self.name)
        env.history.message( cmd + msg ) 

        # Move tmp file to permanent location. Make sure the tmp file is there.
        if os.path.exists(tmp_espimage_file):
            shutil.move(tmp_espimage_file, espimage_file)
        else:
            print "Temporary ESP Image file ", tmp_espimage_file, \
                  " does not exist. Image not loaded."
            return

        self.espimage_file = espimage_file
        self.load_espimage_file()
        self.assy.changed()
        self.assy.w.win_update()

        return
示例#8
0
def get_nh_simspec_filename(basename):
    """
    Return the full path of the Nano-Hive simulation specification file.
    """
    if basename:
        nhdir = find_or_make_Nanorex_subdir("Nano-Hive")
        fn = os.path.normpath(os.path.join(nhdir,str(basename)+"-sim.xml"))
        #print "get_nh_simspec_filename(): filename=", fn
        return fn
    else:
        return None
示例#9
0
def get_nh_workflow_filename(basename):
    """
    Return the full path of the Nano-Hive workflow file.
    """
    if basename:
        nhdir = find_or_make_Nanorex_subdir("Nano-Hive")
        fn = os.path.normpath(os.path.join(nhdir,str(basename)+"-flow.tcl"))
        #print "get_nh_workflow_filename(): filename=", fn
        return fn
    else:
        return None
示例#10
0
def get_nh_mmp_filename(basename):
    """
    Return the full path of the Nano-Hive MMP input file.
    """
    if basename:
        nhdir = find_or_make_Nanorex_subdir("Nano-Hive")
        fn = os.path.normpath(os.path.join(nhdir, str(basename) + ".mmp"))
        # print "get_nh_mmp_filename(): filename=", fn
        return fn
    else:
        return None
示例#11
0
def get_nh_workflow_filename(basename):
    """
    Return the full path of the Nano-Hive workflow file.
    """
    if basename:
        nhdir = find_or_make_Nanorex_subdir("Nano-Hive")
        fn = os.path.normpath(os.path.join(nhdir, str(basename) + "-flow.tcl"))
        # print "get_nh_workflow_filename(): filename=", fn
        return fn
    else:
        return None
示例#12
0
def get_nh_simspec_filename(basename):
    """
    Return the full path of the Nano-Hive simulation specification file.
    """
    if basename:
        nhdir = find_or_make_Nanorex_subdir("Nano-Hive")
        fn = os.path.normpath(os.path.join(nhdir, str(basename) + "-sim.xml"))
        # print "get_nh_simspec_filename(): filename=", fn
        return fn
    else:
        return None
示例#13
0
def get_nh_mmp_filename(basename):
    """
    Return the full path of the Nano-Hive MMP input file.
    """
    if basename:
        nhdir = find_or_make_Nanorex_subdir("Nano-Hive")
        fn = os.path.normpath(os.path.join(nhdir,str(basename)+".mmp"))
        #print "get_nh_mmp_filename(): filename=", fn
        return fn
    else:
        return None
def getFavoriteTempFilename():
    """
    Returns the full path to the single Lighting Scheme favorite temporary file.
    
    @note: The fullpath returned is
           $HOME/Nanorex/temp/LightingSchemeTempfile.txt.
    """
    _basename = "LightingSchemeTempfile"
    _ext = "txt"

    # Make favorite filename (i.e. ~/Nanorex/Favorites/LightingScheme/basename.txt)
    from platform_dependent.PlatformDependent import find_or_make_Nanorex_subdir
    _dir = find_or_make_Nanorex_subdir('temp')
    return os.path.join(_dir, "%s.%s" % (_basename, _ext))
def getFavoriteTempFilename():
    """
    Returns the full path to the single Lighting Scheme favorite temporary file.
    
    @note: The fullpath returned is
           $HOME/Nanorex/temp/LightingSchemeTempfile.txt.
    """
    _basename = "LightingSchemeTempfile"
    _ext = "txt"
    
    # Make favorite filename (i.e. ~/Nanorex/Favorites/LightingScheme/basename.txt)
    from platform_dependent.PlatformDependent import find_or_make_Nanorex_subdir
    _dir = find_or_make_Nanorex_subdir('temp')
    return os.path.join(_dir, "%s.%s" % (_basename, _ext))
示例#16
0
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 (supresses 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
示例#17
0
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 (supresses 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
示例#18
0
def getFavoritePathFromBasename( basename ):
    """
    Returns the full path to the favorite file given a basename.

    @param basename: The favorite filename (without the .txt extension).
    @type  basename: string

    @note: The (default) directory for all favorite files is
           $HOME/Nanorex/Favorites/ProteinDisplayStyle.
    """
    _ext = "txt"

    # Make favorite filename (i.e. ~/Nanorex/Favorites/ProteinDisplayStyleFavorites/basename.txt)
    from platform_dependent.PlatformDependent import find_or_make_Nanorex_subdir
    _dir = find_or_make_Nanorex_subdir('Favorites/ProteinDisplayStyle')
    return os.path.join(_dir, "%s.%s" % (basename, _ext))
示例#19
0
    def open_tmp_inputfile(self):
        '''Writes a temporary GAMESS inputfile of the current Gamess jig and opens the
        file in an editor.
        '''
        # Make tmp_inputfile filename (i.e. ~/Nanorex/temp/jigname_parms_info.inp)
        from platform_dependent.PlatformDependent import find_or_make_Nanorex_subdir
        tmpdir = find_or_make_Nanorex_subdir('temp')
        basename = self.gamessJig.name + "-" + self.gamessJig.gms_parms_info('_')
        tmp_inputfile = os.path.join(tmpdir, "%s.inp" % basename)

        # Write INP file (in ~/Nanorex/temp subdirectory)
        from analysis.GAMESS.files_gms import writegms_inpfile
        writegms_inpfile(tmp_inputfile, self.gamessJig)

        from platform_dependent.PlatformDependent import open_file_in_editor
        open_file_in_editor(tmp_inputfile)
def getFavoritePathFromBasename( basename ):
    """
    Returns the full path to the favorite file given a basename.

    @param basename: The favorite filename (without the .txt extension).
    @type  basename: string

    @note: The (default) directory for all favorite files is
           $HOME/Nanorex/Favorites/ColorScheme.
    """
    _ext = "txt"

    # Make favorite filename (i.e. ~/Nanorex/Favorites/ColorScheme/basename.txt)
    from platform_dependent.PlatformDependent import find_or_make_Nanorex_subdir
    _dir = find_or_make_Nanorex_subdir('Favorites/ColorScheme')
    return os.path.join(_dir, "%s.%s" % (basename, _ext))
示例#21
0
    def get_povfile_trio(self, tmpfile=False):
        """
        Makes up and returns the trio of POV-Ray filenames (as absolute paths):
        POV-Ray INI file, POV-Ray Scene file, and output image filename. 
        If there was any problem, returns None, None, None.
        <tmpfile> flag controls how we choose their directory.
        [WARNING: current code may call it more than once during the same operation,
         so it needs to be sure to return the same names each time! [bruce guess 060711]]
        """
        # The ini, pov and out files must be in the same directory due to POV-Ray's I/O Restriction feature. Mark 060625.

        ini_filename = "povray.ini"
        # Critically important: POV-Ray uses the INI filename as an argument; it cannot have any whitespaces.
        # This is a POV-Ray bug on Windows only. For more information about this problem, see:
        # http://news.povray.org/povray.windows/thread/%3C3e28a17f%40news.povray.org%3E/?ttop=227783&toff=150
        # Mark 060624.

        if tmpfile:
            pov_filename = "raytracescene.pov"
            dir = find_or_make_Nanorex_subdir("POV-Ray")
            if not dir:
                return None, None, None
        else:
            pov_filename = self.name
            errorcode, dir = self.assy.find_or_make_pov_files_directory()
            if errorcode:
                return None, None, None  ###e ought to return something containing dir (errortext) instead

        # Build image output filename <out_filename>.
        # WARNING and BUG: this code is roughly duplicated in povray.py, and they need to match;
        # and .bmp is probably not properly supported for Mac in povray.py. [bruce 060711 comment]
        if self.output_type == 'bmp':
            output_ext = '.bmp'
        else:  # default
            output_ext = '.png'
        base, ext = os.path.splitext(pov_filename)
        out_filename = base + output_ext

        ini = os.path.normpath(os.path.join(dir, ini_filename))
        pov = os.path.normpath(os.path.join(dir, pov_filename))
        out = os.path.normpath(os.path.join(dir, out_filename))

        #print "get_povfile_trio():\n  ini=", ini, "\n  pov=", pov, "\n  out=", out
        return ini, pov, out
示例#22
0
 def get_povfile_trio(self, tmpfile = False):
     """
     Makes up and returns the trio of POV-Ray filenames (as absolute paths):
     POV-Ray INI file, POV-Ray Scene file, and output image filename. 
     If there was any problem, returns None, None, None.
     <tmpfile> flag controls how we choose their directory.
     [WARNING: current code may call it more than once during the same operation,
      so it needs to be sure to return the same names each time! [bruce guess 060711]]
     """
     # The ini, pov and out files must be in the same directory due to POV-Ray's I/O Restriction feature. Mark 060625.
 
     ini_filename = "povray.ini"
     # Critically important: POV-Ray uses the INI filename as an argument; it cannot have any whitespaces.
     # This is a POV-Ray bug on Windows only. For more information about this problem, see:
     # http://news.povray.org/povray.windows/thread/%3C3e28a17f%40news.povray.org%3E/?ttop=227783&toff=150
     # Mark 060624.
 
     if tmpfile:
         pov_filename = "raytracescene.pov"
         dir = find_or_make_Nanorex_subdir("POV-Ray")
         if not dir:
             return None, None, None
     else:
         pov_filename = self.name
         errorcode, dir = self.assy.find_or_make_pov_files_directory()
         if errorcode:
             return None, None, None ###e ought to return something containing dir (errortext) instead
     
     # Build image output filename <out_filename>.
     # WARNING and BUG: this code is roughly duplicated in povray.py, and they need to match;
     # and .bmp is probably not properly supported for Mac in povray.py. [bruce 060711 comment]
     if self.output_type == 'bmp':
         output_ext = '.bmp'
     else: # default
         output_ext = '.png'
     base, ext = os.path.splitext(pov_filename)
     out_filename = base + output_ext
 
     ini = os.path.normpath(os.path.join(dir, ini_filename))
     pov = os.path.normpath(os.path.join(dir, pov_filename))
     out = os.path.normpath(os.path.join(dir, out_filename))
 
     #print "get_povfile_trio():\n  ini=", ini, "\n  pov=", pov, "\n  out=", out
     return ini, pov, out
示例#23
0
def touch_job_id_status_file(job_id, Status = 'Queued'):
    """
    Creates the status file for a given job provided the job_id and status.
    It will remove any existing status file(s) in the directory.
    Status must be one of: Queued, Running, Completed, Suspended or Failed.
    Return values:
        0 = Status file created in the Job Id directory.
        1 = Job Id directory did not exists.  Status file was not created.
        2 = Invalid Status.
    """
    
    # Get the Job Manager directory
    from platform_dependent.PlatformDependent import find_or_make_Nanorex_subdir
    jobdir = find_or_make_Nanorex_subdir('JobManager')
    
    # Job Id dir (i.e. ~/Nanorex/JobManager/123/)
    job_id_dir  = os.path.join(jobdir, str(job_id))
        
    # Make sure the directory exists
    if not os.path.exists(job_id_dir):
        print "touch_job_id_status_file error: The directory ", job_id_dir, " does not exist."
        return 1
    
    # Make sure Status is valid.
    if Status not in ('Queued', 'Running', 'Completed', 'Suspended', 'Failed'):
        print "touch_job_id_status_file error: Status is invalid: ", Status
        return 2
    
    # Remove any status files (i.e. Status-Running in the directory)
    import glob
    wildcard_str = os.path.join(job_id_dir, 'Status-*')
    status_files = glob.glob(wildcard_str)
#    print "Status Files:", status_files # Commented this out for A6.  Mark 050712.
    for sfile in status_files:
        os.remove(sfile)
    
    # Write zero length status file.
    status_file = os.path.join(job_id_dir, 'Status-'+Status)
    f = open(status_file, 'w')
    f.close()
    
    return 0
示例#24
0
def get_job_manager_job_id_and_dir():
    """
    Returns a unique Job Id number and JobManager subdirectory for this Job Id.
    The Job Id is stored in the User Preference db.
    """
    from foundation.preferences import prefs_context
    prefs = prefs_context()
    job_id = prefs.get('JobId')

    if not job_id:
        job_id = 100  # Start with Job Id 100
    ##Temporarily comment out by Huaicai 6/22/05
    #else:
    #    job_id += 1 # Increment the Job Id

    # Get the Job Manager directory
    from platform_dependent.PlatformDependent import find_or_make_Nanorex_subdir
    jobdir = find_or_make_Nanorex_subdir('JobManager')

    while 1:

        # Create Job Id subdir (i.e. ~/Nanorex/JobManager/123/)
        job_id_dir = os.path.join(jobdir, str(job_id))

        # Make sure there isn't already a Job Id subdir in ~/Nanorex/JobManager/
        if os.path.exists(job_id_dir):
            job_id += 1  # It is there, so increment the Job Id and try again.

        else:
            from utilities.debug import print_compact_traceback
            try:
                os.mkdir(job_id_dir)
            except:
                print_compact_traceback(
                    "exception in creating directory: \"%s\"" % job_id_dir)
                return -1, 0

            prefs['JobId'] = 100  #job_id # Save the most recent Job Id
            touch_job_id_status_file(job_id, 'Queued')
            return str(job_id), job_id_dir
示例#25
0
def get_job_manager_job_id_and_dir():
    """
    Returns a unique Job Id number and JobManager subdirectory for this Job Id.  
    The Job Id is stored in the User Preference db.
    """
    from foundation.preferences import prefs_context
    prefs = prefs_context()
    job_id = prefs.get('JobId')
    
    if not job_id:
        job_id = 100 # Start with Job Id 100
    ##Temporarily comment out by Huaicai 6/22/05    
    #else:
    #    job_id += 1 # Increment the Job Id
    
    # Get the Job Manager directory
    from platform_dependent.PlatformDependent import find_or_make_Nanorex_subdir
    jobdir = find_or_make_Nanorex_subdir('JobManager')
    
    while 1:
        
        # Create Job Id subdir (i.e. ~/Nanorex/JobManager/123/)
        job_id_dir  = os.path.join(jobdir, str(job_id))
        
        # Make sure there isn't already a Job Id subdir in ~/Nanorex/JobManager/
        if os.path.exists(job_id_dir):
            job_id += 1 # It is there, so increment the Job Id and try again.
            
        else:
            from utilities.debug import print_compact_traceback
            try:
                os.mkdir(job_id_dir)
            except:
                print_compact_traceback("exception in creating directory: \"%s\"" % job_id_dir)
                return -1, 0
            
            prefs['JobId'] = 100#job_id # Save the most recent Job Id
            touch_job_id_status_file(job_id, 'Queued')
            return str(job_id), job_id_dir
示例#26
0
from PyQt4.Qt import SIGNAL

import foundation.env as env
from utilities import debug_flags

from platform_dependent.PlatformDependent import find_or_make_Nanorex_subdir
from foundation.wiki_help import WikiHelpBrowser
from utilities.debug import print_compact_stack, print_compact_traceback
from utilities.qt4transition import qt4todo
from utilities.prefs_constants import sponsor_download_permission_prefs_key
from utilities.prefs_constants import sponsor_permanent_permission_prefs_key
from utilities.prefs_constants import sponsor_md5_mismatch_flag_key
from utilities.Log import redmsg, orangemsg, greenmsg
from utilities.icon_utilities import geticon

_sponsordir = find_or_make_Nanorex_subdir('Sponsors')
_sponsors = { }

# Include a trailing slash in the following sponsor server URLs.
_sponsor_servers = \
    ['http://nanoengineer-1.com/NE1_Sponsors/',
     #'file:///transfers/',
     ]


def _fixHtml(rc): #bruce 071217 renamed this to be private
    startUrl=re.compile('\[')
    middleUrl=re.compile(' ')
    finishUrl=re.compile('\]')
    rc = string.replace(rc, '[P]', '<p>')
    rc = string.replace(rc, '[p]', '<p>')
示例#27
0
def _tempfilename( basename): # todo: rename, refile
    """
    @warning: does not check whether file already exists.
    """
    tmpdir = find_or_make_Nanorex_subdir("TemporaryFiles") # also hardcoded elsewhere
    return os.path.join( tmpdir, basename )
示例#28
0
    def _loadGroupBox1(self, pmGroupBox):
        """
        Load widgets in group box.
        @param pmGroupBox: group box that contains various favorite buttons
        @see: L{PM_GroupBox}  
        """
        # Other info
        # Not only loads the factory default settings but also all the favorite
        # files stored in the ~/Nanorex/Favorites/ProteinDisplayStyle directory
        favoriteChoices = ['Factory default settings']

        #look for all the favorite files in the favorite folder and add them to
        # the list
        from platform_dependent.PlatformDependent import find_or_make_Nanorex_subdir
        _dir = find_or_make_Nanorex_subdir('Favorites/ProteinDisplayStyle')

        for file in os.listdir(_dir):
            fullname = os.path.join(_dir, file)
            if os.path.isfile(fullname):
                if fnmatch.fnmatch(file, "*.txt"):
                    # leave the extension out
                    favoriteChoices.append(file[0:len(file) - 4])
        self.favoritesComboBox  = \
            PM_ComboBox( pmGroupBox,
                         choices       =  favoriteChoices,
                         spanWidth  =  True)
        self.favoritesComboBox.setWhatsThis("""<b> List of Favorites </b>
            <p>
            Creates a list of favorite Protein display styles. Once favorite
            styles have been added to the list using the Add Favorite button,
            the list will display the chosen favorites.
            To change the current favorite, select a current favorite from
            the list, and push the Apply Favorite button.""")

        # PM_ToolButtonRow ===============

        # Button list to create a toolbutton row.
        # Format:
        # - QToolButton, buttonId, buttonText,
        # - iconPath,
        # - tooltip, shortcut, column

        BUTTON_LIST = [
            ( "QToolButton", 1,  "APPLY_FAVORITE","ui/actions/Properties Manager/ApplyPeptideDisplayStyleFavorite.png",
              "Apply Favorite", "", 0),
            ( "QToolButton", 2,  "ADD_FAVORITE",
              "ui/actions/Properties Manager/AddFavorite.png","Add Favorite", "", 1),
            ( "QToolButton", 3,  "DELETE_FAVORITE", "ui/actions/Properties Manager/DeleteFavorite.png",
              "Delete Favorite", "", 2),
            ( "QToolButton", 4,  "SAVE_FAVORITE",
              "ui/actions/Properties Manager/SaveFavorite.png",
              "Save Favorite", "", 3),
            ( "QToolButton", 5,  "LOAD_FAVORITE",
              "ui/actions/Properties Manager/LoadFavorite.png",
              "Load Favorite", \
              "", 4)
            ]

        self.favsButtonGroup = \
            PM_ToolButtonRow( pmGroupBox,
                              title        = "",
                              buttonList   = BUTTON_LIST,
                              spanWidth    = True,
                              isAutoRaise  = False,
                              isCheckable  = False,
                              setAsDefault = True,
                              )

        self.favsButtonGroup.buttonGroup.setExclusive(False)
        self.applyFavoriteButton = self.favsButtonGroup.getButtonById(1)
        self.addFavoriteButton = self.favsButtonGroup.getButtonById(2)
        self.deleteFavoriteButton = self.favsButtonGroup.getButtonById(3)
        self.saveFavoriteButton = self.favsButtonGroup.getButtonById(4)
        self.loadFavoriteButton = self.favsButtonGroup.getButtonById(5)
示例#29
0
from PyQt4.Qt import SIGNAL

import foundation.env as env
from utilities import debug_flags

from platform_dependent.PlatformDependent import find_or_make_Nanorex_subdir
from foundation.wiki_help import WikiHelpBrowser
from utilities.debug import print_compact_stack, print_compact_traceback
from utilities.qt4transition import qt4todo
from utilities.prefs_constants import sponsor_download_permission_prefs_key
from utilities.prefs_constants import sponsor_permanent_permission_prefs_key
from utilities.prefs_constants import sponsor_md5_mismatch_flag_key
from utilities.Log import redmsg, orangemsg, greenmsg
from utilities.icon_utilities import geticon

_sponsordir = find_or_make_Nanorex_subdir("Sponsors")
_sponsors = {}

# Include a trailing slash in the following sponsor server URLs.
_sponsor_servers = [
    "http://nanoengineer-1.com/NE1_Sponsors/",
    #'file:///transfers/',
]


def _fixHtml(rc):  # bruce 071217 renamed this to be private
    startUrl = re.compile("\[")
    middleUrl = re.compile(" ")
    finishUrl = re.compile("\]")
    rc = string.replace(rc, "[P]", "<p>")
    rc = string.replace(rc, "[p]", "<p>")
示例#30
0
def run_nh_simulation(assy, sim_id, sim_parms, sims_to_run, results_to_save):
    """
    Run a Nano-Hive simulation on the part (assy).  Only the MPQC_ESP plug-in
    used for creating an ESP Image file is supported in A7.
    
    sim_id is the simulation id of the simulation.  It is used to construct the 
    basename of all the simulation files and is the name of the Nano-Hive simulation run.
    
    sims_to_run is a list of simulations to run, where:
        MPQC_ESP = MPQC ESP Plane
        MPQC_GD = MPQC Gradient Dynamics (not supported in A7)
        AIREBO = AIREBO (not supported in A7)
        
    results_to_save is a list of results to save, where:
        MEASUREMENTS = Measurements to file
        POVRAYVIDEO = POVRay Video
        NETCDF = NetCDF

    Return values:
        0 = successful
        1 = Nano-Hive plug-in not enabled
        2 = Nano-Hive plug-in path is empty
        3 = Nano-Hive plug-in path points to a file that does not exist
        4 = Nano-Hive plug-in is not Version 1.2b
        5 = Couldn't connect to Nano-Hive instance
        6 = "load" command failed
        7 = "run" command failed
        8 = Simulation aborted
    """
    if not sims_to_run:
        return # No simulations to run in the list.
        
    # Validate that the Nano-Hive plug-in is enabled.
    if not env.prefs[nanohive_enabled_prefs_key]:
        r = activate_nh_plugin(assy.w)
        
        if r:
            return 1 # Nano-Hive plug-in not enabled.
            
    if not env.prefs[nanohive_path_prefs_key]:
        return 2 # Nano-Hive plug-in path is empty
    
    if not os.path.exists(env.prefs[nanohive_path_prefs_key]):
        return 3 # Nano-Hive plug-in path points to a file that does not exist
        
    r = verify_nh_program()
    if r:
        return 4 # Nano-Hive plug-in is not Version 1.2b
    
    if not sim_id:
        sim_id = get_sim_id()   
        
    output_dir = find_or_make_Nanorex_subdir("Nano-Hive") # ~/Nanorex/Nano-Hive
    
    # Put up the wait cursor.  The cursor will be restored by exit_nh().       
    QApplication.setOverrideCursor( assy.w.ArrowWaitCursor )
    
    # 1. Try to connect to Nano-Hive, get socket.
    # 99% of the time, no socket will be returned since Nano-Hive hasn't been started yet.
    # Let's check, just in case this is a Nano-Hive instance running.
    nh_socket = connect_to_nh()
    
    if nh_socket:
        kill_nh = False
    else: # No Nano-Hive instance is running.  Start it.
        kill_nh = True
        r = start_nh() # Start Nano-Hive server (instance).
        
        if r:
            print "Nano-Hive startup aborted."
        
        # It may take a second or two to connect to the new Nano-Hive instance.
        # Keep trying until we get a socket.  Give up if we haven't connected within 4 seconds.
        start = time.time()
        while not nh_socket:
            time.sleep(0.25)
            nh_socket = connect_to_nh() 
            duration = time.time() - start
            if duration > 4.0: # Give up after 4 seconds
                exit_nh(nh_socket, kill_nh) # Only restore's the cursor
                return 5 # Couldn't connect to Nano-Hive socket.
        
    # 2. Write the MMP file that Nano-Hive will use for the sim run.
    assy.writemmpfile(get_nh_mmp_filename(sim_id))
        
    # 3. Write the sim-spec file using the parameters from the Nano-Hive dialog widgets
    from analysis.ESP.files_nh import write_nh_simspec_file
    write_nh_simspec_file(sim_id, sim_parms, sims_to_run, results_to_save, output_dir)
    
    # 4. Write the Sim Workflow file
    from analysis.ESP.files_nh import write_nh_workflow_file
    write_nh_workflow_file(sim_id)
    
    # 5. Send commands to Nano-Hive.  There can be no spaces in partname.  Need to fix this.
    cmd = 'load simulation -f "' + get_nh_simspec_filename(sim_id) + '" -n ' + sim_id
    #print "NanoHiveUtils.run_nh_simulation(): N-H load command: ", cmd
    
    success, response = nh_socket.sendCommand(cmd) # Send "load" command.
    if not success:
        print success, response
        exit_nh(nh_socket, kill_nh)
        return 6 # "load" command failed
    
    cmd = "run " + sim_id
    #print "NanoHiveUtils.run_nh_simulation(): N-H run command: ", cmd
    
    success, response = nh_socket.sendCommand(cmd) # Send "run" command.
    if not success:
        print success, response
        exit_nh(nh_socket, kill_nh)
        return 7 # "run" command failed
    
    statusBar = assy.w.statusBar()
    progressReporter = NanoHiveProgressReporter(nh_socket, sim_id)
    r = statusBar.show_progressbar_and_stop_button(progressReporter, "NanoHive", True)
    
    if r:
        stop_nh_sim(sim_id)
        exit_nh(nh_socket, kill_nh)
        return 8 # simulation aborted
    
    exit_nh(nh_socket, kill_nh)
    
    return 0
示例#31
0
    def set_options_errQ(self): #e maybe split further into several setup methods? #bruce 051115 removed unused 'options' arg
        """
        Figure out and set filenames, including sim executable path.
        All inputs and outputs are self attrs or globals or other obj attrs...
        except, return error code if sim executable missing
        or on other errors detected by subrs.
        """
        part = self.part
        movie = self._movie
        
        # simFilesPath = "~/Nanorex/RosettaDesignFiles".
        simFilesPath = find_or_make_Nanorex_subdir('RosettaDesignFiles')

        # Create temporary part-specific filename, for example:
        # "partname-minimize-pid1000".
        # We'll be appending various extensions to tmp_file_prefix to make temp
        # file names for sim input and output files as needed (e.g. mmp, xyz,
        # etc.)
        
        pdbId, chunk = self.getPDBIDFromChunk(part)
        #write the residue file
        resFile = pdbId + ".resfile"
        resFilePath = os.path.join(simFilesPath, resFile)
        success = write_rosetta_resfile(resFilePath, chunk)
        if success:
            self.resFile = resFile
        else:
            print "Residue file could not be written"
        
        #remove all previously existing fasta files
        fastaFile = pdbId + "_out_design.fasta"
        checkPointFile = pdbId + "_out_design.checkpoint"
        checkPointPath = os.path.join(simFilesPath, checkPointFile)
        fastaFilePath = os.path.join(simFilesPath, fastaFile)
        if os.path.exists(fastaFilePath):
            os.remove(fastaFilePath)
        
        if os.path.exists(checkPointPath):
            os.remove(checkPointPath)
            
        if pdbId is None:
            basename = "Untitled"
        else:
            basename = pdbId
        timestampString = ""
        if (self.background):
            # Add a timestamp to the pid so that multiple backgrounded
            # calculations don't clobber each other's files.
            timestamp = datetime.today()
            timestampString = timestamp.strftime(".%y%m%d%H%M%S")
        self.tmp_file_prefix = \
            os.path.join(simFilesPath,
                         "%s-rosetta-design-pid%d%s" % (basename, os.getpid(),
                                                  timestampString))

        
        #get program path, database path and write path.txt
        self.program = self.getExecutablePluginPath()
        if self.program is None:
            msg = redmsg("The simulator program is missing.  Simulation aborted.")
            env.history.message(self.cmdname + ": " + msg)
            return -1
        databasePath = self.getDatabasePluginPath()
        if databasePath is None:
            msg = redmsg("The protein database is missing.  Simulation aborted.")
            env.history.message(self.cmdname + ": " + msg)
            return -1
        self.path = self.getPathLocation(databasePath, simFilesPath)
        
        return None # no error
示例#32
0
from PyQt4.Qt import SIGNAL

import foundation.env as env
from utilities import debug_flags

from platform_dependent.PlatformDependent import find_or_make_Nanorex_subdir
from foundation.wiki_help import WikiHelpBrowser
from utilities.debug import print_compact_stack, print_compact_traceback
from utilities.qt4transition import qt4todo
from utilities.prefs_constants import sponsor_download_permission_prefs_key
from utilities.prefs_constants import sponsor_permanent_permission_prefs_key
from utilities.prefs_constants import sponsor_md5_mismatch_flag_key
from utilities.Log import redmsg, orangemsg, greenmsg
from utilities.icon_utilities import geticon

_sponsordir = find_or_make_Nanorex_subdir('Sponsors')
_sponsors = {}

# Include a trailing slash in the following sponsor server URLs.
_sponsor_servers = \
    ['http://nanoengineer-1.com/NE1_Sponsors/',
     #'file:///transfers/',
     ]


def _fixHtml(rc):  #bruce 071217 renamed this to be private
    startUrl = re.compile('\[')
    middleUrl = re.compile(' ')
    finishUrl = re.compile('\]')
    rc = string.replace(rc, '[P]', '<p>')
    rc = string.replace(rc, '[p]', '<p>')
示例#33
0
    def _loadGroupBox1(self, pmGroupBox):
        """
        Load widgets in group box.
        @param pmGroupBox: group box that contains various favorite buttons
        @see: L{PM_GroupBox}  
        """
        # Other info
        # Not only loads the factory default settings but also all the favorite
        # files stored in the ~/Nanorex/Favorites/ProteinDisplayStyle directory
        favoriteChoices = ['Factory default settings']

        #look for all the favorite files in the favorite folder and add them to
        # the list
        from platform_dependent.PlatformDependent import find_or_make_Nanorex_subdir
        _dir = find_or_make_Nanorex_subdir('Favorites/ProteinDisplayStyle')

        for file in os.listdir(_dir):
            fullname = os.path.join( _dir, file)
            if os.path.isfile(fullname):
                if fnmatch.fnmatch( file, "*.txt"):
                    # leave the extension out
                    favoriteChoices.append(file[0:len(file)-4])
        self.favoritesComboBox  = \
            PM_ComboBox( pmGroupBox,
                         choices       =  favoriteChoices,
                         spanWidth  =  True)
        self.favoritesComboBox.setWhatsThis(
            """<b> List of Favorites </b>
            <p>
            Creates a list of favorite Protein display styles. Once favorite
            styles have been added to the list using the Add Favorite button,
            the list will display the chosen favorites.
            To change the current favorite, select a current favorite from
            the list, and push the Apply Favorite button.""")

        # PM_ToolButtonRow ===============

        # Button list to create a toolbutton row.
        # Format:
        # - QToolButton, buttonId, buttonText,
        # - iconPath,
        # - tooltip, shortcut, column

        BUTTON_LIST = [
            ( "QToolButton", 1,  "APPLY_FAVORITE","ui/actions/Properties Manager/ApplyPeptideDisplayStyleFavorite.png",
              "Apply Favorite", "", 0),   
            ( "QToolButton", 2,  "ADD_FAVORITE",
              "ui/actions/Properties Manager/AddFavorite.png","Add Favorite", "", 1),
            ( "QToolButton", 3,  "DELETE_FAVORITE", "ui/actions/Properties Manager/DeleteFavorite.png",
              "Delete Favorite", "", 2),
            ( "QToolButton", 4,  "SAVE_FAVORITE",
              "ui/actions/Properties Manager/SaveFavorite.png",
              "Save Favorite", "", 3),
            ( "QToolButton", 5,  "LOAD_FAVORITE",
              "ui/actions/Properties Manager/LoadFavorite.png",
              "Load Favorite", \
              "", 4)
            ]

        self.favsButtonGroup = \
            PM_ToolButtonRow( pmGroupBox,
                              title        = "",
                              buttonList   = BUTTON_LIST,
                              spanWidth    = True,
                              isAutoRaise  = False,
                              isCheckable  = False,
                              setAsDefault = True,
                              )

        self.favsButtonGroup.buttonGroup.setExclusive(False)
        self.applyFavoriteButton  = self.favsButtonGroup.getButtonById(1)
        self.addFavoriteButton    = self.favsButtonGroup.getButtonById(2)
        self.deleteFavoriteButton = self.favsButtonGroup.getButtonById(3)
        self.saveFavoriteButton   = self.favsButtonGroup.getButtonById(4)
        self.loadFavoriteButton   = self.favsButtonGroup.getButtonById(5)
示例#34
0
    def run(self, operation):
        """
        Creates a temp directory, generates a structure files from the part,
        pre-processes them with GROMACS tools, spawns the GROMACS simulation,
        and spawns an HK_Simulation process to view it with.
        
        operation - either "em" to perform an energy minimization, or "md" to
                    perform molecular dynamics simulation
        """

        # Create a unique directory under the Nanorex/SimFiles directory for our
        # files: Nanorex/SimFiles/GMX-<timestamp>
        #
        from platform_dependent.PlatformDependent import find_or_make_Nanorex_subdir
        simFilesPath = find_or_make_Nanorex_subdir('SimFiles')
        timestamp = datetime.today()
        self.tempFilePath = \
            os.path.join(simFilesPath,
                         "GMX-%s" % timestamp.strftime("%Y%m%d%H%M%S"))
        os.mkdir(self.tempFilePath)

        # Create the structure files from our part.
        #
        self.atomIndex = 1
        self.residueIndex = 1
        self.pdbFileHandle = 0
        self.atomsFileHandle = 0
        self.confFileHandle = 0
        self.bondsFileHandle = 0
        self.anglesFileHandle = 0
        self.pseudoPass = 1
        partType = self.writeStructure_Helper(self.part.topnode)
        if partType == "pseudo":
            # The first pass was to process and index atoms, now we have
            # sufficient information to determine bonds and angles. It's
            # probably possible to do everything in one pass.
            #
            if self.atomsFileHandle != 0:
                self.atomsFileHandle.close()
            self.pseudoPass = 2
            self.residueIndex = 1
            self.writeStructure_Helper(self.part.topnode)

        if self.pdbFileHandle != 0:
            self.pdbFileHandle.close()
        if self.confFileHandle != 0:
            self.confFileHandle.close()
        if self.bondsFileHandle != 0:
            self.bondsFileHandle.close()
        if self.anglesFileHandle != 0:
            self.anglesFileHandle.close()

        script = ""
        if partType == "pseudo":
            # Combine the fragments of the topology into the topol.top file,
            # tweak with GROMACS tools, and run the operation.
            script = "pseudo_" + operation + ".bat"

        else:
            # Pre-process the .pdb file with the GROMACS tools and run the
            # operation.
            #
            script = "atomic_" + operation + ".bat"

        os.spawnl(os.P_NOWAIT, os.path.join(self.gmxHome, script),
                  os.path.join(self.gmxHome, script),
                  os.path.normpath(self.gmxHome),
                  '"' + os.path.normpath(self.tempFilePath) + '"')
        return
示例#35
0
def run_nh_simulation(assy, sim_id, sim_parms, sims_to_run, results_to_save):
    """
    Run a Nano-Hive simulation on the part (assy).  Only the MPQC_ESP plug-in
    used for creating an ESP Image file is supported in A7.
    
    sim_id is the simulation id of the simulation.  It is used to construct the 
    basename of all the simulation files and is the name of the Nano-Hive simulation run.
    
    sims_to_run is a list of simulations to run, where:
        MPQC_ESP = MPQC ESP Plane
        MPQC_GD = MPQC Gradient Dynamics (not supported in A7)
        AIREBO = AIREBO (not supported in A7)
        
    results_to_save is a list of results to save, where:
        MEASUREMENTS = Measurements to file
        POVRAYVIDEO = POVRay Video
        NETCDF = NetCDF

    Return values:
        0 = successful
        1 = Nano-Hive plug-in not enabled
        2 = Nano-Hive plug-in path is empty
        3 = Nano-Hive plug-in path points to a file that does not exist
        4 = Nano-Hive plug-in is not Version 1.2b
        5 = Couldn't connect to Nano-Hive instance
        6 = "load" command failed
        7 = "run" command failed
        8 = Simulation aborted
    """
    if not sims_to_run:
        return  # No simulations to run in the list.

    # Validate that the Nano-Hive plug-in is enabled.
    if not env.prefs[nanohive_enabled_prefs_key]:
        r = activate_nh_plugin(assy.w)

        if r:
            return 1  # Nano-Hive plug-in not enabled.

    if not env.prefs[nanohive_path_prefs_key]:
        return 2  # Nano-Hive plug-in path is empty

    if not os.path.exists(env.prefs[nanohive_path_prefs_key]):
        return 3  # Nano-Hive plug-in path points to a file that does not exist

    r = verify_nh_program()
    if r:
        return 4  # Nano-Hive plug-in is not Version 1.2b

    if not sim_id:
        sim_id = get_sim_id()

    output_dir = find_or_make_Nanorex_subdir("Nano-Hive")  # ~/Nanorex/Nano-Hive

    # Put up the wait cursor.  The cursor will be restored by exit_nh().
    QApplication.setOverrideCursor(assy.w.ArrowWaitCursor)

    # 1. Try to connect to Nano-Hive, get socket.
    # 99% of the time, no socket will be returned since Nano-Hive hasn't been started yet.
    # Let's check, just in case this is a Nano-Hive instance running.
    nh_socket = connect_to_nh()

    if nh_socket:
        kill_nh = False
    else:  # No Nano-Hive instance is running.  Start it.
        kill_nh = True
        r = start_nh()  # Start Nano-Hive server (instance).

        if r:
            print "Nano-Hive startup aborted."

        # It may take a second or two to connect to the new Nano-Hive instance.
        # Keep trying until we get a socket.  Give up if we haven't connected within 4 seconds.
        start = time.time()
        while not nh_socket:
            time.sleep(0.25)
            nh_socket = connect_to_nh()
            duration = time.time() - start
            if duration > 4.0:  # Give up after 4 seconds
                exit_nh(nh_socket, kill_nh)  # Only restore's the cursor
                return 5  # Couldn't connect to Nano-Hive socket.

    # 2. Write the MMP file that Nano-Hive will use for the sim run.
    assy.writemmpfile(get_nh_mmp_filename(sim_id))

    # 3. Write the sim-spec file using the parameters from the Nano-Hive dialog widgets
    from analysis.ESP.files_nh import write_nh_simspec_file

    write_nh_simspec_file(sim_id, sim_parms, sims_to_run, results_to_save, output_dir)

    # 4. Write the Sim Workflow file
    from analysis.ESP.files_nh import write_nh_workflow_file

    write_nh_workflow_file(sim_id)

    # 5. Send commands to Nano-Hive.  There can be no spaces in partname.  Need to fix this.
    cmd = 'load simulation -f "' + get_nh_simspec_filename(sim_id) + '" -n ' + sim_id
    # print "NanoHiveUtils.run_nh_simulation(): N-H load command: ", cmd

    success, response = nh_socket.sendCommand(cmd)  # Send "load" command.
    if not success:
        print success, response
        exit_nh(nh_socket, kill_nh)
        return 6  # "load" command failed

    cmd = "run " + sim_id
    # print "NanoHiveUtils.run_nh_simulation(): N-H run command: ", cmd

    success, response = nh_socket.sendCommand(cmd)  # Send "run" command.
    if not success:
        print success, response
        exit_nh(nh_socket, kill_nh)
        return 7  # "run" command failed

    statusBar = assy.w.statusBar()
    progressReporter = NanoHiveProgressReporter(nh_socket, sim_id)
    r = statusBar.show_progressbar_and_stop_button(progressReporter, "NanoHive", True)

    if r:
        stop_nh_sim(sim_id)
        exit_nh(nh_socket, kill_nh)
        return 8  # simulation aborted

    exit_nh(nh_socket, kill_nh)

    return 0
示例#36
0
    def set_options_errQ(self, args):
        """
        Figure out and set filenames, including sim executable path.
        All inputs and outputs are self attrs or globals or other obj attrs...
        except, return error code if sim executable missing
        or on other errors detected by subrs.

        @param args: name of the protein for which rosetta simulation is run and
                     if its empty then it is run for the first available chunk
        @type args: str
        """
        movie = self._movie
        simFilesPath = find_or_make_Nanorex_subdir('RosettaDesignFiles')

        # Create temporary part-specific filename, for example:
        # "partname-minimize-pid1000".
        # We'll be appending various extensions to tmp_file_prefix to make temp
        # file names for sim input and output files as needed
        if args != "":
            pdbId = args
            for mol in self.win.assy.molecules:
                if mol.name == args:
                    chunk = mol
                    break
        else:
            pdbId, chunk = self.getPDBIDFromChunk()

        if self.cmd_type == "BACKRUB_PROTEIN_SEQUENCE_DESIGN":
            backrubSetupCorrect = chunk.protein.is_backrub_setup_correctly()
            #Urmi 20080807: The backrub motion is so poorly documented that
            #I do not have any idea what is the threshold value
            #my experiments with 2gb1 seems to show that its 3, but I dont know for sure
            if not backrubSetupCorrect:
                msg = redmsg("Rosetta sequence design with backrub motion failed. Please edit your residues properly from Edit REsidues command.")
                env.history.message(self.cmdname + "," + self.cmd_type + ": " + msg)
                return -1
        #write the residue file
        resFile = pdbId + ".resfile"
        resFilePath = os.path.join(simFilesPath, resFile)
        success = write_rosetta_resfile(resFilePath, chunk)
        if success:
            self.resFile = resFile
        else:
            #Shall we refuse to run the program if we cannot write the residue file?
            print "Residue file could not be written"
            return -1
        #remove all previously existing fasta files
        #may not be needed. But we are doing with out pdb, might as well do it
        #fasta and design files as well
        fastaFile = pdbId + "_out_design.fasta"
        checkPointFile = pdbId + "_out_design.checkpoint"
        checkPointPath = os.path.join(simFilesPath, checkPointFile)
        fastaFilePath = os.path.join(simFilesPath, fastaFile)
        if os.path.exists(fastaFilePath):
            os.remove(fastaFilePath)
        if os.path.exists(checkPointPath):
            os.remove(checkPointPath)
        if pdbId is None:
            basename = "Untitled"
        else:
            basename = pdbId
        timestampString = ""
        if (self.background):
            # Add a timestamp to the pid so that multiple backgrounded
            # calculations don't clobber each other's files.
            #We are not running Rosetta in the background now, so may not be useful
            timestamp = datetime.today()
            timestampString = timestamp.strftime(".%y%m%d%H%M%S")
        self.tmp_file_prefix = \
            os.path.join(simFilesPath,
                         "%s-rosetta-design-pid%d%s" % (basename, os.getpid(),
                                                  timestampString))
        #get program path, database path and write path.txt
        self.program = self.getExecutablePluginPath()
        if self.program is None:
            msg = redmsg("The simulator program is missing.  Simulation aborted.")
            env.history.message(self.cmdname + ": " + msg)
            return -1
        databasePath = self.getDatabasePluginPath()
        if databasePath is None:
            msg = redmsg("The protein database is missing.  Simulation aborted.")
            env.history.message(self.cmdname + ": " + msg)
            return -1
        self.path = self.getPathLocation(databasePath, simFilesPath)
        return None # no error
    def _loadGroupBox1(self, pmGroupBox):
        """
        Load widgets in group box.
        """
        # Other info
        # Not only loads the factory default settings but also all the favorite
        # files stored in the ~/Nanorex/Favorites/DnaDisplayStyle directory

        favoriteChoices = ['Factory default settings']

        #look for all the favorite files in the favorite folder and add them to
        # the list
        from platform_dependent.PlatformDependent import find_or_make_Nanorex_subdir
        _dir = find_or_make_Nanorex_subdir('Favorites/ColorScheme')


        for file in os.listdir(_dir):
            fullname = os.path.join( _dir, file)
            if os.path.isfile(fullname):
                if fnmatch.fnmatch( file, "*.txt"):

                    # leave the extension out
                    favoriteChoices.append(file[0:len(file)-4])

        self.favoritesComboBox  = \
            PM_ComboBox( pmGroupBox,
                         choices       =  favoriteChoices,
                         spanWidth  =  True)

        # PM_ToolButtonRow ===============

        # Button list to create a toolbutton row.
        # Format:
        # - QToolButton, buttonId, buttonText,
        # - iconPath,
        # - tooltip, shortcut, column

        BUTTON_LIST = [
            ( "QToolButton", 1,  "APPLY_FAVORITE",
              "ui/actions/Properties Manager/ApplyColorSchemeFavorite.png",
              "Apply Favorite", "", 0),
            ( "QToolButton", 2,  "ADD_FAVORITE",
              "ui/actions/Properties Manager/AddFavorite.png",
              "Add Favorite", "", 1),
            ( "QToolButton", 3,  "DELETE_FAVORITE",
              "ui/actions/Properties Manager/DeleteFavorite.png",
              "Delete Favorite", "", 2),
            ( "QToolButton", 4,  "SAVE_FAVORITE",
              "ui/actions/Properties Manager/SaveFavorite.png",
              "Save Favorite", "", 3),
            ( "QToolButton", 5,  "LOAD_FAVORITE",
              "ui/actions/Properties Manager/LoadFavorite.png",
              "Load Favorite", \
              "", 4)
            ]

        self.favsButtonGroup = \
            PM_ToolButtonRow( pmGroupBox,
                              title        = "",
                              buttonList   = BUTTON_LIST,
                              spanWidth    = True,
                              isAutoRaise  = False,
                              isCheckable  = False,
                              setAsDefault = True,
                              )

        self.favsButtonGroup.buttonGroup.setExclusive(False)

        self.applyFavoriteButton  = self.favsButtonGroup.getButtonById(1)
        self.addFavoriteButton    = self.favsButtonGroup.getButtonById(2)
        self.deleteFavoriteButton = self.favsButtonGroup.getButtonById(3)
        self.saveFavoriteButton   = self.favsButtonGroup.getButtonById(4)
        self.loadFavoriteButton   = self.favsButtonGroup.getButtonById(5)
示例#38
0
    def run(self, operation):
        """
        Creates a temp directory, generates a structure files from the part,
        pre-processes them with GROMACS tools, spawns the GROMACS simulation,
        and spawns an HK_Simulation process to view it with.
        
        operation - either "em" to perform an energy minimization, or "md" to
                    perform molecular dynamics simulation
        """
        
        # Create a unique directory under the Nanorex/SimFiles directory for our
        # files: Nanorex/SimFiles/GMX-<timestamp>
        #
        from platform_dependent.PlatformDependent import find_or_make_Nanorex_subdir
        simFilesPath = find_or_make_Nanorex_subdir('SimFiles')
        timestamp = datetime.today()
        self.tempFilePath = \
            os.path.join(simFilesPath,
                         "GMX-%s" % timestamp.strftime("%Y%m%d%H%M%S"))
        os.mkdir(self.tempFilePath)
 
        # Create the structure files from our part.
        #
        self.atomIndex = 1
        self.residueIndex = 1
        self.pdbFileHandle = 0
        self.atomsFileHandle = 0
        self.confFileHandle = 0
        self.bondsFileHandle = 0
        self.anglesFileHandle = 0
        self.pseudoPass = 1
        partType = self.writeStructure_Helper(self.part.topnode)
        if partType == "pseudo":
            # The first pass was to process and index atoms, now we have
            # sufficient information to determine bonds and angles. It's
            # probably possible to do everything in one pass.
            #
            if self.atomsFileHandle != 0:
                self.atomsFileHandle.close()
            self.pseudoPass = 2
            self.residueIndex = 1
            self.writeStructure_Helper(self.part.topnode)

        if self.pdbFileHandle != 0:
            self.pdbFileHandle.close()
        if self.confFileHandle != 0:
            self.confFileHandle.close()
        if self.bondsFileHandle != 0:
            self.bondsFileHandle.close()
        if self.anglesFileHandle != 0:
            self.anglesFileHandle.close()
        
        script = ""
        if partType == "pseudo":
            # Combine the fragments of the topology into the topol.top file,
            # tweak with GROMACS tools, and run the operation.
            script = "pseudo_" + operation + ".bat"
            
        else:
            # Pre-process the .pdb file with the GROMACS tools and run the
            # operation.
            #
            script = "atomic_" + operation + ".bat"
            
        os.spawnl(os.P_NOWAIT, os.path.join(self.gmxHome, script),
                  os.path.join(self.gmxHome, script),
                  os.path.normpath(self.gmxHome),
                  '"' + os.path.normpath(self.tempFilePath) + '"')
        return