Ejemplo n.º 1
0
        /// <summary> writes a single frame in XYZ format to the Writer.</summary>
        /// <param name="mol">the Molecule to write
        /// </param>
        public virtual void writeMolecule(IMolecule mol)
        {
            System.String st          = "";
            bool          writecharge = true;

            try
            {
                System.String s1 = ((System.Int32)mol.AtomCount).ToString();
                //UPGRADE_NOTE: Exceptions thrown by the equivalent in .NET of method 'java.io.BufferedWriter.write' may be different. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1099'"
                writer.Write(s1.ToCharArray(), 0, s1.Length);
                //UPGRADE_TODO: Method 'java.io.BufferedWriter.newLine' was converted to 'System.IO.TextWriter.WriteLine' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073'"
                writer.WriteLine();

                System.String s2 = null; // FIXME: add some interesting comment
                if (s2 != null)
                {
                    //UPGRADE_NOTE: Exceptions thrown by the equivalent in .NET of method 'java.io.BufferedWriter.write' may be different. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1099'"
                    writer.Write(s2.ToCharArray(), 0, s2.Length);
                }
                //UPGRADE_TODO: Method 'java.io.BufferedWriter.newLine' was converted to 'System.IO.TextWriter.WriteLine' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073'"
                writer.WriteLine();

                // Loop through the atoms and write them out:
                IAtom[] atoms = mol.Atoms;
                for (int i = 0; i < atoms.Length; i++)
                {
                    IAtom a = atoms[i];
                    st = a.Symbol;

                    Point3d p3 = a.getPoint3d();
                    if (p3 != null)
                    {
                        st = st + "\t" + p3.x.ToString() + "\t" + p3.y.ToString() + "\t" + p3.z.ToString();
                    }

                    if (writecharge)
                    {
                        double ct = a.getCharge();
                        st = st + "\t" + ct;
                    }

                    //UPGRADE_NOTE: Exceptions thrown by the equivalent in .NET of method 'java.io.BufferedWriter.write' may be different. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1099'"
                    writer.Write(st.ToCharArray(), 0, st.Length);
                    //UPGRADE_TODO: Method 'java.io.BufferedWriter.newLine' was converted to 'System.IO.TextWriter.WriteLine' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073'"
                    writer.WriteLine();
                }
            }
            catch (System.IO.IOException e)
            {
                //            throw e;
                //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Throwable.getMessage' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'"
                //logger.error("Error while writing file: ", e.Message);
                //logger.debug(e);
            }
        }
Ejemplo n.º 2
0
 /// <summary> Constructs an Atom from a String containing an element symbol.
 ///
 /// </summary>
 /// <param name="atom"> Atom from which the PseudoAtom is constructed
 /// </param>
 public PseudoAtom(IAtom atom)
     : base("R")
 {
     base.fractionalPoint3d = atom.getFractionalPoint3d();
     base.point3d           = atom.getPoint3d();
     base.point2d           = atom.getPoint2d();
     this.label             = atom.Symbol;
     base.hydrogenCount     = 0;
     base.stereoParity      = 0;
     base.exactMass         = 0.0;
     base.formalCharge      = 0;
     base.charge            = 0.0;
 }
Ejemplo n.º 3
0
 /// <summary> Returns true if the two atoms are within the distance fudge
 /// factor of each other.
 ///
 /// </summary>
 /// <param name="atom1">               Description of Parameter
 /// </param>
 /// <param name="atom2">               Description of Parameter
 /// </param>
 /// <param name="distanceFudgeFactor"> Description of Parameter
 /// </param>
 /// <returns>                      Description of the Returned Value
 /// </returns>
 /// <cdk.keyword>                  join-the-dots </cdk.keyword>
 /// <cdk.keyword>                  bond creation </cdk.keyword>
 public static bool closeEnoughToBond(IAtom atom1, IAtom atom2, double distanceFudgeFactor)
 {
     if (atom1 != atom2)
     {
         double distanceBetweenAtoms = atom1.getPoint3d().distance(atom2.getPoint3d());
         double bondingDistance      = atom1.CovalentRadius + atom2.CovalentRadius;
         if (distanceBetweenAtoms <= (distanceFudgeFactor * bondingDistance))
         {
             return(true);
         }
     }
     return(false);
 }
