Esempio n. 1
0
    def __init__(self,
                 fcrd,
                 fref,
                 box=0,
                 rnAmber=0,
                 pdbCode=None,
                 log=StdLog(),
                 verbose=0):
        """
        @param fcrd: path to input coordinate file
        @type  fcrd: str
        @param fref: PDB or pickled PDBModel with same atom content and order
        @type  fref: str
        @param box: expect line with box info at the end of each frame
                    (default: 0)
        @type  box: 1|0
        @param rnAmber: rename amber style residues into standard (default: 0)
        @type  rnAmber: 1|0
        @param pdbCode: pdb code to be put into the model (default: None)
        @type  pdbCode: str
        @param log: LogFile instance [Biskit.StdLog]
        @type  log: Biskit.LogFile
        @param verbose: print progress to log [0]
        @type  verbose: int
        """
        self.fcrd = T.absfile(fcrd)
        self.crd = T.gzopen(self.fcrd)

        self.ref = PDBModel(T.absfile(fref), pdbCode=pdbCode)
        self.box = box

        self.n = self.ref.lenAtoms()

        self.log = log
        self.verbose = verbose

        if rnAmber:
            self.ref.renameAmberRes()

        ## pre-compile pattern for line2numbers
        xnumber = "-*\d+\.\d+"  # optionally negtive number
        xspace = ' *'  # one or more space char
        self.xnumbers = re.compile('(' + xspace + xnumber + ')')

        ## pre-compute lines expected per frame
        self.lines_per_frame = self.n * 3 / 10

        if self.n % 10 != 0: self.lines_per_frame += 1
        if self.box: self.lines_per_frame += 1
Esempio n. 2
0
    def test_AmberCrdParser(self):
        """AmberCrdParser test"""

        self.p = AmberCrdParser(self.finp,
                                self.fref,
                                box=True,
                                rnAmber=True,
                                log=self.log,
                                verbose=self.local)
        self.t = self.p.crd2traj()

        self.t.removeAtoms(
            lambda a: a['residue_name'] in ['WAT', 'Na+', 'Cl-'])
        self.t.removeAtoms(lambda a: a['element'] == 'H')

        if self.local:
            print "Dumping result to ", self.fout

        T.dump(self.t, T.absfile(self.fout))

        if self.local:
            print "Dumped Trajectory with %i frames and %i atoms." % \
                  (len(self.t), self.t.lenAtoms() )

        self.assertEqual(len(self.t), 10)
        self.assertEqual(self.t.lenAtoms(), 440)
Esempio n. 3
0
    def writeCrd( self, fcrd, append=1, lastAtom=None ):
        """
        Write/Append Amber-formatted block of coordinates to a file.
        If a file handle is given, the file will not be closed.

        @param fcrd: file to write to
        @type  fcrd: str or file object
        @param append: append to existing file (default: 1)
        @type  append: 0|1
        @param lastAtom: skip all atoms beyond this one (default: None)
        @type  lastAtom: int
        """
        if not self.xyz:
            self.getXyz()

        if type( fcrd ) == file:
            ## take file handle
            f = fcrd
        else:
            ## create new file handle
            mode = 'w'
            if append:
                mode = 'a'
            f = open( T.absfile( fcrd ), mode )

            newf = (mode=='w' or not os.path.exists( T.absfile(fcrd) ))
            if newf:
                f.write("\n")

        i = 0
        for x in N.ravel( self.xyz ):
            i = i + 1

            f.write( "%8.3f" % x )

            if (i % 10) == 0:
                f.write("\n")

            if lastAtom and i / 3.0 == lastAtom:
                break

        if ((i % 10) != 0):
            f.write("\n")

        if type( fcrd ) != file:
            ## don't close file that was already given
            f.close()
