Esempio n. 1
0
 /// <summary> 
 /// Tells if a certain bond is center of a valid double bond configuration.
 /// </summary>
 /// <param name="container"> The atomcontainer.
 /// </param>
 /// <param name="bond">      The bond.
 /// </param>
 /// <returns>            true=is a potential configuration, false=is not.
 /// </returns>
 public static bool isValidDoubleBondConfiguration(IAtomContainer container, IBond bond)
 {
     IAtom[] atoms = bond.getAtoms();
     IAtom[] connectedAtoms = container.getConnectedAtoms(atoms[0]);
     IAtom from = null;
     for (int i = 0; i < connectedAtoms.Length; i++)
     {
         if (connectedAtoms[i] != atoms[1])
         {
             from = connectedAtoms[i];
         }
     }
     bool[] array = new bool[container.Bonds.Length];
     for (int i = 0; i < array.Length; i++)
     {
         array[i] = true;
     }
     if (isStartOfDoubleBond(container, atoms[0], from, array) && isEndOfDoubleBond(container, atoms[1], atoms[0], array) && !bond.getFlag(CDKConstants.ISAROMATIC))
     {
         return (true);
     }
     else
     {
         return (false);
     }
 }
Esempio n. 2
0
        public CouponHistory(IBond instrument, DateTime startAccrualDate, DateTime endAccrualDate)
            : base(instrument)
        {
            if (Util.IsNullDate(startAccrualDate) || Util.IsNullDate(endAccrualDate) || startAccrualDate >= endAccrualDate)
                throw new ApplicationException("The accrual dates are not correct.");

            this.StartAccrualDate = startAccrualDate;
            this.EndAccrualDate = endAccrualDate;
            this.Description = string.Format("Coupon {0}: {1} - {2}",
                instrument.DisplayIsinWithName,
                startAccrualDate.ToString("dd-MM-yyyy"),
                endAccrualDate.ToString("dd-MM-yyyy"));
        }
Esempio n. 3
0
        public void TestBond()
        {
            var  mol   = new AtomContainer();
            Atom atom  = new Atom("C");
            Atom atom2 = new Atom("O");

            mol.Atoms.Add(atom);
            mol.Atoms.Add(atom2);
            Bond bond = new Bond(atom, atom2, BondOrder.Single);

            mol.Bonds.Add(bond);

            IAtomContainer roundTrippedMol = CMLRoundTripTool.RoundTripMolecule(convertor, mol);

            Assert.AreEqual(2, roundTrippedMol.Atoms.Count);
            Assert.AreEqual(1, roundTrippedMol.Bonds.Count);
            IBond roundTrippedBond = roundTrippedMol.Bonds[0];

            Assert.AreEqual(2, roundTrippedBond.Atoms.Count);
            Assert.AreEqual("C", roundTrippedBond.Begin.Symbol); // preserved direction?
            Assert.AreEqual("O", roundTrippedBond.End.Symbol);
            Assert.AreEqual(bond.Order, roundTrippedBond.Order);
        }
Esempio n. 4
0
 /// <inheritdoc/>
 /// <param name="targetConatiner">target container</param>
 /// <param name="targetBond">target bond</param>
 /// <returns>true if bonds match</returns>
 public bool Matches(TargetProperties targetConatiner, IBond targetBond)
 {
     if (this.smartQueryBond != null)
     {
         return(smartQueryBond.Matches(targetBond));
     }
     else
     {
         if (!IsBondMatchFlag)
         {
             return(true);
         }
         if (IsBondMatchFlag && IsBondTypeMatch(targetBond))
         {
             return(true);
         }
         if (IsBondMatchFlag && this.unsaturation == GetUnsaturation(targetConatiner, targetBond))
         {
             return(true);
         }
     }
     return(false);
 }
Esempio n. 5
0
        internal static bool IsMatchFeasible(IAtomContainer ac1, IBond bondA1, IAtomContainer ac2, IBond bondA2,
                                             bool shouldMatchBonds)
        {
            if (ac1 is IQueryAtomContainer)
            {
                if (((IQueryBond)bondA1).Matches(bondA2))
                {
                    IQueryAtom atom1 = (IQueryAtom)(bondA1.Begin);
                    IQueryAtom atom2 = (IQueryAtom)(bondA1.End);
                    // ok, bonds match
                    if (atom1.Matches(bondA2.Begin) && atom2.Matches(bondA2.End) ||
                        atom1.Matches(bondA2.End) && atom2.Matches(bondA2.Begin))
                    {
                        // ok, atoms match in either order
                        return(true);
                    }
                    return(false);
                }
                return(false);
            }
            else
            {
                //Bond Matcher
                var bondMatcher = new Matchers.DefaultBondMatcher(ac1, bondA1, shouldMatchBonds);
                //Atom Matcher
                var atomMatcher1 = new Matchers.DefaultMCSPlusAtomMatcher(ac1, bondA1.Begin, shouldMatchBonds);
                //Atom Matcher
                var atomMatcher2 = new Matchers.DefaultMCSPlusAtomMatcher(ac1, bondA1.End, shouldMatchBonds);

                if (Matchers.DefaultMatcher.IsBondMatch(bondMatcher, ac2, bondA2, shouldMatchBonds) &&
                    Matchers.DefaultMatcher.IsAtomMatch(atomMatcher1, atomMatcher2, ac2, bondA2, shouldMatchBonds))
                {
                    return(true);
                }
                return(false);
            }
        }
Esempio n. 6
0
        public static IAtomContainer CreateAcetone()
        {
            IAtomContainer result = builder.NewAtomContainer();

            IAtom c1 = builder.NewAtom("C");

            c1.Id = "1";
            IAtom c2 = builder.NewAtom("C");

            c2.Id = "2";
            IAtom c3 = builder.NewAtom("C");

            c3.Id = "3";
            IAtom c4 = builder.NewAtom("O");

            c4.Id = "4";

            result.Atoms.Add(c1);
            result.Atoms.Add(c2);
            result.Atoms.Add(c3);
            result.Atoms.Add(c4);

            IBond bond1 = builder.NewBond(c1, c2, BondOrder.Single);
            IBond bond2 = builder.NewBond(c2, c3, BondOrder.Single);
            IBond bond3 = builder.NewBond(c3, c4, BondOrder.Double);

            result.Bonds.Add(bond1);
            result.Bonds.Add(bond2);
            result.Bonds.Add(bond3);
            AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(result);
            var adder = CDK.HydrogenAdder;

            adder.AddImplicitHydrogens(result);
            Aromaticity.CDKLegacy.Apply(result);

            return(result);
        }
Esempio n. 7
0
        public void ObtainNonPerfectCardinalBonds()
        {
            IAtom focus = Atom("C", 0, -0.40d, 3.37d);

            IAtom north = Atom("C", 0, -0.43d, 4.18d);
            IAtom east  = Atom("O", 1, 0.44d, 3.33d);
            IAtom south = Atom("C", 2, -0.42d, 2.65d);
            IAtom west  = Atom("H", 0, -1.21d, 3.36d);

            IBond[] expected = new IBond[] {
                new Bond(focus, north),
                new Bond(focus, east),
                new Bond(focus, south),
                new Bond(focus, west)
            };

            IBond[] actual = FischerRecognition.CardinalBonds(focus,
                                                              new IBond[] { expected[1],
                                                                            expected[2],
                                                                            expected[3],
                                                                            expected[0] }
                                                              );
            Assert.IsTrue(Compares.AreDeepEqual(actual, expected));
        }
Esempio n. 8
0
        public void ObtainCardinalBonds()
        {
            IAtom focus = Atom("C", 0, 0.80d, 0.42d);

            IAtom north = Atom("C", 0, 0.80d, 1.24d);
            IAtom east  = Atom("O", 1, 1.63d, 0.42d);
            IAtom south = Atom("C", 2, 0.80d, -0.41d);
            IAtom west  = Atom("H", 0, -0.02d, 0.42d);

            IBond[] expected = new IBond[] {
                new Bond(focus, north),
                new Bond(focus, east),
                new Bond(focus, south),
                new Bond(focus, west)
            };

            IBond[] actual = FischerRecognition.CardinalBonds(focus,
                                                              new IBond[] { expected[1],
                                                                            expected[2],
                                                                            expected[3],
                                                                            expected[0] }
                                                              );
            Assert.IsTrue(Compares.AreDeepEqual(actual, expected));
        }
Esempio n. 9
0
        /// <inheritdoc/>
        public override string GetEdgeLabel(int vertexIndex, int otherVertexIndex)
        {
            IAtom atomA = this.molecule.Atoms[vertexIndex];
            IAtom atomB = this.molecule.Atoms[otherVertexIndex];
            IBond bond  = this.molecule.GetBond(atomA, atomB);

            if (bond != null)
            {
                if (bond.IsAromatic)
                {
                    return("p");
                }
                switch (bond.Order)
                {
                //                case Single: return "-";
                case BondOrder.Single:
                    return("");

                case BondOrder.Double:
                    return("=");

                case BondOrder.Triple:
                    return("#");

                case BondOrder.Quadruple:
                    return("$");

                default:
                    return("");
                }
            }
            else
            {
                return("");
            }
        }
Esempio n. 10
0
        public void TestS4oxide()
        {
            IAtomContainer mol = builder.NewAtomContainer();
            IAtom          s   = builder.NewAtom("S");
            IAtom          o1  = builder.NewAtom("O");
            IAtom          o2  = builder.NewAtom("O");
            IAtom          o3  = builder.NewAtom("O");

            IBond b1 = builder.NewBond(s, o1, BondOrder.Double);
            IBond b2 = builder.NewBond(s, o2, BondOrder.Double);
            IBond b3 = builder.NewBond(s, o3, BondOrder.Double);

            mol.Atoms.Add(s);
            mol.Atoms.Add(o1);
            mol.Atoms.Add(o2);
            mol.Atoms.Add(o3);

            mol.Bonds.Add(b1);
            mol.Bonds.Add(b2);
            mol.Bonds.Add(b3);

            StructGenMatcher matcher = new StructGenMatcher();
            IAtomType        matched;

            matched = matcher.FindMatchingAtomType(mol, mol.Atoms[0]);
            AssertAtomType(testedAtomTypes, "S4", matched);

            matched = matcher.FindMatchingAtomType(mol, mol.Atoms[1]);
            AssertAtomType(testedAtomTypes, "O2", matched);

            matched = matcher.FindMatchingAtomType(mol, mol.Atoms[2]);
            AssertAtomType(testedAtomTypes, "O2", matched);

            matched = matcher.FindMatchingAtomType(mol, mol.Atoms[3]);
            AssertAtomType(testedAtomTypes, "O2", matched);
        }
Esempio n. 11
0
        public void TestOxygen2()
        {
            IAtomContainer mol = builder.NewAtomContainer();
            IAtom          o1  = builder.NewAtom("O");
            IAtom          o2  = builder.NewAtom("O");
            IAtom          h1  = builder.NewAtom("H");
            IAtom          h2  = builder.NewAtom("H");

            IBond bond1 = builder.NewBond(h1, o1, BondOrder.Single);
            IBond bond2 = builder.NewBond(o1, o2, BondOrder.Single);
            IBond bond3 = builder.NewBond(o2, h2, BondOrder.Single);

            mol.Atoms.Add(o1);
            mol.Atoms.Add(o2);
            mol.Atoms.Add(h1);
            mol.Atoms.Add(h2);

            mol.Bonds.Add(bond1);
            mol.Bonds.Add(bond2);
            mol.Bonds.Add(bond3);

            StructGenMatcher matcher = new StructGenMatcher();
            IAtomType        matched;

            matched = matcher.FindMatchingAtomType(mol, mol.Atoms[0]);
            AssertAtomType(testedAtomTypes, "O2", matched);

            matched = matcher.FindMatchingAtomType(mol, mol.Atoms[1]);
            AssertAtomType(testedAtomTypes, "O2", matched);

            matched = matcher.FindMatchingAtomType(mol, mol.Atoms[2]);
            AssertAtomType(testedAtomTypes, "H1", matched);

            matched = matcher.FindMatchingAtomType(mol, mol.Atoms[3]);
            AssertAtomType(testedAtomTypes, "H1", matched);
        }