Ejemplo n.º 4
0
        /// <summary> Rotates a 3D point about a specified line segment by a specified angle.
        /// 
        /// The code is based on code available <a href="http://astronomy.swin.edu.au/~pbourke/geometry/rotate/source.c">here</a>.
        /// Positive angles are anticlockwise looking down the axis towards the origin.
        /// Assume right hand coordinate system.
        /// 
        /// </summary>
        /// <param name="atom">The atom to rotate
        /// </param>
        /// <param name="p1"> The  first point of the line segment
        /// </param>
        /// <param name="p2"> The second point of the line segment
        /// </param>
        /// <param name="angle"> The angle to rotate by (in degrees)
        /// </param>
        public static void rotate(IAtom atom, Point3d p1, Point3d p2, double angle)
        {
            double costheta, sintheta;

            Point3d r = new Point3d();

            r.x = p2.x - p1.x;
            r.y = p2.y - p1.y;
            r.z = p2.z - p1.z;
            normalize(r);


            angle = angle * System.Math.PI / 180.0;
            costheta = System.Math.Cos(angle);
            sintheta = System.Math.Sin(angle);

            Point3d p = atom.getPoint3d();
            p.x -= p1.x;
            p.y -= p1.y;
            p.z -= p1.z;

            Point3d q = new Point3d(0, 0, 0);
            q.x += (costheta + (1 - costheta) * r.x * r.x) * p.x;
            q.x += ((1 - costheta) * r.x * r.y - r.z * sintheta) * p.y;
            q.x += ((1 - costheta) * r.x * r.z + r.y * sintheta) * p.z;

            q.y += ((1 - costheta) * r.x * r.y + r.z * sintheta) * p.x;
            q.y += (costheta + (1 - costheta) * r.y * r.y) * p.y;
            q.y += ((1 - costheta) * r.y * r.z - r.x * sintheta) * p.z;

            q.z += ((1 - costheta) * r.x * r.z - r.y * sintheta) * p.x;
            q.z += ((1 - costheta) * r.y * r.z + r.x * sintheta) * p.y;
            q.z += (costheta + (1 - costheta) * r.z * r.z) * p.z;

            q.x += p1.x;
            q.y += p1.y;
            q.z += p1.z;

            atom.setPoint3d(q);
        }
Ejemplo n.º 5
0
 /// <summary>  Returns the atoms which are closes to an atom in an AtomContainer by
 /// distance in 3d.
 /// 
 /// </summary>
 /// <param name="ac">               The AtomContainer to examine
 /// </param>
 /// <param name="a">                the atom to start from
 /// </param>
 /// <param name="max">              the number of neighbours to return
 /// </param>
 /// <returns>                   the average bond length
 /// </returns>
 /// <exception cref="CDKException"> Description of the Exception
 /// </exception>
 public static System.Collections.ArrayList findClosestInSpace(IAtomContainer ac, IAtom a, int max)
 {
     IAtom[] atoms = ac.Atoms;
     Point3d originalPoint = a.getPoint3d();
     if (originalPoint == null)
     {
         throw new CDKException("No point3d, but findClosestInSpace is working on point3ds");
     }
     //UPGRADE_TODO: Constructor 'java.util.TreeMap.TreeMap' was converted to 'System.Collections.SortedList' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilTreeMapTreeMap'"
     //UPGRADE_ISSUE: Class hierarchy differences between 'java.util.TreeMap' and 'System.Collections.SortedList' may cause compilation errors. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1186'"
     System.Collections.IDictionary hm = new System.Collections.SortedList();
     for (int i = 0; i < atoms.Length; i++)
     {
         if (atoms[i] != a)
         {
             if (atoms[i].getPoint3d() == null)
             {
                 throw new CDKException("No point3d, but findClosestInSpace is working on point3ds");
             }
             double distance = atoms[i].getPoint3d().distance(originalPoint);
             hm[(double)distance] = atoms[i];
         }
     }
     //UPGRADE_TODO: Method 'java.util.Map.keySet' was converted to 'CSGraphT.SupportClass.HashSetSupport' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilMapkeySet'"
     CSGraphT.SupportClass.SetSupport ks = new CSGraphT.SupportClass.HashSetSupport(hm.Keys);
     System.Collections.IEnumerator it = ks.GetEnumerator();
     System.Collections.ArrayList returnValue = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10));
     int i2 = 0;
     //UPGRADE_TODO: Method 'java.util.Iterator.hasNext' was converted to 'System.Collections.IEnumerator.MoveNext' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilIteratorhasNext'"
     while (it.MoveNext() && i2 < max)
     {
         //UPGRADE_TODO: Method 'java.util.Iterator.next' was converted to 'System.Collections.IEnumerator.Current' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilIteratornext'"
         returnValue.Add(hm[it.Current]);
         i2++;
     }
     return (returnValue);
 }
