/// <summary>
        /// Reads a timestep from an .xtc file.
        /// </summary>
        private static PrimaryStructureFrame getFrame(BinaryReader reader)
        {
            PrimaryStructureFrame frame = new PrimaryStructureFrame();

            // Check magic number
            if (getInt32(reader) != magicNumber)
            {
                throw new FileParseException("XTC file not well formed, no magic number in frame header");
            }

            // get timestep header info
            frame.AtomCount = getInt32(reader);
            frame.Step      = getInt32(reader);
            frame.Time      = getFloat32(reader);

            // read and discard the box
            for (int i = 0; i < 9; i++)
            {
                getFloat32(reader);
            }

            // get the coordinates
            float[] coords = new float[3 * frame.AtomCount];
            xtc_3dfcoord(reader, coords);
            frame.Coords = coords;

            return(frame);
        }
        /// <summary>
        /// Returns the number of atoms in the first frame of the trajectory.
        /// </summary>
        /// <param name="filename"></param>
        /// <returns></returns>
        public static int GetAtomCount(string filename)
        {
            StreamReader sr        = null;
            int          atomCount = 0;

            try {
                sr = new StreamReader(filename);

                // discard first frame, which should be the structure
                getFrame(sr);                               // discard frame

                PrimaryStructureFrame frame = getFrame(sr); // get first trajectory frame
                if (frame != null)
                {
                    atomCount = frame.AtomCount;
                }
            }
            catch (Exception e) {
                throw new FileParseException(e.Message);
            }
            finally {
                if (sr != null)
                {
                    sr.Close();
                }
            }

            return(atomCount);
        }
        private static PrimaryStructureFrame getFrame(StreamReader sr)
        {
            PrimaryStructureFrame frame;

            try {
                frame = new PrimaryStructureFrame();

                string titleLine = sr.ReadLine();

                // remove any blank lines before title line
                while (titleLine != null && titleLine.Trim().Equals(""))
                {
                    titleLine = sr.ReadLine();
                }

                if (titleLine == null)   // if we have reached the end of the file
                {
                    return(null);
                }

                frame.Time = 0;

                Regex g = new Regex(@"\st=\s*(\d+\.?\d*)");
                Match m = g.Match(titleLine);
                if (m.Success)
                {
                    string frameTimeString = m.Groups[1].Value;
                    frame.Time = float.Parse(frameTimeString);
                    // Console.WriteLine("Success parsing [" + titleLine + "] for frame time");
                }

                frame.AtomCount = Int32.Parse(sr.ReadLine().Trim());
                float[] coords = new float[3 * frame.AtomCount];

                for (int i = 0; i < frame.AtomCount; i++)
                {
                    string atomLine = sr.ReadLine();
                    if (atomLine == null)   // if something is wrong with the file, i.e. ends before total atom count
                    {
                        throw new FileParseException("Error reading atoms. Frame atom count doesn't equal frame atom total");
                    }

                    coords[3 * i] = float.Parse(atomLine.Substring(20, 8));
                    coords[3 * i] = float.Parse(atomLine.Substring(28, 8));
                    coords[3 * i] = float.Parse(atomLine.Substring(36, 8));
                    frame.Coords  = coords;
                }

                // read box vectors.
                string boxLine = sr.ReadLine();
            }
            catch (Exception e) {
                throw new FileParseException(e.Message);
            }

            return(frame);
        }
        public static PrimaryStructureTrajectory GetTrajectory(string filename, int startFrame, int numFrames, int frameFrequency)
        {
            StreamReader sr = null;
            PrimaryStructureTrajectory trajectory = new PrimaryStructureTrajectory();

            try {
                sr = new StreamReader(filename);

                // discard first frame, which should be the structure
                getFrame(sr); // discard frame

                for (int i = 0; i < startFrame; i++)
                {
                    getFrame(sr); // discard frame
                }

                int framesAdded  = 0;
                int currentFrame = 0;

                while (framesAdded < numFrames)
                {
                    currentFrame++;

                    if (currentFrame % frameFrequency == 0)
                    {
                        PrimaryStructureFrame frame = getFrame(sr);

                        if (frame == null)  // end of file, no more frames in file
                        {
                            break;
                        }

                        trajectory.AddFrame(frame);
                        framesAdded++;
                    }
                    else
                    {
                        PrimaryStructureFrame frame = getFrame(sr); // discard frame
                        if (frame == null)                          // end of file, no more frames in file
                        {
                            break;
                        }
                    }
                }
            }
            catch (Exception e) {
                throw new FileParseException(e.Message);
            }
            finally {
                if (sr != null)
                {
                    sr.Close();
                }
            }

            return(trajectory);
        }
        public static PrimaryStructureTrajectory GetTrajectory(string filename, int startFrame, int numFrames, int frameFrequency)
        {
            PrimaryStructureTrajectory trajectory = new PrimaryStructureTrajectory();
            BinaryReader reader = null;

            try {
                int    frameCount;
                int    atomCount;
                bool   cellInfo;
                string title;

                reader = new BinaryReader(new FileStream(filename, FileMode.Open));
                parseDCDHeader(reader, out frameCount, out atomCount, out cellInfo, out title);

                for (int i = 0; i < startFrame; i++)
                {
                    discardFrame(reader, cellInfo, atomCount);
                }

                int frameIndex   = 0;
                int currentFrame = 0;

                while (reader.BaseStream.Position != reader.BaseStream.Length && frameIndex < numFrames)
                {
                    currentFrame++;

                    if (currentFrame % frameFrequency == 0)
                    {
                        PrimaryStructureFrame frame = new PrimaryStructureFrame();
                        frame.AtomCount = atomCount;
                        //frame.Step = ;
                        //frame.Time = ;

                        parseFrame(reader, cellInfo, frame);
                        trajectory.AddFrame(frame);
                        frameIndex++;
                    }
                    else
                    {
                        discardFrame(reader, cellInfo, atomCount);
                    }
                }
            }
            catch (Exception e) {
                throw new FileParseException(e.Message);
            }
            finally {
                if (reader != null)
                {
                    reader.Close();
                }
            }

            return(trajectory);
        }
        private static void parseFrame(BinaryReader reader, bool cellInfo, PrimaryStructureFrame frame)
        {
            // discard cell information if present

            if (cellInfo)
            {
                int cellInfoLength = reader.ReadInt32();
                reader.ReadBytes(cellInfoLength);
                reader.ReadInt32(); // discard end of index array length
            }

            float[] coords = new float[3 * frame.AtomCount];

            reader.ReadInt32(); // discard block size

            for (int i = 0; i < frame.AtomCount; i++)
            {
                coords[3 * i] = (float)Math.Round((decimal)(reader.ReadSingle() / 10f), 3);
            }

            reader.ReadInt32(); // discard block size
            reader.ReadInt32(); // discard block size

            for (int i = 0; i < frame.AtomCount; i++)
            {
                coords[3 * i + 1] = (float)Math.Round((decimal)(reader.ReadSingle() / 10f), 3);
            }

            reader.ReadInt32(); // discard block size
            reader.ReadInt32(); // discard block size

            for (int i = 0; i < frame.AtomCount; i++)
            {
                byte[] input = reader.ReadBytes(4);
                float  num   = System.BitConverter.ToSingle(input, 0);
                if (num < 0)
                {
                    // Console.WriteLine("Negative number: " + num);
                }
                coords[3 * i + 2] = (float)Math.Round((decimal)(num / 10f), 3);
            }

            reader.ReadInt32(); // discard block size

            frame.Coords = coords;
        }
        private static void discardFrame(BinaryReader reader)
        {
            PrimaryStructureFrame frame = new PrimaryStructureFrame();

            // Check magic number
            if (getInt32(reader) != magicNumber)
            {
                throw new FileParseException("XTC file not well formed, no magic number in frame header");
            }

            // discard 12 frame metadata fields
            reader.BaseStream.Seek(12 * 4, SeekOrigin.Current);

            // discard the coordinates metadata & data

            int lsize = getInt32(reader);

            if (lsize <= 9)
            {
                reader.BaseStream.Seek(lsize * 3 * 4, SeekOrigin.Current);
                return;
            }
            else
            {
                // discard 7 coord metadata fields
                reader.BaseStream.Seek(8 * 4, SeekOrigin.Current);

                // get length of coord data
                int len = getInt32(reader);
                if (len < 1)
                {
                    throw new FileParseException("Error reading coordinates");
                }

                // discard coordinate data
                reader.BaseStream.Seek(len, SeekOrigin.Current);

                // round out byte read to nearest 4 bytes
                if (len % 4 != 0)
                {
                    reader.BaseStream.Seek(4 - (len % 4), SeekOrigin.Current);
                }
            }
        }
        public override string ToString()
        {
            string output = "";

            if (frames != null)
            {
                for (int i = 0; i < frames.Count; i++)
                {
                    if (i > 10)
                    {
                        break;
                    }
                    output += "Frame[" + (i + 1) + "]\n";

                    PrimaryStructureFrame frame = frames[i];
                    int totalCoords             = 0;

                    for (int j = 0; j < frame.AtomCount; j++)
                    {
                        if (j > 10)
                        {
                            break;
                        }

                        float x = frame.Coords[j * 3];
                        float y = frame.Coords[j * 3 + 1];
                        float z = frame.Coords[j * 3 + 2];

                        output += "Time [" + frame.Time + "] Coords[" + j + "]: [" + x + ", " + y + ", " + z + "]\n";
                        totalCoords++;
                    }

                    output += "\n";
                }
            }
            else
            {
                output = "No frames in trajectory";
            }

            return(output);
        }
        /// <summary>
        /// Returns the number of atoms in the first frame of the trajectory file.
        /// </summary>
        /// <param name="filename"></param>
        /// <returns></returns>
        public static int GetAtomCount(string filename)
        {
            BinaryReader reader = null;
            int          count  = 0;

            try {
                reader = new BinaryReader(new FileStream(filename, FileMode.Open));
                PrimaryStructureFrame frame = getFrame(reader);
                count = frame.Coords.Length / 3;
            }
            catch (Exception e) {
                throw new FileParseException(e.Message);
            }
            finally {
                if (reader != null)
                {
                    reader.Close();
                }
            }

            return(count);
        }