Esempio n. 12
0
        public void CreateCenterWithThreeNeighbors_right()
        {
            IAtom focus = Atom("C", 0, 0.80d, 0.42d);

            IAtom north = Atom("C", 0, 0.80d, 1.24d);
            IAtom east  = Atom("O", 1, 1.63d, 0.42d);
            IAtom south = Atom("C", 2, 0.80d, -0.41d);

            IBond[] bonds = new IBond[] {
                new Bond(focus, south),
                new Bond(focus, north),
                new Bond(focus, east)
            };

            ITetrahedralChirality element = FischerRecognition.NewTetrahedralCenter(focus,
                                                                                    bonds);

            Assert.AreSame(focus, element.ChiralAtom);
            Assert.AreEqual(TetrahedralStereo.AntiClockwise, element.Stereo);
            Assert.AreSame(north, element.Ligands[0]);
            Assert.AreSame(east, element.Ligands[1]);
            Assert.AreSame(south, element.Ligands[2]);
            Assert.AreSame(focus, element.Ligands[3]);
        }
Esempio n. 13
0
 private static bool IsInRingSize(IAtom atom, IBond prev, IAtom beg, int size, int req)
 {
     atom.IsVisited = true;
     foreach (var bond in atom.Bonds)
     {
         if (bond == prev)
         {
             continue;
         }
         var nbr = bond.GetOther(atom);
         if (nbr.Equals(beg))
         {
             return(size == req);
         }
         else if (size < req &&
                  !nbr.IsVisited &&
                  IsInRingSize(nbr, bond, beg, size + 1, req))
         {
             return(true);
         }
     }
     atom.IsVisited = false;
     return(false);
 }
        /// <summary>
        /// Generate Compatibility Graph Nodes Bond Insensitive
        /// </summary>
        /// <exception cref="System.IO.IOException"></exception>
        internal int CompatibilityGraph()
        {
            int compGraphNodesListSize = compGraphNodes.Count;

            cEdges = new List <int>(); //Initialize the cEdges List
            dEdges = new List <int>(); //Initialize the dEdges List

            for (int a = 0; a < compGraphNodesListSize; a += 3)
            {
                int indexA      = compGraphNodes[a];
                int indexAPlus1 = compGraphNodes[a + 1];

                for (int b = a + 3; b < compGraphNodesListSize; b += 3)
                {
                    int indexB      = compGraphNodes[b];
                    int indexBPlus1 = compGraphNodes[b + 1];

                    // if element atomCont !=jIndex and atoms on the adjacent sides of the bonds are not equal
                    if (a != b && indexA != indexB && indexAPlus1 != indexBPlus1)
                    {
                        IBond reactantBond = null;
                        IBond productBond  = null;

                        reactantBond = source.GetBond(source.Atoms[indexA], source.Atoms[indexB]);
                        productBond  = target.GetBond(target.Atoms[indexAPlus1], target.Atoms[indexBPlus1]);
                        if (reactantBond != null && productBond != null)
                        {
                            AddEdges(reactantBond, productBond, a, b);
                        }
                    }
                }
            }
            cEdgesSize = cEdges.Count;
            dEdgesSize = dEdges.Count;
            return(0);
        }
Esempio n. 15
0
        public static IAtomContainer CreateIsobutane()
        {
            IAtomContainer result = builder.NewAtomContainer();

            IAtom c1 = builder.NewAtom("C");
            IAtom c2 = builder.NewAtom("C");
            IAtom c3 = builder.NewAtom("C");
            IAtom c4 = builder.NewAtom("C");

            result.Atoms.Add(c1);
            result.Atoms.Add(c2);
            result.Atoms.Add(c3);
            result.Atoms.Add(c4);

            IBond bond1 = builder.NewBond(c1, c2, BondOrder.Single);
            IBond bond2 = builder.NewBond(c2, c3, BondOrder.Single);
            IBond bond3 = builder.NewBond(c2, c4, BondOrder.Single);

            result.Bonds.Add(bond1);
            result.Bonds.Add(bond2);
            result.Bonds.Add(bond3);

            return(result);
        }
Esempio n. 16
0
        public void GetAromaticEdgeLabelTest()
        {
            IAtomContainer benzeneRing = builder.NewAtomContainer();

            for (int i = 0; i < 6; i++)
            {
                benzeneRing.Atoms.Add(builder.NewAtom("C"));
            }
            for (int i = 0; i < 6; i++)
            {
                IAtom a    = benzeneRing.Atoms[i];
                IAtom b    = benzeneRing.Atoms[(i + 1) % 6];
                IBond bond = builder.NewBond(a, b);
                benzeneRing.Bonds.Add(bond);
                bond.IsAromatic = true;
            }

            AtomSignature signature = new AtomSignature(0, benzeneRing);

            for (int i = 0; i < 6; i++)
            {
                Assert.AreEqual("p", signature.GetEdgeLabel(i, (i + 1) % 6), "Failed for " + i);
            }
        }
Esempio n. 17
0
        public virtual void TestGetNextBond_IBond_IAtom()
        {
            IRing ring = (IRing)NewChemObject();
            IAtom c1   = ring.Builder.NewAtom("C");
            IAtom c2   = ring.Builder.NewAtom("C");
            IAtom c3   = ring.Builder.NewAtom("C");
            IBond b1   = ring.Builder.NewBond(c1, c2, BondOrder.Single);
            IBond b2   = ring.Builder.NewBond(c3, c2, BondOrder.Single);
            IBond b3   = ring.Builder.NewBond(c1, c3, BondOrder.Single);

            ring.Atoms.Add(c1);
            ring.Atoms.Add(c2);
            ring.Atoms.Add(c3);
            ring.Bonds.Add(b1);
            ring.Bonds.Add(b2);
            ring.Bonds.Add(b3);

            Assert.AreEqual(b1, ring.GetNextBond(b2, c2));
            Assert.AreEqual(b1, ring.GetNextBond(b3, c1));
            Assert.AreEqual(b2, ring.GetNextBond(b1, c2));
            Assert.AreEqual(b2, ring.GetNextBond(b3, c3));
            Assert.AreEqual(b3, ring.GetNextBond(b1, c1));
            Assert.AreEqual(b3, ring.GetNextBond(b2, c3));
        }
Esempio n. 18
0
        private bool IsBondMatch(IAtomContainer reactant, IAtomContainer product)
        {
            int counter = 0;
            var ketSet  = firstAtomMCS.Keys.ToArray();

            for (int i = 0; i < ketSet.Length; i++)
            {
                for (int j = i + 1; j < ketSet.Length; j++)
                {
                    IAtom indexI = (IAtom)ketSet[i];
                    IAtom indexJ = (IAtom)ketSet[j];
                    IBond rBond  = reactant.GetBond(indexI, indexJ);
                    if (rBond != null)
                    {
                        counter++;
                    }
                }
            }

            var valueSet = firstAtomMCS.Values.ToArray();

            for (int i = 0; i < valueSet.Length; i++)
            {
                for (int j = i + 1; j < valueSet.Length; j++)
                {
                    IAtom indexI = (IAtom)valueSet[i];
                    IAtom indexJ = (IAtom)valueSet[j];
                    IBond pBond  = product.GetBond(indexI, indexJ);
                    if (pBond != null)
                    {
                        counter--;
                    }
                }
            }
            return(counter == 0 ? true : false);
        }
Esempio n. 19
0
        /// <summary>
        /// Convert a CDK <see cref="IBond"/> to the Beam edge label type.
        /// </summary>
        /// <param name="b">cdk bond</param>
        /// <returns>the edge label for the Beam edge</returns>
        /// <exception cref="NullReferenceException">the bond order was null and the bond was not-aromatic</exception>
        /// <exception cref="ArgumentException">the bond order could not be converted</exception>
        private static Bond ToBeamEdgeLabel(IBond b, SmiFlavors flavour)
        {
            if (SmiFlavorTool.IsSet(flavour, SmiFlavors.UseAromaticSymbols) && b.IsAromatic)
            {
                if (!b.Begin.IsAromatic || !b.End.IsAromatic)
                {
                    throw new InvalidOperationException("Aromatic bond connects non-aromatic atomic atoms");
                }
                return(Bond.Aromatic);
            }

            if (b.Order.IsUnset())
            {
                throw new CDKException("A bond had undefined order, possible query bond?");
            }

            var order = b.Order;

            switch (order)
            {
            case BondOrder.Single:
                return(Bond.Single);

            case BondOrder.Double:
                return(Bond.Double);

            case BondOrder.Triple:
                return(Bond.Triple);

            case BondOrder.Quadruple:
                return(Bond.Quadruple);

            default:
                throw new CDKException("Unsupported bond order: " + order);
            }
        }
Esempio n. 20
0
        /// <summary>
        /// Creates a molecule graph for use with jgrapht.
        /// Bond orders are not respected.
        /// </summary>
        /// <param name="molecule">the specified molecule</param>
        /// <returns>a graph representing the molecule</returns>
        static public SimpleGraph getMoleculeGraph(IAtomContainer molecule)
        {
            SimpleGraph graph = new SimpleGraph();

            for (int i = 0; i < molecule.AtomCount; i++)
            {
                IAtom atom = molecule.Atoms[i];
                graph.addVertex(atom);
            }

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

                /*
                 * int order = (int) bond.getOrder();
                 * for (int j=0; j<order; j++) {
                 *      graph.addEdge(bond.getAtoms()[0], bond.getAtoms()[1]);
                 * }
                 */
                graph.addEdge(bond.getAtoms()[0], bond.getAtoms()[1]);
            }
            return(graph);
        }
Esempio n. 21
0
 /// <summary>  Returns the geometric length of this bond in 2D space.
 /// See comment for center(IAtomContainer atomCon, Dimension areaDim, HashMap renderingCoordinates) for details on coordinate sets
 /// 
 /// </summary>
 /// <param name="bond"> Description of the Parameter
 /// </param>
 /// <returns>       The geometric length of this bond
 /// </returns>
 public static double getLength2D(IBond bond)
 {
     if (bond.getAtomAt(0) == null || bond.getAtomAt(1) == null)
     {
         return 0.0;
     }
     Point2d p1 = bond.getAtomAt(0).getPoint2d();
     Point2d p2 = bond.getAtomAt(1).getPoint2d();
     if (p1 == null || p2 == null)
     {
         return 0.0;
     }
     return p1.distance(p2);
 }
Esempio n. 22
0
 /// <summary>  Writes the coordinates of the atoms participating the given bond into an
 /// array.
 /// See comment for center(IAtomContainer atomCon, Dimension areaDim, HashMap renderingCoordinates) for details on coordinate sets
 /// 
 /// </summary>
 /// <param name="bond"> The given bond
 /// </param>
 /// <returns>       The array with the coordinates
 /// </returns>
 public static int[] getBondCoordinates(IBond bond)
 {
     if (bond.getAtomAt(0).getPoint2d() == null || bond.getAtomAt(1).getPoint2d() == null)
     {
         //logger.error("getBondCoordinates() called on Bond without 2D coordinates!");
         return new int[0];
     }
     int beginX = (int)bond.getAtomAt(0).getPoint2d().x;
     int endX = (int)bond.getAtomAt(1).getPoint2d().x;
     int beginY = (int)bond.getAtomAt(0).getPoint2d().y;
     int endY = (int)bond.getAtomAt(1).getPoint2d().y;
     int[] coords = new int[] { beginX, beginY, endX, endY };
     return coords;
 }