Ejemplo n.º 6
0
        /// <summary> Writes a Molecule to an OutputStream in MDL sdf format.
        ///
        /// </summary>
        /// <param name="container"> Molecule that is written to an OutputStream
        /// </param>
        /// <param name="isVisible">Should a certain atom be written to mdl?
        /// </param>
        public virtual void writeMolecule(IMolecule container, bool[] isVisible)
        {
            System.String line = "";
            // taking care of the $$$$ signs:
            // we do not write such a sign at the end of the first molecule, thus we have to write on BEFORE the second molecule
            if (moleculeNumber == 2)
            {
                writer.Write("$$$$");
                //UPGRADE_TODO: Method 'java.io.BufferedWriter.newLine' was converted to 'System.IO.TextWriter.WriteLine' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073'"
                writer.WriteLine();
            }
            // write header block
            // lines get shortened to 80 chars, that's in the spec
            System.String title = (System.String)container.getProperty(CDKConstants.TITLE);
            if (title == null)
            {
                title = "";
            }
            if (title.Length > 80)
            {
                title = title.Substring(0, (80) - (0));
            }
            writer.Write(title + "\n");

            /* From CTX spec
             * This line has the format:
             * IIPPPPPPPPMMDDYYHHmmddSSssssssssssEEEEEEEEEEEERRRRRR
             * (FORTRAN: A2<--A8--><---A10-->A2I2<--F10.5-><---F12.5--><-I6-> )
             * User's first and last initials (l), program name (P),
             * date/time (M/D/Y,H:m), dimensional codes (d), scaling factors (S, s),
             * energy (E) if modeling program input, internal registry number (R)
             * if input through MDL form.
             * A blank line can be substituted for line 2.
             */
            writer.Write("  CDK    ");
            //UPGRADE_ISSUE: Constructor 'java.text.SimpleDateFormat.SimpleDateFormat' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javatextSimpleDateFormat'"
            //UPGRADE_TODO: The equivalent in .NET for method 'java.util.Calendar.getTime' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'"
            System.TimeZone generatedAux3 = System.TimeZone.CurrentTimeZone;
            //writer.Write(SupportClass.FormatDateTime(new SimpleDateFormat("M/d/y,H:m", new System.Globalization.CultureInfo("en-US")), SupportClass.CalendarManager.manager.GetDateTime(new System.Globalization.GregorianCalendar())));
            writer.Write('\n');

            System.String comment = (System.String)container.getProperty(CDKConstants.REMARK);
            if (comment == null)
            {
                comment = "";
            }
            if (comment.Length > 80)
            {
                comment = comment.Substring(0, (80) - (0));
            }
            writer.Write(comment + "\n");

            // write Counts line
            int upToWhichAtom = 0;

            for (int i = 0; i < isVisible.Length; i++)
            {
                if (isVisible[i])
                {
                    upToWhichAtom++;
                }
            }
            line += formatMDLInt(upToWhichAtom, 3);
            int numberOfBonds = 0;

            if (upToWhichAtom < container.AtomCount)
            {
                for (int i = 0; i < container.getBondCount(); i++)
                {
                    if (isVisible[container.getAtomNumber(container.getBondAt(i).getAtoms()[0])] && isVisible[container.getAtomNumber(container.getBondAt(i).getAtoms()[1])])
                    {
                        numberOfBonds++;
                    }
                }
            }
            else
            {
                numberOfBonds = container.getBondCount();
            }
            line += formatMDLInt(numberOfBonds, 3);
            line += "  0  0  0  0  0  0  0  0999 V2000\n";
            writer.Write(line);

            // write Atom block
            IAtom[] atoms = container.Atoms;
            for (int f = 0; f < atoms.Length; f++)
            {
                if (isVisible[f])
                {
                    IAtom atom = atoms[f];
                    line = "";
                    if (atom.getPoint3d() != null)
                    {
                        //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'"
                        line += formatMDLFloat((float)atom.X3d);
                        //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'"
                        line += formatMDLFloat((float)atom.Y3d);
                        //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'"
                        line += (formatMDLFloat((float)atom.Z3d) + " ");
                    }
                    else if (atom.getPoint2d() != null)
                    {
                        //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'"
                        line += formatMDLFloat((float)atom.X2d);
                        //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'"
                        line += formatMDLFloat((float)atom.Y2d);
                        line += "    0.0000 ";
                    }
                    else
                    {
                        // if no coordinates available, then output a number
                        // of zeros
                        line += formatMDLFloat((float)0.0);
                        line += formatMDLFloat((float)0.0);
                        line += (formatMDLFloat((float)0.0) + " ");
                    }
                    if (container.getAtomAt(f) is IPseudoAtom)
                    {
                        line += formatMDLString(((IPseudoAtom)container.getAtomAt(f)).Label, 3);
                    }
                    else
                    {
                        line += formatMDLString(container.getAtomAt(f).Symbol, 3);
                    }
                    line += " 0  0  0  0  0  0  0  0  0  0  0  0";
                    writer.Write(line);
                    //UPGRADE_TODO: Method 'java.io.BufferedWriter.newLine' was converted to 'System.IO.TextWriter.WriteLine' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073'"
                    writer.WriteLine();
                }
            }

            // write Bond block
            IBond[] bonds = container.Bonds;
            for (int g = 0; g < bonds.Length; g++)
            {
                if (upToWhichAtom == container.AtomCount || (isVisible[container.getAtomNumber(container.getBondAt(g).getAtoms()[0])] && isVisible[container.getAtomNumber(container.getBondAt(g).getAtoms()[1])]))
                {
                    IBond bond = bonds[g];
                    if (bond.getAtoms().Length != 2)
                    {
                        //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Object.toString' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'"
                        //logger.warn("Skipping bond with more/less than two atoms: " + bond);
                    }
                    else
                    {
                        if (bond.Stereo == CDKConstants.STEREO_BOND_UP_INV || bond.Stereo == CDKConstants.STEREO_BOND_DOWN_INV)
                        {
                            // turn around atom coding to correct for inv stereo
                            line  = formatMDLInt(container.getAtomNumber(bond.getAtomAt(1)) + 1, 3);
                            line += formatMDLInt(container.getAtomNumber(bond.getAtomAt(0)) + 1, 3);
                        }
                        else
                        {
                            line  = formatMDLInt(container.getAtomNumber(bond.getAtomAt(0)) + 1, 3);
                            line += formatMDLInt(container.getAtomNumber(bond.getAtomAt(1)) + 1, 3);
                        }
                        //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'"
                        line += formatMDLInt((int)bond.Order, 3);
                        line += "  ";
                        switch (bond.Stereo)
                        {
                        case CDKConstants.STEREO_BOND_UP:
                            line += "1";
                            break;

                        case CDKConstants.STEREO_BOND_UP_INV:
                            line += "1";
                            break;

                        case CDKConstants.STEREO_BOND_DOWN:
                            line += "6";
                            break;

                        case CDKConstants.STEREO_BOND_DOWN_INV:
                            line += "6";
                            break;

                        default:
                            line += "0";
                            break;
                        }
                        line += "  0  0  0 ";
                        writer.Write(line);
                        //UPGRADE_TODO: Method 'java.io.BufferedWriter.newLine' was converted to 'System.IO.TextWriter.WriteLine' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073'"
                        writer.WriteLine();
                    }
                }
            }

            // write formal atomic charges
            for (int i = 0; i < atoms.Length; i++)
            {
                IAtom atom   = atoms[i];
                int   charge = atom.getFormalCharge();
                if (charge != 0)
                {
                    writer.Write("M  CHG  1 ");
                    writer.Write(formatMDLInt(i + 1, 3));
                    writer.Write(" ");
                    writer.Write(formatMDLInt(charge, 3));
                    //UPGRADE_TODO: Method 'java.io.BufferedWriter.newLine' was converted to 'System.IO.TextWriter.WriteLine' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073'"
                    writer.WriteLine();
                }
            }

            // write formal isotope information
            for (int i = 0; i < atoms.Length; i++)
            {
                IAtom atom = atoms[i];
                if (!(atom is IPseudoAtom))
                {
                    int atomicMass = atom.MassNumber;
                    int majorMass  = IsotopeFactory.getInstance(atom.Builder).getMajorIsotope(atom.Symbol).MassNumber;
                    if (atomicMass != 0 && atomicMass != majorMass)
                    {
                        writer.Write("M  ISO  1 ");
                        writer.Write(formatMDLInt(i + 1, 3));
                        writer.Write(" ");
                        writer.Write(formatMDLInt(atomicMass, 3));
                        //UPGRADE_TODO: Method 'java.io.BufferedWriter.newLine' was converted to 'System.IO.TextWriter.WriteLine' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073'"
                        writer.WriteLine();
                    }
                }
            }

            // close molecule
            writer.Write("M  END");
            //UPGRADE_TODO: Method 'java.io.BufferedWriter.newLine' was converted to 'System.IO.TextWriter.WriteLine' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073'"
            writer.WriteLine();
            //write sdfields, if any
            if (sdFields != null)
            {
                //UPGRADE_TODO: Method 'java.util.Map.keySet' was converted to 'CSGraphT.SupportClass.HashSetSupport' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilMapkeySet'"
                CSGraphT.SupportClass.SetSupport set_Renamed = new CSGraphT.SupportClass.HashSetSupport(sdFields.Keys);
                System.Collections.IEnumerator   iterator    = set_Renamed.GetEnumerator();
                //UPGRADE_TODO: Method 'java.util.Iterator.hasNext' was converted to 'System.Collections.IEnumerator.MoveNext' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilIteratorhasNext'"
                while (iterator.MoveNext())
                {
                    //UPGRADE_TODO: Method 'java.util.Iterator.next' was converted to 'System.Collections.IEnumerator.Current' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilIteratornext'"
                    System.Object element = iterator.Current;
                    writer.Write("> <" + ((System.String)element) + ">");
                    //UPGRADE_TODO: Method 'java.io.BufferedWriter.newLine' was converted to 'System.IO.TextWriter.WriteLine' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073'"
                    writer.WriteLine();
                    //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Object.toString' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'"
                    writer.Write(sdFields[element].ToString());
                    //UPGRADE_TODO: Method 'java.io.BufferedWriter.newLine' was converted to 'System.IO.TextWriter.WriteLine' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073'"
                    writer.WriteLine();
                    //UPGRADE_TODO: Method 'java.io.BufferedWriter.newLine' was converted to 'System.IO.TextWriter.WriteLine' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073'"
                    writer.WriteLine();
                }
            }
            // taking care of the $$$$ signs:
            // we write such a sign at the end of all except the first molecule
            if (moleculeNumber != 1)
            {
                writer.Write("$$$$");
                //UPGRADE_TODO: Method 'java.io.BufferedWriter.newLine' was converted to 'System.IO.TextWriter.WriteLine' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073'"
                writer.WriteLine();
            }
            moleculeNumber++;
            writer.Flush();
        }
