當前位置: 首頁>>代碼示例>>Python>>正文


Python Session.close方法代碼示例

本文整理匯總了Python中hpf.hddb.db.Session.close方法的典型用法代碼示例。如果您正苦於以下問題:Python Session.close方法的具體用法?Python Session.close怎麽用?Python Session.close使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在hpf.hddb.db.Session的用法示例。


在下文中一共展示了Session.close方法的7個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: xml

# 需要導入模塊: from hpf.hddb.db import Session [as 別名]
# 或者: from hpf.hddb.db.Session import close [as 別名]
def xml(id):
    from hpf.hddb.db import Session, Family
    session = Session()
    family = session.query(Family).get(id)
    filename = "%i.xml" % family.id

    if runtime().opt(GZIP):
        import gzip
        filename = "%s.gz" % filename
        handle = gzip.open(filename,"w")
    else:
        handle = open(filename,"w")

    try:
        doc = FamilyFeatureBuilder(
            lambda: DefaultXMLGenerator(handle,pretty=True),
            lambda handler: StructureFeatureProvider(handler),
            lambda handler: ColumnFeatureProvider(handler),
            lambda handler: IeaFeatureProvider(handler),
            lambda handler: SelectionFeatureProvider(handler)
            )
        doc.buildDocument(family)
    finally:
        handle.close()
    session.close()
開發者ID:bsmithers,項目名稱:hpf,代碼行數:27,代碼來源:export_xml.py

示例2: __getitem__

# 需要導入模塊: from hpf.hddb.db import Session [as 別名]
# 或者: from hpf.hddb.db.Session import close [as 別名]
 def __getitem__(self, key):
     from hpf.hddb.db import Session, SequenceAc
     amnh = self._oid_amnh[key]
     session = Session()
     try:
         ac = session.query(SequenceAc).filter(SequenceAc.ac==amnh).first()
         return ac.protein_key if ac else None
     finally:
         session.close()
開發者ID:bsmithers,項目名稱:hpf,代碼行數:11,代碼來源:oid.py

示例3: _make_seqfile

# 需要導入模塊: from hpf.hddb.db import Session [as 別名]
# 或者: from hpf.hddb.db.Session import close [as 別名]
 def _make_seqfile(self, ):
     from hpf.hddb.db import Session, Sequence
     session=Session()
     sequence = session.query(Sequence).get(self.sequence_id)
     if not sequence:
         raise Exception("Getting sequence object from database failed")
     outhandle = open(self.sequence_file, 'w')
     outhandle.write(">hpf_seqid|{0}\n".format(sequence.id))
     outhandle.write("{0}\n".format(sequence.sequence))
     outhandle.close()
     session.close()
開發者ID:bsmithers,項目名稱:hpf,代碼行數:13,代碼來源:interpro.py

示例4: OIDImporter

# 需要導入模塊: from hpf.hddb.db import Session [as 別名]
# 或者: from hpf.hddb.db.Session import close [as 別名]
class OIDImporter(object):
    """
    Import a set of OID files into the database
    """

    def __init__(
        self,
        familyName,
        alignFile,
        alignColcullLog,
        alignSeqcullLog,
        treeFile,
        treeDiagCharsFile,
        codemlFile=None,
        alignFormat="fasta",
        oid_key=None,
    ):
        self.familyName = familyName
        self.treeFile = treeFile
        self.treeDiagCharsFile = treeDiagCharsFile
        self.alignFile = alignFile
        self.alignColcullLog = alignColcullLog
        self.alignSeqcullLog = alignSeqcullLog
        self.codemlFile = codemlFile
        self.alignFormat = alignFormat
        self.oid_key = oid_key

    def merge(self):
        from hpf.hddb.db import Session, Family

        self.session = Session()

        self.family = self.session.query(Family).filter(Family.name == self.familyName).first()
        if not self.family:
            runtime().debug("Creating family", self.familyName)
            self._family()
            self._alignment()
            self._tree()
        else:
            self.alignment = self.family.alignment
            self.tree = self.alignment.tree
            runtime().debug("Found family", self.family.id)

        if not self.family.alignments[0].tree.codeml:
            runtime().debug("Importing codeml")
            self._codeml()
        else:
            runtime().debug("Already found codeml", self.family.alignments[0].tree.codeml.id)

        # Commit the session, close, and finish
        self.session.commit()
        self.session.close()

    def _index(self, name):
        n = name.split("#")[-1]
        if n.startswith("N"):
            n = n[1:]
        assert n.isdigit()
        return n

    def _tree(self):
        session = self.session

        # # Load the tree file and rename the taxa.
        # from Bio.Nexus.Nexus import Nexus
        # nex=Nexus(self.treeFile)
        # self.nexus = nex.trees[0]

        from Bio.Nexus.Trees import Tree as NewickTree

        tree_str = open(self.treeFile).read()
        self.nexus = NewickTree(tree_str)

        # Rename all the taxa.
        for id in self.nexus.get_terminals():
            node = self.nexus.node(id)
            node.data.taxon = self._index(node.data.taxon)

        # Create the DB object
        from hpf.hddb.db import Tree

        self.tree = Tree(
            alignment_key=self.alignment.id,
            text=self.nexus.to_string(plain=False, plain_newick=True),
            filename=self.treeFile,
        )
        session.add(self.tree)
        session.flush()

        # Now add in the node references
        self.nexus.name = self.tree.id
        assert self.tree.id != None
        runtime().debug("Added tree", self.tree)
        from hpf.hddb.db import TreeNodeFactory

        nodes = list(TreeNodeFactory().create(self.nexus))
        for node in nodes:
            node.ancestor_node = node.ancestor.id if node.ancestor else None
            # This should add the new object into the session
            self.tree.nodes.append(node)
