Loads a single molecule from a pdb file.

       This function does support only a small fragment from the pdb specification.
       It assumes that there is only one molecular geometry in the pdb file.
971976
def load_pdb(filename):
    
    with open(filename) as f:
        numbers = []
        coordinates = []
        occupancies = []
        betas = []
        for line in f:
            if line.startswith("ATOM"):
                symbol = line[76:78].strip()
                numbers.append(periodic[symbol].number)
                coordinates.append([float(line[30:38])*angstrom, float(line[38:46])*angstrom, float(line[46:54])*angstrom])
                occupancies.append(float(line[54:60]))
                betas.append(float(line[60:66]))
    if len(numbers) > 0:
        molecule = Molecule(numbers, coordinates)
        molecule.occupancies = np.array(occupancies)
        molecule.betas = np.array(betas)
        return molecule
    else:
        raise FileFormatError("No molecule found in pdb file %s" % filename)
705537
def _parse_geometry(self, geom):
        
        atoms = []
        for i, line in enumerate(geom.splitlines()):
           sym, atno, x, y, z = line.split()
           atoms.append(Atom(sym, [float(x), float(y), float(z)], id=i))
        
        return Molecule(atoms)
680234
def load_pdb(self, pdbpath, as_string=False):
        """"""
        if as_string:
            self.sourcefiles['pdbcomplex.original'] = None
            self.sourcefiles['pdbcomplex'] = None
            self.sourcefiles['pdbstring'] = pdbpath
        else:
            self.sourcefiles['pdbcomplex.original'] = pdbpath
            self.sourcefiles['pdbcomplex'] = pdbpath
        self.information['pdbfixes'] = False
        pdbparser = PDBParser(pdbpath, as_string=as_string)  # Parse PDB file to find errors and get additonal data
        # #@todo Refactor and rename here
        self.Mapper.proteinmap = pdbparser.proteinmap
        self.Mapper.reversed_proteinmap = {v: k for k, v in self.Mapper.proteinmap.items()}
        self.modres = pdbparser.modres
        self.covalent = pdbparser.covalent
        self.altconf = pdbparser.altconformations
        self.corrected_pdb = pdbparser.corrected_pdb

        if not config.PLUGIN_MODE:
            if pdbparser.num_fixed_lines > 0:
                write_message('%i lines automatically fixed in PDB input file.\n' % pdbparser.num_fixed_lines)
                # Save modified PDB file
                if not as_string:
                    basename = os.path.basename(pdbpath).split('.')[0]
                else:
                    basename = "from_stdin"
                pdbpath_fixed = tmpfile(prefix='plipfixed.' + basename + '_', direc=self.output_path)
                create_folder_if_not_exists(self.output_path)
                self.sourcefiles['pdbcomplex'] = pdbpath_fixed
                self.corrected_pdb = re.sub(r'[^\x00-\x7F]+', ' ', self.corrected_pdb)  # Strip non-unicode chars
                if not config.NOFIXFILE:  # Only write to file if this option is not activated
                    with open(pdbpath_fixed, 'w') as f:
                        f.write(self.corrected_pdb)
                self.information['pdbfixes'] = True

        if not as_string:
            self.sourcefiles['filename'] = os.path.basename(self.sourcefiles['pdbcomplex'])
        self.protcomplex, self.filetype = read_pdb(self.corrected_pdb, as_string=True)

        # Update the model in the Mapper class instance
        self.Mapper.original_structure = self.protcomplex.OBMol
        write_message('PDB structure successfully read.\n')

        # Determine (temporary) PyMOL Name from Filename
        self.pymol_name = pdbpath.split('/')[-1].split('.')[0] + '-Protein'
        # Replace characters causing problems in PyMOL
        self.pymol_name = self.pymol_name.replace(' ', '').replace('(', '').replace(')', '').replace('-', '_')
        # But if possible, name it after PDBID in Header
        if 'HEADER' in self.protcomplex.data:  # If the PDB file has a proper header
            potential_name = self.protcomplex.data['HEADER'][56:60].lower()
            if extract_pdbid(potential_name) != 'UnknownProtein':
                self.pymol_name = potential_name
        write_message("Pymol Name set as: '%s'\n" % self.pymol_name, mtype='debug')

        # Extract and prepare ligands
        ligandfinder = LigandFinder(self.protcomplex, self.altconf, self.modres, self.covalent, self.Mapper)
        self.ligands = ligandfinder.ligands
        self.excluded = ligandfinder.excluded

        # Add polar hydrogens
        self.protcomplex.OBMol.AddPolarHydrogens()
        for atm in self.protcomplex:
            self.atoms[atm.idx] = atm
        write_message("Assigned polar hydrogens\n", mtype='debug')

        if len(self.excluded) != 0:
            write_message("Excluded molecules as ligands: %s\n" % ','.join([lig for lig in self.excluded]))

        if config.DNARECEPTOR:
            self.resis = [obres for obres in pybel.ob.OBResidueIter(
                self.protcomplex.OBMol) if obres.GetName() in config.DNA+config.RNA]
        else:
            self.resis = [obres for obres in pybel.ob.OBResidueIter(
                self.protcomplex.OBMol) if obres.GetResidueProperty(0)]

        num_ligs = len(self.ligands)
        if num_ligs == 1:
            write_message("Analyzing one ligand...\n")
        elif num_ligs > 1:
            write_message("Analyzing %i ligands...\n" % num_ligs)
        else:
            write_message("Structure contains no ligands.\n\n")
