Read a `~chemlab.core.Molecule` from a file.

    .. seealso:: `chemlab.io.datafile`
11999
def load_molecule(name, format=None):
    '''
    
    '''    
    mol = datafile(name, format=format).read('molecule')
    display_system(System([mol]))
881452
def read_dftbp(filename):
    

    infile = open(filename, 'r')

    lines = infile.readlines()

    # remove any comments
    for ss in lines:
        if ss.strip().startswith('#'):
            lines.remove(ss)

    natoms = int(lines[0].split()[0])
    symbols = lines[1].split()

    if (lines[0].split()[1].lower() == 'f'):
        is_scaled = True
        scale_pos = 1
        scale_latvecs = dftbpToBohr
    else:
        is_scaled = False
        scale_pos = dftbpToBohr
        scale_latvecs = dftbpToBohr

    # assign positions and expanded symbols
    positions = []
    expaned_symbols = []

    for ii in range(2, natoms+2):
        lsplit = lines[ii].split()

        expaned_symbols.append(symbols[int(lsplit[1]) - 1])
        positions.append([float(ss)*scale_pos for ss in lsplit[2:5]])

    # origin is ignored, may be used in future
    origin = [float(ss) for ss in lines[natoms+2].split()]

    # assign coords of unitcell
    cell = []

    for ii in range(natoms+3, natoms+6):
        lsplit = lines[ii].split()

        cell.append([float(ss)*scale_latvecs for ss in lsplit[:3]])
    cell = np.array(cell)

    if is_scaled:
        atoms = Atoms(symbols=expaned_symbols,
                      cell=cell,
                      scaled_positions=positions)
    else:
        atoms = Atoms(symbols=expaned_symbols,
                      cell=cell,
                      positions=positions)

    return atoms
793706
def read_molden(inputfile, start_index=0, get_bonds=True):
    
    from chemcoord.cartesian_coordinates.cartesian_class_main import Cartesian
    with open(inputfile, 'r') as f:
        found = False
        while not found:
            line = f.readline()
            if '[N_GEO]' in line:
                found = True
                number_of_molecules = int(f.readline().strip())

        energies = []
        found = False
        while not found:
            line = f.readline()
            if 'energy' in line:
                found = True
                for _ in range(number_of_molecules):
                    energies.append(float(f.readline().strip()))

        found = False
        while not found:
            line = f.readline()
            if '[GEOMETRIES] (XYZ)' in line:
                found = True
                current_line = f.tell()
                number_of_atoms = int(f.readline().strip())
                f.seek(current_line)

        cartesians = []
        for energy in energies:
            cartesian = Cartesian.read_xyz(
                f, start_index=start_index, get_bonds=get_bonds,
                nrows=number_of_atoms, engine='python')
            cartesian.metadata['energy'] = energy
            cartesians.append(cartesian)
    return cartesians
379447
def inspect_file(path):
    
    with open(path, 'rb') as f:
        labels, count = inspect(tx.decode(line) for line in f)
    return labels, count
1220538
def parse_results_mol2(mol2_outpath):
    
    docked_ligands = pd.DataFrame()

    lines = [line.strip() for line in open(mol2_outpath, 'r')]
    props = {}

    for i, line in enumerate(lines):
        if line.startswith('########## Name:'):
            ligand = line.strip().strip('##########').replace(' ', '').replace('\t', '').split(':')[1]
            line = lines[i + 1]
            props = {}
            props['Ligand'] = ligand
        if line.startswith('##########'):
            splitter = line.strip().strip('##########').replace(' ', '').replace('\t', '').split(':')
            props[splitter[0]] = float(splitter[1])
        if line.startswith('@<TRIPOS>MOLECULE'):
            if props:
                docked_ligands = docked_ligands.append(props, ignore_index=True)

    return docked_ligands
