Generate different hash codes for stereoisomers. The currently supported
geometries are:

<ul>
<li>Tetrahedral</li>
<li>Double Bond</li>
<li>Cumulative Double Bonds</li>
</ul>

@return fluent API reference (self)
491607
public HashGeneratorMaker chiral() {
        this.stereoEncoders.add(new GeometricTetrahedralEncoderFactory());
        this.stereoEncoders.add(new GeometricDoubleBondEncoderFactory());
        this.stereoEncoders.add(new GeometricCumulativeDoubleBondFactory());
        this.stereoEncoders.add(new TetrahedralElementEncoderFactory());
        this.stereoEncoders.add(new DoubleBondElementEncoderFactory());
        return this;
    }
667526
@Override
	public Point3d[] getVertices() {
		Point3d[] octahedron = new Point3d[6];
	    octahedron[0] = new Point3d(-cirumscribedRadius, 0, 0);
	    octahedron[1] = new Point3d( cirumscribedRadius, 0, 0);
	    octahedron[2] = new Point3d(0, -cirumscribedRadius, 0);
	    octahedron[3] = new Point3d(0,  cirumscribedRadius, 0);
	    octahedron[4] = new Point3d(0, 0, -cirumscribedRadius);
	    octahedron[5] = new Point3d(0, 0,  cirumscribedRadius);

		return octahedron;
	}
278004
private Set<IChemObject> getAromatics(IAtomContainer mol) {
        Set<IChemObject> oldArom = new HashSet<>();
        for (IAtom atom : mol.atoms())
            if (atom.getFlag(CDKConstants.ISAROMATIC))
                oldArom.add(atom);
        for (IBond bond : mol.bonds())
            if (bond.getFlag(CDKConstants.ISAROMATIC))
                oldArom.add(bond);
        return oldArom;
    }
1167725
def get_geometries(self, coordination=None, returned='cg'):
        
        geom = list()
        if coordination is None:
            for gg in self.cg_list:
                if returned == 'cg':
                    geom.append(gg)
                elif returned == 'mp_symbol':
                    geom.append(gg.mp_symbol)
        else:
            for gg in self.cg_list:
                if gg.get_coordination_number() == coordination:
                    if returned == 'cg':
                        geom.append(gg)
                    elif returned == 'mp_symbol':
                        geom.append(gg.mp_symbol)
        return geom
1187796
private String getSphereCode(List<TreeNode> sphereNodes) throws CDKException {
        if (sphereNodes == null || sphereNodes.size() < 1) {
            return sphereDelimiters[sphere - 1];
        }
        TreeNode treeNode = null;
        StringBuffer code = new StringBuffer();
        /*
         * append the tree node code to the HOSECode in their now determined
         * order, using commas to separate nodes from different branches
         */
        IAtom branch = sphereNodes.get(0).source.atom;
        StringBuffer tempCode = null;
        for (int i = 0; i < sphereNodes.size(); i++) {
            treeNode = sphereNodes.get(i);
            tempCode = new StringBuffer();
            if (!treeNode.source.stopper && !treeNode.source.atom.equals(branch)) {
                branch = treeNode.source.atom;
                code.append(',');
            }

            if (!treeNode.source.stopper && treeNode.source.atom.equals(branch)) {
                if (treeNode.bondType <= 4) {
                    tempCode.append(bondSymbols[(int) treeNode.bondType]);
                } else {
                    throw new CDKException("Unknown bond type");
                }
                if (treeNode.atom != null && !treeNode.atom.getFlag(CDKConstants.VISITED)) {
                    tempCode.append(getElementSymbol(treeNode.symbol));
                } else if (treeNode.atom != null && treeNode.atom.getFlag(CDKConstants.VISITED)) {
                    tempCode.append('&');
                    treeNode.stopper = true;
                }
                code.append(tempCode + createChargeCode(treeNode.atom));
                treeNode.hSymbol = tempCode.toString();
            }
            if (treeNode.atom != null) treeNode.atom.setFlag(CDKConstants.VISITED, true);
            if (treeNode.source.stopper) treeNode.stopper = true;
        }
        code.append(sphereDelimiters[sphere - 1]);
        return code.toString();
    }