Esempio n. 4
0
    def writeCrd(self, fcrd, append=1, lastAtom=None):
        """
        Write/Append Amber-formatted block of coordinates to a file.
        If a file handle is given, the file will not be closed.

        @param fcrd: file to write to
        @type  fcrd: str or file object
        @param append: append to existing file (default: 1)
        @type  append: 0|1
        @param lastAtom: skip all atoms beyond this one (default: None)
        @type  lastAtom: int
        """
        if not self.xyz:
            self.getXyz()

        if type(fcrd) == file:
            ## take file handle
            f = fcrd
        else:
            ## create new file handle
            mode = 'w'
            if append:
                mode = 'a'
            f = open(T.absfile(fcrd), mode)

            newf = (mode == 'w' or not os.path.exists(T.absfile(fcrd)))
            if newf:
                f.write("\n")

        i = 0
        for x in N0.ravel(self.xyz):
            i = i + 1

            f.write("%8.3f" % x)

            if (i % 10) == 0:
                f.write("\n")

            if lastAtom and i / 3.0 == lastAtom:
                break

        if ((i % 10) != 0):
            f.write("\n")

        if type(fcrd) != file:
            ## don't close file that was already given
            f.close()
Esempio n. 5
0
    def __init__(self, path):
        """
        Take chains from ChainCleaner and write pdb files.
        File names are created from segid of each chain + '_seg.pdb'

        @param path: output path for PDB files
        @type  path: string
        """
        self.path = T.absfile(path)
Esempio n. 6
0
    def __init__(self, path):
        """
        Take chains from ChainCleaner and write pdb files.
        File names are created from segid of each chain + '_seg.pdb'

        @param path: output path for PDB files
        @type  path: string
        """
        self.path = T.absfile( path )
Esempio n. 7
0
def redirect_output():
    import tempfile, os, sys

    f_out = open( tempfile.mktemp( '.out', 'slave_', T.absfile('~')),'w')

    sys.stdout = f_out
    sys.stderr = f_out
    flusher = Flusher( f_out )
    flusher.start()
Esempio n. 8
0
def redirect_output():
    import tempfile, os, sys

    f_out = open(tempfile.mktemp('.out', 'slave_', T.absfile('~')), 'w')

    sys.stdout = f_out
    sys.stderr = f_out
    flusher = Flusher(f_out)
    flusher.start()
Esempio n. 9
0
    def __getDatabase(self, db=None, createEmpty=False):
        """
        Select and return database (which is actually a dictionary type) for which the user has writing permisions.
        By default, the package database will be used but if the user cannot write there,
        a new database will be created under the users home directory: $HOME/.mdmix/SOLVENTS.db
        which will also contain all solvents from the package db.

        :arg None|str db: If *db* != None:
                                - Check if this DB filename is writtable and return full path. Create it otherwise.
                            If None:
                                - Check if user has writing permisions in package DB and return the path.
                                - If not, create a user-spacific database and return the path.
        :arg bool createEmpty:   If the database has to be created, ignore solvents from the package DB.
                            Will create an empty DB.

        :return: Path to a db for which the user should have writting permisions.
        :type: string
        """
        import shutil
        # Try to use specified db
        if db:
            if osp.exists(db) and T.filePermission(db)['WRITE']:
                return T.absfile(db)
            else:
                if createEmpty: T.dump({}, db)
                else: shutil.copy(S.SOLVENTDB, db)
                return T.absfile(db)
        else:
            # USE USER DATABASE IF IT EXISTS
            if osp.exists(S.USER_SOLVENT_DB):
                return T.absfile(S.USER_SOLVENT_DB)
            else:
                db = S.SOLVENTDB

        # Create USER DB from package if user cannot write to package directory
        if not T.filePermission(db)['WRITE']:
            # User cannot write to package DB so create a custom one
            if createEmpty: T.dump({}, S.USER_SOLVENT_DB)
            else:
                shutil.copy(db, S.USER_SOLVENT_DB
                            )  # Make a copy to user's home mdmix folder
            db = S.USER_SOLVENT_DB

        return T.absfile(db)