180025
public  Structure parsePDBFile(BufferedReader buf)
			throws IOException
			{
		// set the correct max values for parsing...
		loadMaxAtoms = params.getMaxAtoms();
		atomCAThreshold = params.getAtomCaThreshold();


		// (re)set structure

		allModels = new ArrayList<>();
		structure     = new StructureImpl() ;
		currentModel  = null;
		currentChain  = null;
		currentGroup  = null;
		// we initialise to true since at the beginning of the file we are always starting a new molecule
		startOfMolecule = true;
		startOfModel = true;

		seqResChains  = new ArrayList<Chain>();
		siteMap = new LinkedHashMap<String, Site>();
		pdbHeader     = new PDBHeader();
		connects      = new ArrayList<Map<String,Integer>>();
		previousContinuationField = "";
		continuationField = "";
		continuationString = "";
		current_compound = null;
		sourceLines.clear();
		compndLines.clear();
		isLastCompndLine = false;
		isLastSourceLine = false;
		prevMolId = -1;
		entities.clear();
		helixList.clear();
		strandList.clear();
		turnList.clear();
		lengthCheck = -1;
		atomCount = 0;
		atomOverflow = false;
		linkRecords = new ArrayList<LinkRecord>();
		siteToResidueMap.clear();

		blankChainIdsPresent = false;

		parseCAonly = params.isParseCAOnly();

		String line = null;

		while ((line = buf.readLine()) != null) {

			// ignore empty lines
			if ( line.equals("") ||
					(line.equals(NEWLINE))){
				continue;
			}


			// ignore short TER and END lines
			if ( line.startsWith("END")) {
				continue;
			}

			if ( line.length() < 6 && !line.startsWith("TER")) {
				logger.info("Found line length below 6. Ignoring it, line: >" + line +"<" );
				continue;
			}

			String recordName = null;
			if (line.length()<6)
				recordName = line.trim();
			else
				recordName = line.substring (0, 6).trim ();

			try {
				if (recordName.equals("ATOM"))
					pdb_ATOM_Handler(line);
				else if (recordName.equals("SEQRES"))
					pdb_SEQRES_Handler(line);
				else if (recordName.equals("HETATM"))
					pdb_ATOM_Handler(line);
				else if (recordName.equals("MODEL"))
					pdb_MODEL_Handler(line);
				else if (recordName.equals("TER"))
					pdb_TER_Handler();
				else if (recordName.equals("HEADER"))
					pdb_HEADER_Handler(line);
				else if (recordName.equals("AUTHOR"))
					pdb_AUTHOR_Handler(line);
				else if (recordName.equals("TITLE"))
					pdb_TITLE_Handler(line);
				else if (recordName.equals("SOURCE"))
					sourceLines.add(line); //pdb_SOURCE_Handler
				else if (recordName.equals("COMPND"))
					compndLines.add(line); //pdb_COMPND_Handler
				else if (recordName.equals("JRNL"))
					pdb_JRNL_Handler(line);
				else if (recordName.equals("EXPDTA"))
					pdb_EXPDTA_Handler(line);
				else if (recordName.equals("CRYST1"))
					pdb_CRYST1_Handler(line);
				else if (recordName.startsWith("MTRIX"))
					pdb_MTRIXn_Handler(line);
				else if (recordName.equals("REMARK"))
					pdb_REMARK_Handler(line);
				else if (recordName.equals("CONECT"))
					pdb_CONECT_Handler(line);
				else if (recordName.equals("REVDAT"))
					pdb_REVDAT_Handler(line);
				else if (recordName.equals("DBREF"))
					pdb_DBREF_Handler(line);
				else if (recordName.equals("SITE"))
					pdb_SITE_Handler(line);
				else if (recordName.equals("SSBOND"))
					pdb_SSBOND_Handler(line);
				else if (recordName.equals("LINK"))
					pdb_LINK_Handler(line);
				else if ( params.isParseSecStruc()) {
					if ( recordName.equals("HELIX") ) pdb_HELIX_Handler (  line ) ;
					else if (recordName.equals("SHEET")) pdb_SHEET_Handler(line ) ;
					else if (recordName.equals("TURN")) pdb_TURN_Handler(   line ) ;
				}
			} catch (StringIndexOutOfBoundsException | NullPointerException ex) {
				logger.info("Unable to parse [" + line + "]");
			}
		}

		makeCompounds(compndLines, sourceLines);

		triggerEndFileChecks();

		if (params.shouldCreateAtomBonds()) {
			formBonds();
		}

		if ( params.shouldCreateAtomCharges()) {
			addCharges();
		}

		if ( params.isParseSecStruc() && !params.isHeaderOnly())
			setSecStruc();

		// Now correct the alternate location group
		StructureTools.cleanUpAltLocs(structure);

		return structure;

			}