Esempio n. 23
0
 public bool Contains(IBond bond)
 => false;
Esempio n. 24
0
        public static CIPChirality GetCIPChirality(IAtomContainer container, IDoubleBondStereochemistry stereoCenter)
        {
            IBond stereoBond = stereoCenter.StereoBond;
            IBond leftBond   = stereoCenter.Bonds[0];
            IBond rightBond  = stereoCenter.Bonds[1];

            // the following variables are usd to label the atoms - makes things
            // a little more concise
            //
            // x       y       x
            //  \     /         \
            //   u = v    or     u = v
            //                        \
            //                         y
            //
            var u = stereoBond.Begin;
            var v = stereoBond.End;
            var x = leftBond.GetOther(u);
            var y = rightBond.GetOther(v);

            var conformation = stereoCenter.Stereo;

            var leftLigands  = GetLigands(u, container, v).ToList();
            var rightLigands = GetLigands(v, container, u).ToList();

            if (leftLigands.Count > 2 || rightLigands.Count > 2)
            {
                return(CIPChirality.None);
            }

            // invert if x/y aren't in the first position
            if (leftLigands[0].LigandAtom != x)
            {
                conformation = conformation.Invert();
            }
            if (rightLigands[0].LigandAtom != y)
            {
                conformation = conformation.Invert();
            }

            int p = PermParity(leftLigands) * PermParity(rightLigands);

            if (p == 0)
            {
                return(CIPChirality.None);
            }
            else if (p < 0)
            {
                conformation = conformation.Invert();
            }

            switch (conformation)
            {
            case DoubleBondConformation.Together:
                return(CIPChirality.Z);

            case DoubleBondConformation.Opposite:
                return(CIPChirality.E);

            default:
                return(CIPChirality.None);
            }
        }
Esempio n. 25
0
		/// <summary> Saturate atom by adjusting its bond orders.</summary>
		public virtual bool newSaturate(IBond bond, IAtomContainer atomContainer)
		{
			IAtom[] atoms = bond.getAtoms();
			IAtom atom = atoms[0];
			IAtom partner = atoms[1];
			//logger.debug("  saturating bond: ", atom.Symbol, "-", partner.Symbol);
			IAtomType[] atomTypes1 = getAtomTypeFactory(bond.Builder).getAtomTypes(atom.Symbol);
			IAtomType[] atomTypes2 = getAtomTypeFactory(bond.Builder).getAtomTypes(partner.Symbol);
			bool bondOrderIncreased = true;
			while (bondOrderIncreased && !isSaturated(bond, atomContainer))
			{
				//logger.debug("Can increase bond order");
				bondOrderIncreased = false;
				for (int atCounter1 = 0; atCounter1 < atomTypes1.Length && !bondOrderIncreased; atCounter1++)
				{
					IAtomType aType1 = atomTypes1[atCounter1];
					//logger.debug("  condidering atom type: ", aType1);
					if (couldMatchAtomType(atomContainer, atom, aType1))
					{
						//logger.debug("  trying atom type: ", aType1);
						for (int atCounter2 = 0; atCounter2 < atomTypes2.Length && !bondOrderIncreased; atCounter2++)
						{
							IAtomType aType2 = atomTypes2[atCounter2];
							//logger.debug("  condidering partner type: ", aType1);
							if (couldMatchAtomType(atomContainer, partner, atomTypes2[atCounter2]))
							{
								//logger.debug("    with atom type: ", aType2);
								if (bond.Order >= aType2.MaxBondOrder || bond.Order >= aType1.MaxBondOrder)
								{
									//logger.debug("Bond order not increased: atoms has reached (or exceeded) maximum bond order for this atom type");
								}
								else if (bond.Order < aType2.MaxBondOrder && bond.Order < aType1.MaxBondOrder)
								{
									bond.Order = bond.Order + 1;
									//logger.debug("Bond order now " + bond.Order);
									bondOrderIncreased = true;
								}
							}
						}
					}
				}
			}
			return isSaturated(bond, atomContainer);
		}
Esempio n. 26
0
		/// <summary> Resets the bond order of the Bond to 1.0.</summary>
		public virtual void  unsaturate(IBond[] bonds)
		{
			for (int i = 1; i < bonds.Length; i++)
			{
				bonds[i].Order = 1.0;
			}
		}
Esempio n. 27
0
 /// <summary> Checks wether a bond is connected to another one.
 /// This can only be true if the bonds have an Atom in common.
 /// 
 /// </summary>
 /// <param name="bond"> The bond which is checked to be connect with this one
 /// </param>
 /// <returns>       True, if the bonds share an atom, otherwise false
 /// </returns>
 public virtual bool isConnectedTo(IBond bond)
 {
     for (int f = 0; f < AtomCount; f++)
     {
         if (bond.contains(getAtomAt(f)))
         {
             return true;
         }
     }
     return false;
 }
Esempio n. 28
0
 /// <summary> Returns the next bond in order, relative to a given bond and atom.
 /// Example: Let the ring be composed of 0-1, 1-2, 2-3 and 3-0. A request getNextBond(1-2, 2)
 /// will return Bond 2-3.
 /// 
 /// </summary>
 /// <param name="bond"> A bond for which an atom from a consecutive bond is sought
 /// </param>
 /// <param name="atom"> A atom from the bond above to assign a search direction
 /// </param>
 /// <returns>  The next bond in the order given by the above assignment   
 /// </returns>
 public virtual IBond getNextBond(IBond bond, IAtom atom)
 {
     Bond tempBond;
     for (int f = 0; f < ElectronContainerCount; f++)
     {
         IElectronContainer electronContainer = getElectronContainerAt(f);
         if (electronContainer is IBond)
         {
             tempBond = (Bond)electronContainer;
             if (tempBond.contains(atom) && bond != tempBond)
             {
                 return tempBond;
             }
         }
     }
     return null;
 }
Esempio n. 29
0
		/// <summary> Calculate the number of missing hydrogens by substracting the number of
		/// bonds for the atom from the expected number of bonds. Charges are included
		/// in the calculation. The number of expected bonds is defined by the AtomType
		/// generated with the AtomTypeFactory.
		/// 
		/// </summary>
		/// <param name="atom">     Description of the Parameter
		/// </param>
		/// <param name="throwExceptionForUnknowAtom"> Should an exception be thrown if an unknown atomtype is found or 0 returned ?
		/// </param>
		/// <returns>           Description of the Return Value
		/// </returns>
		/// <seealso cref="AtomTypeFactory">
		/// </seealso>
		public virtual int calculateNumberOfImplicitHydrogens(IAtom atom, double bondOrderSum, IBond[] connectedBonds, bool throwExceptionForUnknowAtom)
		{
			int missingHydrogen = 0;
			if (atom is IPseudoAtom)
			{
				// don't figure it out... it simply does not lack H's
			}
			else if (atom.AtomicNumber == 1 || atom.Symbol.Equals("H"))
			{
				//UPGRADE_WARNING: Data types in Visual C# might be different.  Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'"
				missingHydrogen = (int) (1 - bondOrderSum - atom.getFormalCharge());
			}
			else
			{
				//logger.info("Calculating number of missing hydrogen atoms");
				// get default atom
				IAtomType[] atomTypes = getAtomTypeFactory(atom.Builder).getAtomTypes(atom.Symbol);
				if (atomTypes.Length == 0 && throwExceptionForUnknowAtom)
					return 0;
				//logger.debug("Found atomtypes: " + atomTypes.Length);
				if (atomTypes.Length > 0)
				{
					IAtomType defaultAtom = atomTypes[0];
					//logger.debug("DefAtom: ", defaultAtom);
					//UPGRADE_WARNING: Data types in Visual C# might be different.  Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'"
					missingHydrogen = (int) (defaultAtom.BondOrderSum - bondOrderSum + atom.getFormalCharge());
					if (atom.getFlag(CDKConstants.ISAROMATIC))
					{
						bool subtractOne = true;
						for (int i = 0; i < connectedBonds.Length; i++)
						{
							if (connectedBonds[i].Order == 2 || connectedBonds[i].Order == CDKConstants.BONDORDER_AROMATIC)
								subtractOne = false;
						}
						if (subtractOne)
							missingHydrogen--;
					}
					//logger.debug("Atom: ", atom.Symbol);
					//logger.debug("  max bond order: " + defaultAtom.BondOrderSum);
					//logger.debug("  bond order sum: " + bondOrderSum);
					//logger.debug("  charge        : " + atom.getFormalCharge());
				}
				else
				{
					//logger.warn("Could not find atom type for ", atom.Symbol);
				}
			}
			return missingHydrogen;
		}
Esempio n. 30
0
		public virtual int calculateNumberOfImplicitHydrogens(IAtom atom)
		{
			IBond[] bonds = new IBond[0];
			return this.calculateNumberOfImplicitHydrogens(atom, 0, bonds, false);
		}
Esempio n. 31
0
 private static Expr GetBondExpr(IBond bond)
 {
     return(((QueryBond)BondRef.Deref(bond)).Expression);
 }
		/// <summary> Saturates a set of Bonds in an AtomContainer.</summary>
		public virtual bool saturate(IBond[] bonds, IAtomContainer atomContainer)
		{
			//logger.debug("Saturating bond set of size: ", bonds.Length);
			bool bondsAreFullySaturated = false;
			if (bonds.Length > 0)
			{
				IBond bond = bonds[0];
				
				// determine bonds left
				int leftBondCount = bonds.Length - 1;
				IBond[] leftBonds = new IBond[leftBondCount];
				Array.Copy(bonds, 1, leftBonds, 0, leftBondCount);
				
				// examine this bond
				//logger.debug("Examining this bond: ", bond);
				if (isSaturated(bond, atomContainer))
				{
					//logger.debug("OK, bond is saturated, now try to saturate remaining bonds (if needed)");
					bondsAreFullySaturated = saturate(leftBonds, atomContainer);
				}
				else if (isUnsaturated(bond, atomContainer))
				{
					//logger.debug("Ok, this bond is unsaturated, and can be saturated");
					// two options now: 
					// 1. saturate this one directly
					// 2. saturate this one by saturating the rest
					//logger.debug("Option 1: Saturating this bond directly, then trying to saturate rest");
					// considering organic bonds, the max order is 3, so increase twice
					double increment = 1.0;
					bool bondOrderIncreased = saturateByIncreasingBondOrder(bond, atomContainer, increment);
					bondsAreFullySaturated = bondOrderIncreased && saturate(bonds, atomContainer);
					if (bondsAreFullySaturated)
					{
						//logger.debug("Option 1: worked");
					}
					else
					{
						//logger.debug("Option 1: failed. Trying option 2.");
						//logger.debug("Option 2: Saturing this bond by saturating the rest");
						// revert the increase (if succeeded), then saturate the rest
						if (bondOrderIncreased)
							unsaturateByDecreasingBondOrder(bond, increment);
						bondsAreFullySaturated = saturate(leftBonds, atomContainer) && isSaturated(bond, atomContainer);
						//if (!bondsAreFullySaturated)
							//logger.debug("Option 2: failed");
					}
				}
				else
				{
					//logger.debug("Ok, this bond is unsaturated, but cannot be saturated");
					// try recursing and see if that fixes things
					bondsAreFullySaturated = saturate(leftBonds, atomContainer) && isSaturated(bond, atomContainer);
				}
			}
			else
			{
				bondsAreFullySaturated = true; // empty is saturated by default
			}
			return bondsAreFullySaturated;
		}
