Read the ShelX from input. Each ShelX document is expected to contain
one crystal structure.

@return a ChemFile with the coordinates, charges, vectors, etc.
180137
private IChemFile readChemFile(IChemFile file) throws IOException {
        IChemSequence seq = file.getBuilder().newInstance(IChemSequence.class);
        IChemModel model = file.getBuilder().newInstance(IChemModel.class);
        ICrystal crystal = readCrystal(file.getBuilder().newInstance(ICrystal.class));
        model.setCrystal(crystal);
        seq.addChemModel(model);
        file.addChemSequence(seq);
        return file;
    }
11251
def load(ctx, input, output):
    """"""
    log.debug('chemdataextractor.cluster.load')
    import pickle
    click.echo('Reading %s' % input.name)
    clusters = {}
    for line in input.readlines():
        cluster, word, freq = line.split()
        clusters[word] = cluster
    pickle.dump(clusters, output, protocol=pickle.HIGHEST_PROTOCOL)
975980
def from_file(cls, filename):
        '''
        '''
        with open(filename) as f:
            molecule, origin, axes, nrep, subtitle, nuclear_charges = \
                read_cube_header(f)
            data = np.zeros(tuple(nrep), float)
            tmp = data.ravel()
            counter = 0
            while True:
                line = f.readline()
                if len(line) == 0:
                    break
                words = line.split()
                for word in words:
                    tmp[counter] = float(word)
                    counter += 1
        return cls(molecule, origin, axes, nrep, data, subtitle, nuclear_charges)
1277879
def _get_valences(self):
        
        try:
            bv = BVAnalyzer()
            self._structure = bv.get_oxi_state_decorated_structure(
                self._structure)
            valences = bv.get_valences(self._structure)
        except:
            try:
                bv = BVAnalyzer(symm_tol=0.0)
                self._structure = bv.get_oxi_state_decorated_structure(
                    self._structure)
                valences = bv.get_valences(self._structure)
            except:
                valences = []
                for site in self._structure.sites:
                    if len(site.specie.common_oxidation_states) > 0:
                        valences.append(site.specie.common_oxidation_states[0])
                    # Handle noble gas species
                    # which have no entries in common_oxidation_states.
                    else:
                        valences.append(0)
                if sum(valences):
                    valences = [0] * self._structure.num_sites
                else:
                    self._structure.add_oxidation_state_by_site(valences)
                # raise

        # el = [site.specie.symbol for site in self._structure.sites]
        # el = [site.species_string for site in self._structure.sites]
        # el = [site.specie for site in self._structure.sites]
        # valence_dict = dict(zip(el, valences))
        # print valence_dict
        return valences
280020
private IReactionSet readReactionSet(IReactionSet setOfReactions) throws CDKException {

        IReaction r = readReaction(setOfReactions.getBuilder());
        if (r != null) {
            setOfReactions.addReaction(r);
        }

        try {
            String line;
            while ((line = input.readLine()) != null) {
                logger.debug("line: ", line);
                // apparently, this is a SDF file, continue with
                // reading mol files
                if (line.equals("$$$$")) {
                    r = readReaction(setOfReactions.getBuilder());

                    if (r != null) {
                        setOfReactions.addReaction(r);
                    }
                } else {
                    // here the stuff between 'M  END' and '$$$$'
                    if (r != null) {
                        // ok, the first lines should start with '>'
                        String fieldName = null;
                        if (line.startsWith("> ")) {
                            // ok, should extract the field name
                            int index = line.indexOf('<');
                            if (index != -1) {
                                int index2 = line.substring(index).indexOf('>');
                                if (index2 != -1) {
                                    fieldName = line.substring(index + 1, index + index2);
                                }
                            }
                            // end skip all other lines
                            while ((line = input.readLine()) != null && line.startsWith(">")) {
                                logger.debug("data header line: ", line);
                            }
                        }
                        if (line == null) {
                            throw new CDKException("Expecting data line here, but found null!");
                        }
                        String data = line;
                        while ((line = input.readLine()) != null && line.trim().length() > 0) {
                            if (line.equals("$$$$")) {
                                logger.error("Expecting data line here, but found end of molecule: ", line);
                                break;
                            }
                            logger.debug("data line: ", line);
                            data += line;
                            // preserve newlines, unless the line is exactly 80 chars; in that case it
                            // is assumed to continue on the next line. See MDL documentation.
                            if (line.length() < 80) data += "\n";
                        }
                        if (fieldName != null) {
                            logger.info("fieldName, data: ", fieldName, ", ", data);
                            r.setProperty(fieldName, data);
                        }
                    }
                }
            }
        } catch (CDKException cdkexc) {
            throw cdkexc;
        } catch (IOException exception) {
            String error = "Error while parsing SDF";
            logger.error(error);
            logger.debug(exception);
            throw new CDKException(error, exception);
        }

        return setOfReactions;
    }