895869
def read_molcas(basis_lines, fname):
    '''
    '''

    skipchars = '*#$'
    basis_lines = [l for l in basis_lines if l and not l[0] in skipchars]

    bs_data = create_skel('component')

    i = 0
    while i < len(basis_lines):
        line = basis_lines[i]

        if not line.startswith('/'):
            raise RuntimeError("Expecting line starting with /")

        line_splt = line[1:].split('.')
        elementsym = line_splt[0]

        element_Z = lut.element_Z_from_sym(elementsym)
        element_Z = str(element_Z)

        if not element_Z in bs_data['elements']:
            bs_data['elements'][element_Z] = {}

        element_data = bs_data['elements'][element_Z]

        if "ecp" in line.lower():
            raise NotImplementedError("MolCAS ECPs not supported")

            #if not 'ecp_potentials' in element_data:
            #    element_data['ecp_potentials'] = []

            #i += 1
            #line = basis_lines[i]

            #lsplt = line.split('=')
            #maxam = int(lsplt[2])
            #n_elec = int(lsplt[1].split()[0])

            #amlist = [maxam]
            #amlist.extend(list(range(0, maxam)))

            #i += 1
            #for shell_am in amlist:
            #    shell_am2 = lut.amchar_to_int(basis_lines[i][0])[0]
            #    if shell_am2 != shell_am:
            #        raise RuntimeError("AM not in expected order?")

            #    i += 1

            #    ecp_shell = {
            #        'ecp_type': 'scalar',
            #        'angular_momentum': [shell_am],
            #    }
            #    ecp_exponents = []
            #    ecp_rexponents = []
            #    ecp_coefficients = []

            #    while i < len(basis_lines) and basis_lines[i][0].isalpha() is False:
            #        lsplt = basis_lines[i].split()
            #        ecp_exponents.append(lsplt[2])
            #        ecp_rexponents.append(int(lsplt[1]))
            #        ecp_coefficients.append(lsplt[0])
            #        i += 1

            #    ecp_shell['r_exponents'] = ecp_rexponents
            #    ecp_shell['gaussian_exponents'] = ecp_exponents
            #    ecp_shell['coefficients'] = [ecp_coefficients]
            #    element_data['ecp_potentials'].append(ecp_shell)

            #element_data['ecp_electrons'] = n_elec

        else:
            if not 'electron_shells' in element_data:
                element_data['electron_shells'] = []

            # Skip two comment lines (usually ref)
            i += 3

            # Skip over an options block
            line = basis_lines[i]
            if line.lower() == 'options':
                while basis_lines[i].lower() != 'endoptions':
                    i += 1
                i += 1

            lsplt = basis_lines[i].split()
            max_am = int(lsplt[1])
            i += 1

            for shell_am in range(max_am+1):
                lsplt = basis_lines[i].replace(',', ' ').split()
                nprim = int(lsplt[0])
                ngen = int(lsplt[1])
                i += 1

                if shell_am <= 1:
                    func_type = 'gto'
                else:
                    func_type = 'gto_spherical'

                shell = {
                    'function_type': func_type,
                    'region': '',
                    'angular_momentum': [shell_am]
                }

                exponents = []
                coefficients = []

                j = 0
                while j < nprim:
                    line = basis_lines[i].replace('D', 'E')
                    line = line.replace('d', 'E')
                    lsplt = line.split()
                    exponents.extend(lsplt)
                    i += 1
                    j += len(lsplt)

                for j in range(nprim):
                    line = basis_lines[i].replace('D', 'E')
                    line = line.replace('d', 'E')
                    lsplt = line.split()
                    if len(lsplt) != ngen:
                        print(fname)
                        print(line)
                        raise RuntimeError("Unexpected number of coefficients")
                    coefficients.append(lsplt)


                    i += 1

                shell['exponents'] = exponents

                # We need to transpose the coefficient matrix
                # (we store a matrix with primitives being the column index and
                # general contraction being the row index)
                shell['coefficients'] = list(map(list, zip(*coefficients)))

                element_data['electron_shells'].append(shell)

                # Skip energies?
                to_skip = int(basis_lines[i].strip())
                skipped = 0
                i += 1
                while skipped < to_skip:
                    skipped += len(basis_lines[i].split())
                    i += 1
                
    return bs_data