#.........這裏部分代碼省略.........
開發者ID:bsmithers,項目名稱:hpf,代碼行數:103,代碼來源:oid.py

示例5: McmDBExporter

# 需要導入模塊: from hpf.hddb.db import Session [as 別名]
# 或者: from hpf.hddb.db.Session import close [as 別名]
class McmDBExporter(object):
    """
    Writes an MCM data file, calculating SS values using DSSP.
    """
    
    # Order of columns for data file
    columns = ["structure_key",
               "sequence_key",
               "length", 
               "percent_alpha", 
               "percent_beta", 
               "sccs", 
               "astral_ac"]
    
    def __init__(self, 
                 mcmdb, 
                 mammoth_list="list.mammoth", 
                 info_file="data.mammothDb", 
                 dir=None):
        self.mcmdb = mcmdb
        self.mammoth_list = mammoth_list
        self.info_file = info_file
        self.dir = dir
        
    def __enter__(self):
        if not self.dir:
            self.dir = mkdtemp()
        from hpf.hddb.db import Session
        self.session = Session()
        self.list_handle = open(self.mammoth_list,"w")
        self.info_handle = open(self.info_file,"w")
        
        print >>self.info_handle, "\t".join(McmDBExporter.columns)
        print >>self.list_handle, "MAMMOTH List\n%s" % self.dir
        return self
        
    def __exit__(self, type, value, traceback):
        self.session.close()
        self.session = None
        self.list_handle.close()
        self.info_handle.close()

    def export(self):
        for id in self.mcmdb._ids:
            try:
                self._write(self._dict(id))
            except:
                print "error on",id
                continue

    def _write(self, d):
        data = [d[key] for key in McmDBExporter.columns]
        astral = d["astral"]
        print >>self.info_handle, "\t".join([str(value) for value in data])
        f = "%i.pdb" % astral.structure_key
        print >>self.list_handle, f
        full = os.path.join(self.dir,f)
        with open(full,"w") as handle:
            handle.write(astral.structure.text)
        
        
    def _dict(self, id):
        """
        @return:  
        """
        values = {}
        from hpf.hddb.db import Astral
        astral = self.session.query(Astral).get(id)
        dssp = self._dssp(astral.structure)
        
        ss = []
        first_model = list(astral.structure.pdb)[0]
        for i,res in enumerate(first_model.get_residues()):
            chain = res.get_parent().get_id() 
            hetero,seq,insertion = res.get_id()
            key = (chain,(' ',seq,insertion))
            try:
                aa, s, accessibility = dssp[key]
                ss.append(s)
            except:
                continue
        length = i+1
        assert float(abs(length-len(ss)))/float(length)<0.1
        alpha = [a for a in ss if a in ('H','G','I')]
        beta = [a for a in ss if a in ('E','B')]
        
        values['percent_alpha'] = float(len(alpha))/float(length)
        values['percent_beta'] = float(len(beta))/float(length)
        values["astral"] = astral
        values["length"] = length
        values["sccs"] = astral.sccs
        values["astral_ac"] = astral.stype+astral.pdbid+astral.part
        values["sequence_key"] = astral.sequence_key
        values["structure_key"] = astral.structure_key
        
        return values
            
    def _dssp(self, structure):
        structure_temp = NamedTemporaryFile(dir = self.dir)
        structure_file = structure_temp.name