1741
def geometry_hash(geometry):
    
    if hasattr(geometry, 'md5'):
        # for most of our trimesh objects
        md5 = geometry.md5()
    elif hasattr(geometry, 'tostring'):
        # for unwrapped ndarray objects
        md5 = str(hash(geometry.tostring()))

    if hasattr(geometry, 'visual'):
        # if visual properties are defined
        md5 += str(geometry.visual.crc())
    return md5
205091
public IAtomContainer generate() throws CDKException {
        boolean structureFound = false;
        boolean bondFormed;
        double order;
        double max, cmax1, cmax2;
        int iteration = 0;
        IAtom partner;
        IAtom atom;
        do {
            iteration++;
            atomContainer.removeAllElectronContainers();
            do {
                bondFormed = false;
                for (int f = 0; f < atomContainer.getAtomCount(); f++) {
                    atom = atomContainer.getAtom(f);

                    if (!satCheck.isSaturated(atom, atomContainer)) {
                        partner = getAnotherUnsaturatedNode(atom);
                        if (partner != null) {
                            cmax1 = satCheck.getCurrentMaxBondOrder(atom, atomContainer);

                            cmax2 = satCheck.getCurrentMaxBondOrder(partner, atomContainer);
                            max = Math.min(cmax1, cmax2);
                            order = Math.min(Math.max(1.0, random.nextInt((int) Math.round(max))), 3.0);
                            logger.debug("Forming bond of order ", order);
                            atomContainer.addBond(atomContainer.getBuilder().newInstance(IBond.class, atom, partner,
                                    BondManipulator.createBondOrder(order)));
                            bondFormed = true;
                        }
                    }
                }
            } while (bondFormed);
            if (ConnectivityChecker.isConnected(atomContainer) && satCheck.allSaturated(atomContainer)) {
                structureFound = true;
            }
        } while (!structureFound && iteration < 20);
        logger.debug("Structure found after #iterations: ", iteration);
        return atomContainer.getBuilder().newInstance(IAtomContainer.class, atomContainer);
    }
581528
def multiplicity(self):
        
        if self._multiplicity is None:
            # generate multiplicity based on space group symmetry operations performed on defect coordinates
            try:
                d_structure = create_saturated_interstitial_structure(self)
            except ValueError:
                logger.debug('WARNING! Multiplicity was not able to be calculated adequately '
                             'for interstitials...setting this to 1 and skipping for now...')
                return 1

            sga = SpacegroupAnalyzer(d_structure)
            periodic_struc = sga.get_symmetrized_structure()
            poss_deflist = sorted(
                periodic_struc.get_sites_in_sphere(self.site.coords, 2, include_index=True),
                key=lambda x: x[1])
            defindex = poss_deflist[0][2]

            equivalent_sites = periodic_struc.find_equivalent_sites(periodic_struc[defindex])
            return len(equivalent_sites)

        else:
            return self._multiplicity
1374773
public static Map<String, IAminoAcid> getHashMapByThreeLetterCode() {
        AminoAcid[] monomers = createAAs();
        Map<String, IAminoAcid> map = new HashMap<String, IAminoAcid>();
        for (int i = 0; i < monomers.length; i++) {
            map.put((String) monomers[i].getProperty(RESIDUE_NAME), monomers[i]);
        }
        return map;
    }
1374150
def get_zmatrix(self):
        
        output = []
        outputvar = []
        for i, site in enumerate(self._mol):
            if i == 0:
                output.append("{}".format(site.specie))
            elif i == 1:
                nn = self._find_nn_pos_before_site(i)
                bondlength = self._mol.get_distance(i, nn[0])
                output.append("{} {} B{}".format(self._mol[i].specie,
                                                 nn[0] + 1, i))
                outputvar.append("B{}={:.6f}".format(i, bondlength))
            elif i == 2:
                nn = self._find_nn_pos_before_site(i)
                bondlength = self._mol.get_distance(i, nn[0])
                angle = self._mol.get_angle(i, nn[0], nn[1])
                output.append("{} {} B{} {} A{}".format(self._mol[i].specie,
                                                        nn[0] + 1, i,
                                                        nn[1] + 1, i))
                outputvar.append("B{}={:.6f}".format(i, bondlength))
                outputvar.append("A{}={:.6f}".format(i, angle))
            else:
                nn = self._find_nn_pos_before_site(i)
                bondlength = self._mol.get_distance(i, nn[0])
                angle = self._mol.get_angle(i, nn[0], nn[1])
                dih = self._mol.get_dihedral(i, nn[0], nn[1], nn[2])
                output.append("{} {} B{} {} A{} {} D{}"
                              .format(self._mol[i].specie, nn[0] + 1, i,
                                      nn[1] + 1, i, nn[2] + 1, i))
                outputvar.append("B{}={:.6f}".format(i, bondlength))
                outputvar.append("A{}={:.6f}".format(i, angle))
                outputvar.append("D{}={:.6f}".format(i, dih))
        return "\n".join(output) + "\n\n" + "\n".join(outputvar)