25817
def load(cls, rr, pk):
        '''
        
        '''
        if pk is None:
            return None
        d = rr.table(cls.table).get(pk).run()
        if d is None:
            return None
        doc = cls(rr, d)
        return doc
376120
def substructure(mol, query, largest_only=True, ignore_hydrogen=True):
    
    def subset_filter(cnt1, cnt2):
        diff = cnt2
        diff.subtract(cnt1)
        if any(v < 0 for v in diff.values()):
            return True

    if not (len(mol) and len(query)):
        return False  # two blank molecules are not isomorphic
    m = molutil.clone(mol)
    q = molutil.clone(query)
    if largest_only:
        m = molutil.largest_graph(m)
        q = molutil.largest_graph(q)
    if ignore_hydrogen:
        m = molutil.make_Hs_implicit(m)
        q = molutil.make_Hs_implicit(q)
    if filter_(m, q, f=subset_filter):
        gm = GraphMatcher(q.graph, m.graph, node_match=atom_match)
        return gm.subgraph_is_isomorphic()
    return False
359592
def _fetch_pdb(pdb_code):
        """"""
        txt = None
        url = 'http://www.rcsb.org/pdb/files/%s.pdb' % pdb_code.lower()
        try:
            response = urlopen(url)
            txt = response.read()
            if sys.version_info[0] >= 3:
                txt = txt.decode('utf-8')
            else:
                txt = txt.encode('ascii')
        except HTTPError as e:
            print('HTTP Error %s' % e.code)
        except URLError as e:
            print('URL Error %s' % e.args)
        return url, txt
1229480
def from_lines(pdb_file_lines, strict = True, parse_ligands = False):
        ''''''
        return PDB("\n".join(pdb_file_lines), strict = strict, parse_ligands = parse_ligands)