1139033
def read_nwchem(basis_lines, fname):
    '''
    '''

    skipchars = '#'
    basis_lines = [l for l in basis_lines if l and not l[0] in skipchars]

    bs_data = create_skel('component')

    i = 0

    while i < len(basis_lines):
        line = basis_lines[i]

        if line.lower().startswith('basis'):
            i += 1

            # NWChem doesn't seem to really block by element
            # It just has shells labeled with each element symbol

            while i < len(basis_lines) and not basis_lines[i].lower().startswith('end'):
                line = basis_lines[i]
                lsplt = line.split()
                elementsym = lsplt[0]
                shell_am = lut.amchar_to_int(lsplt[1])

                element_Z = lut.element_Z_from_sym(elementsym)
                element_Z = str(element_Z)

                if not element_Z in bs_data['elements']:
                    bs_data['elements'][element_Z] = {}
                if not 'electron_shells' in bs_data['elements'][element_Z]:
                    bs_data['elements'][element_Z]['electron_shells'] = []

                element_data = bs_data['elements'][element_Z]

                if max(shell_am) <= 1:
                    func_type = 'gto'
                else:
                    func_type = 'gto_spherical'

                shell = {
                    'function_type': func_type,
                    'region': '',
                    'angular_momentum': shell_am
                }

                exponents = []
                coefficients = []

                i += 1
                while True:
                    if i >= len(basis_lines) or basis_lines[i][0].isalpha():
                        break

                    line = basis_lines[i].replace('D', 'E')
                    line = line.replace('d', 'E')
                    lsplt = line.split()
                    exponents.append(lsplt[0])
                    coefficients.append(lsplt[1:])
                    i += 1

                shell['exponents'] = exponents

                # We need to transpose the coefficient matrix
                # (we store a matrix with primitives being the column index and
                # general contraction being the row index)
                shell['coefficients'] = list(map(list, zip(*coefficients)))

                element_data['electron_shells'].append(shell)

        elif line.lower().startswith('ecp'):
            i += 1
            while i < len(basis_lines) and not basis_lines[i].lower().startswith('end'):
                line = basis_lines[i]
                if 'nelec' in line.lower():
                    lsplt = line.split()
                    elementsym = lsplt[0]
                    n_elec = int(lsplt[2])

                    element_Z = lut.element_Z_from_sym(elementsym)
                    element_Z = str(element_Z)

                    if not element_Z in bs_data['elements']:
                        bs_data['elements'][element_Z] = {}
                    if not 'ecp_electrons' in bs_data['elements'][element_Z]:
                        bs_data['elements'][element_Z]['ecp_electrons'] = n_elec

                    i += 1
                    continue

                # Now parsing a shell
                lsplt = line.split()
                elementsym = lsplt[0]

                shell_am = lsplt[1]
                if shell_am.lower() == 'ul':
                    shell_am = -1  # Placeholder - leave for later
                else:
                    shell_am = lut.amchar_to_int(lsplt[1])

                element_Z = lut.element_Z_from_sym(elementsym)
                element_Z = str(element_Z)

                if not element_Z in bs_data['elements']:
                    bs_data['elements'][element_Z] = {}
                if not 'ecp_potentials' in bs_data['elements'][element_Z]:
                    bs_data['elements'][element_Z]['ecp_potentials'] = []
                element_data = bs_data['elements'][element_Z]

                ecp_shell = {'angular_momentum': shell_am, 'ecp_type': 'scalar_ecp'}

                rexponents = []
                gexponents = []
                coefficients = []

                i += 1
                while True:
                    if i >= len(basis_lines) or basis_lines[i][0].isalpha():
                        break

                    line = basis_lines[i].replace('D', 'E')
                    line = line.replace('d', 'E')
                    lsplt = line.split()
                    rexponents.append(int(lsplt[0]))
                    gexponents.append(lsplt[1])
                    coefficients.append(lsplt[2:])
                    i += 1

                ecp_shell['r_exponents'] = rexponents
                ecp_shell['gaussian_exponents'] = gexponents

                # We need to transpose the coefficient matrix
                # (we store a matrix with primitives being the column index and
                # general contraction being the row index)
                ecp_shell['coefficients'] = list(map(list, zip(*coefficients)))

                element_data['ecp_potentials'].append(ecp_shell)
        i += 1

        # Fix ecp angular momentum now that everything has been read
        for el, v in bs_data['elements'].items():
            if not 'ecp_potentials' in v:
                continue

            max_ecp_am = -1
            for s in v['ecp_potentials']:
                if s['angular_momentum'] == -1:
                    continue
                max_ecp_am = max(max_ecp_am, max(s['angular_momentum']))

            for s in v['ecp_potentials']:
                if s['angular_momentum'] == -1:
                    s['angular_momentum'] = [max_ecp_am + 1]

    return bs_data