Esempio n. 33
0
        /// <summary>
        /// Initiates the process for the given mechanism. The atoms and bonds to apply are mapped between
        /// reactants and products.
        /// </summary>
        /// <param name="atomContainerSet"></param>
        /// <param name="atomList">The list of atoms taking part in the mechanism. Only allowed three atoms</param>
        /// <param name="bondList">The list of bonds taking part in the mechanism. Only allowed one bond</param>
        /// <returns>The Reaction mechanism</returns>
        public IReaction Initiate(IChemObjectSet <IAtomContainer> atomContainerSet, IList <IAtom> atomList, IList <IBond> bondList)
        {
            var atMatcher = CDK.AtomTypeMatcher;

            if (atomContainerSet.Count != 2)
            {
                throw new CDKException("AdductionPBMechanism expects two IAtomContainer's");
            }
            if (atomList.Count != 3)
            {
                throw new CDKException("AdductionPBMechanism expects two atoms in the List");
            }
            if (bondList.Count != 1)
            {
                throw new CDKException("AdductionPBMechanism don't expect bonds in the List");
            }
            IAtomContainer molecule1 = atomContainerSet[0];
            IAtomContainer molecule2 = atomContainerSet[1];

            IAtomContainer reactantCloned;

            reactantCloned = (IAtomContainer)atomContainerSet[0].Clone();
            reactantCloned.Add((IAtomContainer)atomContainerSet[1].Clone());
            IAtom atom1    = atomList[0]; // Atom 1: to be deficient in charge
            IAtom atom1C   = reactantCloned.Atoms[molecule1.Atoms.IndexOf(atom1)];
            IAtom atom2    = atomList[1]; // Atom 2: receive the adduct
            IAtom atom2C   = reactantCloned.Atoms[molecule1.Atoms.IndexOf(atom2)];
            IAtom atom3    = atomList[2]; // Atom 2: deficient in charge
            IAtom atom3C   = reactantCloned.Atoms[molecule1.Atoms.Count + molecule2.Atoms.IndexOf(atom3)];
            IBond bond1    = bondList[0];
            int   posBond1 = atomContainerSet[0].Bonds.IndexOf(bond1);

            BondManipulator.DecreaseBondOrder(reactantCloned.Bonds[posBond1]);
            IBond newBond = molecule1.Builder.NewBond(atom2C, atom3C, BondOrder.Single);

            reactantCloned.Bonds.Add(newBond);

            int charge = atom1C.FormalCharge.Value;

            atom1C.FormalCharge  = charge + 1;
            atom1C.Hybridization = Hybridization.Unset;
            AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(reactantCloned);
            IAtomType type = atMatcher.FindMatchingAtomType(reactantCloned, atom1C);

            if (type == null || type.AtomTypeName.Equals("X", StringComparison.Ordinal))
            {
                return(null);
            }

            atom2C.Hybridization = Hybridization.Unset;
            AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(reactantCloned);
            type = atMatcher.FindMatchingAtomType(reactantCloned, atom2C);
            if (type == null || type.AtomTypeName.Equals("X", StringComparison.Ordinal))
            {
                return(null);
            }

            charge = atom3C.FormalCharge.Value;
            atom3C.FormalCharge  = charge - 1;
            atom3C.Hybridization = Hybridization.Unset;
            AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(reactantCloned);
            type = atMatcher.FindMatchingAtomType(reactantCloned, atom3C);
            if (type == null || type.AtomTypeName.Equals("X", StringComparison.Ordinal))
            {
                return(null);
            }

            IReaction reaction = atom1C.Builder.NewReaction();

            reaction.Reactants.Add(molecule1);

            /* mapping */
            foreach (var atom in molecule1.Atoms)
            {
                IMapping mapping = atom1C.Builder.NewMapping(atom,
                                                             reactantCloned.Atoms[molecule1.Atoms.IndexOf(atom)]);
                reaction.Mappings.Add(mapping);
            }
            foreach (var atom in molecule2.Atoms)
            {
                IMapping mapping = atom1C.Builder.NewMapping(atom,
                                                             reactantCloned.Atoms[molecule2.Atoms.IndexOf(atom)]);
                reaction.Mappings.Add(mapping);
            }

            reaction.Products.Add(reactantCloned);

            return(reaction);
        }
Esempio n. 34
0
 private IRing getRing(IAtomContainer spt, IBond bond)
 {
     IRing ring = spt.Builder.newRing();
     PathTools.resetFlags(spt);
     ring.addAtom(bond.getAtomAt(0));
     PathTools.depthFirstTargetSearch(spt, bond.getAtomAt(0), bond.getAtomAt(1), ring);
     ring.addBond(bond);
     return ring;
 }
		/// <summary> Returns wether a bond is saturated. A bond is saturated if 
		/// <b>both</b> Atoms in the bond are saturated.
		/// </summary>
		public virtual bool isSaturated(IBond bond, IAtomContainer atomContainer)
		{
			//logger.debug("isBondSaturated?: ", bond);
			IAtom[] atoms = bond.getAtoms();
			bool isSaturated = true;
			for (int i = 0; i < atoms.Length; i++)
			{
				//logger.debug("isSaturated(Bond, AC): atom I=", i);
				isSaturated = isSaturated && this.isSaturated(atoms[i], atomContainer);
			}
			//logger.debug("isSaturated(Bond, AC): result=", isSaturated);
			return isSaturated;
		}
Esempio n. 36
0
		/// <summary> Saturates a set of Bonds in an AtomContainer.</summary>
		public virtual bool newSaturate(IBond[] bonds, IAtomContainer atomContainer)
		{
			//logger.debug("Saturating bond set of size: " + bonds.Length);
			bool bondsAreFullySaturated = true;
			if (bonds.Length > 0)
			{
				IBond bond = bonds[0];
				
				// determine bonds left
				int leftBondCount = bonds.Length - 1;
				IBond[] leftBonds = new IBond[leftBondCount];
				Array.Copy(bonds, 1, leftBonds, 0, leftBondCount);
				
				// examine this bond
				if (isUnsaturated(bond, atomContainer))
				{
					// either this bonds should be saturated or not
					
					// try to leave this bond unsaturated and saturate the left bondssaturate this bond
					if (leftBondCount > 0)
					{
						//logger.debug("Recursing with unsaturated bond with #bonds: " + leftBondCount);
						bondsAreFullySaturated = newSaturate(leftBonds, atomContainer) && !isUnsaturated(bond, atomContainer);
					}
					else
					{
						bondsAreFullySaturated = false;
					}
					
					// ok, did it work? if not, saturate this bond, and recurse
					if (!bondsAreFullySaturated)
					{
						//logger.debug("First try did not work...");
						// ok, revert saturating this bond, and recurse again
						bool couldSaturate = newSaturate(bond, atomContainer);
						if (couldSaturate)
						{
							if (leftBondCount > 0)
							{
								//logger.debug("Recursing with saturated bond with #bonds: " + leftBondCount);
								bondsAreFullySaturated = newSaturate(leftBonds, atomContainer);
							}
							else
							{
								bondsAreFullySaturated = true;
							}
						}
						else
						{
							bondsAreFullySaturated = false;
							// no need to recurse, because we already know that this bond
							// unsaturated does not work
						}
					}
				}
				else if (isSaturated(bond, atomContainer))
				{
					//logger.debug("This bond is already saturated.");
					if (leftBondCount > 0)
					{
						//logger.debug("Recursing with #bonds: " + leftBondCount);
						bondsAreFullySaturated = newSaturate(leftBonds, atomContainer);
					}
					else
					{
						bondsAreFullySaturated = true;
					}
				}
				else
				{
					//logger.debug("Cannot saturate this bond");
					// but, still recurse (if possible)
					if (leftBondCount > 0)
					{
						//logger.debug("Recursing with saturated bond with #bonds: " + leftBondCount);
						bondsAreFullySaturated = newSaturate(leftBonds, atomContainer) && !isUnsaturated(bond, atomContainer);
					}
					else
					{
						bondsAreFullySaturated = !isUnsaturated(bond, atomContainer);
					}
				}
			}
			//logger.debug("Is bond set fully saturated?: " + bondsAreFullySaturated);
			//logger.debug("Returning to level: " + (bonds.Length + 1));
			return bondsAreFullySaturated;
		}
 public virtual void writeBond(IBond bond)
 {
     writer.Write("  Bond " + bond.ID + " = new Bond(" + bond.getAtomAt(0).ID + ", " + bond.getAtomAt(1).ID + ", " + bond.Order + ");\n");
 }
Esempio n. 38
0
		/// <summary> Saturate atom by adjusting its bond orders.</summary>
		public virtual bool saturate(IBond bond, IAtomContainer atomContainer)
		{
			IAtom[] atoms = bond.getAtoms();
			IAtom atom = atoms[0];
			IAtom partner = atoms[1];
			//logger.debug("  saturating bond: ", atom.Symbol, "-", partner.Symbol);
			bool bondOrderIncreased = true;
			while (bondOrderIncreased && isUnsaturated(bond, atomContainer))
			{
				//logger.debug("Can increase bond order");
				bondOrderIncreased = saturateByIncreasingBondOrder(bond, atomContainer, 1.0);
			}
			return isSaturated(bond, atomContainer);
		}
 public static IAtomContainer getRelevantAtomContainer(ISetOfReactions set_Renamed, IBond bond)
 {
     IReaction[] reactions = set_Renamed.Reactions;
     for (int i = 0; i < reactions.Length; i++)
     {
         IReaction reaction = reactions[i];
         IAtomContainer container = ReactionManipulator.getRelevantAtomContainer(reaction, bond);
         if (container != null)
         {
             // a match!
             return container;
         }
     }
     return null;
 }
Esempio n. 40
0
        public bool Matches(IBond bond, int stereo)
        {
            switch (type)
            {
            case ExprType.True:
                return(true);

            case ExprType.False:
                return(false);

            case ExprType.AliphaticOrder:
                return(!bond.IsAromatic &&
                       !bond.Order.IsUnset() &&
                       bond.Order.Numeric() == value);

            case ExprType.Order:
                return(!bond.Order.IsUnset() && bond.Order.Numeric() == value);

            case ExprType.IsAromatic:
                return(bond.IsAromatic);

            case ExprType.IsAliphatic:
                return(!bond.IsAromatic);

            case ExprType.IsInRing:
                return(bond.IsInRing);

            case ExprType.IsInChain:
                return(!bond.IsInRing);

            case ExprType.SingleOrAromatic:
                return(bond.IsAromatic ||
                       BondOrder.Single.Equals(bond.Order));

            case ExprType.DoubleOrAromatic:
                return(bond.IsAromatic ||
                       BondOrder.Double.Equals(bond.Order));

            case ExprType.SingleOrDouble:
                return(BondOrder.Single.Equals(bond.Order) ||
                       BondOrder.Double.Equals(bond.Order));

            case ExprType.Stereochemistry:
                return(stereo == UnknownStereo || value == stereo);

            case ExprType.And:
                return(left.Matches(bond, stereo) && right.Matches(bond, stereo));

            case ExprType.Or:
                return(left.Matches(bond, stereo) || right.Matches(bond, stereo));

            case ExprType.Not:
                return(!left.Matches(bond, stereo)
                       // XXX: ugly but needed, when matching stereo
                       || (stereo == UnknownStereo &&
                           (left.type == ExprType.Stereochemistry ||
                            left.type == ExprType.Or &&
                            left.left.type == ExprType.Stereochemistry)));

            default:
                throw new ArgumentException($"Cannot match BondExpr, type={type}", nameof(type));
            }
        }
 public static IAtomContainer getRelevantAtomContainer(IReaction reaction, IBond bond)
 {
     IAtomContainer result = SetOfMoleculesManipulator.getRelevantAtomContainer(reaction.Reactants, bond);
     if (result != null)
     {
         return result;
     }
     return SetOfMoleculesManipulator.getRelevantAtomContainer(reaction.Products, bond);
 }