790806
def retrieve_data_from_rcsb(cls, ligand_code, pdb_id = None, silent = True, cached_dir = None):
        ''''''
        if not silent:
            colortext.printf("Retrieving data from RCSB")
        if cached_dir:
            assert(os.path.exists(cached_dir))

        ligand_info_path, ligand_info, pdb_ligand_info, pdb_ligand_info_path = None, None, None, None
        if cached_dir:
            ligand_info_path = os.path.join(cached_dir, '{0}.cif'.format(ligand_code))
            if os.path.exists(ligand_info_path):
                ligand_info = read_file(ligand_info_path)
        if not ligand_info:
            ligand_info = retrieve_ligand_cif(ligand_code)
            if cached_dir:
                write_file(ligand_info_path, ligand_info)

        # Parse .cif
        l = cls(ligand_code)
        l.parse_cif(ligand_info)
        l.pdb_id = pdb_id or l.pdb_id
        has_pdb_id = l.pdb_id and (len(l.pdb_id) == 4) and (l.pdb_id != '?')  # the last case is unnecessary and will be short-cut but I included it to show possible values

        # Parse PDB XML
        if has_pdb_id:
            if cached_dir:
                pdb_ligand_info_path = os.path.join(cached_dir, '{0}.pdb.ligandinfo'.format(l.pdb_id.lower()))
                if os.path.exists(pdb_ligand_info_path):
                    pdb_ligand_info = read_file(pdb_ligand_info_path)
                else:
                    pdb_ligand_info = retrieve_pdb_ligand_info(l.pdb_id)
                    write_file(pdb_ligand_info_path, pdb_ligand_info)
            else:
                pdb_ligand_info = retrieve_pdb_ligand_info(l.pdb_id)
        if pdb_ligand_info:
            l.parse_pdb_ligand_info(pdb_ligand_info)

        # Retrive the diagram image
        l.get_diagram()

        return l
1064170
def load_bioassembly_info_from_file(self, biomol_num):
        

        # current functionality is to take in a pre-assembled bioassembly file, parse it's MODELs and get info from that
        pass
        from Bio.PDB import PDBParser
        p = PDBParser(PERMISSIVE=True, QUIET=True)

        structure = StructureIO(self.structure_path, self.file_type)

        structure = p.get_structure('tmp', infile)
        bioass_to_chain_stoich = defaultdict(int)
        for model in structure:
            for chain in model:
                bioass_to_chain_stoich[chain.id] += 1
        return dict(bioass_to_chain_stoich)
1322543
def load_cml(cml_filename):
    
    parser = make_parser()
    parser.setFeature(feature_namespaces, 0)
    dh = CMLMoleculeLoader()
    parser.setContentHandler(dh)
    parser.parse(cml_filename)
    return dh.molecules
985556
static public SimpleGraph getMoleculeGraph(IAtomContainer molecule) {
        SimpleGraph graph = new SimpleGraph();
        for (int i = 0; i < molecule.getAtomCount(); i++) {
            IAtom atom = molecule.getAtom(i);
            graph.addVertex(atom);
        }

        for (int i = 0; i < molecule.getBondCount(); i++) {
            IBond bond = molecule.getBond(i);

            /*
             * int order = (int) bond.getOrder(); for (int j=0; j<order; j++) {
             * graph.addEdge(bond.getAtoms()[0], bond.getAtoms()[1]); }
             */
            graph.addEdge(bond.getBegin(), bond.getEnd());
        }
        return graph;
    }
965291
def load(cls, filename, schema_only=False):
        
        o = open(filename)
        s = o.read()
        a = cls.parse(s, schema_only=schema_only)
        if not schema_only:
            a._filename = filename
        o.close()
        return a
