Example #1
0
        private void addBond(PDBPolymer obp, int bondAtomNo, int bondedAtomNo)
        {
            IAtom firstAtom  = (PDBAtom)atomNumberMap[(System.Int32)bondAtomNo];
            IAtom secondAtom = (PDBAtom)atomNumberMap[(System.Int32)bondedAtomNo];

            if (firstAtom == null)
            {
                //logger.error("Could not find bond start atom in map with serial id: ", bondAtomNo);
            }
            if (secondAtom == null)
            {
                //logger.error("Could not find bond target atom in map with serial id: ", bondAtomNo);
            }
            obp.addBond(firstAtom.Builder.newBond(firstAtom, secondAtom, 1));
        }
Example #2
0
        public /*Chem*/ Frame(Org.OpenScience.CDK.Interfaces.IChemFile chemFile, Device graphicsDevice)
        {
            shapes             = new Shape[JmolConstants.SHAPE_MAX];
            this.g3d           = new NuGraphics3D(graphicsDevice);
            this.frameRenderer = new FrameRenderer();

            for (int i = MAX_BONDS_LENGTH_TO_CACHE; --i > 0;)  // .GT. 0
            {
                freeBonds[i] = new Bond[MAX_NUM_TO_CACHE][];
            }

            // convert to jmol native
            mmset = new Mmset(this);

            // set properties
            mmset.ModelSetProperties = new System.Collections.Specialized.NameValueCollection();

            // init build
            currentModelIndex          = -1;
            currentModel               = null;
            currentChainID             = '\uFFFF';
            currentChain               = null;
            currentGroupSequenceNumber = -1;
            currentGroupInsertionCode  = '\uFFFF';

            int atomCountEstimate = 0;

            for (int seq = 0; seq < chemFile.ChemSequenceCount; seq++)
            {
                for (int model = 0; model < chemFile.ChemSequences[seq].ChemModelCount; model++)
                {
                    Org.OpenScience.CDK.Interfaces.IChemModel chemModel = chemFile.ChemSequences[seq].ChemModels[model];
                    for (int atomC = 0; atomC < chemModel.SetOfMolecules.AtomContainerCount; atomC++)
                    {
                        atomCountEstimate += chemModel.SetOfMolecules.AtomContainers[atomC].AtomCount;
                    }
                }
            }

            if (atomCountEstimate <= 0)
            {
                atomCountEstimate = ATOM_GROWTH_INCREMENT;
            }
            atoms = new Atom[atomCountEstimate];
            bonds = new Bond[2 * atomCountEstimate];
            htAtomMap.Clear();

            // translate IChemSequence[] into Model[]
            mmset.ModelCount = chemFile.ChemSequenceCount;
            for (int seq = 0; seq < chemFile.ChemSequenceCount; ++seq)
            {
                int    modelNumber = seq + 1;
                string modelName   = modelNumber.ToString();
                NameValueCollection modelProperties = new NameValueCollection();    // FIXME: Loading property values
                mmset.setModelNameNumberProperties(seq, modelName, modelNumber, modelProperties);
            }

            // translate Atoms
            Dictionary <Org.OpenScience.CDK.Interfaces.IAtom, Atom> atomsList = new Dictionary <Org.OpenScience.CDK.Interfaces.IAtom, Atom>();

            //try
            //{
            for (int seq = 0; seq < chemFile.ChemSequenceCount; seq++)
            {
                for (int model = 0; model < chemFile.ChemSequences[seq].ChemModelCount; model++)
                {
                    Org.OpenScience.CDK.Interfaces.IChemModel chemModel = chemFile.ChemSequences[seq].ChemModels[model];
                    for (int atomC = 0; atomC < chemModel.SetOfMolecules.AtomContainerCount; atomC++)
                    {
                        for (int atomIdx = 0; atomIdx < chemModel.SetOfMolecules.AtomContainers[atomC].AtomCount; atomIdx++)
                        {
                            Org.OpenScience.CDK.Interfaces.IAtom atom = chemModel.SetOfMolecules.AtomContainers[atomC].Atoms[atomIdx];

                            sbyte elementNumber = (sbyte)atom.AtomicNumber;
                            if (elementNumber <= 0)
                            {
                                elementNumber = JmolConstants.elementNumberFromSymbol(atom.Symbol);
                            }
                            char alternateLocation = '\0';

                            int  sequenceNumber     = int.MinValue;
                            char groupInsertionCode = '\0';

                            string atomName   = null;
                            string group3Name = null;
                            char   chainID    = '\0';
                            if (atom is PDBAtom)
                            {
                                PDBAtom pdbAtom = (PDBAtom)atom;
                                if (pdbAtom.ResSeq != null && pdbAtom.ResSeq.Length > 0)
                                {
                                    sequenceNumber = int.Parse(pdbAtom.ResSeq);
                                }
                                if (pdbAtom.ICode != null && pdbAtom.ICode.Length > 0)
                                {
                                    groupInsertionCode = pdbAtom.ICode[0];
                                }

                                atomName   = pdbAtom.Name;
                                group3Name = pdbAtom.ResName;
                                if (pdbAtom.ChainID != null && pdbAtom.ChainID.Length >= 1)
                                {
                                    chainID = pdbAtom.ChainID[0];
                                }
                            }
                            else
                            {
                                atomName = atom.AtomTypeName;
                            }

                            atomsList[atom] = AddAtom(model, atom, elementNumber, atomName, atom.getFormalCharge(),
                                                      (float)atom.getCharge(), 100, float.NaN, (float)atom.X3d, (float)atom.Y3d,
                                                      (float)atom.Z3d, false, int.MinValue, chainID, group3Name, sequenceNumber,
                                                      groupInsertionCode, float.NaN, float.NaN, float.NaN, alternateLocation, null);
                        }
                    }
                }
            }
            //}
            //catch (Exception e)
            //{
            //    throw new ApplicationException("Problem translating atoms", e);
            //}

            fileHasHbonds = false;

            // translate bonds
            try
            {
                for (int seq = 0; seq < chemFile.ChemSequenceCount; seq++)
                {
                    for (int model = 0; model < chemFile.ChemSequences[seq].ChemModelCount; model++)
                    {
                        Org.OpenScience.CDK.Interfaces.IChemModel chemModel = chemFile.ChemSequences[seq].ChemModels[model];

                        for (int atomC = 0; atomC < chemModel.SetOfMolecules.AtomContainerCount; atomC++)
                        {
                            for (int bondIdx = 0; bondIdx < chemModel.SetOfMolecules.AtomContainers[atomC].Bonds.Length; bondIdx++)
                            {
                                Org.OpenScience.CDK.Interfaces.IBond   bond     = chemModel.SetOfMolecules.AtomContainers[atomC].Bonds[bondIdx];
                                Org.OpenScience.CDK.Interfaces.IAtom[] cdkAtoms = bond.getAtoms();
                                // locate translated atoms
                                Atom atom1, atom2;
                                atomsList.TryGetValue(cdkAtoms[0], out atom1);
                                atomsList.TryGetValue(cdkAtoms[1], out atom2);
                                bondAtoms(atom1, atom2, (int)bond.Order);
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                throw new ApplicationException("Problem translating bonds", e);
            }
            atomsList.Clear();

            // translate structures of PDBPolymer only
            for (int seq = 0; seq < chemFile.ChemSequenceCount; seq++)
            {
                for (int model = 0; model < chemFile.ChemSequences[seq].ChemModelCount; model++)
                {
                    Org.OpenScience.CDK.Interfaces.IChemModel chemModel = chemFile.ChemSequences[seq].ChemModels[model];

                    foreach (Org.OpenScience.CDK.Interfaces.IMolecule molecule in chemModel.SetOfMolecules.Molecules)
                    {
                        if (molecule is PDBPolymer)
                        {
                            PDBPolymer pdbPolymer = (PDBPolymer)molecule;
                            if (pdbPolymer.Structures != null && pdbPolymer.Structures.Count > 0)
                            {
                                structuresDefined = true;
                                foreach (PDBStructure pdbStruct in pdbPolymer.Structures)
                                {
                                    structuresDefined = true;
                                    mmset.defineStructure(pdbStruct.StructureType, pdbStruct.StartChainID,
                                                          pdbStruct.StartSequenceNumber, pdbStruct.StartInsertionCode,
                                                          pdbStruct.EndChainID, pdbStruct.EndSequenceNumber, pdbStruct.EndInsertionCode);
                                }
                            }
                        }
                    }
                }
            }
            autoBond(null, null);

            // build groups
            FinalizeGroupBuild();
            BuildPolymers();
            Freeze();

            finalizeBuild();

            // create ribbon shapes
            try
            {
                setShapeSize(JmolConstants.SHAPE_RIBBONS, -1, new BitArray(0));
                setShapeSize(JmolConstants.SHAPE_CARTOON, -1, new BitArray(0));
            }
            catch (Exception) { }
        }
Example #3
0
        /// <summary>
        /// Read a <see cref="IChemFile"/> from a file in PDB format. The molecules
        /// in the file are stored as <see cref="IBioPolymer"/>s in the
        /// <see cref="IChemFile"/>. The residues are the monomers of the
        /// <see cref="IBioPolymer"/>, and their names are the concatenation of the
        /// residue, chain id, and the sequence number. Separate chains (denoted by
        /// TER records) are stored as separate <see cref="IBioPolymer"/> molecules.
        /// </summary>
        /// <remarks>
        /// Connectivity information is not currently read.
        /// </remarks>
        /// <returns>The ChemFile that was read from the PDB file.</returns>
        private IChemFile ReadChemFile(IChemFile oFile)
        {
            // initialize all containers
            var oSeq   = oFile.Builder.NewChemSequence();
            var oModel = oFile.Builder.NewChemModel();
            var oSet   = oFile.Builder.NewAtomContainerSet();

            // some variables needed
            var    oBP = new PDBPolymer();
            var    molecularStructure = oFile.Builder.NewAtomContainer();
            string cRead      = "";
            char   chain      = 'A'; // To ensure stringent name giving of monomers
            int    lineLength = 0;

            bool isProteinStructure = false;

            atomNumberMap = new Dictionary <int, IAtom>();
            if (readConnect.IsSet)
            {
                bondsFromConnectRecords = new List <IBond>();
            }

            // do the reading of the Input
            try
            {
                do
                {
                    cRead = oInput.ReadLine();
                    Debug.WriteLine($"Read line: {cRead}");
                    if (cRead != null)
                    {
                        lineLength = cRead.Length;

                        // make sure the record name is 6 characters long
                        if (lineLength < 6)
                        {
                            cRead = cRead + "      ";
                        }
                        // check the first column to decide what to do
                        var cCol = cRead.Substring(0, 6);
                        switch (cCol.ToUpperInvariant())
                        {
                        case "SEQRES":
                        {
                            isProteinStructure = true;
                        }
                        break;

                        case "ATOM  ":
                        {
                            #region
                            // read an atom record
                            var oAtom = ReadAtom(cRead, lineLength);

                            if (isProteinStructure)
                            {
                                // construct a string describing the residue
                                var cResidue = new StringBuilder(8);
                                var oObj     = oAtom.ResName;
                                if (oObj != null)
                                {
                                    cResidue = cResidue.Append(oObj.Trim());
                                }
                                oObj = oAtom.ChainID;
                                if (oObj != null)
                                {
                                    // cResidue = cResidue.Append(((string)oObj).Trim());
                                    cResidue = cResidue.Append(chain);
                                }
                                oObj = oAtom.ResSeq;
                                if (oObj != null)
                                {
                                    cResidue = cResidue.Append(oObj.Trim());
                                }

                                // search for an existing strand or create a new one.
                                var strandName = oAtom.ChainID;
                                if (strandName == null || strandName.Length == 0)
                                {
                                    strandName = chain.ToString(NumberFormatInfo.InvariantInfo);
                                }
                                var oStrand = oBP.GetStrand(strandName);
                                if (oStrand == null)
                                {
                                    oStrand = new PDBStrand
                                    {
                                        StrandName = strandName,
                                        Id         = chain.ToString(NumberFormatInfo.InvariantInfo)
                                    };
                                }

                                // search for an existing monomer or create a new one.
                                var oMonomer = oBP.GetMonomer(cResidue.ToString(), chain.ToString(NumberFormatInfo.InvariantInfo));
                                if (oMonomer == null)
                                {
                                    var monomer = new PDBMonomer
                                    {
                                        MonomerName = cResidue.ToString(),
                                        MonomerType = oAtom.ResName,
                                        ChainID     = oAtom.ChainID,
                                        ICode       = oAtom.ICode,
                                        ResSeq      = oAtom.ResSeq
                                    };
                                    oMonomer = monomer;
                                }

                                // add the atom
                                oBP.AddAtom(oAtom, oMonomer, oStrand);
                            }
                            else
                            {
                                molecularStructure.Atoms.Add(oAtom);
                            }

                            if (readConnect.IsSet)
                            {
                                var isDup = atomNumberMap.ContainsKey(oAtom.Serial.Value);
                                atomNumberMap[oAtom.Serial.Value] = oAtom;
                                if (isDup)
                                {
                                    Trace.TraceWarning($"Duplicate serial ID found for atom: {oAtom}");
                                }
                            }
                            Debug.WriteLine($"Added ATOM: {oAtom}");

                            // As HETATMs cannot be considered to either belong to a certain monomer or strand,
                            // they are dealt with separately.
                            #endregion
                        }
                        break;

                        case "HETATM":
                        {
                            #region
                            // read an atom record
                            var oAtom = ReadAtom(cRead, lineLength);
                            oAtom.HetAtom = true;
                            if (isProteinStructure)
                            {
                                oBP.Atoms.Add(oAtom);
                            }
                            else
                            {
                                molecularStructure.Atoms.Add(oAtom);
                            }
                            var isDup = atomNumberMap.ContainsKey(oAtom.Serial.Value);
                            atomNumberMap[oAtom.Serial.Value] = oAtom;
                            if (isDup)
                            {
                                Trace.TraceWarning($"Duplicate serial ID found for atom: {oAtom}");
                            }

                            Debug.WriteLine($"Added HETATM: {oAtom}");
                            #endregion
                        }
                        break;

                        case "TER   ":
                        {
                            #region
                            // start new strand
                            chain++;
                            var oStrand = new PDBStrand
                            {
                                StrandName = chain.ToString(NumberFormatInfo.InvariantInfo)
                            };
                            Debug.WriteLine("Added new STRAND");
                            #endregion
                        }
                        break;

                        case "END   ":
                        {
                            #region
                            atomNumberMap.Clear();
                            if (isProteinStructure)
                            {
                                // create bonds and finish the molecule
                                oSet.Add(oBP);
                                if (useRebondTool.IsSet)
                                {
                                    try
                                    {
                                        if (!CreateBondsWithRebondTool(oBP))
                                        {
                                            // Get rid of all potentially created bonds.
                                            Trace.TraceInformation("Bonds could not be created using the RebondTool when PDB file was read.");
                                            oBP.Bonds.Clear();
                                        }
                                    }
                                    catch (Exception exception)
                                    {
                                        Trace.TraceInformation("Bonds could not be created when PDB file was read.");
                                        Debug.WriteLine(exception);
                                    }
                                }
                            }
                            else
                            {
                                if (useRebondTool.IsSet)
                                {
                                    CreateBondsWithRebondTool(molecularStructure);
                                }
                                oSet.Add(molecularStructure);
                            }
                            #endregion
                        }
                        break;

                        case "MODEL ":
                        {
                            #region
                            // OK, start a new model and save the current one first *if* it contains atoms
                            if (isProteinStructure)
                            {
                                if (oBP.Atoms.Count > 0)
                                {
                                    // save the model
                                    oSet.Add(oBP);
                                    oModel.MoleculeSet = oSet;
                                    oSeq.Add(oModel);
                                    // setup a new one
                                    oBP    = new PDBPolymer();
                                    oModel = oFile.Builder.NewChemModel();
                                    oSet   = oFile.Builder.NewAtomContainerSet();
                                    // avoid duplicate atom warnings
                                    atomNumberMap.Clear();
                                }
                            }
                            else
                            {
                                if (molecularStructure.Atoms.Count > 0)
                                {
                                    // save the model
                                    oSet.Add(molecularStructure);
                                    oModel.MoleculeSet = oSet;
                                    oSeq.Add(oModel);
                                    // setup a new one
                                    molecularStructure = oFile.Builder.NewAtomContainer();
                                    oModel             = oFile.Builder.NewChemModel();
                                    oSet = oFile.Builder.NewAtomContainerSet();
                                }
                            }
                            #endregion
                        }
                        break;

                        case "REMARK":
                        {
                            #region
                            var comment = oFile.GetProperty <string>(CDKPropertyName.Comment, "");
                            if (lineLength > 12)
                            {
                                comment = comment + cRead.Substring(11).Trim()
                                          + "\n";
                                oFile.SetProperty(CDKPropertyName.Comment, comment);
                            }
                            else
                            {
                                Trace.TraceWarning("REMARK line found without any comment!");
                            }
                            #endregion
                        }
                        break;

                        case "COMPND":
                        {
                            #region
                            var title = cRead.Substring(10).Trim();
                            oFile.SetProperty(CDKPropertyName.Title, title);
                            #endregion
                        }
                        break;

                        case "CONECT":
                        {
                            #region
                            // Read connectivity information from CONECT records. Only
                            // covalent bonds are dealt with. Perhaps salt bridges
                            // should be dealt with in the same way..?
                            if (!readConnect.IsSet)
                            {
                                break;
                            }
                            cRead = cRead.Trim();
                            if (cRead.Length < 16)
                            {
                                Debug.WriteLine($"Skipping unexpected empty CONECT line! : {cRead}");
                            }
                            else
                            {
                                int lineIndex      = 6;
                                int atomFromNumber = -1;
                                int atomToNumber   = -1;
                                var molecule       = (isProteinStructure) ? oBP : molecularStructure;
                                while (lineIndex + 5 <= cRead.Length)
                                {
                                    var part = cRead.Substring(lineIndex, 5).Trim();
                                    if (atomFromNumber == -1)
                                    {
                                        try
                                        {
                                            atomFromNumber = int.Parse(part, NumberFormatInfo.InvariantInfo);
                                        }
                                        catch (FormatException)
                                        {
                                        }
                                    }
                                    else
                                    {
                                        try
                                        {
                                            atomToNumber = int.Parse(part, NumberFormatInfo.InvariantInfo);
                                        }
                                        catch (FormatException)
                                        {
                                            atomToNumber = -1;
                                        }
                                        if (atomFromNumber != -1 && atomToNumber != -1)
                                        {
                                            AddBond(molecule, atomFromNumber, atomToNumber);
                                            Debug.WriteLine($"Bonded {atomFromNumber} with {atomToNumber}");
                                        }
                                    }
                                    lineIndex += 5;
                                }
                            }
                            #endregion
                        }
                        break;

                        case "HELIX ":
                        {
                            #region
                            // HELIX    1 H1A CYS A   11  LYS A   18  1 RESIDUE 18 HAS POSITIVE PHI    1D66  72
                            //           1         2         3         4         5         6         7
                            // 01234567890123456789012345678901234567890123456789012345678901234567890123456789
                            var structure = new PDBStructure
                            {
                                StructureType       = PDBStructure.Helix,
                                StartChainID        = cRead[19],
                                StartSequenceNumber = int.Parse(cRead.Substring(21, 4).Trim(), NumberFormatInfo.InvariantInfo),
                                StartInsertionCode  = cRead[25],
                                EndChainID          = cRead[31],
                                EndSequenceNumber   = int.Parse(cRead.Substring(33, 4).Trim(), NumberFormatInfo.InvariantInfo),
                                EndInsertionCode    = cRead[37]
                            };
                            oBP.Add(structure);
                            #endregion
                        }
                        break;

                        case "SHEET ":
                        {
                            #region
                            var structure = new PDBStructure
                            {
                                StructureType       = PDBStructure.Sheet,
                                StartChainID        = cRead[21],
                                StartSequenceNumber = int.Parse(cRead.Substring(22, 4).Trim(), NumberFormatInfo.InvariantInfo),
                                StartInsertionCode  = cRead[26],
                                EndChainID          = cRead[32],
                                EndSequenceNumber   = int.Parse(cRead.Substring(33, 4).Trim(), NumberFormatInfo.InvariantInfo),
                                EndInsertionCode    = cRead[37]
                            };
                            oBP.Add(structure);
                            #endregion
                        }
                        break;

                        case "TURN  ":
                        {
                            #region
                            var structure = new PDBStructure
                            {
                                StructureType       = PDBStructure.Turn,
                                StartChainID        = cRead[19],
                                StartSequenceNumber = int.Parse(cRead.Substring(20, 4).Trim(), NumberFormatInfo.InvariantInfo),
                                StartInsertionCode  = cRead[24],
                                EndChainID          = cRead[30],
                                EndSequenceNumber   = int.Parse(cRead.Substring(31, 4).Trim(), NumberFormatInfo.InvariantInfo),
                                EndInsertionCode    = cRead[35]
                            };
                            oBP.Add(structure);
                            #endregion
                        }
                        break;

                        default:
                            break;      // ignore all other commands
                        }
                    }
                } while (cRead != null);
            }
            catch (Exception e)
            {
                if (e is IOException || e is ArgumentException)
                {
                    Trace.TraceError("Found a problem at line:");
                    Trace.TraceError(cRead);
                    Trace.TraceError("01234567890123456789012345678901234567890123456789012345678901234567890123456789");
                    Trace.TraceError("          1         2         3         4         5         6         7         ");
                    Trace.TraceError($"  error: {e.Message}");
                    Debug.WriteLine(e);
                    Console.Error.WriteLine(e.StackTrace);
                }
                else
                {
                    throw;
                }
            }

            // try to close the Input
            try
            {
                oInput.Close();
            }
            catch (Exception e)
            {
                Debug.WriteLine(e);
            }

            // Set all the dependencies
            oModel.MoleculeSet = oSet;
            oSeq.Add(oModel);
            oFile.Add(oSeq);

            return(oFile);
        }
Example #4
0
        /// <summary> Read a <code>ChemFile</code> from a file in PDB format. The molecules
        /// in the file are stored as <code>BioPolymer</code>s in the
        /// <code>ChemFile</code>. The residues are the monomers of the
        /// <code>BioPolymer</code>, and their names are the concatenation of the
        /// residue, chain id, and the sequence number. Separate chains (denoted by
        /// TER records) are stored as separate <code>BioPolymer</code> molecules.
        ///
        /// <p>Connectivity information is not currently read.
        ///
        /// </summary>
        /// <returns> The ChemFile that was read from the PDB file.
        /// </returns>
        private IChemFile readChemFile(IChemFile oFile)
        {
            int bonds = 0;
            // initialize all containers
            IChemSequence   oSeq   = oFile.Builder.newChemSequence();
            IChemModel      oModel = oFile.Builder.newChemModel();
            ISetOfMolecules oSet   = oFile.Builder.newSetOfMolecules();

            // some variables needed
            string     cCol;
            PDBAtom    oAtom;
            PDBPolymer oBP = new PDBPolymer();

            System.Text.StringBuilder cResidue;
            string   oObj;
            IMonomer oMonomer;
            string   cRead = "";
            char     chain = 'A'; // To ensure stringent name giving of monomers
            IStrand  oStrand;
            int      lineLength = 0;

            atomNumberMap = System.Collections.Hashtable.Synchronized(new System.Collections.Hashtable());

            // do the reading of the Input
            try
            {
                do
                {
                    cRead = _oInput.ReadLine();
                    //logger.debug("Read line: ", cRead);
                    if (cRead != null)
                    {
                        lineLength = cRead.Length;

                        if (lineLength < 80)
                        {
                            //logger.warn("Line is not of the expected length 80!");
                        }

                        // make sure the record name is 6 characters long
                        if (lineLength < 6)
                        {
                            cRead = cRead + "      ";
                        }
                        // check the first column to decide what to do
                        cCol = cRead.Substring(0, (6) - (0));
                        if ("ATOM  ".ToUpper().Equals(cCol.ToUpper()))
                        {
                            // read an atom record
                            oAtom = readAtom(cRead, lineLength);

                            // construct a string describing the residue
                            cResidue = new System.Text.StringBuilder(8);
                            oObj     = oAtom.ResName;
                            if (oObj != null)
                            {
                                cResidue = cResidue.Append(oObj.Trim());
                            }
                            oObj = oAtom.ChainID;
                            if (oObj != null)
                            {
                                // cResidue = cResidue.append(((String)oObj).trim());
                                cResidue = cResidue.Append(System.Convert.ToString(chain));
                            }
                            oObj = oAtom.ResSeq;
                            if (oObj != null)
                            {
                                cResidue = cResidue.Append(oObj.Trim());
                            }

                            // search for an existing strand or create a new one.
                            oStrand = oBP.getStrand(System.Convert.ToString(chain));
                            if (oStrand == null)
                            {
                                oStrand            = new PDBStrand();
                                oStrand.StrandName = System.Convert.ToString(chain);
                            }

                            // search for an existing monomer or create a new one.
                            oMonomer = oBP.getMonomer(cResidue.ToString(), System.Convert.ToString(chain));
                            if (oMonomer == null)
                            {
                                PDBMonomer monomer = new PDBMonomer();
                                monomer.MonomerName = cResidue.ToString();
                                monomer.MonomerType = oAtom.ResName;
                                monomer.ChainID     = oAtom.ChainID;
                                monomer.ICode       = oAtom.ICode;
                                oMonomer            = monomer;
                            }

                            // add the atom
                            oBP.addAtom(oAtom, oMonomer, oStrand);
                            System.Object tempObject;
                            //UPGRADE_WARNING: At least one expression was used more than once in the target code. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1181'"
                            tempObject = atomNumberMap[(System.Int32)oAtom.Serial];
                            atomNumberMap[(System.Int32)oAtom.Serial] = oAtom;
                            if (readConnect.Set && tempObject != null)
                            {
                                //logger.warn("Duplicate serial ID found for atom: ", oAtom);
                            }
                            //						//logger.debug("Added ATOM: ", oAtom);

                            /** As HETATMs cannot be considered to either belong to a certain monomer or strand,
                             * they are dealt with seperately.*/
                        }
                        else if ("HETATM".ToUpper().Equals(cCol.ToUpper()))
                        {
                            // read an atom record
                            oAtom         = readAtom(cRead, lineLength);
                            oAtom.HetAtom = true;
                            oBP.addAtom(oAtom);
                            System.Object tempObject2;
                            //UPGRADE_WARNING: At least one expression was used more than once in the target code. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1181'"
                            tempObject2 = atomNumberMap[(System.Int32)oAtom.Serial];
                            atomNumberMap[(System.Int32)oAtom.Serial] = oAtom;
                            if (tempObject2 != null)
                            {
                                //logger.warn("Duplicate serial ID found for atom: ", oAtom);
                            }
                            //logger.debug("Added HETATM: ", oAtom);
                        }
                        else if ("TER   ".ToUpper().Equals(cCol.ToUpper()))
                        {
                            // start new strand
                            chain++;
                            oStrand            = new PDBStrand();
                            oStrand.StrandName = System.Convert.ToString(chain);
                            //logger.debug("Added new STRAND");
                        }
                        else if ("END   ".ToUpper().Equals(cCol.ToUpper()))
                        {
                            atomNumberMap.Clear();
                            // create bonds and finish the molecule
                            if (deduceBonding.Set)
                            {
                                // OK, try to deduce the bonding patterns
                                if (oBP.AtomCount != 0)
                                {
                                    // Create bonds. If bonds could not be created, all bonds are deleted.
                                    try
                                    {
                                        if (useRebondTool.Set)
                                        {
                                            if (!createBondsWithRebondTool(oBP))
                                            {
                                                // Get rid of all potentially created bonds.
                                                //logger.info("Bonds could not be created using the RebondTool when PDB file was read.");
                                                oBP.removeAllBonds();
                                            }
                                        }
                                        else
                                        {
                                            if (!createBonds(oBP))
                                            {
                                                // Get rid of all potentially created bonds.
                                                //logger.info("Bonds could not be created when PDB file was read.");
                                                oBP.removeAllBonds();
                                            }
                                        }
                                    }
                                    catch (System.Exception exception)
                                    {
                                        //logger.info("Bonds could not be created when PDB file was read.");
                                        //logger.debug(exception);
                                    }
                                }
                            }
                            oSet.addMolecule(oBP);
                            //						oBP = new BioPolymer();
                            //				} else if (cCol.equals("USER  ")) {
                            //						System.out.println(cLine);
                            //					System.out.println(cLine);
                            //				} else if (cCol.equals("ENDMDL")) {
                            //					System.out.println(cLine);
                        }
                        else if (cCol.Equals("MODEL "))
                        {
                            // OK, start a new model and save the current one first *if* it contains atoms
                            if (oBP.AtomCount > 0)
                            {
                                // save the model
                                oSet.addAtomContainer(oBP);
                                oModel.SetOfMolecules = oSet;
                                oSeq.addChemModel(oModel);
                                // setup a new one
                                oBP    = new PDBPolymer();
                                oModel = oFile.Builder.newChemModel();
                                oSet   = oFile.Builder.newSetOfMolecules();
                            }
                        }
                        else if ("REMARK".ToUpper().Equals(cCol.ToUpper()))
                        {
                            System.Object comment = oFile.getProperty(CDKConstants.COMMENT);
                            if (comment == null)
                            {
                                comment = "";
                            }
                            if (lineLength > 12)
                            {
                                //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'"
                                comment = comment.ToString() + cRead.Substring(11).Trim() + "\n";
                                oFile.setProperty(CDKConstants.COMMENT, comment);
                            }
                            else
                            {
                                //logger.warn("REMARK line found without any comment!");
                            }
                        }
                        else if ("COMPND".ToUpper().Equals(cCol.ToUpper()))
                        {
                            string title = cRead.Substring(10).Trim();
                            oFile.setProperty(CDKConstants.TITLE, title);
                        }

                        /*************************************************************
                         * Read connectivity information from CONECT records.
                         * Only covalent bonds are dealt with. Perhaps salt bridges
                         * should be dealt with in the same way..?
                         */
                        else if (readConnect.Set && "CONECT".ToUpper().Equals(cCol.ToUpper()))
                        {
                            cRead.Trim();
                            if (cRead.Length < 16)
                            {
                                //logger.debug("Skipping unexpected empty CONECT line! : ", cRead);
                            }
                            else
                            {
                                string bondAtom   = cRead.Substring(7, 5).Trim();
                                int    bondAtomNo = System.Int32.Parse(bondAtom);

                                for (int b = 0; b < 9; b += (b == 5 ? 2 : 1))
                                {
                                    string bondedAtom = cRead.Substring((b * 5) + 11, 5).Trim();
                                    int    bondedAtomNo;
                                    if (int.TryParse(bondedAtom, out bondedAtomNo))
                                    {
                                        bonds++;
                                        addBond(oBP, bondAtomNo, bondedAtomNo);
                                    }
                                }

                                //string bondedAtom = cRead.Substring(12, 5).Trim();
                                //int bondedAtomNo = -1;

                                //try
                                //{
                                //    bondedAtomNo = System.Int32.Parse(bondedAtom);
                                //}
                                //catch (System.Exception e)
                                //{
                                //    bondedAtomNo = -1;
                                //}

                                //if (bondedAtomNo != -1)
                                //{
                                //    bonds++;
                                //    addBond(oBP, bondAtomNo, bondedAtomNo);
                                //    //logger.warn("Bonded " + bondAtomNo + " with " + bondedAtomNo);
                                //}
                                //else
                                //{
                                //}

                                //if (cRead.Length > 17)
                                //{
                                //    bondedAtom = cRead.Substring(16, 5);
                                //    bondedAtom = bondedAtom.Trim();
                                //    try
                                //    {
                                //        bondedAtomNo = System.Int32.Parse(bondedAtom);
                                //    }
                                //    catch (System.Exception e)
                                //    {
                                //        bondedAtomNo = -1;
                                //    }

                                //    if (bondedAtomNo != -1)
                                //    {
                                //        bonds++;
                                //        addBond(oBP, bondAtomNo, bondedAtomNo);
                                //        //logger.warn("Bonded " + bondAtomNo + " with " + bondedAtomNo);
                                //    }
                                //}

                                //if (cRead.Length > 22)
                                //{
                                //    bondedAtom = cRead.Substring(22, 5);
                                //    bondedAtom = bondedAtom.Trim();
                                //    try
                                //    {
                                //        bondedAtomNo = System.Int32.Parse(bondedAtom);
                                //    }
                                //    catch (System.Exception e)
                                //    {
                                //        bondedAtomNo = -1;
                                //    }

                                //    if (bondedAtomNo != -1)
                                //    {
                                //        bonds++;
                                //        addBond(oBP, bondAtomNo, bondedAtomNo);
                                //        //logger.warn("Bonded " + bondAtomNo + " with " + bondedAtomNo);
                                //    }
                                //}

                                //if (cRead.Length > 27)
                                //{
                                //    bondedAtom = cRead.Substring(27, 5);
                                //    bondedAtom = bondedAtom.Trim();
                                //    try
                                //    {
                                //        bondedAtomNo = System.Int32.Parse(bondedAtom);
                                //    }
                                //    catch (System.Exception e)
                                //    {
                                //        bondedAtomNo = -1;
                                //    }

                                //    if (bondedAtomNo != -1)
                                //    {
                                //        bonds++;
                                //        addBond(oBP, bondAtomNo, bondedAtomNo);
                                //        //logger.warn("Bonded " + bondAtomNo + " with " + bondedAtomNo);
                                //    }
                                //}
                            }
                        }
                        /*************************************************************/
                        else if ("HELIX ".ToUpper().Equals(cCol.ToUpper()))
                        {
                            //						HELIX    1 H1A CYS A   11  LYS A   18  1 RESIDUE 18 HAS POSITIVE PHI    1D66  72
                            //						          1         2         3         4         5         6         7
                            //						01234567890123456789012345678901234567890123456789012345678901234567890123456789
                            PDBStructure structure = new PDBStructure();
                            structure.StructureType       = PDBStructure.HELIX;
                            structure.StartChainID        = cRead[19];
                            structure.StartSequenceNumber = System.Int32.Parse(cRead.Substring(21, (25) - (21)).Trim());
                            structure.StartInsertionCode  = cRead[25];
                            structure.EndChainID          = cRead[31];
                            structure.EndSequenceNumber   = System.Int32.Parse(cRead.Substring(33, (37) - (33)).Trim());
                            structure.EndInsertionCode    = cRead[37];
                            oBP.addStructure(structure);
                        }
                        else if ("SHEET ".ToUpper().Equals(cCol.ToUpper()))
                        {
                            PDBStructure structure = new PDBStructure();
                            structure.StructureType       = PDBStructure.SHEET;
                            structure.StartChainID        = cRead[21];
                            structure.StartSequenceNumber = System.Int32.Parse(cRead.Substring(22, (26) - (22)).Trim());
                            structure.StartInsertionCode  = cRead[26];
                            structure.EndChainID          = cRead[32];
                            structure.EndSequenceNumber   = System.Int32.Parse(cRead.Substring(33, (37) - (33)).Trim());
                            structure.EndInsertionCode    = cRead[37];
                            oBP.addStructure(structure);
                        }
                        else if ("TURN  ".ToUpper().Equals(cCol.ToUpper()))
                        {
                            PDBStructure structure = new PDBStructure();
                            structure.StructureType       = PDBStructure.TURN;
                            structure.StartChainID        = cRead[19];
                            structure.StartSequenceNumber = System.Int32.Parse(cRead.Substring(20, (24) - (20)).Trim());
                            structure.StartInsertionCode  = cRead[24];
                            structure.EndChainID          = cRead[30];
                            structure.EndSequenceNumber   = System.Int32.Parse(cRead.Substring(31, (35) - (31)).Trim());
                            structure.EndInsertionCode    = cRead[35];
                            oBP.addStructure(structure);
                        } // ignore all other commands
                    }
                }while (_oInput.Peek() != -1 && (cRead != null));
            }
            catch (System.Exception e)
            {
                //logger.error("Found a problem at line:\n");
                //logger.error(cRead);
                //logger.error("01234567890123456789012345678901234567890123456789012345678901234567890123456789");
                //logger.error("          1         2         3         4         5         6         7         ");
                //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: " + e.Message);
                //logger.debug(e);
            }

            // try to close the Input
            try
            {
                _oInput.Close();
            }
            catch (System.Exception e)
            {
                //logger.debug(e);
            }

            // Set all the dependencies
            oModel.SetOfMolecules = oSet;
            oSeq.addChemModel(oModel);
            oFile.addChemSequence(oSeq);

            return(oFile);
        }