Ejemplo n.º 7
0
        /// <summary>  Read a Molecule from a file in MDL sd format
        ///
        /// </summary>
        /// <returns>    The Molecule that was read from the MDL file.
        /// </returns>
        private IMolecule readMolecule(IMolecule molecule)
        {
            //logger.debug("Reading new molecule");
            int linecount     = 0;
            int atoms         = 0;
            int bonds         = 0;
            int atom1         = 0;
            int atom2         = 0;
            int order         = 0;
            int stereo        = 0;
            int RGroupCounter = 1;
            int Rnumber       = 0;

            System.String[] rGroup = null;
            double          x      = 0.0;
            double          y      = 0.0;
            double          z      = 0.0;
            double          totalZ = 0.0;
            //int[][] conMat = new int[0][0];
            //String help;
            IBond bond;
            IAtom atom;

            System.String line = "";

            try
            {
                //logger.info("Reading header");
                line = input.ReadLine(); linecount++;
                if (line == null)
                {
                    return(null);
                }
                //logger.debug("Line " + linecount + ": " + line);

                if (line.StartsWith("$$$$"))
                {
                    //logger.debug("File is empty, returning empty molecule");
                    return(molecule);
                }
                if (line.Length > 0)
                {
                    molecule.setProperty(CDKConstants.TITLE, line);
                }
                line = input.ReadLine(); linecount++;
                //logger.debug("Line " + linecount + ": " + line);
                line = input.ReadLine(); linecount++;
                //logger.debug("Line " + linecount + ": " + line);
                if (line.Length > 0)
                {
                    molecule.setProperty(CDKConstants.REMARK, line);
                }

                //logger.info("Reading rest of file");
                line = input.ReadLine(); linecount++;
                //logger.debug("Line " + linecount + ": " + line);
                atoms = System.Int32.Parse(line.Substring(0, (3) - (0)).Trim());
                //logger.debug("Atomcount: " + atoms);
                bonds = System.Int32.Parse(line.Substring(3, (6) - (3)).Trim());
                //logger.debug("Bondcount: " + bonds);

                // read ATOM block
                //logger.info("Reading atom block");
                for (int f = 0; f < atoms; f++)
                {
                    line = input.ReadLine(); linecount++;
                    //UPGRADE_TODO: The differences in the format  of parameters for constructor 'java.lang.Double.Double'  may cause compilation errors.  "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1092'"
                    x = System.Double.Parse(line.Substring(0, (10) - (0)).Trim());
                    //UPGRADE_TODO: The differences in the format  of parameters for constructor 'java.lang.Double.Double'  may cause compilation errors.  "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1092'"
                    y = System.Double.Parse(line.Substring(10, (20) - (10)).Trim());
                    //UPGRADE_TODO: The differences in the format  of parameters for constructor 'java.lang.Double.Double'  may cause compilation errors.  "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1092'"
                    z       = System.Double.Parse(line.Substring(20, (30) - (20)).Trim());
                    totalZ += System.Math.Abs(z); // *all* values should be zero, not just the sum
                    //logger.debug("Coordinates: " + x + "; " + y + "; " + z);
                    System.String element = line.Substring(31, (34) - (31)).Trim();

                    //logger.debug("Atom type: ", element);
                    if (IsotopeFactory.getInstance(molecule.Builder).isElement(element))
                    {
                        atom = IsotopeFactory.getInstance(molecule.Builder).configure(molecule.Builder.newAtom(element));
                    }
                    else
                    {
                        //logger.debug("Atom ", element, " is not an regular element. Creating a PseudoAtom.");
                        //check if the element is R
                        rGroup = element.Split(new char[] { '^', 'R' }); // ????
                        if (rGroup.Length > 1)
                        {
                            try
                            {
                                Rnumber       = System.Int32.Parse(rGroup[(rGroup.Length - 1)]);
                                RGroupCounter = Rnumber;
                            }
                            catch (System.Exception ex)
                            {
                                Rnumber = RGroupCounter;
                                RGroupCounter++;
                            }
                            element = "R" + Rnumber;
                        }
                        atom = molecule.Builder.newPseudoAtom(element);
                    }

                    // store as 3D for now, convert to 2D (if totalZ == 0.0) later
                    atom.setPoint3d(new Point3d(x, y, z));

                    // parse further fields
                    System.String massDiffString = line.Substring(34, (36) - (34)).Trim();
                    //logger.debug("Mass difference: ", massDiffString);
                    if (!(atom is IPseudoAtom))
                    {
                        try
                        {
                            int massDiff = System.Int32.Parse(massDiffString);
                            if (massDiff != 0)
                            {
                                IIsotope major = IsotopeFactory.getInstance(molecule.Builder).getMajorIsotope(element);
                                atom.AtomicNumber = major.AtomicNumber + massDiff;
                            }
                        }
                        catch (System.Exception exception)
                        {
                            //logger.error("Could not parse mass difference field");
                        }
                    }
                    else
                    {
                        //logger.error("Cannot set mass difference for a non-element!");
                    }


                    System.String chargeCodeString = line.Substring(36, (39) - (36)).Trim();
                    //logger.debug("Atom charge code: ", chargeCodeString);
                    int chargeCode = System.Int32.Parse(chargeCodeString);
                    if (chargeCode == 0)
                    {
                        // uncharged species
                    }
                    else if (chargeCode == 1)
                    {
                        atom.setFormalCharge(+3);
                    }
                    else if (chargeCode == 2)
                    {
                        atom.setFormalCharge(+2);
                    }
                    else if (chargeCode == 3)
                    {
                        atom.setFormalCharge(+1);
                    }
                    else if (chargeCode == 4)
                    {
                    }
                    else if (chargeCode == 5)
                    {
                        atom.setFormalCharge(-1);
                    }
                    else if (chargeCode == 6)
                    {
                        atom.setFormalCharge(-2);
                    }
                    else if (chargeCode == 7)
                    {
                        atom.setFormalCharge(-3);
                    }

                    try
                    {
                        // read the mmm field as position 61-63
                        System.String reactionAtomIDString = line.Substring(60, (63) - (60)).Trim();
                        //logger.debug("Parsing mapping id: ", reactionAtomIDString);
                        try
                        {
                            int reactionAtomID = System.Int32.Parse(reactionAtomIDString);
                            if (reactionAtomID != 0)
                            {
                                atom.ID = reactionAtomIDString;
                            }
                        }
                        catch (System.Exception exception)
                        {
                            //logger.error("Mapping number ", reactionAtomIDString, " is not an integer.");
                            //logger.debug(exception);
                        }
                    }
                    catch (System.Exception exception)
                    {
                        // older mol files don't have all these fields...
                        //logger.warn("A few fields are missing. Older MDL MOL file?");
                    }

                    molecule.addAtom(atom);
                }

                // convert to 2D, if totalZ == 0
                if (totalZ == 0.0 && !forceReadAs3DCoords.Set)
                {
                    //logger.info("Total 3D Z is 0.0, interpreting it as a 2D structure");
                    IAtom[] atomsToUpdate = molecule.Atoms;
                    for (int f = 0; f < atomsToUpdate.Length; f++)
                    {
                        IAtom   atomToUpdate = atomsToUpdate[f];
                        Point3d p3d          = atomToUpdate.getPoint3d();
                        atomToUpdate.setPoint2d(new Point2d(p3d.x, p3d.y));
                        atomToUpdate.setPoint3d(null);
                    }
                }

                // read BOND block
                //logger.info("Reading bond block");
                for (int f = 0; f < bonds; f++)
                {
                    line  = input.ReadLine(); linecount++;
                    atom1 = System.Int32.Parse(line.Substring(0, (3) - (0)).Trim());
                    atom2 = System.Int32.Parse(line.Substring(3, (6) - (3)).Trim());
                    order = System.Int32.Parse(line.Substring(6, (9) - (6)).Trim());
                    if (line.Length > 12)
                    {
                        stereo = System.Int32.Parse(line.Substring(9, (12) - (9)).Trim());
                    }
                    else
                    {
                        //logger.warn("Missing expected stereo field at line: " + line);
                    }
                    //if (//logger.DebugEnabled)
                    //{
                    //    //logger.debug("Bond: " + atom1 + " - " + atom2 + "; order " + order);
                    //}
                    if (stereo == 1)
                    {
                        // MDL up bond
                        stereo = CDKConstants.STEREO_BOND_UP;
                    }
                    else if (stereo == 6)
                    {
                        // MDL down bond
                        stereo = CDKConstants.STEREO_BOND_DOWN;
                    }
                    else if (stereo == 4)
                    {
                        //MDL bond undefined
                        stereo = CDKConstants.STEREO_BOND_UNDEFINED;
                    }
                    // interpret CTfile's special bond orders
                    IAtom a1 = molecule.getAtomAt(atom1 - 1);
                    IAtom a2 = molecule.getAtomAt(atom2 - 1);
                    if (order == 4)
                    {
                        // aromatic bond
                        bond = molecule.Builder.newBond(a1, a2, CDKConstants.BONDORDER_AROMATIC, stereo);
                        // mark both atoms and the bond as aromatic
                        bond.setFlag(CDKConstants.ISAROMATIC, true);
                        a1.setFlag(CDKConstants.ISAROMATIC, true);
                        a2.setFlag(CDKConstants.ISAROMATIC, true);
                        molecule.addBond(bond);
                    }
                    else
                    {
                        bond = molecule.Builder.newBond(a1, a2, (double)order, stereo);
                        molecule.addBond(bond);
                    }
                }

                // read PROPERTY block
                //logger.info("Reading property block");
                while (true)
                {
                    line = input.ReadLine(); linecount++;
                    if (line == null)
                    {
                        throw new CDKException("The expected property block is missing!");
                    }
                    if (line.StartsWith("M  END"))
                    {
                        break;
                    }

                    bool lineRead = false;
                    if (line.StartsWith("M  CHG"))
                    {
                        // FIXME: if this is encountered for the first time, all
                        // atom charges should be set to zero first!
                        int infoCount             = System.Int32.Parse(line.Substring(6, (9) - (6)).Trim());
                        SupportClass.Tokenizer st = new SupportClass.Tokenizer(line.Substring(9));
                        for (int i = 1; i <= infoCount; i++)
                        {
                            System.String token      = st.NextToken();
                            int           atomNumber = System.Int32.Parse(token.Trim());
                            token = st.NextToken();
                            int charge = System.Int32.Parse(token.Trim());
                            molecule.getAtomAt(atomNumber - 1).setFormalCharge(charge);
                        }
                    }
                    else if (line.StartsWith("M  ISO"))
                    {
                        try
                        {
                            System.String          countString = line.Substring(6, (9) - (6)).Trim();
                            int                    infoCount   = System.Int32.Parse(countString);
                            SupportClass.Tokenizer st          = new SupportClass.Tokenizer(line.Substring(9));
                            for (int i = 1; i <= infoCount; i++)
                            {
                                int atomNumber = System.Int32.Parse(st.NextToken().Trim());
                                int absMass    = System.Int32.Parse(st.NextToken().Trim());
                                if (absMass != 0)
                                {
                                    IAtom isotope = molecule.getAtomAt(atomNumber - 1);
                                    isotope.MassNumber = absMass;
                                }
                            }
                        }
                        catch (System.FormatException exception)
                        {
                            //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Throwable.getMessage' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'"
                            System.String error = "Error (" + exception.Message + ") while parsing line " + linecount + ": " + line + " in property block.";
                            //logger.error(error);
                            throw new CDKException("NumberFormatException in isotope information on line: " + line, exception);
                        }
                    }
                    else if (line.StartsWith("M  RAD"))
                    {
                        try
                        {
                            System.String          countString = line.Substring(6, (9) - (6)).Trim();
                            int                    infoCount   = System.Int32.Parse(countString);
                            SupportClass.Tokenizer st          = new SupportClass.Tokenizer(line.Substring(9));
                            for (int i = 1; i <= infoCount; i++)
                            {
                                int atomNumber       = System.Int32.Parse(st.NextToken().Trim());
                                int spinMultiplicity = System.Int32.Parse(st.NextToken().Trim());
                                if (spinMultiplicity > 1)
                                {
                                    IAtom radical = molecule.getAtomAt(atomNumber - 1);
                                    for (int j = 2; j <= spinMultiplicity; j++)
                                    {
                                        // 2 means doublet -> one unpaired electron
                                        // 3 means triplet -> two unpaired electron
                                        molecule.addElectronContainer(molecule.Builder.newSingleElectron(radical));
                                    }
                                }
                            }
                        }
                        catch (System.FormatException exception)
                        {
                            //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Throwable.getMessage' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'"
                            System.String error = "Error (" + exception.Message + ") while parsing line " + linecount + ": " + line + " in property block.";
                            //logger.error(error);
                            throw new CDKException("NumberFormatException in radical information on line: " + line, exception);
                        }
                    }
                    else if (line.StartsWith("G  "))
                    {
                        try
                        {
                            System.String atomNumberString = line.Substring(3, (6) - (3)).Trim();
                            int           atomNumber       = System.Int32.Parse(atomNumberString);
                            //String whatIsThisString = line.substring(6,9).trim();

                            System.String atomName = input.ReadLine();

                            // convert Atom into a PseudoAtom
                            IAtom       prevAtom   = molecule.getAtomAt(atomNumber - 1);
                            IPseudoAtom pseudoAtom = molecule.Builder.newPseudoAtom(atomName);
                            if (prevAtom.getPoint2d() != null)
                            {
                                pseudoAtom.setPoint2d(prevAtom.getPoint2d());
                            }
                            if (prevAtom.getPoint3d() != null)
                            {
                                pseudoAtom.setPoint3d(prevAtom.getPoint3d());
                            }
                            AtomContainerManipulator.replaceAtomByAtom(molecule, prevAtom, pseudoAtom);
                        }
                        catch (System.FormatException exception)
                        {
                            //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Throwable.toString' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'"
                            System.String error = "Error (" + exception.ToString() + ") while parsing line " + linecount + ": " + line + " in property block.";
                            //logger.error(error);
                            throw new CDKException("NumberFormatException in group information on line: " + line, exception);
                        }
                    }
                    if (!lineRead)
                    {
                        //logger.warn("Skipping line in property block: ", line);
                    }
                }
            }
            catch (CDKException exception)
            {
                //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Throwable.getMessage' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'"
                System.String error = "Error while parsing line " + linecount + ": " + line + " -> " + exception.Message;
                //logger.error(error);
                //logger.debug(exception);
                throw exception;
            }
            catch (System.Exception exception)
            {
                //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Throwable.getMessage' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'"
                System.String error = "Error while parsing line " + linecount + ": " + line + " -> " + exception.Message;
                //logger.error(error);
                //logger.debug(exception);
                throw new CDKException(error, exception);
            }
            return(molecule);
        }