Esempio n. 42
0
        /// <summary>
        /// Reads atoms, bonds etc from atom container and converts to format
        /// InChI library requires, then places call for the library to generate
        /// the InChI.
        /// </summary>
        /// <param name="atomContainer">AtomContainer to generate InChI for.</param>
        /// <param name="ignore"></param>
        private void GenerateInChIFromCDKAtomContainer(IAtomContainer atomContainer, bool ignore)
        {
            this.ReferringAtomContainer = atomContainer;

            // Check for 3d coordinates
            bool all3d = true;
            bool all2d = true;

            foreach (var atom in atomContainer.Atoms)
            {
                if (all3d && atom.Point3D == null)
                {
                    all3d = false;
                }
                if (all2d && atom.Point2D == null)
                {
                    all2d = false;
                }
            }

            var atomMap = new Dictionary <IAtom, NInchiAtom>();

            foreach (var atom in atomContainer.Atoms)
            {
                // Get coordinates
                // Use 3d if possible, otherwise 2d or none
                double x, y, z;
                if (all3d)
                {
                    var p = atom.Point3D.Value;
                    x = p.X;
                    y = p.Y;
                    z = p.Z;
                }
                else if (all2d)
                {
                    var p = atom.Point2D.Value;
                    x = p.X;
                    y = p.Y;
                    z = 0.0;
                }
                else
                {
                    x = 0.0;
                    y = 0.0;
                    z = 0.0;
                }

                // Chemical element symbol
                var el = atom.Symbol;

                // Generate InChI atom
                var iatom = Input.Add(new NInchiAtom(x, y, z, el));
                atomMap[atom] = iatom;

                // Check if charged
                var charge = atom.FormalCharge.Value;
                if (charge != 0)
                {
                    iatom.Charge = charge;
                }

                // Check whether isotopic
                var isotopeNumber = atom.MassNumber;
                if (isotopeNumber != null)
                {
                    iatom.IsotopicMass = isotopeNumber.Value;
                }

                // Check for implicit hydrogens
                // atom.HydrogenCount returns number of implicit hydrogens, not
                // total number
                // Ref: Posting to cdk-devel list by Egon Willighagen 2005-09-17
                int?implicitH = atom.ImplicitHydrogenCount;

                // set implicit hydrogen count, -1 tells the inchi to determine it
                iatom.ImplicitH = implicitH ?? -1;

                // Check if radical
                int count = atomContainer.GetConnectedSingleElectrons(atom).Count();
                if (count == 0)
                {
                    // TODO - how to check whether singlet or undefined multiplicity
                }
                else if (count == 1)
                {
                    iatom.Radical = INCHI_RADICAL.Doublet;
                }
                else if (count == 2)
                {
                    iatom.Radical = INCHI_RADICAL.Triplet;
                }
                else
                {
                    throw new CDKException("Unrecognised radical type");
                }
            }

            // Process bonds
            var bondMap = new Dictionary <IBond, NInchiBond>();

            foreach (var bond in atomContainer.Bonds)
            {
                // Assumes 2 centre bond
                var at0 = atomMap[bond.Begin];
                var at1 = atomMap[bond.End];

                // Get bond order
                INCHI_BOND_TYPE order;
                var             bo = bond.Order;
                if (!ignore && bond.IsAromatic)
                {
                    order = INCHI_BOND_TYPE.Altern;
                }
                else if (bo == BondOrder.Single)
                {
                    order = INCHI_BOND_TYPE.Single;
                }
                else if (bo == BondOrder.Double)
                {
                    order = INCHI_BOND_TYPE.Double;
                }
                else if (bo == BondOrder.Triple)
                {
                    order = INCHI_BOND_TYPE.Triple;
                }
                else
                {
                    throw new CDKException("Failed to generate InChI: Unsupported bond type");
                }

                // Create InChI bond
                var ibond = new NInchiBond(at0, at1, order);
                bondMap[bond] = ibond;
                Input.Add(ibond);

                // Check for bond stereo definitions
                var stereo = bond.Stereo;
                // No stereo definition
                if (stereo == BondStereo.None)
                {
                    ibond.BondStereo = INCHI_BOND_STEREO.None;
                }
                // Bond ending (fat end of wedge) below the plane
                else if (stereo == BondStereo.Down)
                {
                    ibond.BondStereo = INCHI_BOND_STEREO.Single1Down;
                }
                // Bond ending (fat end of wedge) above the plane
                else if (stereo == BondStereo.Up)
                {
                    ibond.BondStereo = INCHI_BOND_STEREO.Single1Up;
                }
                // Bond starting (pointy end of wedge) below the plane
                else if (stereo == BondStereo.DownInverted)
                {
                    ibond.BondStereo = INCHI_BOND_STEREO.Single2Down;
                }
                // Bond starting (pointy end of wedge) above the plane
                else if (stereo == BondStereo.UpInverted)
                {
                    ibond.BondStereo = INCHI_BOND_STEREO.Single2Up;
                }
                else if (stereo == BondStereo.EOrZ)
                {
                    ibond.BondStereo = INCHI_BOND_STEREO.DoubleEither;
                }
                else if (stereo == BondStereo.UpOrDown)
                {
                    ibond.BondStereo = INCHI_BOND_STEREO.Single1Either;
                }
                else if (stereo == BondStereo.UpOrDownInverted)
                {
                    ibond.BondStereo = INCHI_BOND_STEREO.Single2Either;
                }
                // Bond with undefined stereochemistry
                else if (stereo == BondStereo.None)
                {
                    if (order == INCHI_BOND_TYPE.Single)
                    {
                        ibond.BondStereo = INCHI_BOND_STEREO.Single1Either;
                    }
                    else if (order == INCHI_BOND_TYPE.Double)
                    {
                        ibond.BondStereo = INCHI_BOND_STEREO.DoubleEither;
                    }
                }
            }

            // Process tetrahedral stereo elements
            foreach (var stereoElem in atomContainer.StereoElements)
            {
                if (stereoElem is ITetrahedralChirality chirality)
                {
                    var stereoType = chirality.Stereo;

                    var atC = atomMap[chirality.ChiralAtom];
                    var at0 = atomMap[chirality.Ligands[0]];
                    var at1 = atomMap[chirality.Ligands[1]];
                    var at2 = atomMap[chirality.Ligands[2]];
                    var at3 = atomMap[chirality.Ligands[3]];
                    var p   = INCHI_PARITY.Unknown;
                    if (stereoType == TetrahedralStereo.AntiClockwise)
                    {
                        p = INCHI_PARITY.Odd;
                    }
                    else if (stereoType == TetrahedralStereo.Clockwise)
                    {
                        p = INCHI_PARITY.Even;
                    }
                    else
                    {
                        throw new CDKException("Unknown tetrahedral chirality");
                    }

                    var jniStereo = new NInchiStereo0D(atC, at0, at1, at2, at3, INCHI_STEREOTYPE.Tetrahedral, p);
                    Input.Stereos.Add(jniStereo);
                }
                else if (stereoElem is IDoubleBondStereochemistry dbStereo)
                {
                    var surroundingBonds = dbStereo.Bonds;
                    if (surroundingBonds[0] == null || surroundingBonds[1] == null)
                    {
                        throw new CDKException("Cannot generate an InChI with incomplete double bond info");
                    }
                    var stereoType = dbStereo.Stereo;

                    IBond      stereoBond = dbStereo.StereoBond;
                    NInchiAtom at0        = null;
                    NInchiAtom at1        = null;
                    NInchiAtom at2        = null;
                    NInchiAtom at3        = null;
                    // TODO: I should check for two atom bonds... or maybe that should happen when you
                    //    create a double bond stereochemistry
                    if (stereoBond.Contains(surroundingBonds[0].Begin))
                    {
                        // first atom is A
                        at1 = atomMap[surroundingBonds[0].Begin];
                        at0 = atomMap[surroundingBonds[0].End];
                    }
                    else
                    {
                        // first atom is X
                        at0 = atomMap[surroundingBonds[0].Begin];
                        at1 = atomMap[surroundingBonds[0].End];
                    }
                    if (stereoBond.Contains(surroundingBonds[1].Begin))
                    {
                        // first atom is B
                        at2 = atomMap[surroundingBonds[1].Begin];
                        at3 = atomMap[surroundingBonds[1].End];
                    }
                    else
                    {
                        // first atom is Y
                        at2 = atomMap[surroundingBonds[1].End];
                        at3 = atomMap[surroundingBonds[1].Begin];
                    }
                    var p = INCHI_PARITY.Unknown;
                    if (stereoType == DoubleBondConformation.Together)
                    {
                        p = INCHI_PARITY.Odd;
                    }
                    else if (stereoType == DoubleBondConformation.Opposite)
                    {
                        p = INCHI_PARITY.Even;
                    }
                    else
                    {
                        throw new CDKException("Unknown double bond stereochemistry");
                    }

                    var jniStereo = new NInchiStereo0D(null, at0, at1, at2, at3, INCHI_STEREOTYPE.DoubleBond, p);
                    Input.Stereos.Add(jniStereo);
                }
                else if (stereoElem is ExtendedTetrahedral extendedTetrahedral)
                {
                    TetrahedralStereo winding = extendedTetrahedral.Winding;

                    // The peripherals (p<i>) and terminals (t<i>) are referring to
                    // the following atoms. The focus (f) is also shown.
                    //
                    //   p0          p2
                    //    \          /
                    //     t0 = f = t1
                    //    /         \
                    //   p1         p3
                    var terminals   = extendedTetrahedral.FindTerminalAtoms(atomContainer);
                    var peripherals = extendedTetrahedral.Peripherals.ToArray();

                    // InChI API is particular about the input, each terminal atom
                    // needs to be present in the list of neighbors and they must
                    // be at index 1 and 2 (i.e. in the middle). This is true even
                    // of explicit atoms. For the implicit atoms, the terminals may
                    // be in the peripherals already and so we correct the winding
                    // and reposition as needed.

                    var t0Bonds = OnlySingleBonded(atomContainer.GetConnectedBonds(terminals[0]));
                    var t1Bonds = OnlySingleBonded(atomContainer.GetConnectedBonds(terminals[1]));

                    // first if there are two explicit atoms we need to replace one
                    // with the terminal atom - the configuration does not change
                    if (t0Bonds.Count == 2)
                    {
                        var orgBond = t0Bonds[0];
                        t0Bonds.RemoveAt(0);
                        var replace = orgBond.GetOther(terminals[0]);
                        for (int i = 0; i < peripherals.Length; i++)
                        {
                            if (replace == peripherals[i])
                            {
                                peripherals[i] = terminals[0];
                            }
                        }
                    }

                    if (t1Bonds.Count == 2)
                    {
                        var orgBond = t0Bonds[0];
                        t1Bonds.RemoveAt(0);
                        var replace = orgBond.GetOther(terminals[1]);
                        for (int i = 0; i < peripherals.Length; i++)
                        {
                            if (replace == peripherals[i])
                            {
                                peripherals[i] = terminals[1];
                            }
                        }
                    }

                    // the neighbor attached to each terminal atom that we will
                    // define the configuration of
                    var t0Neighbor = t0Bonds[0].GetOther(terminals[0]);
                    var t1Neighbor = t1Bonds[0].GetOther(terminals[1]);

                    // we now need to move all the atoms into the correct positions
                    // everytime we exchange atoms the configuration inverts
                    for (int i = 0; i < peripherals.Length; i++)
                    {
                        if (i != 0 && t0Neighbor == peripherals[i])
                        {
                            Swap(peripherals, i, 0);
                            winding = winding.Invert();
                        }
                        else if (i != 1 && terminals[0] == peripherals[i])
                        {
                            Swap(peripherals, i, 1);
                            winding = winding.Invert();
                        }
                        else if (i != 2 && terminals[1] == peripherals[i])
                        {
                            Swap(peripherals, i, 2);
                            winding = winding.Invert();
                        }
                        else if (i != 3 && t1Neighbor == peripherals[i])
                        {
                            Swap(peripherals, i, 3);
                            winding = winding.Invert();
                        }
                    }

                    var parity = INCHI_PARITY.Unknown;
                    if (winding == TetrahedralStereo.AntiClockwise)
                    {
                        parity = INCHI_PARITY.Odd;
                    }
                    else if (winding == TetrahedralStereo.Clockwise)
                    {
                        parity = INCHI_PARITY.Even;
                    }
                    else
                    {
                        throw new CDKException("Unknown extended tetrahedral chirality");
                    }

                    NInchiStereo0D jniStereo = new NInchiStereo0D(atomMap[extendedTetrahedral.Focus],
                                                                  atomMap[peripherals[0]], atomMap[peripherals[1]], atomMap[peripherals[2]],
                                                                  atomMap[peripherals[3]], INCHI_STEREOTYPE.Allene, parity);
                    Input.Stereos.Add(jniStereo);
                }
            }

            try
            {
                Output = NInchiWrapper.GetInchi(Input);
            }
            catch (NInchiException jie)
            {
                throw new CDKException("Failed to generate InChI: " + jie.Message, jie);
            }
        }