Esempio n. 10
0
    def __init__( self, fcrd, fref, box=0, rnAmber=0, pdbCode=None,
                  log=StdLog(), verbose=0 ):
        """
        @param fcrd: path to input coordinate file
        @type  fcrd: str
        @param fref: PDB or pickled PDBModel with same atom content and order
        @type  fref: str
        @param box: expect line with box info at the end of each frame
                    (default: 0)
        @type  box: 1|0
        @param rnAmber: rename amber style residues into standard (default: 0)
        @type  rnAmber: 1|0
        @param pdbCode: pdb code to be put into the model (default: None)
        @type  pdbCode: str
        @param log: LogFile instance [Biskit.StdLog]
        @type  log: Biskit.LogFile
        @param verbose: print progress to log [0]
        @type  verbose: int
        """
        self.fcrd = T.absfile( fcrd )
        self.crd  = T.gzopen( self.fcrd )

        self.ref  = PDBModel( T.absfile(fref), pdbCode=pdbCode )
        self.box  = box

        self.n = self.ref.lenAtoms()

        self.log = log
        self.verbose = verbose

        if rnAmber:
            self.ref.renameAmberRes()

        ## pre-compile pattern for line2numbers
        xnumber = "-*\d+\.\d+"              # optionally negtive number
        xspace  = ' *'                      # one or more space char
        self.xnumbers = re.compile('('+xspace+xnumber+')')

        ## pre-compute lines expected per frame
        self.lines_per_frame = self.n * 3 / 10

        if self.n % 10 != 0:  self.lines_per_frame += 1
        if self.box:          self.lines_per_frame += 1
Esempio n. 11
0
    def loadTraj(self, ftraj):
        """
        Load trajectories from disc.

        @param ftraj: path to trajectory
        @type  ftraj: str

        @return: ensemble trajectory object
        @rtype: EnsembleTraj
        """
        t = T.load(T.absfile(ftraj))
        return traj2ensemble(t)
Esempio n. 12
0
    def loadTraj( self, ftraj ):
        """
        Load trajectories from disc.

        @param ftraj: path to trajectory
        @type  ftraj: str

        @return: ensemble trajectory object
        @rtype: EnsembleTraj
        """
        t = T.load( T.absfile( ftraj ) )
        return traj2ensemble( t )
Esempio n. 13
0
    def __init__( self, frst ):
        """
        @param frst: input restart file
        @type  frst: str
        """
        self.frst = T.absfile( frst )
        self.crd  = open( self.frst )

        self.n = 0       #: number of atoms
        self.lines_per_frame = 0
        self.xyz = None  #: will hold coordinate array
        self.box = None  #: will hold box array if any

        ## pre-compile pattern for line2numbers
        xnumber = "-*\d+\.\d+"              # optionally negtive number
        xspace  = ' *'                      # one or more space char
        self.xnumbers = re.compile('('+xspace+xnumber+')')
Esempio n. 14
0
    def __init__(self, frst):
        """
        @param frst: input restart file
        @type  frst: str
        """
        self.frst = T.absfile(frst)
        self.crd = open(self.frst)

        self.n = 0  #: number of atoms
        self.lines_per_frame = 0
        self.xyz = None  #: will hold coordinate array
        self.box = None  #: will hold box array if any

        ## pre-compile pattern for line2numbers
        xnumber = "-*\d+\.\d+"  # optionally negtive number
        xspace = ' *'  # one or more space char
        self.xnumbers = re.compile('(' + xspace + xnumber + ')')
Esempio n. 15
0
    def __init__(self, fdefault, fuser, createmissing=False, verbose=1):
        """
        @param fdefault: default configuration file
        @type  fdedault: str
        @param fuser: user configuration file
        @type  fuser: str
        @param createmissing: create user config file if missing
        @type  createmissing: bool
        @param verbose: verbosity level (default: 1)
        @type  verbose: 1|0
        """
        self.log = logging.getLogger("SettingsManager")
        self.verbose = verbose
        self.fdefault = fdefault
        self.fuser = fuser
        self.createmissing = createmissing
        self.fusermissing = not os.path.exists(T.absfile(fuser))

        self.settings = []  #: will hold extracted Setting's
Esempio n. 16
0
    def test_AmberCrdParser(self):
        """AmberCrdParser test"""
        
        self.p = AmberCrdParser( self.finp, self.fref, box=True, rnAmber=True,
                                 log=self.log, verbose=self.local )
        self.t = self.p.crd2traj()

        self.t.removeAtoms(lambda a: a['residue_name'] in ['WAT','Na+','Cl-'] )
        self.t.removeAtoms(lambda a: a['element'] == 'H' )

        if self.local:
            print "Dumping result to ", self.fout

        T.dump( self.t, T.absfile(self.fout) )

        if self.local:
            print "Dumped Trajectory with %i frames and %i atoms." % \
                  (len(self.t), self.t.lenAtoms() )

        self.assertEqual( len(self.t), 10 )
        self.assertEqual( self.t.lenAtoms(), 440 )
