Convert RDMol to molecule
555805
def from_rdmol(rdmol, assign_descriptor=True):
    """"""
    mol = Compound()
    conf = rdmol.GetConformer()
    Chem.Kekulize(rdmol)
    for atom in rdmol.GetAtoms():
        key = atom.GetIdx()
        a = Atom(atom.GetSymbol())
        a.coords = conf.GetAtomPosition(key)
        mol.add_atom(key, a)
    for bond in rdmol.GetBonds():
        u = bond.GetBeginAtomIdx()
        v = bond.GetEndAtomIdx()
        b = Bond()
        b.order = int(bond.GetBondTypeAsDouble())
        mol.add_bond(u, v, b)
    if assign_descriptor:
        molutil.assign_descriptors(mol)
    return mol
872895
def assign_charge(mol, force_recalc=False):
    """"""
    # TODO: not implemented yet
    mol.require("Aromatic")
    for i, nbrs in mol.neighbors_iter():
        atom = mol.atom(i)
        nbrcnt = len(nbrs)
        if atom.symbol == "N":
            if not atom.pi:
                # non-conjugated amines are anion
                mol.atom(i).charge_phys = 1
            elif nbrcnt == 1 and atom.pi == 2:
                # amidine, guanidine are conjugated cation
                ni = list(nbrs.keys())[0]
                conj = False
                sp2n = None
                for nni, nnb in mol.neighbors(ni).items():
                    if mol.atom(nni).symbol == "N" and nnb.order == 2 \
                            and not mol.atom(nni).aromatic:
                        mol.atom(nni).charge_conj = 1
                        conj = True
                    elif mol.atom(nni).symbol == "N" and nni != i:
                        sp2n = nni
                if conj:
                    mol.atom(i).charge_phys = 1
                    if sp2n is not None:
                        mol.atom(sp2n).charge_conj = 1
        elif atom.symbol == "O" and nbrcnt == 1 and atom.pi == 2:
            # oxoacid are conjugated anion
            ni = list(nbrs.keys())[0]
            conj = False
            if mol.atom(ni).symbol == "N":
                mol.atom(i).n_oxide = True
                mol.atom(ni).n_oxide = True
            for nni, nnb in mol.neighbors(ni).items():
                if mol.atom(nni).symbol in ("O", "S") \
                        and nnb.order == 2 and not mol.atom(ni).n_oxide:
                    mol.atom(nni).charge_conj = -1
                    conj = True
            if conj:
                mol.atom(i).charge_phys = -1
        elif atom.symbol == "S" and nbrcnt == 1:
            # thiophenols are anion
            ni = list(nbrs.keys())[0]
            if mol.atom(ni).aromatic:
                mol.atom(i).charge_phys = -1
    mol.charge_assigned = True
    mol.descriptors.add("Phys_charge")
288926
private static String calculateMolecularFormula(List<AbstractMolecule> molecules) throws BuilderMoleculeException, CTKException, ChemistryException {
    Map<String, Integer> atomNumberMap = new TreeMap<String, Integer>();
    for (AbstractMolecule molecule : molecules) {
      LOG.info(molecule.getMolecule().toString());
      atomNumberMap = generateAtomNumberMap(molecule, atomNumberMap);
    }
    LOG.info("GET map");
    StringBuilder sb = new StringBuilder();
    Set<String> atoms = atomNumberMap.keySet();
    for (Iterator<String> i = atoms.iterator(); i.hasNext();) {
      String atom = i.next();
      String num = atomNumberMap.get(atom).toString();
      if (num.equals("1")) {
        num = "";
      }
      sb.append(atom);
      sb.append(num.toString());
    }
    return sb.toString();
  }