Esempio n. 43
0
 public override bool Matches(IBond bond)
 {
     return(bond.IsInRing);
 }
Esempio n. 44
0
 public virtual void writeBond(IBond bond)
 {
     writer.Write("  Bond " + bond.ID + " = new Bond(" + bond.getAtomAt(0).ID + ", " + bond.getAtomAt(1).ID + ", " + bond.Order + ");\n");
 }
Esempio n. 45
0
 /// <summary>  Writes the coordinates of the atoms participating the given bond into an
 /// array, using renderingCoordinates, using an external set of coordinates.
 /// See comment for center(IAtomContainer atomCon, Dimension areaDim, HashMap renderingCoordinates) for details on coordinate sets
 /// 
 /// </summary>
 /// <param name="bond"> The given bond
 /// </param>
 /// <param name="renderingCoordinates"> The set of coordinates to use coming from RendererModel2D
 /// </param>
 /// <returns>       The array with the coordinates
 /// </returns>
 //UPGRADE_TODO: Class 'java.util.HashMap' was converted to 'System.Collections.Hashtable' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilHashMap'"
 public static int[] getBondCoordinates(IBond bond, System.Collections.Hashtable renderingCoordinates)
 {
     //UPGRADE_TODO: Method 'java.util.HashMap.get' was converted to 'System.Collections.Hashtable.Item' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilHashMapget_javalangObject'"
     if (renderingCoordinates[bond.getAtomAt(0)] == null && bond.getAtomAt(0).getPoint2d() != null)
     {
         renderingCoordinates[bond.getAtomAt(0)] = new Point2d(bond.getAtomAt(0).getPoint2d().x, bond.getAtomAt(0).getPoint2d().y);
     }
     //UPGRADE_TODO: Method 'java.util.HashMap.get' was converted to 'System.Collections.Hashtable.Item' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilHashMapget_javalangObject'"
     if (renderingCoordinates[bond.getAtomAt(1)] == null && bond.getAtomAt(1).getPoint2d() != null)
     {
         renderingCoordinates[bond.getAtomAt(1)] = new Point2d(bond.getAtomAt(1).getPoint2d().x, bond.getAtomAt(1).getPoint2d().y);
     }
     if (bond.getAtomAt(0).getPoint2d() == null || bond.getAtomAt(1).getPoint2d() == null)
     {
         //logger.error("getBondCoordinates() called on Bond without 2D coordinates!");
         return new int[0];
     }
     //UPGRADE_TODO: Method 'java.util.HashMap.get' was converted to 'System.Collections.Hashtable.Item' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilHashMapget_javalangObject'"
     int beginX = (int)((Point2d)renderingCoordinates[bond.getAtomAt(0)]).x;
     //UPGRADE_TODO: Method 'java.util.HashMap.get' was converted to 'System.Collections.Hashtable.Item' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilHashMapget_javalangObject'"
     int endX = (int)((Point2d)renderingCoordinates[bond.getAtomAt(1)]).x;
     //UPGRADE_TODO: Method 'java.util.HashMap.get' was converted to 'System.Collections.Hashtable.Item' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilHashMapget_javalangObject'"
     int beginY = (int)((Point2d)renderingCoordinates[bond.getAtomAt(0)]).y;
     //UPGRADE_TODO: Method 'java.util.HashMap.get' was converted to 'System.Collections.Hashtable.Item' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilHashMapget_javalangObject'"
     int endY = (int)((Point2d)renderingCoordinates[bond.getAtomAt(1)]).y;
     int[] coords = new int[] { beginX, beginY, endX, endY };
     return coords;
 }
 /// <summary> We define the heaviest ring as the one with the highest number of double bonds.
 /// Needed for example for the placement of in-ring double bonds.
 /// 
 /// </summary>
 /// <param name="bond"> A bond which must be contained by the heaviest ring 
 /// </param>
 /// <returns>  The ring with the higest number of double bonds connected to a given bond
 /// </returns>
 public static IRing getHeaviestRing(IRingSet ringSet, IBond bond)
 {
     System.Collections.IList rings = ringSet.getRings(bond);
     IRing ring = null;
     int maxOrderSum = 0;
     for (int i = 0; i < rings.Count; i++)
     {
         if (maxOrderSum < ((IRing)rings[i]).OrderSum)
         {
             ring = (IRing)rings[i];
             maxOrderSum = ring.OrderSum;
         }
     }
     return ring;
 }
Esempio n. 47
0
 /// <summary>  Returns the geometric length of this bond in 2D space, using an external set of coordinates
 /// See comment for center(IAtomContainer atomCon, Dimension areaDim, HashMap renderingCoordinates) for details on coordinate sets
 /// 
 /// </summary>
 /// <param name="bond"> Description of the Parameter
 /// </param>
 /// <param name="renderingCoordinates"> The set of coordinates to use coming from RendererModel2D
 /// </param>
 /// <returns>       The geometric length of this bond
 /// </returns>
 //UPGRADE_TODO: Class 'java.util.HashMap' was converted to 'System.Collections.Hashtable' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilHashMap'"
 public static double getLength2D(IBond bond, System.Collections.Hashtable renderingCoordinates)
 {
     if (bond.getAtomAt(0) == null || bond.getAtomAt(1) == null)
     {
         return 0.0;
     }
     //UPGRADE_TODO: Method 'java.util.HashMap.get' was converted to 'System.Collections.Hashtable.Item' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilHashMapget_javalangObject'"
     Point2d p1 = ((Point2d)renderingCoordinates[bond.getAtomAt(0)]);
     //UPGRADE_TODO: Method 'java.util.HashMap.get' was converted to 'System.Collections.Hashtable.Item' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilHashMapget_javalangObject'"
     Point2d p2 = ((Point2d)renderingCoordinates[bond.getAtomAt(1)]);
     if (p1 == null || p2 == null)
     {
         return 0.0;
     }
     return p1.distance(p2);
 }
		public virtual bool unsaturateByDecreasingBondOrder(IBond bond, double decrement)
		{
			if (bond.Order > decrement)
			{
				bond.Order = bond.Order - decrement;
				return true;
			}
			else
			{
				return false;
			}
		}
Esempio n. 49
0
 /// <summary>  Determines if this Bond contains 2D coordinates.
 /// See comment for center(IAtomContainer atomCon, Dimension areaDim, HashMap renderingCoordinates) for details on coordinate sets
 /// 
 /// </summary>
 /// <param name="b"> Description of the Parameter
 /// </param>
 /// <returns>    boolean indication that 2D coordinates are available
 /// </returns>
 public static bool has2DCoordinates(IBond b)
 {
     IAtom[] atoms = b.getAtoms();
     for (int i = 0; i < atoms.Length; i++)
     {
         if (atoms[i].getPoint2d() == null)
         {
             return false;
         }
     }
     return true;
 }
		/// <summary> Returns wether a bond is unsaturated. A bond is unsaturated if 
		/// <b>all</b> Atoms in the bond are unsaturated.
		/// </summary>
		public virtual bool isUnsaturated(IBond bond, IAtomContainer atomContainer)
		{
			//logger.debug("isBondUnsaturated?: ", bond);
			IAtom[] atoms = bond.getAtoms();
			bool isUnsaturated = true;
			for (int i = 0; i < atoms.Length && isUnsaturated; i++)
			{
				isUnsaturated = isUnsaturated && !isSaturated(atoms[i], atomContainer);
			}
			//logger.debug("Bond is unsaturated?: ", isUnsaturated);
			return isUnsaturated;
		}