Ejemplo n.º 8
0
        /// <summary> writes all the molecules supplied in a SetOfMolecules class to
        /// a single HIN file. You can also supply a single Molecule object
        /// as well
        /// </summary>
        /// <param name="mol">the Molecule to write
        /// </param>
        private void writeMolecule(ISetOfMolecules som)
        {
            //int na = 0;
            //String info = "";
            System.String sym  = "";
            double        chrg = 0.0;

            //boolean writecharge = true;

            for (int molnum = 0; molnum < som.MoleculeCount; molnum++)
            {
                IMolecule mol = som.getMolecule(molnum);

                try
                {
                    int natom = mol.AtomCount;
                    int nbond = mol.getBondCount();

                    System.String molname = "mol " + (molnum + 1) + " " + ((System.String)mol.getProperty(CDKConstants.TITLE));

                    //UPGRADE_NOTE: Exceptions thrown by the equivalent in .NET of method 'java.io.BufferedWriter.write' may be different. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1099'"
                    writer.Write(molname.ToCharArray(), 0, molname.Length);
                    //UPGRADE_TODO: Method 'java.io.BufferedWriter.newLine' was converted to 'System.IO.TextWriter.WriteLine' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073'"
                    writer.WriteLine();

                    // Loop through the atoms and write them out:
                    IAtom[] atoms = mol.Atoms;
                    IBond[] bonds = mol.Bonds;

                    for (int i = 0; i < natom; i++)
                    {
                        System.String line = "atom ";
                        IAtom         a    = atoms[i];

                        sym  = a.Symbol;
                        chrg = a.getCharge();
                        Point3d p3 = a.getPoint3d();

                        line = line + ((System.Int32)(i + 1)).ToString() + " - " + sym + " ** - " + ((double)chrg).ToString() + " " + p3.x.ToString() + " " + p3.y.ToString() + " " + p3.z.ToString() + " ";

                        System.String buf  = "";
                        int           ncon = 0;
                        for (int j = 0; j < nbond; j++)
                        {
                            IBond b = bonds[j];
                            if (b.contains(a))
                            {
                                // current atom is in the bond so lets get the connected atom
                                IAtom         ca     = b.getConnectedAtom(a);
                                double        bo     = b.Order;
                                int           serial = -1;
                                System.String bt     = "";

                                // get the serial no for this atom
                                serial = mol.getAtomNumber(ca);

                                if (bo == 1)
                                {
                                    bt = new System.Text.StringBuilder("s").ToString();
                                }
                                else if (bo == 2)
                                {
                                    bt = new System.Text.StringBuilder("d").ToString();
                                }
                                else if (bo == 3)
                                {
                                    bt = new System.Text.StringBuilder("t").ToString();
                                }
                                else if (bo == 1.5)
                                {
                                    bt = new System.Text.StringBuilder("a").ToString();
                                }
                                buf = buf + ((System.Int32)(serial + 1)).ToString() + " " + bt + " ";
                                ncon++;
                            }
                        }
                        line = line + " " + ((System.Int32)ncon).ToString() + " " + buf;
                        //UPGRADE_NOTE: Exceptions thrown by the equivalent in .NET of method 'java.io.BufferedWriter.write' may be different. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1099'"
                        writer.Write(line.ToCharArray(), 0, line.Length);
                        //UPGRADE_TODO: Method 'java.io.BufferedWriter.newLine' was converted to 'System.IO.TextWriter.WriteLine' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073'"
                        writer.WriteLine();
                    }
                    System.String buf2 = "endmol " + (molnum + 1);
                    //UPGRADE_NOTE: Exceptions thrown by the equivalent in .NET of method 'java.io.BufferedWriter.write' may be different. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1099'"
                    writer.Write(buf2.ToCharArray(), 0, buf2.Length);
                    //UPGRADE_TODO: Method 'java.io.BufferedWriter.newLine' was converted to 'System.IO.TextWriter.WriteLine' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073'"
                    writer.WriteLine();
                }
                catch (System.IO.IOException e)
                {
                    throw e;
                }
            }
        }
Ejemplo n.º 9
0
        /// <summary> Returns true if the two atoms are within the distance fudge
        /// factor of each other.
        /// 
        /// </summary>
        /// <param name="atom1">               Description of Parameter
        /// </param>
        /// <param name="atom2">               Description of Parameter
        /// </param>
        /// <param name="distanceFudgeFactor"> Description of Parameter
        /// </param>
        /// <returns>                      Description of the Returned Value
        /// </returns>
        /// <cdk.keyword>                  join-the-dots </cdk.keyword>
        /// <cdk.keyword>                  bond creation </cdk.keyword>
        public static bool closeEnoughToBond(IAtom atom1, IAtom atom2, double distanceFudgeFactor)
        {

            if (atom1 != atom2)
            {
                double distanceBetweenAtoms = atom1.getPoint3d().distance(atom2.getPoint3d());
                double bondingDistance = atom1.CovalentRadius + atom2.CovalentRadius;
                if (distanceBetweenAtoms <= (distanceFudgeFactor * bondingDistance))
                {
                    return true;
                }
            }
            return false;
        }