1013232
@Override
    public DescriptorValue calculate(IAtomContainer container) {
        if (!GeometryUtil.has3DCoordinates(container))
            return getDummyDescriptorValue(new CDKException("Molecule must have 3D coordinates"));

        IAtomContainer clone;
        IsotopeFactory factory;
        try {
            clone = (IAtomContainer) container.clone();
            factory = Isotopes.getInstance();
            factory.configureAtoms(clone);
        } catch (CloneNotSupportedException | IOException e) {
            logger.debug(e);
            return getDummyDescriptorValue(e);
        }

        DoubleArrayResult retval = new DoubleArrayResult(7);

        double ccf = 1.000138;
        double eps = 1e-5;

        double[][] imat = new double[3][3];
        Point3d centerOfMass = GeometryUtil.get3DCentreOfMass(clone);

        double xdif;
        double ydif;
        double zdif;
        double xsq;
        double ysq;
        double zsq;
        for (int i = 0; i < clone.getAtomCount(); i++) {
            IAtom currentAtom = clone.getAtom(i);

            Double mass = factory.getMajorIsotope(currentAtom.getSymbol()).getExactMass();
            if (mass == null)
                mass = factory.getNaturalMass(currentAtom);

            xdif = currentAtom.getPoint3d().x - centerOfMass.x;
            ydif = currentAtom.getPoint3d().y - centerOfMass.y;
            zdif = currentAtom.getPoint3d().z - centerOfMass.z;
            xsq = xdif * xdif;
            ysq = ydif * ydif;
            zsq = zdif * zdif;

            imat[0][0] += mass * (ysq + zsq);
            imat[1][1] += mass * (xsq + zsq);
            imat[2][2] += mass * (xsq + ysq);

            imat[1][0] += -1 * mass * ydif * xdif;
            imat[0][1] = imat[1][0];

            imat[2][0] += -1 * mass * xdif * zdif;
            imat[0][2] = imat[2][0];

            imat[2][1] += -1 * mass * ydif * zdif;
            imat[1][2] = imat[2][1];
        }

        // diagonalize the MI tensor
        Matrix tmp = new Matrix(imat);
        EigenvalueDecomposition eigenDecomp = tmp.eig();
        double[] eval = eigenDecomp.getRealEigenvalues();

        retval.add(eval[2]);
        retval.add(eval[1]);
        retval.add(eval[0]);

        double etmp = eval[0];
        eval[0] = eval[2];
        eval[2] = etmp;

        if (Math.abs(eval[1]) > 1e-3)
            retval.add(eval[0] / eval[1]);
        else
            retval.add(1000);

        if (Math.abs(eval[2]) > 1e-3) {
            retval.add(eval[0] / eval[2]);
            retval.add(eval[1] / eval[2]);
        } else {
            retval.add(1000);
            retval.add(1000);
        }

        // finally get the radius of gyration
        double pri;
        IMolecularFormula formula = MolecularFormulaManipulator.getMolecularFormula(clone);
        if (Math.abs(eval[2]) > eps)
            pri = Math.pow(eval[0] * eval[1] * eval[2], 1.0 / 3.0);
        else
            pri = Math.sqrt(eval[0] * ccf / MolecularFormulaManipulator.getTotalExactMass(formula));
        retval.add(Math.sqrt(Math.PI * 2 * pri * ccf / MolecularFormulaManipulator.getTotalExactMass(formula)));

        return new DescriptorValue(getSpecification(), getParameterNames(), getParameters(), retval,
                getDescriptorNames());
    }
1103290
def load_remote_molecule(url, format=None):
    '''

    '''
    filename, headers = urlretrieve(url)
    return load_molecule(filename, format=format)
957271
def get_rotatable_bonds(self,mol):
		
		RotatableBondSmarts = Chem.MolFromSmarts('[!$(*#*)&!D1]-&!@[!$(*#*)&!D1]')
		bonds = mol.GetSubstructMatches(RotatableBondSmarts,uniquify=1)
		return bonds