860823
def _load(self, data_file):
        

       # Load the data from a file.
        try:
            data = Schema().load(data_file)
        except (Exception, IOError, ValueError) as e:
            raise e

        return data
862184
def parse_reaction_file(path, default_compartment=None):
    

    context = FilePathContext(path)

    format = resolve_format(None, context.filepath)
    if format == 'tsv':
        logger.debug('Parsing reaction file {} as TSV'.format(
            context.filepath))
        with context.open('r') as f:
            for reaction in parse_reaction_table_file(
                    context, f, default_compartment):
                yield reaction
    elif format == 'yaml':
        logger.debug('Parsing reaction file {} as YAML'.format(
            context.filepath))
        with context.open('r') as f:
            for reaction in parse_reaction_yaml_file(
                    context, f, default_compartment):
                yield reaction
    else:
        raise ParseError('Unable to detect format of reaction file {}'.format(
            context.filepath))
394560
def readFile(self, pathToFile):
        
        fd = open(pathToFile,  "rb")
        data = fd.read()
        fd.close()
        return data
399244
private IChemFile readChemFile(IChemFile chemFile) {
        IChemSequence chemSequence;
        IChemModel chemModel;
        ICrystal crystal;

        try {
            String line = readLine();
            while (input.ready() && line != null) {
                if (line.startsWith("%%Header Start")) {
                    // parse Header section
                    while (input.ready() && line != null && !(line.startsWith("%%Header End"))) {
                        if (line.startsWith("%%Version Number")) {
                            String version = readLine().trim();
                            if (!version.equals("3.00")) {
                                logger.error("The PMPReader only supports PMP files with version 3.00");
                                return null;
                            }
                        }
                        line = readLine();
                    }
                } else if (line.startsWith("%%Model Start")) {
                    // parse Model section
                    modelStructure = chemFile.getBuilder().newInstance(IAtomContainer.class);
                    while (input.ready() && line != null && !(line.startsWith("%%Model End"))) {
                        Matcher objHeaderMatcher = objHeader.matcher(line);
                        if (objHeaderMatcher.matches()) {
                            String object = objHeaderMatcher.group(2);
                            constructObject(chemFile.getBuilder(), object);
                            int id = Integer.parseInt(objHeaderMatcher.group(1));
                            // logger.debug(object + " id: " + id);
                            line = readLine();
                            while (input.ready() && line != null && !(line.trim().equals(")"))) {
                                // parse object command (or new object header)
                                Matcher objCommandMatcher = objCommand.matcher(line);
                                objHeaderMatcher = objHeader.matcher(line);
                                if (objHeaderMatcher.matches()) {
                                    // ok, forget about nesting and hope for the best
                                    object = objHeaderMatcher.group(2);
                                    id = Integer.parseInt(objHeaderMatcher.group(1));
                                    constructObject(chemFile.getBuilder(), object);
                                } else if (objCommandMatcher.matches()) {
                                    String format = objCommandMatcher.group(1);
                                    String command = objCommandMatcher.group(2);
                                    String field = objCommandMatcher.group(3);

                                    processModelCommand(object, command, format, field);
                                } else {
                                    logger.warn("Skipping line: " + line);
                                }
                                line = readLine();
                            }
                            if (chemObject instanceof IAtom) {
                                atomids.put(id, modelStructure.getAtomCount());
                                atomGivenIds.put(Integer.valueOf((String) chemObject.getProperty(PMP_ID)),
                                                 id);
                                modelStructure.addAtom((IAtom) chemObject);
                            } else if (chemObject instanceof IBond) {
                                // ignored: bonds may be defined before their
                                // atoms so their handling is deferred until the
                                // end of the model
                            } else {
                                logger.error("chemObject is not initialized or of bad class type");
                            }
                            // logger.debug(molecule.toString());
                        }
                        line = readLine();
                    }
                    assert line != null;
                    if (line.startsWith("%%Model End")) {
                        // during the Model Start, all bonds are cached as PMP files might
                        // define bonds *before* the involved atoms :(
                        // the next lines dump the cache into the atom container

                        //                  	bondids.put(new Integer(id), new Integer(molecule.getAtomCount()));
                        //                  	molecule.addBond((IBond)chemObject);
                        int bondsFound = bondids.size();
                        logger.debug("Found #bonds: ", bondsFound);
                        logger.debug("#atom ones: ", bondAtomOnes.size());
                        logger.debug("#atom twos: ", bondAtomTwos.size());
                        logger.debug("#orders: ", bondOrders.size());
                        for (Integer index : bondids.keySet()) {
                            double order = (bondOrders.get(index) != null ? bondOrders.get(index) : 1.0);
                            logger.debug("index: ", index);
                            logger.debug("ones: ", bondAtomOnes.get(index));
                            IAtom atom1 = modelStructure.getAtom(atomids.get(bondAtomOnes.get(index)));
                            IAtom atom2 = modelStructure.getAtom(atomids.get(bondAtomTwos.get(index)));
                            IBond bond = modelStructure.getBuilder().newInstance(IBond.class, atom1, atom2);
                            if (order == 1.0) {
                                bond.setOrder(IBond.Order.SINGLE);
                            } else if (order == 2.0) {
                                bond.setOrder(IBond.Order.DOUBLE);
                            } else if (order == 3.0) {
                                bond.setOrder(IBond.Order.TRIPLE);
                            } else if (order == 4.0) {
                                bond.setOrder(IBond.Order.QUADRUPLE);
                            }
                            modelStructure.addBond(bond);
                        }
                    }
                } else if (line.startsWith("%%Traj Start")) {
                    chemSequence = chemFile.getBuilder().newInstance(IChemSequence.class);
                    double energyFragment = 0.0;
                    double energyTotal = 0.0;
                    int Z = 1;
                    while (input.ready() && line != null && !(line.startsWith("%%Traj End"))) {
                        if (line.startsWith("%%Start Frame")) {
                            chemModel = chemFile.getBuilder().newInstance(IChemModel.class);
                            crystal = chemFile.getBuilder().newInstance(ICrystal.class);
                            while (input.ready() && line != null && !(line.startsWith("%%End Frame"))) {
                                // process frame data
                                if (line.startsWith("%%Atom Coords")) {
                                    // calculate Z: as it is not explicitely given, try to derive it from the
                                    // energy per fragment and the total energy
                                    if (energyFragment != 0.0 && energyTotal != 0.0) {
                                        Z = (int) Math.round(energyTotal / energyFragment);
                                        logger.debug("Z derived from energies: ", Z);
                                    }
                                    // add atomC as atoms to crystal
                                    int expatoms = modelStructure.getAtomCount();
                                    for (int molCount = 1; molCount <= Z; molCount++) {
                                        IAtomContainer clone = modelStructure.getBuilder().newInstance(
                                                IAtomContainer.class);
                                        for (int i = 0; i < expatoms; i++) {
                                            line = readLine();
                                            IAtom a = clone.getBuilder().newInstance(IAtom.class);
                                            StringTokenizer st = new StringTokenizer(line, " ");
                                            a.setPoint3d(new Point3d(Double.parseDouble(st.nextToken()), Double
                                                    .parseDouble(st.nextToken()), Double.parseDouble(st.nextToken())));
                                            a.setCovalentRadius(0.6);
                                            IAtom modelAtom = modelStructure.getAtom(atomids.get(atomGivenIds
                                                    .get(i + 1)));
                                            a.setSymbol(modelAtom.getSymbol());
                                            clone.addAtom(a);
                                        }
                                        rebonder.rebond(clone);
                                        crystal.add(clone);
                                    }
                                } else if (line.startsWith("%%E/Frag")) {
                                    line = readLine().trim();
                                    energyFragment = Double.parseDouble(line);
                                } else if (line.startsWith("%%Tot E")) {
                                    line = readLine().trim();
                                    energyTotal = Double.parseDouble(line);
                                } else if (line.startsWith("%%Lat Vects")) {
                                    StringTokenizer st;
                                    line = readLine();
                                    st = new StringTokenizer(line, " ");
                                    crystal.setA(new Vector3d(Double.parseDouble(st.nextToken()), Double.parseDouble(st
                                            .nextToken()), Double.parseDouble(st.nextToken())));
                                    line = readLine();
                                    st = new StringTokenizer(line, " ");
                                    crystal.setB(new Vector3d(Double.parseDouble(st.nextToken()), Double.parseDouble(st
                                            .nextToken()), Double.parseDouble(st.nextToken())));
                                    line = readLine();
                                    st = new StringTokenizer(line, " ");
                                    crystal.setC(new Vector3d(Double.parseDouble(st.nextToken()), Double.parseDouble(st
                                            .nextToken()), Double.parseDouble(st.nextToken())));
                                } else if (line.startsWith("%%Space Group")) {
                                    line = readLine().trim();
                                    /*
                                     * standardize space group name. See
                                     * Crystal.setSpaceGroup()
                                     */
                                    if ("P 21 21 21 (1)".equals(line)) {
                                        crystal.setSpaceGroup("P 2_1 2_1 2_1");
                                    } else {
                                        crystal.setSpaceGroup("P1");
                                    }
                                }
                                line = readLine();
                            }
                            chemModel.setCrystal(crystal);
                            chemSequence.addChemModel(chemModel);
                        }
                        line = readLine();
                    }
                    chemFile.addChemSequence(chemSequence);
                }  // else disregard line

                // read next line
                line = readLine();
            }
        } catch (IOException e) {
            logger.error("An IOException happened: ", e.getMessage());
            logger.debug(e);
            chemFile = null;
        } catch (CDKException e) {
            logger.error("An CDKException happened: ", e.getMessage());
            logger.debug(e);
            chemFile = null;
        }

        return chemFile;
    }