Esempio n. 17
0
    def writeCrd(self, fname, frames=None):
        """
        Write frames to Amber crd file (w/o box info).

        @param fname: output file name
        @type  fname: str
        @param frames: frame indices (default: all)
        @type  frames: [int]
        """
        if frames == None:
            frames = range(self.lenFrames())

        template = " %7.3f" * 10 + '\n'

        ## open new file
        out = open(T.absfile(fname), 'w')
        __write = out.write  ## cache function address for speed

        __write('\n')

        n_lines = None

        for fi in frames:
            f = N.ravel(self.frames[fi])

            if n_lines is None:
                n_lines = n_lines or len(f) / 10
                overhang = (0 != len(f) % 10)
                i_lines = range(n_lines)

            for i in i_lines:
                __write(template % tuple(f[10 * i:10 * i + 10]))

            if overhang:
                for x in f[i * 10 + 10:]:
                    __write(" %7.3f" % x)
                __write('\n')

        out.close()
Esempio n. 18
0
    def writeCrd( self, fname, frames=None ):
        """
        Write frames to Amber crd file (w/o box info).

        @param fname: output file name
        @type  fname: str
        @param frames: frame indices (default: all)
        @type  frames: [int]
        """
        if frames == None:
            frames = range( self.lenFrames() )

        template = " %7.3f" * 10 + '\n'

        ## open new file
        out = open( T.absfile(fname), 'w')
        __write = out.write  ## cache function address for speed

        __write('\n')

        n_lines = None

        for fi in frames:
            f = N.ravel( self.frames[ fi ] )

            if n_lines is None:
                n_lines = n_lines or len( f ) / 10
                overhang= ( 0 != len( f ) % 10 )
                i_lines = range( n_lines )

            for i in i_lines:
                __write( template % tuple( f[10*i:10*i+10] ) )

            if overhang:
                for x in f[i*10+10:]:
                    __write(" %7.3f" % x )
                __write('\n')

        out.close()
Esempio n. 19
0
    def __init__( self, source=None ):
        """
        @param source: path to EZD file
        @type  source: str OR file handle
        """

        ## Raik says: this is always overridden by the "self.source=source" 
        if type( source ) is str and os.path.isfile( source ):
            self.source = LocalPath( source )

        self.source = source

        ## my suggestion (LocalPath is a bit overkill here):
        self.source = tools.absfile( source )

        #try :
        f=tools.gzopen(self.source)
        self.__jumpComment(f)
        cell=self.__readCell(f)
        self.a=cell[0]
        self.b=cell[1]
        self.c=cell[2]
        self.alpha=cell[3]
        self.beta=cell[4]
        self.gamma=cell[5]

        self.origin=self.__readOrigin(f)
        self.extent=self.__readExtent(f)
        self.gridsize=self.__readGridSize(f)
        self.scale=self.__readScale(f)


        self.EDGrid=self.__readGrid(f)
        self.__setCartesianCoords()
        self.sd=npy.std(self.EDGrid)
        self.mean=npy.mean(self.EDGrid)
        f.close()
Esempio n. 20
0
    def __init__(self, source=None):
        """
        @param source: path to EZD file
        @type  source: str OR file handle
        """

        ## Raik says: this is always overridden by the "self.source=source"
        if type(source) is str and os.path.isfile(source):
            self.source = LocalPath(source)

        self.source = source

        ## my suggestion (LocalPath is a bit overkill here):
        self.source = tools.absfile(source)

        #try :
        f = tools.gzopen(self.source)
        self.__jumpComment(f)
        cell = self.__readCell(f)
        self.a = cell[0]
        self.b = cell[1]
        self.c = cell[2]
        self.alpha = cell[3]
        self.beta = cell[4]
        self.gamma = cell[5]

        self.origin = self.__readOrigin(f)
        self.extent = self.__readExtent(f)
        self.gridsize = self.__readGridSize(f)
        self.scale = self.__readScale(f)

        self.EDGrid = self.__readGrid(f)
        self.__setCartesianCoords()
        self.sd = npy.std(self.EDGrid)
        self.mean = npy.mean(self.EDGrid)
        f.close()