1166148
def convert_compound_entry(self, compound):
        """"""
        d = OrderedDict()
        d['id'] = compound.id

        order = {
            key: i for i, key in enumerate(
                ['name', 'formula', 'formula_neutral', 'charge', 'kegg',
                 'cas'])}
        prop_keys = (
            set(compound.properties) - {'boundary', 'compartment'})
        for prop in sorted(prop_keys,
                           key=lambda x: (order.get(x, 1000), x)):
            if compound.properties[prop] is not None:
                d[prop] = compound.properties[prop]

        return d
594705
def convert(cycle, pyroleLike, usedPyroles):
    """"""

    bonds = cycle.bonds
    atoms = cycle.atoms
    initialBondStates = []
    initialAtomStates = []
    _usedPyroles = {}
    for bond in bonds:
        # store the initial states but assume the
        # bond is aromatic
        initialBondStates.append((bond, bond.symbol,
                                  bond.bondorder, bond.bondtype,
                                  bond.aromatic, bond.stereo))
        # XXX FIX ME
        # until we get proper conjugation, aromatic bond orders
        # are 1.5
        bond.reset(':', bond.bondorder, 4, bond.fixed, bond.stereo)
        
    aromatized = 1
    for atom in atoms:
        initialAtomStates.append((atom, atom.aromatic))
        atom.aromatic = 1

        nonhydrogens = atom.sumBondOrders() + atom.charge

        # look for the lowest valence where we don't
        #  have to change the charge of the atom to
        #  fill the valences
        for valence in atom.valences:
            neededHydrogens = int(valence - nonhydrogens)
            if neededHydrogens >= 0:
                break
        else:
            # we can't change the aromaticity and have correct
            # valence.
            #
            # there is one special case of a five membered
            #  ring and a pyrole nitrogen like atom we need
            #  to look for.
            if len(cycle) == 5 and pyroleLike.has_key(atom.handle):
                _usedPyroles[atom.handle] = 1
            else:
                # nope, the valences don't work out so
                # we can't aromatize
                aromatized = 0
                break

    # sanity check, this should be true because of the
    # canBeAromatic routine above
    assert len(_usedPyroles) <=1, "Too many used pyroles!"
    
    cycle.aromatic = aromatized
    if not aromatized:
        for bond, symbol, order, bondtype, aromatic, stereo in initialBondStates:
            bond.reset(symbol, order, bondtype, bond.fixed, stereo)

        for atom, aromatic in initialAtomStates:
            atom.aromatic = aromatic
    else:
        # we used some pyroles, we'll have to send these to
        # the valence checker later
        usedPyroles.update(_usedPyroles)

    return aromatized
1124600
def mw_wo_sw(mol, ndigits=2):
    
    cp = clone(mol)  # Avoid modification of original object
    remover.remove_water(cp)
    remover.remove_salt(cp)
    return round(sum(a.mw() for _, a in cp.atoms_iter()), ndigits)
887616
def get_molecule(self, index=0):
        
        return Molecule(self.numbers, self.geometries[index], self.titles[index], symbols=self.symbols)
722529
def id_to_atom(self, idx):
        
        mapped_idx = self.mapid(idx, 'reversed')
        return pybel.Atom(self.original_structure.GetAtom(mapped_idx))
38094
public static int markRingAtomsAndBonds(IAtomContainer mol) {
        EdgeToBondMap bonds = EdgeToBondMap.withSpaceFor(mol);
        return markRingAtomsAndBonds(mol, GraphUtil.toAdjList(mol, bonds), bonds);
    }