320873
public static List<IChemObject> getAllChemObjects(IChemModel chemModel) {
        List<IChemObject> list = new ArrayList<IChemObject>();
        // list.add(chemModel); // only add ChemObjects contained within
        ICrystal crystal = chemModel.getCrystal();
        if (crystal != null) {
            list.add(crystal);
        }
        IAtomContainerSet moleculeSet = chemModel.getMoleculeSet();
        if (moleculeSet != null) {
            list.add(moleculeSet);
            List<IChemObject> current = MoleculeSetManipulator.getAllChemObjects(moleculeSet);
            for (IChemObject chemObject : current) {
                if (!list.contains(chemObject)) list.add(chemObject);
            }
        }
        IReactionSet reactionSet = chemModel.getReactionSet();
        if (reactionSet != null) {
            list.add(reactionSet);
            List<IChemObject> current = ReactionSetManipulator.getAllChemObjects(reactionSet);
            for (IChemObject chemObject : current) {
                if (!list.contains(chemObject)) list.add(chemObject);
            }
        }
        return list;
    }
401173
public FSArray getChemicalList() {
    if (ManualDescriptor_Type.featOkTst && ((ManualDescriptor_Type)jcasType).casFeat_chemicalList == null)
      jcasType.jcas.throwFeatMissing("chemicalList", "de.julielab.jules.types.pubmed.ManualDescriptor");
    return (FSArray)(jcasType.ll_cas.ll_getFSForRef(jcasType.ll_cas.ll_getRefValue(addr, ((ManualDescriptor_Type)jcasType).casFeatCode_chemicalList)));}
313453
public Object read() {
    HSSFSheet sheet = workbook.getSheetAt(sheetNum);
    if (indexInSheet > sheet.getLastRowNum()) { return null; }
    HSSFRow row = sheet.getRow(indexInSheet);
    indexInSheet++;
    // 如果是个空行,返回空记录
    if (row == null) {
      return new Object[attrCount];
    } else {
      Object[] values = new Object[((attrCount != 0) ? attrCount : row.getLastCellNum())];
      for (int k = 0; k < values.length; k++) {
        values[k] = getCellValue(row.getCell(k));
      }
      return values;
    }
  }
450049
public ProjectFile read() throws MPXJException
   {
      try
      {
         m_reader = new AstaReader();
         ProjectFile project = m_reader.getProject();
         project.getEventManager().addProjectListeners(m_projectListeners);

         processProjectProperties();
         processCalendars();
         processResources();
         processTasks();
         processPredecessors();
         processAssignments();

         m_reader = null;

         return (project);
      }

      catch (SQLException ex)
      {
         throw new MPXJException(MPXJException.READ_ERROR, ex);
      }

      finally
      {
         if (m_allocatedConnection && m_connection != null)
         {
            try
            {
               m_connection.close();
            }

            catch (SQLException ex)
            {
               // silently ignore errors on close
            }

            m_connection = null;
         }
      }
   }