1149790
private IChemFile readChemFile(IChemFile file) throws IOException {
        IChemSequence seq = file.getBuilder().newInstance(IChemSequence.class);
        IChemModel model = file.getBuilder().newInstance(IChemModel.class);
        crystal = file.getBuilder().newInstance(ICrystal.class);

        String line = input.readLine();
        boolean end_found = false;
        while (input.ready() && line != null && !end_found) {
            if (line.length() == 0) {
                logger.debug("Skipping empty line");
                // skip empty lines
            } else if (line.charAt(0) == '#') {
                logger.warn("Skipping comment: ", line);
                // skip comment lines
            } else if (!(line.charAt(0) == '_' || line.startsWith("loop_"))) {
                logger.warn("Skipping unrecognized line: ", line);
                // skip line
            } else {

                /* determine CIF command */
                String command = "";
                int spaceIndex = line.indexOf(' ');
                if (spaceIndex != -1) {
                    // everything upto space is command
                    try {
                        command = line.substring(0, spaceIndex);
                    } catch (StringIndexOutOfBoundsException sioobe) {
                        // disregard this line
                        break;
                    }
                } else {
                    // complete line is command
                    command = line;
                }

                logger.debug("command: ", command);
                if (command.startsWith("_cell")) {
                    processCellParameter(command, line);
                } else if (command.equals("loop_")) {
                    line = processLoopBlock();
                    continue;
                } else if (command.equals("_symmetry_space_group_name_H-M")) {
                    String value = line.substring(29).trim();
                    crystal.setSpaceGroup(value);
                } else {
                    // skip command
                    logger.warn("Skipping command: ", command);
                    line = input.readLine();
                    if (line != null && line.startsWith(";")) {
                        logger.debug("Skipping block content");
                        while ((line = input.readLine()) != null &&
                               !line.startsWith(";")) {
                            logger.debug("Skipping block line: ", line);
                        }
                    }
                }
            }
            line = input.readLine();
        }
        logger.info("Adding crystal to file with #atoms: ", crystal.getAtomCount());
        model.setCrystal(crystal);
        seq.addChemModel(model);
        file.addChemSequence(seq);
        return file;
    }