1065431
def extract_pp_helices(in_pdb):
    
    t_phi = -75.0
    t_phi_d = 29.0
    t_psi = 145.0
    t_psi_d = 29.0

    pph_dssp = subprocess.check_output(
        [global_settings['dssp']['path'], in_pdb])
    dssp_residues = []
    go = False
    for line in pph_dssp.splitlines():
        if go:
            res_num = int(line[:5].strip())
            chain = line[11:13].strip()
            ss_type = line[16]
            phi = float(line[103:109].strip())
            psi = float(line[109:116].strip())
            dssp_residues.append((res_num, ss_type, chain, phi, psi))
        else:
            if line[2] == '#':
                go = True
            pass
    pp_chains = []
    chain = []
    ch_on = False
    for item in dssp_residues:
        if (item[1] == ' ') and (
            t_phi - t_phi_d < item[3] < t_phi + t_phi_d) and (
            t_psi - t_psi_d < item[4] < t_psi + t_psi_d):
            chain.append(item)
            ch_on = True
        else:
            if ch_on:
                pp_chains.append(chain)
                chain = []
                ch_on = False
    pp_chains = [x for x in pp_chains if len(x) > 1]
    pp_helices = []
    with open(in_pdb, 'r') as pdb:
        pdb_atoms = split_pdb_lines(pdb.read())
    for pp_helix in pp_chains:
        chain_id = pp_helix[0][2]
        res_range = [x[0] for x in pp_helix]
        helix = []
        for atom in pdb_atoms:
            if (atom[2] == "CA") and (
                    atom[5] == chain_id) and (
                    atom[6] in res_range):
                helix.append(tuple(atom[8:11]))
        pp_helices.append(helix)
    return pp_helices
887616
def get_molecule(self, index=0):
        
        return Molecule(self.numbers, self.geometries[index], self.titles[index], symbols=self.symbols)
289257
def pdb_to_structure(filename):
    

    try:
        from Bio.PDB import PDB
    except ImportError:
        print("I can't import Biopython which is needed to handle PDB files.")
        raise
    p = PDB.PDBParser()
    structure = p.get_structure('S', filename)
    for _ in structure.get_chains():
        atoms = [np.array(atom.get_coord()) for atom in structure.get_atoms()]
    return atoms
233608
def write_pdb(self, mol, filename, name=None, num=None):
        

        # ugly hack to get around the openbabel issues with inconsistent
        # residue labelling.
        scratch = tempfile.gettempdir()
        with ScratchDir(scratch, copy_to_current_on_exit=False) as _:
            mol.to(fmt="pdb", filename="tmp.pdb")
            bma = BabelMolAdaptor.from_file("tmp.pdb", "pdb")

        num = num or 1
        name = name or "ml{}".format(num)

        # bma = BabelMolAdaptor(mol)
        pbm = pb.Molecule(bma._obmol)
        for i, x in enumerate(pbm.residues):
            x.OBResidue.SetName(name)
            x.OBResidue.SetNum(num)

        pbm.write(format="pdb", filename=filename, overwrite=True)
791187
def pdbechem_parse(download = False, filename = '/kortemmelab/shared/mirror/PDBeChem/chem_comp.xml'):
    ''''''

    xml_data = None
    if download:
        # this URL will go out of date
        try:
            resource = ['ftp.ebi.ac.uk', '/pub/databases/msd/pdbechem/chem_comp.xml']
            xml_data = get_insecure_resource(resource[0], resource[1])
        except FTPException550, e:
            colortext.error("This resource ftp://%s appears to be missing. The link may need to be updated in the script." % "".join(resource))
            raise
        except Exception, e:
            colortext.error("An error occurred downloading ftp://%s:\n%s" % ("".join(resource), str(e)))
            raise
    else:
        xml_data = read_file(filename)

    _dom = parseString(xml_data)

    main_tag = _dom.getElementsByTagName("chemCompList")
    assert(len(main_tag) == 1)
    main_tag = main_tag[0]
    entries = main_tag.getElementsByTagName("chemComp")

    parsed_dict = {}
    properties = ["id", "name", "formula", "systematicName", "stereoSmiles", "nonStereoSmiles", "InChi"]
    for e in entries:
        d = {}
        for p in properties:
            t = e.getElementsByTagName(p)
            assert(len(t) <= 1)
            if p == "id":
                assert(len(t) == 1 and t[0].childNodes)
            if len(t):
                if t[0].childNodes:
                    d[p] = t[0].firstChild.nodeValue
                else:
                    d[p] = None
            else:
                d[p] = None
        parsed_dict[d['id']] = d
    return parsed_dict