Exemplo n.º 10
0
 public PDBStructureCreator(PrimaryStructure structure, PrimaryStructureFrame frame)
 {
     this.structure = structure;
     this.frame     = frame;
 }
        /// <summary>
        /// generate a box from a provided Primary Structure
        /// </summary>
        /// <returns></returns>
        public BoundingBox(PrimaryStructureFrame frame, bool flipZ = false)
        {
            float minx = 0;
            float maxx = 0;
            float miny = 0;
            float maxy = 0;
            float minz = 0;
            float maxz = 0;

            if (frame.Coords.Length <= 0)
            {
                return;
            }

            // foreach (KeyValuePair<int, Atom> atom in structure.Atoms()) {
            for (int i = 0; i < frame.AtomCount; i++)
            {
                float[] coords = frame.GetAtomCoords(i);

                if (i == 0)
                {
                    minx = coords[0];
                    maxx = coords[0];
                    miny = coords[1];
                    maxy = coords[1];
                    minz = coords[2];
                    maxz = coords[2];
                }
                else
                {
                    if (coords[0] < minx)
                    {
                        minx = coords[0];
                    }
                    if (coords[0] > maxx)
                    {
                        maxx = coords[0];
                    }

                    if (coords[1] < miny)
                    {
                        miny = coords[1];
                    }
                    if (coords[1] > maxy)
                    {
                        maxy = coords[1];
                    }

                    if (coords[2] < minz)
                    {
                        minz = coords[2];
                    }
                    if (coords[2] > maxz)
                    {
                        maxz = coords[2];
                    }
                }
            }

            float edgeBuffer = 0.1f;

            minx -= edgeBuffer;
            maxx += edgeBuffer;
            miny -= edgeBuffer;
            maxy += edgeBuffer;
            minz -= edgeBuffer;
            maxz += edgeBuffer;

            if (flipZ)
            {
                minz *= -1;
                maxz *= -1;
            }

            setVectors(minx, maxx, miny, maxy, minz, maxz);
        }
 public void AddFrame(PrimaryStructureFrame frame)
 {
     frames.Add(frame);
 }