#.........這裏部分代碼省略.........
開發者ID:bsmithers,項目名稱:hpf,代碼行數:103,代碼來源:__init__.py

示例6: tasks

# 需要導入模塊: from hpf.hddb.db import Session [as 別名]
# 或者: from hpf.hddb.db.Session import close [as 別名]
def tasks():
    from hpf.hddb.db import Session, Family
    session = Session()
    ids = session.query(Family.id).filter(Family.manually_curated==0).all()
    session.close()
    return [i[0] for i in ids]
開發者ID:bsmithers,項目名稱:hpf,代碼行數:8,代碼來源:export_xml.py

示例7: MCM

# 需要導入模塊: from hpf.hddb.db import Session [as 別名]
# 或者: from hpf.hddb.db.Session import close [as 別名]

#.........這裏部分代碼省略.........
        """Checks code against static CODE PATTERN. If correct, returns code. Otherwise, exception"""
        if not re.match(CODE_PATTERN, code):
            raise Exception("Given code '{0}' does not match Rosetta prediction code form (eg: aa111)".format(code))
        return code

    def _setup_env(self, ):
        """Creates and checks directories and files. Changes working directory"""
        if not os.path.isdir(self.base_dir):
            os.mkdir(self.base_dir)
        if not os.path.isdir(self.work_dir):
            os.mkdir(self.work_dir)
        os.chdir(self.work_dir)

        # Check decoy file's existence
        if not os.path.isfile(self.decoy_file):
            raise IOError("Given decoy file '{0}' does not exist (is not a file)".format(self.decoy_file))
        # Check for Mammoth files (always required)
        if not os.path.isfile(self.mammoth_listfile):
            raise IOError("Given mammoth list file '{0}' does not exist or is not accessible".format(self.mammoth_listfile))
        if not os.path.isfile(self.mammoth_datafile):
            raise IOError("Given mammoth data file '{0}' does not exist or is not accessible".format(self.mammoth_datafile))
        # Check for rosetta_pathsfile, required for extracting pdb atom records from silent files
        if not os.path.isfile(self.rosetta_pathsfile):
            raise IOError("Given rosetta paths file '{0}' does not exist or is not accessible".format(self.rosetta_pathsfile))
	#kdrew: removing nr db check
        # Do a warning check for files required if Psipred will be run
        #if not os.path.isfile(self.nr_db):
        #    raise Warning("Given nr_db file '{0}' does not exist or is not accessible".format(self.nr_db))

    def _check_session(self, ):
        """Opens session if self.session is None. Closes the session (keeps it from expiring, auto-opened when used)"""
        if not self.session:
            self.session = Session()
        self.session.close()

    def _extract_pdbs(self, denovo_results, cluster_results, log=None, pathfile=None):
        """For each cluster center in cluster results, make an individual silent file and then extracts the PDB
        record from that silent file (outputs PDB record to file)
          denovo_results  - DenovoResultFile object (holds silent records)
          cluster_results - RobettaCluster object (holds cluster centers)
        Returns a dict of form {index => pdb_filename} for all cluster centers
        NOTE: It looks odd to create an individ. silent file for each decoy, but is the only way to guarantee
        extractor is pulling the right decoy for given S_id (which are not unique - why, I'll never know)
        """
        from hpf.mcm.extract import extract
        pdb_files = dict()
        
        for center in cluster_results:
            # Create filenames for holding silent file and target to move output PDB file to
            silent_file = "decoy_{0}.silent".format(center.index)
            pdb_file = "decoy_{0}.pdb".format(center.index)
            
            # Get and write silent record
            silent_record = denovo_results[center.index]
            denovo_results.write_to_file(outfile=silent_file, results_list=[silent_record])
            
            # Run extract and move extracted file to named pdb file
            extract_file = extract(silent_file, center.rosetta_id, log_file=log, paths=pathfile, debug=self.debug)
            shutil.move(extract_file, pdb_file)
            if not os.path.isfile(pdb_file):
                raise OSError("Extract functionality in MCM failed to create pdb file '{0}'".format(pdb_file))
           
            # Set center's pdb_file attribute to created file and add to dictionary
            center.pdb_file = pdb_file
            pdb_files[center.index] = pdb_file
            
開發者ID:dpenfoldbrown,項目名稱:hpf,代碼行數:69,代碼來源:new_mcm.py


注:本文中的hpf.hddb.db.Session.close方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。