1040242
@Override
    public StereoEncoder create(IAtomContainer container, int[][] graph) {

        int n = container.getAtomCount();
        BondMap map = new BondMap(n);

        List<StereoEncoder> encoders = new ArrayList<StereoEncoder>(1);

        // index double bonds by their atoms
        for (IBond bond : container.bonds()) {
            if (isDoubleBond(bond)) map.add(bond);
        }

        Set<IAtom> visited = new HashSet<IAtom>(n);

        // find atoms which are connected between two double bonds
        for (IAtom a : map.atoms()) {

            List<IBond> bonds = map.bonds(a);
            if (bonds.size() == 2) {

                // (s)tart/(e)nd of cumulated system: -s=a=e-
                IAtom s = bonds.get(0).getOther(a);
                IAtom e = bonds.get(1).getOther(a);
                // need the parents to re-use the double bond encoder
                IAtom sParent = a;
                IAtom eParent = a;

                visited.add(a);
                visited.add(s);
                visited.add(e);

                int size = 2;

                // expand out from 'l'
                while (s != null && map.cumulated(s)) {
                    IAtom p = map.bonds(s).get(0).getOther(s);
                    IAtom q = map.bonds(s).get(1).getOther(s);
                    sParent = s;
                    s = visited.add(p) ? p : visited.add(q) ? q : null;
                    size++;
                }

                // expand from 'r'
                while (e != null && map.cumulated(e)) {
                    IAtom p = map.bonds(e).get(0).getOther(e);
                    IAtom q = map.bonds(e).get(1).getOther(e);
                    eParent = e;
                    e = visited.add(p) ? p : visited.add(q) ? q : null;
                    size++;
                }

                // s and e are null if we had a cumulative cycle...
                if (s != null && e != null) {

                    // system has now be expanded, size is the number of double
                    // bonds. For odd numbers we use E/Z whilst for even are
                    // axial M/P.
                    //  \           /
                    //   s = = = = e
                    //  /           \
                    if (isOdd(size)) {
                        StereoEncoder encoder = GeometricDoubleBondEncoderFactory.newEncoder(container, s, sParent, e,
                                eParent, graph);
                        if (encoder != null) {
                            encoders.add(encoder);
                        }
                    } else {
                        StereoEncoder encoder = axialEncoder(container, s, e);
                        if (encoder != null) {
                            encoders.add(encoder);
                        }
                    }
                }
            }
        }

        return encoders.isEmpty() ? StereoEncoder.EMPTY : new MultiStereoEncoder(encoders);
    }
401934
def format_ring_double_bond(mol):
    
    mol.require("Topology")
    mol.require("ScaleAndCenter")
    for r in sorted(mol.rings, key=len, reverse=True):
        vertices = [mol.atom(n).coords for n in r]
        try:
            if geometry.is_clockwise(vertices):
                cpath = iterator.consecutive(itertools.cycle(r), 2)
            else:
                cpath = iterator.consecutive(itertools.cycle(reversed(r)), 2)
        except ValueError:
            continue
        for _ in r:
            u, v = next(cpath)
            b = mol.bond(u, v)
            if b.order == 2:
                b.type = int((u > v) == b.is_lower_first)