612755
def sssr(molecule):
    """"""
    results = {}
    lookup = {}
    fullSet = {}
    oatoms = {}
    # XXX FIX ME
    # copy atom.oatoms to atom._oatoms
    # atom._oatoms will be modified my the routine

    for atom in molecule.atoms:
        atom.rings = []
	fullSet[atom.handle] = 1
	lookup[atom.handle] = atom
        oatoms[atom.handle] = atom.oatoms[:]

    for bond in molecule.bonds:
        bond.rings = []
        
    trimSet = []

    while fullSet:
	nodesN2 = []
        minimum, minimum_degree = None, 100000


	# find the N2 atoms and remove atoms with degree 0
	for atomID in fullSet.keys():
	    atom = lookup[atomID]
	    degree = len(oatoms[atom.handle])
	    if degree == 0:
		del fullSet[atomID]
		#fullSet.remove(atomID)
	    elif degree == 2:
		nodesN2.append(atom)

	    # keep track of the minimum degree
	    if (degree > 0) and ( (not minimum) or 
		                (degree < minimum_degree)):
		minimum, minimum_degree = atom, degree

	if not minimum:
	    # nothing to do!  (i.e. can't have a ring)
	    break

	if minimum_degree == 1:
	    # these cannot be in rings so trim and remove
	    # my version of trimming
            for oatom in oatoms[minimum.handle]:
		oatoms[oatom.handle].remove(minimum)
            oatoms[minimum.handle] = []
	    del fullSet[minimum.handle]

	elif minimum_degree == 2:
	    # find the rings!
	    startNodes = []
	    for atom in nodesN2:
		ring, bonds = getRing(atom, fullSet, lookup, oatoms)

		if ring:
                    rlookup = ring[:]
                    rlookup.sort()
                    rlookup = tuple(rlookup)
		    if (not results.has_key(rlookup)):# not in results):
			results[rlookup] = ring, bonds
			startNodes.append(atom)

	    # in case we didn't get a ring remove the head of the nodesN2
	    startNodes = startNodes or [nodesN2[0]]
	    for atom in startNodes:
		# again, my version of trimming
                if oatoms[atom.handle]:
		    oatom = oatoms[atom.handle].pop()
		    oatoms[oatom.handle].remove(atom)

	elif minimum_degree > 2:
	    # no N2 nodes so remove the "optimum" edge to create
	    # N2 nodes in the next go-around.
	    ring, bonds = getRing(minimum, fullSet, lookup, oatoms)
            if ring:
                key = ring[:]
                key.sort()
                key = tuple(key)
                if not results.has_key(key):
                    results[key] = ring, bonds
                    atoms = map(lookup.get, ring)
                    atoms, bonds = toposort(atoms, bonds)
                    checkEdges(atoms, lookup, oatoms)
            else:
                del fullSet[minimum.handle]
 	else:
	    raise ShouldntGetHereError

    # assign the ring index to the atom
    rings = []
    index = 0

    # transform the handles back to atoms
    for result, bonds in results.values():
	ring = []
        for atomID in result:
	    atom = lookup[atomID]
            assert atom.handle == atomID
	    ring.append(atom)
	rings.append((ring, bonds))
        index = index + 1

    molecule.rings = rings
    potentialCycles = []
    index = 0
    for atoms, bonds in rings:
        # due to the dictionaries used in getRing
        # the atoms are not in the order found
        # we need to topologically sort these
        # for the cycle
        atoms, bonds = toposort(atoms, bonds)
        potentialCycles.append((atoms, bonds))

    rings = potentialCycles#checkRings(potentialCycles)
    molecule.rings = rings
    molecule.cycles = [Cycle(atoms, bonds) for atoms, bonds in rings]
    return molecule
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
485064
def build(self):
        """"""
        self._molecules = []
        if self.handedness == 'l':
            handedness = -1
        else:
            handedness = 1
        rot_ang = self.rot_ang * handedness
        for i in range(self.num_of_repeats):
            dup_unit = copy.deepcopy(self.repeat_unit)
            z = (self.rise * i) * numpy.array([0, 0, 1])
            dup_unit.translate(z)
            dup_unit.rotate(rot_ang * i, [0, 0, 1])
            self.extend(dup_unit)
        self.relabel_all()
        return
654310
def get_molecule_hash(self, mol):
        
        obmol = BabelMolAdaptor(mol).openbabel_mol
        inchi = self._inchi_labels(obmol)[2]
        return inchi
11999
def load_molecule(name, format=None):
    '''
    
    '''    
    mol = datafile(name, format=format).read('molecule')
    display_system(System([mol]))