1296771
def read(filename):
    
    # The format is specified at
    # <http://www.intes.de>.

    cells = {}
    meshio_to_permas_type = {
        "vertex": (1, "PLOT1"),
        "line": (2, "PLOTL2"),
        "triangle": (3, "TRIA3"),
        "quad": (4, "QUAD4"),
        "tetra": (4, "TET4"),
        "hexahedron": (8, "HEXE8"),
        "wedge": (6, "PENTA6"),
        "pyramid": (5, "PYRA5"),
    }

    opener = gzip.open if filename.endswith(".gz") else open

    with opener(filename, "rb") as f:
        while True:
            line = f.readline().decode("utf-8")
            if not line or re.search("\\$END STRUCTURE", line):
                break
            for meshio_type, permas_ele in meshio_to_permas_type.items():
                num_nodes = permas_ele[0]
                permas_type = permas_ele[1]

                if re.search("\\$ELEMENT TYPE = {}".format(permas_type), line):
                    while True:
                        line = f.readline().decode("utf-8")
                        if not line or line.startswith("!"):
                            break
                        data = numpy.array(line.split(), dtype=int)
                        if meshio_type in cells:
                            cells[meshio_type].append(data[-num_nodes:])
                        else:
                            cells[meshio_type] = [data[-num_nodes:]]

            if re.search("\\$COOR", line):
                points = []
                while True:
                    line = f.readline().decode("utf-8")
                    if not line or line.startswith("!"):
                        break
                    for r in numpy.array(line.split(), dtype=float)[1:]:
                        points.append(r)

    points = numpy.array(points)
    points = numpy.reshape(points, newshape=(len(points) // 3, 3))
    for key in cells:
        # Subtract one to account for the fact that python indices
        # are 0-based.
        cells[key] = numpy.array(cells[key], dtype=int) - 1

    return Mesh(points, cells)
944628
public List<String> getChainIds() {

		List<String> chains = new ArrayList<String>(getSubunitCount());

		// Loop through all subunits in the clusters and fill Lists
		for (int c = 0; c < clusters.size(); c++) {
			for (int s = 0; s < clusters.get(c).size(); s++)
				chains.add(clusters.get(c).getSubunits().get(s).getName());
		}

		return chains;
	}

	/**
	 * This method is provisional and should only be used for coloring Subunits.
	 * A new coloring schema has to be implemented to allow the coloring of
	 * Subunits, without implying one Subunit = one Chain.
	 *
	 * @return A List of the Model number of each Subunit
	 */
	public List<Integer> getModelNumbers() {

		List<Integer> models = new ArrayList<Integer>(getSubunitCount());

		// Loop through all subunits in the clusters and fill Lists
		for (int c = 0; c < clusters.size(); c++) {
			for (int s = 0; s < clusters.get(c).size(); s++) {

				Atom[] atoms = clusters.get(c).getAlignedAtomsSubunit(s);

				// TODO guess them chain and model (very ugly)
				Chain chain = atoms[0].getGroup().getChain();

				int model = 0;
				for (int m = 0; m < chain.getStructure().nrModels(); m++) {
					if (chain.getStructure().getModel(m).contains(chain)) {
						model = m;
						break;
					}
				}
				models.add(model);
			}
		}
		return models;
	}

	public int getSubunitCount() {
		run();
		if (centers == null) {
			return 0;
		}
		return centers.size();
	}

	public List<Integer> getFolds() {
		return folds;
	}

	public int getCalphaCount() {
		int count = 0;
		for (Point3d[] trace : caCoords) {
			count += trace.length;
		}
		return count;
	}

	public int getLargestSubunit() {
		int index = -1;
		int maxLength = 0;
		for (int i = 0; i < caCoords.size(); i++) {
			int length = caCoords.get(i).length;
			if (length > maxLength) {
				index = i;
			}
		}
		return index;
	}

	public List<Point3d> getCenters() {
		run();
		return centers;
	}

	public List<Vector3d> getUnitVectors() {
		run();
		return unitVectors;
	}

	public List<Point3d> getOriginalCenters() {
		run();
		return originalCenters;
	}

	public Point3d getCentroid() {
		run();
		return centroid;
	}

	public MomentsOfInertia getMomentsOfInertia() {
		run();
		return momentsOfInertia;
	}

	private void run() {
		if (centers.size() > 0) {
			return;
		}
		calcOriginalCenters();
		calcCentroid();
		calcCenters();
		calcMomentsOfIntertia();
	}

	private void calcOriginalCenters() {
		for (Point3d[] trace : caCoords) {
			Point3d com = CalcPoint.centroid(trace);
			originalCenters.add(com);
		}
	}

	private void calcCentroid() {
		Point3d[] orig = originalCenters.toArray(new Point3d[originalCenters
				.size()]);
		centroid = CalcPoint.centroid(orig);
	}

	private void calcCenters() {
		for (Point3d p : originalCenters) {
			Point3d c = new Point3d(p);
			c.sub(centroid);
			centers.add(c);
			Vector3d v = new Vector3d(c);
			v.normalize();
			unitVectors.add(v);
		}
	}

	public Point3d getLowerBound() {
		Point3d lower = new Point3d();
		for (Point3d p : centers) {
			if (p.x < lower.x) {
				lower.x = p.x;
			}
			if (p.y < lower.y) {
				lower.y = p.y;
			}
			if (p.z < lower.z) {
				lower.z = p.z;
			}
		}
		return lower;
	}

	public Point3d getUpperBound() {
		Point3d upper = new Point3d();
		for (Point3d p : centers) {
			if (p.x > upper.x) {
				upper.x = p.x;
			}
			if (p.y > upper.y) {
				upper.y = p.y;
			}
			if (p.z > upper.z) {
				upper.z = p.z;
			}
		}
		return upper;
	}

	private void calcMomentsOfIntertia() {
		for (Point3d[] trace : caCoords) {
			for (Point3d p : trace) {
				momentsOfInertia.addPoint(p, 1.0f);
			}
		}
	}

}
742606
def read_energies(self, root):
        self.key_value_pairs_reaction = None

        slab_structures = collect_structures(root)

        if len(slab_structures) == 0:
            self.raise_warning('No structure files in {root}: Skipping this folder'
                               .format(root=root))
            return

        # Remove old species from ase_ids
        all_reaction_species = list(self.reaction.values())[0] \
            + list(self.reaction.values())[1]
        all_reaction_species = [clear_prefactor(rs) for rs in
                                all_reaction_species]

        for ase_id in list(self.ase_ids.keys()):
            if ase_id == 'star' or 'bulk' in ase_id:
                continue
            if not ase_id in all_reaction_species:
                del self.ase_ids[ase_id]

        if 'TS' in self.structures:  # Delete old TS
            del self.structures['TS']
            del self.structures['TSempty']
            del self.prefactors['TS']

        for k in list(self.structures.keys()):
            if 'neb' in k:
                del self.structures[k]


        neb_indices = [i for i, slab in enumerate(slab_structures) if 'neb' in
                       slab[-1].info['filename']]
        neb_names = {}

        if len(neb_indices) == 1:
            index = neb_indices[0]
            slab = slab_structures[index]
            f = slab[-1].info['filename']
            del slab_structures[index]
            neb_indices = []
            for i, s in enumerate(slab):
                s.info['filename'] = f
                slab_structures.append(s)
                index = len(slab_structures) - 1
                neb_indices += [index]
                neb_names.update({str(i): 'neb' + str(i)})

        elif len(neb_indices) > 1:
            for i in neb_indices:
                f = slab_structures[i][-1].info['filename']
                neb_names.update({str(i): os.path.basename(f).split('.')[0]})

        for i, slab in enumerate(slab_structures):
            if isinstance(slab, list):
                slab_structures[i] = slab[-1]

        empty = self.empty

        reactant_entries = self.reaction['reactants'] + \
            self.reaction['products']
        if not empty:
            if 'star' in reactant_entries and len(neb_indices) == 0:
                message = 'Empty slab needed for reaction!'
                self.raise_error(message)
                return
            else:
                empty0 = slab_structures[0]
                chemical_composition = ase_tools.get_chemical_formula(empty0)
                self.raise_warning("Using '{}' as a reference instead of empty slab"
                                   .format(empty0.info['filename']))
                empty_atn = list(empty0.get_atomic_numbers())
        else:
            chemical_composition = ase_tools.get_chemical_formula(empty)
            empty_atn = list(empty.get_atomic_numbers())

        prefactor_scale = copy.deepcopy(self.prefactors)
        for key1, values in prefactor_scale.items():
            prefactor_scale[key1] = [1 for v in values]

        key_value_pairs = {}

        key_value_pairs.update({'name':
                                chemical_composition,
                                'facet': self.ase_facet,
                                'state': 'star'})

        
        for i, slab in enumerate(slab_structures):
            f = slab.info['filename']
            atns = list(slab.get_atomic_numbers())
            if not (np.array(atns) > 8).any() and \
               (np.array(empty_atn) > 8).any():
                self.raise_warning("Only molecular species for structure: {}"
                                   .format(f))
                continue

            """Get supercell size relative to empty slab"""
            supercell_factor = 1
            if len(atns) > len(empty_atn) * 2:  # different supercells
                supercell_factor = len(res_slab_atn) // len(empty_atn)

            """Atomic numbers of adsorbate"""
            ads_atn = []
            if 'star' in reactant_entries and len(neb_indices) == 0:
                ads_atn = copy.copy(atns)
                for atn in empty_atn * supercell_factor:
                    try:
                        ads_atn.remove(atn)
                    except ValueError as e:
                        self.raise_error(
                            'Empty slab: {} contains species not in: {}' \
                                .format(empty.info['filename'], f))
                ads_atn = sorted(ads_atn)
                if ads_atn == []:
                    self.raise_warning("No adsorbates for structure: {}"
                                   .format(f))
                    continue

            ase_id = None
            id, ase_id = ase_tools.check_in_ase(slab, self.cathub_db)
            key_value_pairs.update({'epot': ase_tools.get_energies([slab])})

            if 'empty' in f and 'TS' in f:  # empty slab for transition state
                self.structures.update({'TSempty': [slab]})
                self.prefactors.update({'TSempty': [1]})
                prefactor_scale.update({'TSempty': [1]})
                key_value_pairs.update({'species': ''})
                if ase_id is None:
                    ase_id = ase_tools.write_ase(slab, self.cathub_db,
                                                 self.stdout,
                                                 self.user,
                                                 **key_value_pairs)
                elif self.update:
                    ase_tools.update_ase(self.cathub_db, id, self.stdout,
                                         **key_value_pairs)
                self.ase_ids.update({'TSemptystar': ase_id})
                continue

            elif 'TS' in f:  # transition state
                self.structures.update({'TS': [slab]})
                self.prefactors.update({'TS': [1]})
                prefactor_scale.update({'TS': [1]})
                key_value_pairs.update({'species': 'TS'})
                if ase_id is None:
                    ase_id = ase_tools.write_ase(slab, self.cathub_db,
                                                 self.stdout,
                                                 self.user,
                                                 **key_value_pairs)
                elif self.update:
                    ase_tools.update_ase(self.cathub_db, id, self.stdout,
                                         **key_value_pairs)
                self.ase_ids.update({'TSstar': ase_id})
                continue

            if i in neb_indices:
                self.structures.update({neb_names[str(i)]: [slab]})
                key_value_pairs.update({'species': 'neb'})
                if ase_id is None:
                    ase_id = ase_tools.write_ase(slab,
                                                 self.cathub_db,
                                                 self.stdout,
                                                 self.user,
                                                 **key_value_pairs)
                elif self.update:
                    ase_tools.update_ase(self.cathub_db, id, self.stdout,
                                         **key_value_pairs)
                self.ase_ids.update({neb_names[str(i)]: ase_id})
                continue
            

            found = False
            for key, mollist in self.reaction.items():
                if found:
                    break
                for n, molecule in enumerate(mollist):
                    if found:
                        break
                    if not self.states[key][n] == 'star':  # only slab stuff
                        continue
                    if not self.structures[key][n] == '':  # allready found
                        continue
                    molecule = clear_state(clear_prefactor(molecule))
                    if molecule == '':
                        continue
                    molecule_atn = sorted(
                        ase_tools.get_numbers_from_formula(molecule))
                    if slab.info['filename'] == molecule:
                        if ads_atn == molecule_atn:
                            found = True
                            match_key = key
                            match_n = n
                            break
                        else:
                            raise_warning('Name of file does not match chemimcal formula: {}'
                                          .format(slab.info['filename']))

                    for n_ads in range(1, 5):
                        mol_atn = sorted(molecule_atn * n_ads)
                        if (ads_atn == mol_atn or len(ads_atn) == 0):
                            match_n_ads = n_ads
                            found = True
                            match_key = key
                            match_n = n
                            break

            if found:
                key = match_key
                n = match_n
                n_ads = match_n_ads
                self.structures[key][n] = slab
                species = clear_prefactor(
                    self.reaction[key][n])
                id, ase_id = ase_tools.check_in_ase(
                    slab, self.cathub_db)
                key_value_pairs.update(
                    {'species':
                     clear_state(
                         species),
                     'n': n_ads,
                     'site': str(self.sites.get(species, ''))})
                if ase_id is None:
                    ase_id = ase_tools.write_ase(
                        slab, self.cathub_db, self.stdout,
                        self.user,
                        **key_value_pairs)
                elif self.update:
                    ase_tools.update_ase(
                        self.cathub_db, id, self.stdout,
                        **key_value_pairs)
                self.ase_ids.update({species: ase_id})

            if n_ads > 1:
                for key1, values in prefactor_scale.items():
                    for mol_i in range(len(values)):
                        if self.states[key1][mol_i] == 'gas':
                            prefactor_scale[key1][mol_i] = n_ads

            if supercell_factor > 1:
                for key2, values in prefactor_scale.items():
                    for mol_i in range(len(values)):
                        if self.reaction[key2][mol_i] == 'star':
                            prefactor_scale[key2][mol_i] *= supercell_factor


        # Check that all structures have been found
        structurenames = [s for s in list(self.structures.keys())
                          if s not in ['reactants', 'products']]
        for k in ['reactants', 'products']:
            structurenames += [s for s in self.structures[k] if s != ''
                               and s is not None]
        only_neb = np.all(['neb' in s for s in structurenames])
        surface_composition = self.metal

        if only_neb:
            if not self.empty:
                for ads in self.reaction_atoms['reactants']:
                    ads_atn = ase_tools.get_numbers_from_formula(ads)
                    for atn in ads_atn:
                        empty_atn.remove(atn)
                chemical_composition = \
                    ase_tools.get_formula_from_numbers(empty_atn, mode='metal')
            neb_numbers = []
            neb_energies = []
            for key, structure in self.structures.items():
                if key in ['reactants', 'products']:
                    continue

                neb_no = int(key.split('.')[0].replace('neb', ''))
                neb_numbers += [neb_no]
                neb_energies += [structure[0].get_potential_energy()]

            initial = neb_energies[np.argmin(neb_numbers)]
            final = neb_energies[np.argmax(neb_numbers)]
            TS = np.max(neb_energies)

            reaction_energy = final - initial
            activation_energy = TS - initial

            if activation_energy == 0 or activation_energy == reaction_energy:
                activation_energy = None
        else:
            for key, structurelist in self.structures.items():
                if '' in structurelist:
                    index = structurelist.index('')
                    molecule = clear_state(
                        clear_prefactor(self.reaction[key][index]))
                    if self.states[key][index] == 'star':
                        message = "Adsorbate '{}' not found for any structure files in '{}'."\
                            .format(molecule, root) + \
                            " Please check your adsorbate structures and the empty slab."
                    if self.states[key][index] == 'gas':
                        message = "Gas phase molecule '{}' not found for any structure files in '{}'."\
                            .format(molecule, self.gas_folder) + \
                            " Please check your gas phase references."
                    self.raise_error(message)
                    return

            prefactors_final = copy.deepcopy(self.prefactors)
            for key in self.prefactors:
                for i, v in enumerate(self.prefactors[key]):
                    prefactors_final[key][i] = self.prefactors[key][i] * \
                        prefactor_scale[key][i]

            reaction_energy = None
            activation_energy = None
            try:
                reaction_energy, activation_energy = \
                    ase_tools.get_reaction_energy(
                        self.structures, self.reaction,
                        self.reaction_atoms,
                        self.states, prefactors_final,
                        self.prefactors_TS,
                        self.energy_corrections)
            except BaseException as e:
                message = "reaction energy failed for files in '{}'"\
                    .format(root)
                self.raise_error(message + '\n' + str(e))

        if not -self.energy_limit < reaction_energy < self.energy_limit:
            self.raise_error('reaction energy is very large: {} eV \n  '
                             .format(reaction_energy) +
                             'Folder: {}. \n  '.format(root) +
                             'If the value is correct, you can reset the limit with cathub folder2db --energy-limit <value>. Default is --energy-limit=5 (eV)'
                             )
        if activation_energy is not None:
            if activation_energy < reaction_energy:
                self.raise_warning('activation energy is smaller than reaction energy: {} vs {} eV \n  Folder: {}'.format(
                    activation_energy, reaction_energy, root))
            if not activation_energy < self.energy_limit:
                self.raise_error(' Very large activation energy: {} eV \n  Folder: {}'
                                 .format(activation_energy, root))

        reaction_info = {'reactants': {},
                         'products': {}}

        for key in ['reactants', 'products']:
            for i, r in enumerate(self.reaction[key]):
                r = clear_prefactor(r)
                reaction_info[key].update({r: self.prefactors[key][i]})

        self.key_value_pairs_reaction = {
            'chemical_composition': chemical_composition,
            'surface_composition': surface_composition,
            'facet': self.facet,
            'sites': self.sites,
            'coverages': self.coverages,
            'reactants': reaction_info['reactants'],
            'products': reaction_info['products'],
            'reaction_energy': float(reaction_energy),
            'activation_energy': activation_energy,
            'dft_code': self.DFT_code,
            'dft_functional': self.DFT_functional,
            'pub_id': self.pub_id,
            'doi': self.doi,
            'year': int(self.year),
            'ase_ids': self.ase_ids,
            'energy_corrections': self.energy_corrections,
            'username': self.user}
962489
private IAtomContainer readCoordinates(IAtomContainer molecule, boolean coordinatesUnits) throws IOException {

        /*
         * Coordinates must all be given in angstr???ms.
         */
        double unitScaling = GamessReader.scalesCoordinatesUnits(coordinatesUnits);

        String retrievedLineFromFile;

        while (this.input.ready() == true) {
            retrievedLineFromFile = this.input.readLine();
            /*
             * A coordinate set is followed by an empty line, so when this line
             * is reached, there are no more coordinates to add to the current
             * set.
             */
            if ((retrievedLineFromFile == null) || (retrievedLineFromFile.trim().length() == 0)) {
                break;
            }

            int atomicNumber;
            String atomicSymbol;

            //StringReader sr = new StringReader(retrievedLineFromFile);
            StreamTokenizer token = new StreamTokenizer(new StringReader(retrievedLineFromFile));

            /*
             * The first token is ignored. It contains the atomic symbol and may
             * be concatenated with a number.
             */
            token.nextToken();

            if (token.nextToken() == StreamTokenizer.TT_NUMBER) {
                atomicNumber = (int) token.nval;
                atomicSymbol = this.identifyAtomicSymbol(atomicNumber);
                /*
                 * Dummy atoms are assumed to be given with an atomic number set
                 * to zero. We will do not add them to the molecule.
                 */
                if (atomicNumber == 0) {
                    continue;
                }
            } else {
                throw new IOException("Error reading coordinates");
            }

            /*
             * Atom's coordinates are stored in an array.
             */
            double[] coordinates = new double[3];
            for (int i = 0; i < coordinates.length; i++) {
                if (token.nextToken() == StreamTokenizer.TT_NUMBER) {
                    coordinates[i] = token.nval * unitScaling;
                } else {
                    throw new IOException("Error reading coordinates");
                }
            }
            IAtom atom = molecule.getBuilder().newInstance(IAtom.class, atomicSymbol,
                    new Point3d(coordinates[0], coordinates[1], coordinates[2]));
            molecule.addAtom(atom);
        }
        return molecule;
    }
384605
public String getDescriptorExpression() {
    // We only need to import the outermost descriptor.
    Descriptor descriptor = typeDescriptor;
    while (descriptor.getContainingType() != null) {
      descriptor = descriptor.getContainingType();
    }
    return JavaQualifiedNames.getQualifiedName(descriptor) + ".getDescriptor()";
  }
855240
def generate(mnx_dump):
    
    LOGGER.info("Read shortlist.")
    targets = pd.read_table(join(dirname(__file__), "shortlist.tsv"))
    if not exists(mnx_dump):
        # Download the MetaNetX chemicals dump if it doesn't exists.
        # Download done as per https://stackoverflow.com/a/16696317.
        LOGGER.info("MetaNetX dump '%s' does not exist. Downloading...",
                    mnx_dump)
        with open(mnx_dump, "wb") as file_handle, \
            get("https://www.metanetx.org/cgi-bin/mnxget/mnxref/chem_xref.tsv",
                stream=True) as stream:
            for chunk in stream.iter_content(chunk_size=1024):
                file_handle.write(chunk)
        LOGGER.info("Done.")
    LOGGER.info("Read the MetaNetX dump with cross-references.")
    db = pd.read_table(mnx_dump, comment='#',
                       names=['XREF', 'MNX_ID', 'Evidence', 'Description'])
    LOGGER.info("Generate the shortlist cross-references.")
    res = generate_shortlist(db, targets)
    LOGGER.info("Save result.")
    res.to_json(join(dirname(__file__), pardir, "memote", "support", "data",
                     "met_id_shortlist.json"), force_ascii=False)
1077389
public List<Double> getRDBEValue(IMolecularFormula formula) {
        List<Double> RDBEList = new ArrayList<Double>();
        // The number of combinations with repetition
        // (v+n-1)!/[n!(v-1)!]
        int nE = 0; // number of elements to change
        List<Integer> nV = new ArrayList<Integer>(); // number of valence changing
        for (Iterator<IIsotope> it = formula.isotopes().iterator(); it.hasNext();) {
            IIsotope isotope = it.next();
            int[] valence = getOxidationState(formula.getBuilder().newInstance(IAtom.class, isotope.getSymbol()));
            if (valence.length != 1) {
                for (int i = 0; i < valence.length; i++) {
                    nV.add(valence[i]);
                }
                nE += MolecularFormulaManipulator.getElementCount(formula,
                        formula.getBuilder().newInstance(IElement.class, isotope.getSymbol()));
            }
        }

        double RDBE = 0;
        if (nE == 0) {
            for (Iterator<IIsotope> it = formula.isotopes().iterator(); it.hasNext();) {
                IIsotope isotope = it.next();
                int[] valence = getOxidationState(formula.getBuilder().newInstance(IAtom.class, isotope.getSymbol()));
                double value = (valence[0] - 2) * formula.getIsotopeCount(isotope) / 2.0;
                RDBE += value;
            }
            RDBE += 1;
            RDBEList.add(RDBE);
        } else {
            double RDBE_1 = 0;
            for (Iterator<IIsotope> it = formula.isotopes().iterator(); it.hasNext();) {
                IIsotope isotope = it.next();
                int[] valence = getOxidationState(formula.getBuilder().newInstance(IAtom.class, isotope.getSymbol()));
                double value = (valence[0] - 2) * formula.getIsotopeCount(isotope) * 0.5;
                RDBE_1 += value;
            }
            String[] valences = new String[nV.size()];
            for (int i = 0; i < valences.length; i++)
                valences[i] = Integer.toString(nV.get(i));

            Combinations c = new Combinations(valences, nE);
            while (c.hasMoreElements()) {
                double RDBE_int = 0.0;
                Object[] combo = (Object[]) c.nextElement();
                for (int i = 0; i < combo.length; i++) {
                    int value = (Integer.parseInt((String) combo[i]) - 2) / 2;
                    RDBE_int += value;
                }
                RDBE = 1 + RDBE_1 + RDBE_int;
                RDBEList.add(RDBE);
            }
        }
        return RDBEList;
    }
931307
@Override
    public <T extends IChemObject> T read(T object) throws CDKException {
        sp = new SmilesParser(object.getBuilder());

        if (object instanceof IAtomContainerSet) {
            return (T) readAtomContainerSet((IAtomContainerSet) object);
        } else if (object instanceof IChemFile) {
            IChemFile file = (IChemFile) object;
            IChemSequence sequence = file.getBuilder().newInstance(IChemSequence.class);
            IChemModel chemModel = file.getBuilder().newInstance(IChemModel.class);
            chemModel.setMoleculeSet(readAtomContainerSet(file.getBuilder().newInstance(IAtomContainerSet.class)));
            sequence.addChemModel(chemModel);
            file.addChemSequence(sequence);
            return (T) file;
        } else {
            throw new CDKException("Only supported is reading of MoleculeSet objects.");
        }
    }