Esempio n. 21
0
    def __parseConfig(self, configFile):
        """
        Read in a solvent configuration file and process the data to
        create a new solvent in the main or local solvent database.

        Templates for the configuration file can be obtained through
        the user interface.

        :arg str configFile: Solvent configuration filename to read and parse.
                It should contain all mandatory fields.
        """
        import SettingsParser as P
        file = T.absfile(configFile)
        config = P.SettingsParser(file)
        result = config.parse(keepsections=True)

        d = {}

        # GENERAL SECTION
        generalSection = self.__getSection(result, 'GENERAL')
        name = self.__getOption(generalSection, 'name').value
        info = self.__getOption(generalSection, 'info').value
        off = self.__getOption(generalSection, 'objectfile').value
        boxunit = self.__getOption(generalSection, 'boxunit').value
        if generalSection.get('watermodel'):
            watermodel = generalSection.get('watermodel').value
        else:
            watermodel = S.DEF_AMBER_WATBOX

        d.update({
            'name': name,
            'info': info,
            'boxunit': boxunit,
            'watermodel': watermodel
        })

        # Check off file exists and can find it
        if not osp.exists(off):
            # Trye to search it in configfile directory
            off = osp.join(osp.dirname(file), off)
            if not osp.exists(off): raise P.InvalidPath

        # This one is optional. If present, will be loaded along the off file in tleap
        # Usually parameters will be saved inside the off file.
        # If frcmod was given, convert to list and check all files exist
        frcmod = generalSection.get('frcmod')
        frcmodlist = []
        if frcmod:
            frcmod.typeCast(list)
            frcmod = frcmod.value
            frcmodlist = []
            for f in frcmod:
                if not osp.exists(f):
                    # Trye to search it in configfile directory
                    f = osp.join(osp.dirname(file), f)
                    if not osp.exists(f):
                        raise P.InvalidPath, "%f frcmod file not found" % f
                    frcmodlist.append(f)
                else:
                    frcmodlist.append(f)

        # PROBES SECTION
        probesmap = self.__todict(self.__getSection(result, 'PROBES'))

        # TYPES section -- Will contain chemical type mapping to probenames
        typesmap = self.__todict(self.__getSection(result, 'TYPES'))

        d.update({
            'offpath': off,
            'probesmap': probesmap,
            'typesmap': typesmap,
            'frcmodpaths': frcmodlist
        })

        # Check typesMapping and probesMapping have same keys
        if not set(probesmap.keys()) == set(typesmap.keys()):
            typesSet = set(typesmap.keys())
            probesSet = set(probesmap.keys())
            miss = typesSet - probesSet
            self.log.error(
                "Missmatch between probes in [PROBES] section and chemical types in [TYPES] section: %s"
                % miss)
            raise MappingError

        # OPTIONAL SECTIONS BEGIN HERE
        # CORRECTION SECTION IF MODULES ARE IMPLEMENTED THESE SECTIONS ARE NECESSARY
        # TODO fix this mess of correction parsing
        correctionSect = result.get('CORRECTION')
        corrections = {}
        if correctionSect:
            corr = self.__todict(correctionSect)
            for type, val in corr.iteritems():
                type = type.upper()
                corrections[type] = dict(
                    [[el.strip().upper() for el in probe.split(':')]
                     for probe in val.strip().split(',')])
            # transform to float the numbers
            for k, val in corrections.iteritems():
                corrections[k] = dict(zip(val.keys(), map(float,
                                                          val.values())))
            del correctionSect, type, k, val

        d.update({'corrections': corrections})

        # EXTRA SECTION. OPTIONAL.
        # Specific pairs attribute to add to the solvent instances.
        # Implemented for further development.
        extra = result.get('EXTRA') or {}
        if extra:
            self.log.info(
                "Solvent has EXTRA field. Will add each flag to attributes.")
            extra = self.__todict(extra)
        d.update(extra)

        return d
Esempio n. 22
0
 def __init__(self, ini):
     self.log = logging.getLogger("SettingsParser")
     self.f_ini = T.absfile(ini)
     self.result = {}