668489
def from_file(cls, filename):
        """"""

        dsxml = xml_open(filename, 'datasource').getroot()
        return cls(dsxml, filename)
1201932
def write_molecule(filename, format=None):
    ''''''
    datafile(filename, format=format,
             mode='w').write('molecule',current_system())
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
1031391
def _read(
    filename,
    schema,
    seq_label='sequence',
    alphabet=None,
    use_uids=True,
    **kwargs):
    
    # Check Alphabet if given
    if alphabet is None:
        alphabet = Bio.Alphabet.Alphabet()

    elif alphabet in ['dna', 'rna', 'protein', 'nucleotide']:
        alphabet = getattr(Bio.Alphabet, 'generic_{}'.format(alphabet))

    else:
        raise Exception(
            "The alphabet is not recognized. Must be 'dna', 'rna', "
            "'nucleotide', or 'protein'.")

    kwargs.update(alphabet=alphabet)

    # Prepare DataFrame fields.
    data = {
        'id': [],
        seq_label: [],
        'description': [],
        'label': []
    }
    if use_uids:
        data['uid'] = []

    # Parse Fasta file.
    for i, s in enumerate(SeqIO.parse(filename, format=schema, **kwargs)):
        data['id'].append(s.id)
        data[seq_label].append(str(s.seq))
        data['description'].append(s.description)
        data['label'].append(s.name)

        if use_uids:
            data['uid'].append(get_random_id(10))

    # Port to DataFrame.
    return pd.DataFrame(data)