Exemplo n.º 13
0
        public static void GetTrajectoryColours(string filename, PrimaryStructure model, PrimaryStructureTrajectory trajectory, int startFrame, int numFrames, int frameFrequency)
        {
            Stopwatch watch = new Stopwatch();

            watch.Start();

            StreamReader reader = null;
            Regex        g      = new Regex(@"\s*(\d+)\s*(\d+\.?\d*)");

            try {
                reader = new StreamReader(filename);

                discardFrames(reader, startFrame);

                List <float[]> colourFrames      = new List <float[]>();
                int            colourFrameNumber = -1;

                int     atomIndex   = 0;
                float   colour      = 0;
                float[] colourFrame = null;
                string  line;

                while ((line = readLine(reader)) != null && colourFrames.Count < numFrames)
                {
                    if (line.Trim().Length == 0)   // is empty string?
                    {
                        continue;
                    }

                    // discard everything but matches
                    Match m = g.Match(line);
                    if (m.Success)
                    {
                        atomIndex = int.Parse(m.Groups[1].Value);
                        colour    = float.Parse(m.Groups[2].Value);

                        if (atomIndex == 1)
                        {
                            colourFrameNumber++;

                            // save colours
                            if (colourFrame != null)
                            {
                                colourFrames.Add(colourFrame);
                                colourFrame = null;
                            }

                            if (colourFrameNumber % frameFrequency == 0)
                            {
                                // initialise new colour arrary
                                colourFrame = new float[model.AtomCount()];
                                for (int i = 0; i < colourFrame.Length; i++)
                                {
                                    colourFrame[i] = DEFAULT_COLOUR_VALUE;
                                }
                            }
                        }

                        if (colourFrame != null)
                        {
                            if (atomIndex > 0 && atomIndex <= colourFrame.Length)
                            {
                                colourFrame[atomIndex - 1] = colour;
                            }
                        }
                    }
                }

                PrimaryStructureFrame currentFrame = null;
                int frameNumber = 0;

                // copy all colour frames to trajectory frames
                foreach (float[] frame in colourFrames)
                {
                    currentFrame         = trajectory.GetFrame(frameNumber);
                    currentFrame.Colours = frame;
                    frameNumber++;

                    // if we've run out of trajectory frames then stop copying
                    if (frameNumber >= trajectory.FrameCount())
                    {
                        break;
                    }
                }

                // if more trajectory frames than colour frames fill in rest of trajectory frames with default colours
                float[] colours = new float[model.AtomCount()];
                for (int i = 0; i < colours.Length; i++)
                {
                    colours[i] = 0f;
                }

                foreach (PrimaryStructureFrame frame in trajectory.GetFrames())
                {
                    if (frame.Colours == null)
                    {
                        frame.Colours = colours;
                    }
                }
            }
            catch (Exception e) {
                throw new FileParseException(e.Message);
            }
            finally {
                if (reader != null)
                {
                    reader.Close();
                }
            }
        }