Esempio n. 51
0
        /// <summary>
        /// Initiates the process for the given mechanism. The atoms to apply are mapped between
        /// reactants and products.
        /// </summary>
        /// <param name="atomContainerSet"></param>
        /// <param name="atomList">
        /// The list of atoms taking part in the mechanism. Only allowed two atoms.
        ///                    The first atom is the atom which contains the ISingleElectron and the second
        ///                    third is the atom which will be removed
        ///                    the first atom</param>
        /// <param name="bondList">The list of bonds taking part in the mechanism. Only allowed one bond.
        ///                       It is the bond which is moved</param>
        /// <returns>The Reaction mechanism</returns>
        public IReaction Initiate(IChemObjectSet <IAtomContainer> atomContainerSet, IList <IAtom> atomList, IList <IBond> bondList)
        {
            var atMatcher = CDK.AtomTypeMatcher;

            if (atomContainerSet.Count != 1)
            {
                throw new CDKException("RadicalSiteIonizationMechanism only expects one IAtomContainer");
            }
            if (atomList.Count != 3)
            {
                throw new CDKException("RadicalSiteIonizationMechanism expects three atoms in the List");
            }
            if (bondList.Count != 2)
            {
                throw new CDKException("RadicalSiteIonizationMechanism only expect one bond in the List");
            }
            IAtomContainer molecule = atomContainerSet[0];
            IAtomContainer reactantCloned;

            reactantCloned = (IAtomContainer)molecule.Clone();
            IAtom atom1    = atomList[0]; // Atom containing the ISingleElectron
            IAtom atom1C   = reactantCloned.Atoms[molecule.Atoms.IndexOf(atom1)];
            IAtom atom2    = atomList[1]; // Atom
            IAtom atom2C   = reactantCloned.Atoms[molecule.Atoms.IndexOf(atom2)];
            IAtom atom3    = atomList[2]; // Atom to be saved
            IAtom atom3C   = reactantCloned.Atoms[molecule.Atoms.IndexOf(atom3)];
            IBond bond1    = bondList[0]; // Bond to increase the order
            int   posBond1 = molecule.Bonds.IndexOf(bond1);
            IBond bond2    = bondList[1]; // Bond to remove
            int   posBond2 = molecule.Bonds.IndexOf(bond2);

            BondManipulator.IncreaseBondOrder(reactantCloned.Bonds[posBond1]);
            reactantCloned.Bonds.Remove(reactantCloned.Bonds[posBond2]);

            var selectron = reactantCloned.GetConnectedSingleElectrons(atom1C);

            reactantCloned.SingleElectrons.Remove(selectron.Last());
            atom1C.Hybridization = Hybridization.Unset;
            AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(reactantCloned);
            IAtomType type = atMatcher.FindMatchingAtomType(reactantCloned, atom1C);

            if (type == null || type.AtomTypeName.Equals("X", StringComparison.Ordinal))
            {
                return(null);
            }

            atom2C.Hybridization = Hybridization.Unset;
            AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(reactantCloned);
            type = atMatcher.FindMatchingAtomType(reactantCloned, atom2C);
            if (type == null || type.AtomTypeName.Equals("X", StringComparison.Ordinal))
            {
                return(null);
            }

            reactantCloned.SingleElectrons.Add(atom2C.Builder.NewSingleElectron(atom3C));
            atom3C.Hybridization = Hybridization.Unset;
            AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(reactantCloned);
            type = atMatcher.FindMatchingAtomType(reactantCloned, atom3C);
            if (type == null || type.AtomTypeName.Equals("X", StringComparison.Ordinal))
            {
                return(null);
            }

            IReaction reaction = atom2C.Builder.NewReaction();

            reaction.Reactants.Add(molecule);

            /* mapping */
            foreach (var atom in molecule.Atoms)
            {
                IMapping mapping = atom2C.Builder.NewMapping(atom,
                                                             reactantCloned.Atoms[molecule.Atoms.IndexOf(atom)]);
                reaction.Mappings.Add(mapping);
            }

            var moleculeSetP = ConnectivityChecker.PartitionIntoMolecules(reactantCloned);

            foreach (var moleculeP in moleculeSetP)
            {
                reaction.Products.Add(moleculeP);
            }

            return(reaction);
        }
		/// <summary> Tries to saturate a bond by increasing its bond orders by 1.0.
		/// 
		/// </summary>
		/// <returns> true if the bond could be increased
		/// </returns>
		public virtual bool saturateByIncreasingBondOrder(IBond bond, IAtomContainer atomContainer, double increment)
		{
			IAtom[] atoms = bond.getAtoms();
			IAtom atom = atoms[0];
			IAtom partner = atoms[1];
			//logger.debug("  saturating bond: ", atom.Symbol, "-", partner.Symbol);
			IAtomType[] atomTypes1 = getAtomTypeFactory(bond.Builder).getAtomTypes(atom.Symbol);
			IAtomType[] atomTypes2 = getAtomTypeFactory(bond.Builder).getAtomTypes(partner.Symbol);
			for (int atCounter1 = 0; atCounter1 < atomTypes1.Length; atCounter1++)
			{
				IAtomType aType1 = atomTypes1[atCounter1];
				//logger.debug("  condidering atom type: ", aType1);
				if (couldMatchAtomType(atomContainer, atom, aType1))
				{
					//logger.debug("  trying atom type: ", aType1);
					for (int atCounter2 = 0; atCounter2 < atomTypes2.Length; atCounter2++)
					{
						IAtomType aType2 = atomTypes2[atCounter2];
						//logger.debug("  condidering partner type: ", aType1);
						if (couldMatchAtomType(atomContainer, partner, atomTypes2[atCounter2]))
						{
							//logger.debug("    with atom type: ", aType2);
							if (bond.Order < aType2.MaxBondOrder && bond.Order < aType1.MaxBondOrder)
							{
								bond.Order = bond.Order + increment;
								//logger.debug("Bond order now ", bond.Order);
								return true;
							}
						}
					}
				}
			}
			return false;
		}
Esempio n. 53
0
		private IEnumerable<IAtomContainer> splitMolecule(IAtomContainer atomContainer, IBond bond, IDictionary<IAtom, IList<IBond>> atomBonds)
		{
			//if this bond is in a ring we have to split another bond in this ring where at least one 
			//bond is in between. Otherwise we wont have two fragments. Else normal split.

			var ret = new List<IAtomContainer>();

			//get bond energy for splitting this bond
			var currentBondEnergy = BondEnergies.Lookup(bond);			

			//bond is in a ring....so we have to split up another bond to break it
			var rings = allRings.getRings(bond);
			if (rings.getAtomContainerCount() != 0)
			{
				foreach (var bondInRing in rings.getAtomContainer(0).bonds().ToWindowsEnumerable<IBond>())
				{
					//if the bonds are the same...this wont split up the ring
					if (bondInRing == bond)
					{
						continue;
					}

					//check for already tried bonds
					var check = new BondPair(bond, bondInRing);
					if (knownBonds.Contains(check))
					{
						continue;
					}
					knownBonds.Add(new BondPair(bond, bondInRing));


					var set = new List<IAtomContainer>();
					var bondListList = new List<List<IBond>>();
					var fragWeightList = new List<Double>();

					foreach (var currentAtom in bond.atoms().ToWindowsEnumerable<IAtom>())
					{
						//List with bonds in Ring
						var partRing = new List<IBond>();
						//reset the weight because it is computed inside the traverse
						currentFragWeight = 0.0;
						//initialize new atom list
						atomList = new List<IAtom>();

						//clone current atom because a single electron is being added...homolytic cleavage
						partRing = traverse(atomBonds, currentAtom, partRing, bond, bondInRing);

						bondListList.Add(partRing);
						fragWeightList.Add(currentFragWeight);

						var temp = makeAtomContainer(currentAtom, partRing);
						//set the properties again!
						var properties = atomContainer.getProperties();
						temp.setProperties(properties);


						//*********************************************************
						//BOND ENERGY CALCULATION
						//calculate bond energy
						var currentBondEnergyRing = BondEnergies.Lookup(bondInRing);

						//*********************************************************

						//now set property
						temp = setBondEnergy(temp, (currentBondEnergyRing + currentBondEnergy));
						set.Add(temp);
					}

					//now maybe add the fragments to the list
					for (var j = 0; j < set.Count; j++)
					{
						//Render.Draw(set.getAtomContainer(j), "");
						if (set[j].getAtomCount() > 0 && set[j].getBondCount() > 0 && set[j].getAtomCount() != atomContainer.getAtomCount())
						{
							//now check the current mass
							var fragMass = getFragmentMass(set[j], fragWeightList[j]);
							//check the weight of the current fragment
							if (!isHeavyEnough(fragMass))
							{
								continue;
							}

							//returns true if isomorph
							//set the current sum formula
							var fragmentFormula = MolecularFormulaTools.GetMolecularFormula(set[j]);
							var currentSumFormula = MolecularFormulaTools.GetString(fragmentFormula);

							if (isIdentical(set[j], currentSumFormula))
							{
								continue;
							}

							//add the fragment to the return list
							ret.Add(set[j]);
						}
					}
				}
			}
			else
			{
				var set = new List<IAtomContainer>();
				var bondListList = new List<List<IBond>>();
				var fragWeightList = new List<Double>();

				//get the atoms from the splitting bond --> create 2 fragments
				foreach (var currentAtom in bond.atoms().ToWindowsEnumerable<IAtom>())
				{
					var part = new List<IBond>();
					//reset the weight because it is computed inside the traverse
					currentFragWeight = 0.0;
					//initialize new atom list
					atomList = new List<IAtom>();
					part = traverse(atomBonds, currentAtom, part, bond);
					bondListList.Add(part);

					//create Atomcontainer out of bondList        		
					var temp = makeAtomContainer(currentAtom, part);
					//set the properties again!
					var properties = atomContainer.getProperties();
					temp.setProperties(properties);
					//now calculate the correct weight subtrating the possible neutral loss mass

					fragWeightList.Add(currentFragWeight);


					//now set property: BondEnergy!
					temp = setBondEnergy(temp, currentBondEnergy);
					set.Add(temp);
				}


				//at most 2 new molecules
				for (var i = 0; i < set.Count; i++)
				{
					if (set[i].getAtomCount() > 0 && set[i].getBondCount() > 0 && set[i].getAtomCount() != atomContainer.getAtomCount())
					{
						//now check the current mass
						var fragMass = getFragmentMass(set[i], fragWeightList[i]);
						//check the weight of the current fragment
						if (!isHeavyEnough(fragMass))
						{
							continue;
						}

						//set the current sum formula
						var fragmentFormula = MolecularFormulaTools.GetMolecularFormula(set[i]);
						var currentSumFormula = MolecularFormulaTools.GetString(fragmentFormula);
						//returns true if isomorph (fast isomorph check)
						if (isIdentical(set[i], currentSumFormula))
						{
							continue;
						}

						ret.Add(set[i]);
					}
				}
			}

			return ret;
		}
Esempio n. 54
0
		/// <summary> Returns wether a bond is saturated. A bond is saturated if 
		/// <b>both</b> Atoms in the bond are saturated.
		/// </summary>
		public virtual bool isSaturated(IBond bond, IAtomContainer atomContainer)
		{
			IAtom[] atoms = bond.getAtoms();
			bool isSaturated = true;
			for (int i = 0; i < atoms.Length; i++)
			{
				isSaturated = isSaturated && this.isSaturated(atoms[i], atomContainer);
			}
			return isSaturated;
		}
Esempio n. 55
0
 public bool Matches(IBond bond)
 {
     return(Matches(bond, UnknownStereo));
 }
Esempio n. 56
0
		/**
		 * Resursively traverse the molecule to get all the bonds in a list and return them. Start at the given Atom.
		 * Ignore the 2 given bonds --> split up a ring!
		 * 
		 * @param atomContainer the atom container
		 * @param atom the atom
		 * @param bondList the bond list
		 * 
		 * @return the list< i bond>
		 */

		private List<IBond> traverse(IDictionary<IAtom, IList<IBond>> atomBonds, IAtom atom, List<IBond> bondList, IBond bondToRemove, IBond bondToRemove2)
		{
			var connectedBonds = atomBonds[atom];
			foreach (var aBond in connectedBonds)
			{
				if (aBond.Equals(bondToRemove) || aBond.Equals(bondToRemove2) || bondList.Contains(aBond))
				{
					continue;
				}
				bondList.Add(aBond);
				//get the weight of the bonded atoms
				foreach (var atomWeight in aBond.atoms().ToWindowsEnumerable<IAtom>())
				{
					//get the prepared mass of the atom if it is not already counted
					if (!atomList.Contains(atomWeight))
					{
						currentFragWeight += atomMasses[atomWeight.getSymbol()];
						atomList.Add(atomWeight);
					}
				}

				var nextAtom = aBond.getConnectedAtom(atom);
				if (atomBonds[nextAtom].Count == 1)
				{
					continue;
				}
				traverse(atomBonds, nextAtom, bondList, bondToRemove, bondToRemove2);
			}
			return bondList;
		}