975665
def molecule(lines):
    
    count_line = lines[3]
    num_atoms = int(count_line[0:3])
    num_bonds = int(count_line[3:6])
    # chiral_flag = int(count_line[12:15])  # Not used
    # num_prop = int(count_line[30:33])  # "No longer supported"
    compound = Compound()
    compound.graph._node = atoms(lines[4: num_atoms+4])
    compound.graph._adj = bonds(lines[num_atoms+4: num_atoms+num_bonds+4],
                                compound.graph._node.keys())
    props = properties(lines[num_atoms+num_bonds+4:])
    add_properties(props, compound)
    return compound
1187416
public static List<Structure> divideStructure(CeSymmResult symmetry)
			throws StructureException {

		if (!symmetry.isRefined())
			throw new IllegalArgumentException("The symmetry result "
					+ "is not refined, repeats cannot be defined");

		int order = symmetry.getMultipleAlignment().size();
		Atom[] atoms = symmetry.getAtoms();
		Set<Group> allGroups = StructureTools.getAllGroupsFromSubset(atoms, GroupType.HETATM);
		List<StructureIdentifier> repeatsId = symmetry.getRepeatsID();
		List<Structure> repeats = new ArrayList<Structure>(order);

		// Create new structure containing the repeat atoms
		for (int i = 0; i < order; i++) {

			Structure s = new StructureImpl();
			s.addModel(new ArrayList<Chain>(1));
			s.setStructureIdentifier(repeatsId.get(i));

			Block align = symmetry.getMultipleAlignment().getBlock(0);

			// Get the start and end of the repeat
			// Repeats are always sequential blocks
			int res1 = align.getStartResidue(i);
			int res2 = align.getFinalResidue(i);

			// All atoms from the repeat, used for ligand search
			// AA have an average of 8.45 atoms, so guess capacity with that
			List<Atom> repeat = new ArrayList<>(Math.max(9*(res2-res1+1),9));
			// speedy chain lookup
			Chain prevChain = null;
			for(int k=res1;k<=res2; k++) {
				Group g = atoms[k].getGroup();
				prevChain = StructureTools.addGroupToStructure(s, g, 0, prevChain,true);
				repeat.addAll(g.getAtoms());
			}


			List<Group> ligands = StructureTools.getLigandsByProximity(
					allGroups,
					repeat.toArray(new Atom[repeat.size()]),
					StructureTools.DEFAULT_LIGAND_PROXIMITY_CUTOFF);

			logger.warn("Adding {} ligands to {}",ligands.size(), symmetry.getMultipleAlignment().getStructureIdentifier(i));
			for( Group ligand : ligands) {
				prevChain = StructureTools.addGroupToStructure(s, ligand, 0, prevChain,true);
			}

			repeats.add(s);
		}
		return repeats;
	}
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());
    }
796569
private static IRing toRing(IAtomContainer container, int[] cycle, EdgeToBondMap bondMap) {

        IAtom[] atoms = new IAtom[cycle.length - 1];
        IBond[] bonds = new IBond[cycle.length - 1];

        for (int i = 1; i < cycle.length; i++) {
            int v = cycle[i];
            int u = cycle[i - 1];
            atoms[i - 1] = container.getAtom(u);
            bonds[i - 1] = getBond(container, bondMap, u, v);
        }

        IChemObjectBuilder builder = container.getBuilder();
        IAtomContainer ring = builder.newInstance(IAtomContainer.class, 0, 0, 0, 0);
        ring.setAtoms(atoms);
        ring.setBonds(bonds);

        return builder.newInstance(IRing.class, ring);
    }
944532
public double[][] buildBondMatrix() {
        int i, j, k, m;
        for (i = 0; i < nodeNumber; i++) {
            for (j = 1; j <= layerNumber; j++) {
                bondMatrix[i][j - 1] = 0.0;
                for (k = 0; k < nodeNumber; k++) {
                    if (j == 1) {
                        if (apspMatrix[i][k] == j) {
                            bondMatrix[i][j - 1] += adjaMatrix[i][k];
                        }
                    } else {
                        if (apspMatrix[i][k] == j) {
                            for (m = 0; m < nodeNumber; m++) {
                                if (apspMatrix[i][m] == (j - 1)) {
                                    bondMatrix[i][j - 1] += adjaMatrix[k][m];
                                }
                            }
                        }
                    }
                }
            }
        }
        return bondMatrix;
    }