Esempio n. 57
0
        public void Test1Sphere()
        {
            string[] result = { "O-1;=C(//)",   "C-3;=OCC(//)",  "C-3;=CC(//)",   "C-3;=CC(//)",    "C-3;*C*CC(//)", "C-3;*C*C(//)",
                                "C-3;*C*C(//)", "C-3;*C*CC(//)", "C-3;*C*CC(//)", "C-3;*C*C(//)",   "C-3;*C*C(//)",  "C-3;*C*C(//)",
                                "C-3;*C*C(//)", "C-3;*C*CO(//)", "O-2;CC(//)",    "C-3;*C*CO(//)",  "C-3;*C*CO(//)", "O-2;CC(//)",
                                "C-4;O(//)",    "C-3;*C*C(//)",  "C-3;*C*CC(//)", "C-3;*C*C*C(//)", "C-3;*C*C*C(//)" };

            var   mol = builder.NewAtomContainer();
            IAtom a1  = mol.Builder.NewAtom("O");

            a1.Point2D = new Vector2(502.88457268119913, 730.4999999999999);
            mol.Atoms.Add(a1);
            IAtom a2 = mol.Builder.NewAtom("C");

            a2.Point2D = new Vector2(502.8845726811991, 694.4999999999999);
            mol.Atoms.Add(a2);
            IAtom a3 = mol.Builder.NewAtom("C");

            a3.Point2D = new Vector2(534.0614872174388, 676.4999999999999);
            mol.Atoms.Add(a3);
            IAtom a4 = mol.Builder.NewAtom("C");

            a4.Point2D = new Vector2(534.0614872174388, 640.4999999999999);
            mol.Atoms.Add(a4);
            IAtom a5 = mol.Builder.NewAtom("C");

            a5.Point2D = new Vector2(502.8845726811991, 622.4999999999999);
            mol.Atoms.Add(a5);
            IAtom a6 = mol.Builder.NewAtom("C");

            a6.Point2D = new Vector2(502.8845726811991, 586.4999999999999);
            mol.Atoms.Add(a6);
            IAtom a7 = mol.Builder.NewAtom("C");

            a7.Point2D = new Vector2(471.7076581449593, 568.4999999999999);
            mol.Atoms.Add(a7);
            IAtom a8 = mol.Builder.NewAtom("C");

            a8.Point2D = new Vector2(440.5307436087194, 586.5);
            mol.Atoms.Add(a8);
            IAtom a9 = mol.Builder.NewAtom("C");

            a9.Point2D = new Vector2(409.35382907247964, 568.5);
            mol.Atoms.Add(a9);
            IAtom a10 = mol.Builder.NewAtom("C");

            a10.Point2D = new Vector2(409.3538290724796, 532.5);
            mol.Atoms.Add(a10);
            IAtom a11 = mol.Builder.NewAtom("C");

            a11.Point2D = new Vector2(378.1769145362398, 514.5);
            mol.Atoms.Add(a11);
            IAtom a12 = mol.Builder.NewAtom("C");

            a12.Point2D = new Vector2(347.0, 532.5);
            mol.Atoms.Add(a12);
            IAtom a13 = mol.Builder.NewAtom("C");

            a13.Point2D = new Vector2(347.0, 568.5);
            mol.Atoms.Add(a13);
            IAtom a14 = mol.Builder.NewAtom("C");

            a14.Point2D = new Vector2(378.17691453623985, 586.5);
            mol.Atoms.Add(a14);
            IAtom a15 = mol.Builder.NewAtom("O");

            a15.Point2D = new Vector2(378.17691453623985, 622.5);
            mol.Atoms.Add(a15);
            IAtom a16 = mol.Builder.NewAtom("C");

            a16.Point2D = new Vector2(409.3538290724797, 640.5);
            mol.Atoms.Add(a16);
            IAtom a17 = mol.Builder.NewAtom("C");

            a17.Point2D = new Vector2(409.3538290724797, 676.5);
            mol.Atoms.Add(a17);
            IAtom a18 = mol.Builder.NewAtom("O");

            a18.Point2D = new Vector2(378.17691453623996, 694.5);
            mol.Atoms.Add(a18);
            IAtom a19 = mol.Builder.NewAtom("C");

            a19.Point2D = new Vector2(378.17691453624, 730.5);
            mol.Atoms.Add(a19);
            IAtom a20 = mol.Builder.NewAtom("C");

            a20.Point2D = new Vector2(440.5307436087195, 694.4999999999999);
            mol.Atoms.Add(a20);
            IAtom a21 = mol.Builder.NewAtom("C");

            a21.Point2D = new Vector2(471.7076581449593, 676.4999999999999);
            mol.Atoms.Add(a21);
            IAtom a22 = mol.Builder.NewAtom("C");

            a22.Point2D = new Vector2(471.7076581449593, 640.4999999999999);
            mol.Atoms.Add(a22);
            IAtom a23 = mol.Builder.NewAtom("C");

            a23.Point2D = new Vector2(440.53074360871943, 622.4999999999999);
            mol.Atoms.Add(a23);
            IBond b1 = mol.Builder.NewBond(a2, a1, BondOrder.Double);

            mol.Bonds.Add(b1);
            IBond b2 = mol.Builder.NewBond(a3, a2, BondOrder.Single);

            mol.Bonds.Add(b2);
            IBond b3 = mol.Builder.NewBond(a4, a3, BondOrder.Double);

            mol.Bonds.Add(b3);
            IBond b4 = mol.Builder.NewBond(a5, a4, BondOrder.Single);

            mol.Bonds.Add(b4);
            IBond b5 = mol.Builder.NewBond(a6, a5, BondOrder.Single);

            mol.Bonds.Add(b5);
            IBond b6 = mol.Builder.NewBond(a7, a6, BondOrder.Double);

            mol.Bonds.Add(b6);
            IBond b7 = mol.Builder.NewBond(a8, a7, BondOrder.Single);

            mol.Bonds.Add(b7);
            IBond b8 = mol.Builder.NewBond(a9, a8, BondOrder.Single);

            mol.Bonds.Add(b8);
            IBond b9 = mol.Builder.NewBond(a10, a9, BondOrder.Single);

            mol.Bonds.Add(b9);
            IBond b10 = mol.Builder.NewBond(a11, a10, BondOrder.Double);

            mol.Bonds.Add(b10);
            IBond b11 = mol.Builder.NewBond(a12, a11, BondOrder.Single);

            mol.Bonds.Add(b11);
            IBond b12 = mol.Builder.NewBond(a13, a12, BondOrder.Double);

            mol.Bonds.Add(b12);
            IBond b13 = mol.Builder.NewBond(a14, a13, BondOrder.Single);

            mol.Bonds.Add(b13);
            IBond b14 = mol.Builder.NewBond(a14, a9, BondOrder.Double);

            mol.Bonds.Add(b14);
            IBond b15 = mol.Builder.NewBond(a15, a14, BondOrder.Single);

            mol.Bonds.Add(b15);
            IBond b16 = mol.Builder.NewBond(a16, a15, BondOrder.Single);

            mol.Bonds.Add(b16);
            IBond b17 = mol.Builder.NewBond(a17, a16, BondOrder.Double);

            mol.Bonds.Add(b17);
            IBond b18 = mol.Builder.NewBond(a18, a17, BondOrder.Single);

            mol.Bonds.Add(b18);
            IBond b19 = mol.Builder.NewBond(a19, a18, BondOrder.Single);

            mol.Bonds.Add(b19);
            IBond b20 = mol.Builder.NewBond(a20, a17, BondOrder.Single);

            mol.Bonds.Add(b20);
            IBond b21 = mol.Builder.NewBond(a21, a20, BondOrder.Double);

            mol.Bonds.Add(b21);
            IBond b22 = mol.Builder.NewBond(a21, a2, BondOrder.Single);

            mol.Bonds.Add(b22);
            IBond b23 = mol.Builder.NewBond(a22, a21, BondOrder.Single);

            mol.Bonds.Add(b23);
            IBond b24 = mol.Builder.NewBond(a22, a5, BondOrder.Double);

            mol.Bonds.Add(b24);
            IBond b25 = mol.Builder.NewBond(a23, a22, BondOrder.Single);

            mol.Bonds.Add(b25);
            IBond b26 = mol.Builder.NewBond(a23, a16, BondOrder.Single);

            mol.Bonds.Add(b26);
            IBond b27 = mol.Builder.NewBond(a23, a8, BondOrder.Double);

            mol.Bonds.Add(b27);

            AddImplicitHydrogens(mol);

            //MoleculeViewer2D.Display(molecule, true);
            AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol);
            Aromaticity.CDKLegacy.Apply(mol);
            HOSECodeGenerator hcg = new HOSECodeGenerator();
            string            s   = null;

            for (int f = 0; f < 23; f++)
            {
                s = hcg.GetHOSECode(mol, mol.Atoms[f], 1);
                if (standAlone)
                {
                    Console.Out.Write("|" + s + "| -> " + result[f]);
                }
                Assert.AreEqual(result[f], s);
                if (standAlone)
                {
                    Console.Out.WriteLine("  OK");
                }
            }
        }
Esempio n. 58
0
        public void OnNewDataSource(IAtom[] atoms, IBond[] bonds, Vector3 origin, Bounds3D bounds)
        {
            sceneGraph = new OcTree<ChemEntity>((int)bounds.radius * 2, -bounds.min);
            /*screenEntities.Add(new BondAngle(device, atoms[0], atoms[1], atoms[2]));
            screenEntities[0].Init(device);

            postSceneWorldEntities.Add(new BoundingBoxEntity(new BoundingBox(bounds.min, bounds.max), false, Color.LightGray.ToArgb()));
            postSceneWorldEntities[0].Init(device);
            postSceneWorldEntities.Add(new SphereAxis3D());
            postSceneWorldEntities[1].Init(device);*/
            
            sceneGraphEntities = sceneGraph.SceneItems;

            // create molecule entities
            foreach (IAtom atom in atoms)
            {
                AtomEntity aentity = AtomEntity.BuildEntity(atom);
                sceneGraph.Insert(aentity);
                /*ScreenLabelVSpaceEntity entity = new ScreenLabelVSpaceEntity(atom.ID + ":" + aentity.UId.ToString(), (Vector3)aentity.Position3D);
                entity.Init(device);
                screenEntities.Add(entity);*/
                /*AtomSymbolEntity entity = new AtomSymbolEntity(aentity);
                entity.Init(device);
                postSceneViewEntities.Add(entity);*/
            }
            
            //foreach (IBond bond in bonds)
            //{
                //sceneGraph.Insert(new BondE);
            //}

            scheme.SetOutputDescription(coDesc);
            scheme.SetupScene(origin, bounds.radius);

            // pass throught scheme & effects
            IGeometryCreator[] schStreams = scheme.GetAtomStreams();
            DataFields[] efxFields = null;
            //effect.DesiredData(out efxFields, false);

            DataFields[][] allStreams = new DataFields[1 + (efxFields != null ? 1 : 0 )][];
            //if (efxFields != null)
            //    allStreams[1] = efxFields;
            if (scheme.HandlesAtoms && atoms != null)
            {
                GeomDataBufferStream[] geomStream = new GeomDataBufferStream[schStreams.Length];
                for (int i = 0; i < geomStream.Length; i++)
                {
                    allStreams[0] = schStreams[i].Fields;
                    GeomDataTransformer.CreateBufferStream(allStreams, out geomStream[i]);
                }
                // fill buffer stream
                scheme.SetAtomData(atoms, geomStream);
            }

            schStreams = scheme.GetBondStreams();
            if (scheme.HandlesBonds && bonds != null)
            {
                GeomDataBufferStream[] geomStream = new GeomDataBufferStream[schStreams.Length];
                for (int i = 0; i < geomStream.Length; i++)
                {
                    allStreams[0] = schStreams[i].Fields;
                    GeomDataTransformer.CreateBufferStream(allStreams, out geomStream[i]);
                }
                // fill buffer stream
                scheme.SetBondData(bonds, geomStream);
            }
        }
Esempio n. 59
0
 protected BondDecorator(IBond toDecorate)
 {
     _toDecorate = toDecorate ?? throw new ArgumentNullException(nameof(toDecorate));
 }
Esempio n. 60
0
        public void UpdateBonds(CompleteOutputDescription latestCoDesc, IBond[] bonds)
        {
            if (scheme.HandlesBonds)
            {
                scheme.SetOutputDescription(coDesc);

                DataFields[][] allStreams = new DataFields[1][];
                IGeometryCreator[] schStreams = scheme.GetBondStreams();
                GeomDataBufferStream[] geomStream = new GeomDataBufferStream[schStreams.Length];
                
                for (int i = 0; i < geomStream.Length; i++)
                {
                    allStreams[0] = schStreams[i].Fields;
                    GeomDataTransformer.CreateBufferStream(allStreams, out geomStream[i]);
                }
                // fill buffer stream
                scheme.SetBondData(bonds, geomStream);
            }
        }