Example #1
0
        /// <summary>
        /// Parses specified BAM file using index file.
        /// Index file is assumed to be in the same location as that of the specified bam file with the name "filename".bai
        /// For example, if the specified bam file name is D:\BAMdata\sample.bam then index file name will be taken as D:\BAMdata\sample.bam.bai
        /// If index file is not available then this method throw an exception.
        /// </summary>
        /// <param name="parser">BAM parser</param>
        /// <param name="fileName">BAM file name.</param>
        /// <param name="refSeqName">Name of reference sequence.</param>
        /// <returns>SequenceAlignmentMap object which contains alignments for specified reference sequence.</returns>
        public static SequenceAlignmentMap ParseRange(this BAMParser parser, string fileName, string refSeqName)
        {
            if (parser == null)
            {
                throw new ArgumentNullException("parser");
            }

            if (string.IsNullOrWhiteSpace(fileName))
            {
                throw new ArgumentNullException("fileName");
            }

            if (refSeqName == null)
            {
                throw new ArgumentNullException("refSeqName");
            }

            using (var bamStream = File.OpenRead(fileName))
            {
                string bamIndexFileName = GetBAMIndexFileName(fileName);
                using (FileStream bamIndexFile = File.OpenRead(bamIndexFileName))
                using (var bamIndexStorage = new BAMIndexStorage(bamIndexFile))
                {
                    return parser.GetAlignment(bamStream, bamIndexStorage, refSeqName);
                }
            }
        }
Example #2
0
        /// <summary>
        /// Parses specified BAM file using index file.
        /// Index file is assumed to be in the same location as that of the specified bam file with the name "filename".bai
        /// For example, if the specified bam file name is D:\BAMdata\sample.bam then index file name will be taken as D:\BAMdata\sample.bam.bai
        /// If index file is not available then this method throw an exception.
        /// </summary>
        /// <param name="parser">BAM parser</param>
        /// <param name="fileName">BAM file name.</param>
        /// <param name="refSeqName">Name of reference sequence.</param>
        /// <returns>SequenceAlignmentMap object which contains alignments for specified reference sequence.</returns>
        public static SequenceAlignmentMap ParseRange(this BAMParser parser, string fileName, string refSeqName)
        {
            if (parser == null)
            {
                throw new ArgumentNullException("parser");
            }

            if (string.IsNullOrWhiteSpace(fileName))
            {
                throw new ArgumentNullException("fileName");
            }

            if (refSeqName == null)
            {
                throw new ArgumentNullException("refSeqName");
            }

            using (var bamStream = File.OpenRead(fileName))
            {
                string bamIndexFileName = GetBAMIndexFileName(fileName);
                using (FileStream bamIndexFile = File.OpenRead(bamIndexFileName))
                    using (var bamIndexStorage = new BAMIndexStorage(bamIndexFile))
                    {
                        return(parser.GetAlignment(bamStream, bamIndexStorage, refSeqName));
                    }
            }
        }
Example #3
0
        /// <summary>
        /// Creates BAMIndex object from the specified BAM file and writes to specified BAMIndex file.
        /// </summary>
        /// <param name="compressedBAMStream"></param>
        /// <param name="indexStorage"></param>
        private static void CreateBAMIndexFile(Stream compressedBAMStream, BAMIndexStorage indexStorage)
        {
            var      parser   = new BAMParser();
            BAMIndex bamIndex = parser.GetIndexFromBAMStorage(compressedBAMStream);

            indexStorage.Write(bamIndex);
        }
Example #4
0
        /// <summary>
        /// Write out the given SequenceAlignmentMap to the file
        /// </summary>
        /// <param name="formatter">BAMFormatter</param>
        /// <param name="sam">SequenceAlignmentMap</param>
        /// <param name="filename">File to write to</param>
        /// <param name="indexFilename">BAM index file</param>
        public static void Format(this BAMFormatter formatter, ISequenceAlignment sam, string filename, string indexFilename)
        {
            if (formatter == null)
            {
                throw new ArgumentNullException("formatter");
            }
            if (sam == null)
            {
                throw new ArgumentNullException("sam");
            }
            if (string.IsNullOrWhiteSpace(filename))
            {
                throw new ArgumentNullException("filename");
            }
            if (string.IsNullOrWhiteSpace(indexFilename))
            {
                throw new ArgumentNullException("indexFilename");
            }

            if (filename == indexFilename)
            {
                throw new ArgumentException("Use different filenames for index and alignment.", "indexFilename");
            }

            using (var fs = File.Create(filename))
            using (var bamIndexFile = new BAMIndexStorage(File.Create(indexFilename)))
            {
                formatter.Format(fs, bamIndexFile, sam);
            }
        }
Example #5
0
        /// <summary>
        /// Write out the given SequenceAlignmentMap to the file
        /// </summary>
        /// <param name="formatter">BAMFormatter</param>
        /// <param name="sam">SequenceAlignmentMap</param>
        /// <param name="filename">File to write to</param>
        public static void Format(this BAMFormatter formatter, SequenceAlignmentMap sam, string filename)
        {
            if (formatter == null)
            {
                throw new ArgumentNullException("formatter");
            }
            if (sam == null)
            {
                throw new ArgumentNullException("sam");
            }
            if (string.IsNullOrWhiteSpace(filename))
            {
                throw new ArgumentNullException("filename");
            }

            using (var fs = File.Create(filename))
            {
                // Create the IndexFile if necessary
                if (formatter.CreateIndexFile)
                {
                    using (var bamIndexFile = new BAMIndexStorage(
                        File.Create(filename + Properties.Resource.BAM_INDEXFILEEXTENSION)))
                    {
                        formatter.Format(fs, bamIndexFile, sam);
                    }
                }
                else
                {
                    formatter.Format(fs, sam);
                }
            }
        }
Example #6
0
        /// <summary>
        /// Write out the given SequenceAlignmentMap to the file
        /// </summary>
        /// <param name="formatter">BAMFormatter</param>
        /// <param name="sam">SequenceAlignmentMap</param>
        /// <param name="filename">File to write to</param>
        public static void Format(this BAMFormatter formatter, SequenceAlignmentMap sam, string filename)
        {
            if (formatter == null)
            {
                throw new ArgumentNullException("formatter");
            }
            if (sam == null)
            {
                throw new ArgumentNullException("sam");
            }
            if (string.IsNullOrWhiteSpace(filename))
            {
                throw new ArgumentNullException("filename");
            }

            using (var fs = File.Create(filename))
            {
                // Create the IndexFile if necessary
                if (formatter.CreateIndexFile)
                {
                    using (var bamIndexFile = new BAMIndexStorage(
                               File.Create(filename + Properties.Resource.BAM_INDEXFILEEXTENSION)))
                    {
                        formatter.Format(fs, bamIndexFile, sam);
                    }
                }
                else
                {
                    formatter.Format(fs, sam);
                }
            }
        }
Example #7
0
        /// <summary>
        /// Write out the given SequenceAlignmentMap to the file
        /// </summary>
        /// <param name="formatter">BAMFormatter</param>
        /// <param name="sam">SequenceAlignmentMap</param>
        /// <param name="filename">File to write to</param>
        /// <param name="indexFilename">BAM index file</param>
        public static void Format(this BAMFormatter formatter, ISequenceAlignment sam, string filename, string indexFilename)
        {
            if (formatter == null)
            {
                throw new ArgumentNullException("formatter");
            }
            if (sam == null)
            {
                throw new ArgumentNullException("sam");
            }
            if (string.IsNullOrWhiteSpace(filename))
            {
                throw new ArgumentNullException("filename");
            }
            if (string.IsNullOrWhiteSpace(indexFilename))
            {
                throw new ArgumentNullException("indexFilename");
            }

            if (filename == indexFilename)
            {
                throw new ArgumentException("Use different filenames for index and alignment.", "indexFilename");
            }

            using (var fs = File.Create(filename))
                using (var bamIndexFile = new BAMIndexStorage(File.Create(indexFilename)))
                {
                    formatter.Format(fs, bamIndexFile, sam);
                }
        }
Example #8
0
 static void CreateBAMIndexFile(string bamFileName, string indexFileName)
 {
     using (var bamStream = File.OpenRead(bamFileName))
     using (var indexStream = File.Create(indexFileName))
     using (var indexStorage = new BAMIndexStorage(indexStream))
     {
         BAMIndex indexFromBamStorage = new BAMParser().GetIndexFromBAMStorage(bamStream);
         indexStorage.Write(indexFromBamStorage);
     }
 }
Example #9
0
            internal LinearIndexArrayMaker(int refSeqLength)
            {
                int size;

                if (refSeqLength <= 0)
                {
                    size = BAMIndexStorage.MaxLinerindexArraySize;
                }
                else
                {
                    size = BAMIndexStorage.LargestBinPossibleForSequenceLength(refSeqLength);
                }
                //TODO: Plus one now because weird things could happen with alignment length such that the bin is one higher
                //never seen this, but not sure it can't happen.
                offSetArray = new FileOffset[size + 1];
            }
Example #10
0
        /// <summary>
        /// Writes specified alignment object to a stream.
        /// The output is formatted according to the BAM specification.
        /// </summary>
        /// <param name="writer">Stream to write BAM data.</param>
        /// <param name="indexWriter">BAMIndexFile to write index data.</param>
        /// <param name="sequenceAlignment">SequenceAlignmentMap object.</param>
        public void Format(Stream writer, BAMIndexStorage indexWriter, ISequenceAlignment sequenceAlignment)
        {
            if (sequenceAlignment == null)
            {
                throw new ArgumentNullException("sequenceAlignment");
            }

            if (writer == null)
            {
                throw new ArgumentNullException("writer");
            }

            if (indexWriter == null)
            {
                throw new ArgumentNullException("indexWriter");
            }

            WriteSequenceAlignment(sequenceAlignment, writer, indexWriter);
        }
Example #11
0
        /// <summary>
        /// Parses specified BAM file using index file.
        /// </summary>
        /// <param name="parser">BAM parser</param>
        /// <param name="fileName">BAM file name.</param>
        /// <param name="range">SequenceRange object which contains reference sequence name and start and end co-ordinates.</param>
        /// <returns>SequenceAlignmentMap object which contains alignments for specified reference sequence and for specified range.</returns>
        public static SequenceAlignmentMap ParseRange(this BAMParser parser, string fileName, SequenceRange range)
        {
            if (parser == null)
            {
                throw new ArgumentNullException("parser");
            }

            if (string.IsNullOrWhiteSpace(fileName))
            {
                throw new ArgumentNullException("fileName");
            }

            if (range == null)
            {
                throw new ArgumentNullException("range");
            }

            if (string.IsNullOrEmpty(range.ID))
            {
                throw new ArgumentException("Reference sequence name (range.ID) can't empty or null.");
            }

            int start = range.Start >= int.MaxValue ? int.MaxValue : (int)range.Start;
            int end   = range.End >= int.MaxValue ? int.MaxValue : (int)range.End;

            using (FileStream bamStream = File.OpenRead(fileName))
            {
                string bamIndexFileName = GetBAMIndexFileName(fileName);
                using (FileStream bamIndexFile = File.OpenRead(bamIndexFileName))
                    using (BAMIndexStorage bamIndexStorage = new BAMIndexStorage(bamIndexFile))
                    {
                        if (start == 0 && end == int.MaxValue)
                        {
                            return(parser.GetAlignment(bamStream, bamIndexStorage, range.ID));
                        }
                        return(parser.GetAlignment(bamStream, bamIndexStorage, range.ID, start, end));
                    }
            }
        }
Example #12
0
        /// <summary>
        /// Writes specified alignment object to a stream.
        /// The output is formatted according to the BAM specification.
        /// </summary>
        /// <param name="writer">Stream to write BAM data.</param>
        /// <param name="indexWriter">BAMIndexFile to write index data.</param>
        /// <param name="sequenceAlignment">SequenceAlignmentMap object.</param>
        public void Format(Stream writer, BAMIndexStorage indexWriter, ISequenceAlignment sequenceAlignment)
        {
            if (sequenceAlignment == null)
            {
                throw new ArgumentNullException("sequenceAlignment");
            }

            if (writer == null)
            {
                throw new ArgumentNullException("writer");
            }

            if (indexWriter == null)
            {
                throw new ArgumentNullException("indexWriter");
            }

            WriteSequenceAlignment(sequenceAlignment, writer, indexWriter);
        }
Example #13
0
        /// <summary>
        /// Format BAM file and validate.
        /// </summary>
        /// <param name="nodeName">Different xml nodes used for different test cases</param>
        /// <param name="BAMParserPam">BAM Format method parameters</param>
        void ValidateBAMFormatter(string nodeName,
             BAMParserParameters BAMParserPam)
        {
            // Get input and output values from xml node.
            string BAMStoragePath = this.utilityObj.xmlUtil.GetTextValue(nodeName,
                Constants.FilePathNode);
            string expectedAlignedSeqFilePath = this.utilityObj.xmlUtil.GetTextValue(
                nodeName, Constants.ExpectedSequence);
            string alignedSeqCount = this.utilityObj.xmlUtil.GetTextValue(
                nodeName, Constants.AlignedSeqCountNode);

            SequenceAlignmentMap seqAlignment = null;

            try {
            using (BAMIndexStorage BAMIndexStorageObj = new BAMIndexStorage(
                File.Create(Constants.BAMTempIndexFileForIndexData)))
                {
                    // Parse a BAM file.
                    BAMParser bamParserObj = new BAMParser();
                    seqAlignment = bamParserObj.ParseOne<SequenceAlignmentMap>(BAMStoragePath);

                    // Create a BAM formatter object.
                    BAMFormatter formatterObj = new BAMFormatter();

                    // Write/Format aligned sequences to BAM file.
                    switch (BAMParserPam)
                    {
                        case BAMParserParameters.StreamAndIndexFile:
                            using (Stream stream = new FileStream(Constants.BAMTempFileName,
                                FileMode.Create, FileAccess.ReadWrite))
                            {
                                formatterObj.Format(stream, BAMIndexStorageObj, seqAlignment);
                            }
                            break;
                        default:
                            break;
                    }

                    // Parse formatted BAM file and validate aligned sequences.
                    SequenceAlignmentMap expectedSeqAlignmentMap = bamParserObj.ParseOne<SequenceAlignmentMap>(
                        Constants.BAMTempFileName);

                    // Validate Parsed BAM file Header record fields.
                    this.ValidateBAMHeaderRecords(nodeName, expectedSeqAlignmentMap);

                    IList<SAMAlignedSequence> alignedSeqs = expectedSeqAlignmentMap.QuerySequences;

                    Assert.AreEqual(alignedSeqCount, alignedSeqs.Count.ToString((IFormatProvider)null));

                    // Get expected sequences
                    FastAParser parserObj = new FastAParser();
                    IEnumerable<ISequence> expectedSequences = parserObj.Parse(expectedAlignedSeqFilePath);
                    IList<ISequence> expectedSequencesList = expectedSequences.ToList();

                    // Validate aligned sequences from BAM file.
                    for (int index = 0; index < alignedSeqs.Count; index++)
                    {
                        Assert.AreEqual(new string(expectedSequencesList[index].Select(a => (char)a).ToArray()),
                            new string(alignedSeqs[index].QuerySequence.Select(a => (char)a).ToArray()));

                        // Log to VSTest GUI.
                        ApplicationLog.WriteLine(string.Format((IFormatProvider)null,
                            "BAM Formatter P1 : Validated Aligned sequence :{0} successfully",
                            alignedSeqs[index].QuerySequence.ToString()));
                    }
                }
            }
            finally 
            {
                File.Delete(Constants.BAMTempFileName);
                File.Delete(Constants.BAMTempIndexFile);
            }
        }
Example #14
0
        public void ValidateBAMIndexMatchesExpectation()
        {
            // Get input and output values from xml node.
            string BAMStoragePath = this.utilityObj.xmlUtil.GetTextValue(
                Constants.BAMHumanLargeNode, Constants.FilePathNode);
            string expectedIndexPath= this.utilityObj.xmlUtil.GetTextValue(
                Constants.BAMHumanLargeNode, Constants.BAMIndexFileNode);
            var bp = new BAMParser();
            //get observed index file
            BAMIndex bi;
            using (Stream bamStream = new FileStream(BAMStoragePath, FileMode.Open, FileAccess.Read))
            {
               bi = bp.GetIndexFromBAMStorage(bamStream);
            }
            //get expected
            var bi2 = new BAMIndexStorage(File.OpenRead(expectedIndexPath)).Read();
            //now verify
            Assert.AreEqual(bi2.RefIndexes.Count, bi.RefIndexes.Count);
            for (int i = 0; i < bi.RefIndexes.Count; i++)
            {
                var obs = bi.RefIndexes[i];
                var exp = bi2.RefIndexes[i];
                Assert.AreEqual(obs.Bins.Count, exp.Bins.Count);
                Assert.AreEqual(obs.LinearIndex.Count, exp.LinearIndex.Count);
                Assert.AreEqual(obs.MappedReadsCount, exp.MappedReadsCount);
                Assert.AreEqual(obs.UnMappedReadsCount, exp.UnMappedReadsCount);
                var ob = obs.Bins.ToList();
                var eb = exp.Bins.ToList();
                ob.Sort((x, y) => x.BinNumber.CompareTo(y.BinNumber));
                eb.Sort((x, y) => x.BinNumber.CompareTo(y.BinNumber));
                for (int j = 0; j < ob.Count; j++)
                {
                    var obb=ob[0];
                    var ebb=eb[0];
                    Assert.AreEqual(obb.BinNumber, ebb.BinNumber);
                    Assert.AreEqual(obb.Chunks.Count, ebb.Chunks.Count);
                    var c1 = obb.Chunks.ToList();
                    var c2 = ebb.Chunks.ToList();
                    c1.Sort((x, y) => x.ChunkStart.CompareTo(y.ChunkStart));
                    c2.Sort((x, y) => x.ChunkStart.CompareTo(y.ChunkStart));

                    for (int k = 0; k < c1.Count; k++)
                    {
                        var co = c1[k];
                        var eo = c2[k];
                        Assert.AreEqual(eo.ChunkStart, co.ChunkStart);
                        Assert.AreEqual(eo.ChunkEnd, co.ChunkEnd);


                    }
                }


            }
        }
Example #15
0
        /// <summary>
        /// Writes sequence alignment to specified stream.
        /// </summary>
        /// <param name="sequenceAlignment">Sequence alignment object</param>
        /// <param name="writer">Stream to write.</param>
        /// <param name="indexStorage">BAMIndex file.</param>
        private void WriteSequenceAlignment(ISequenceAlignment sequenceAlignment, Stream writer, BAMIndexStorage indexStorage)
        {
            // validate sequenceAlignment.
            SequenceAlignmentMap sequenceAlignmentMap = ValidateAlignment(sequenceAlignment);

            // write bam struct to temp file.
            using (var fstemp = PlatformManager.Services.CreateTempStream())
            {
                WriteUncompressed(sequenceAlignmentMap, fstemp, CreateSortedBAMFile);

                fstemp.Seek(0, SeekOrigin.Begin);

                // Compress and write to the specified stream.
                CompressBAMFile(fstemp, writer);
            }

            // if index file need to be created.
            if (indexStorage != null)
            {
                writer.Seek(0, SeekOrigin.Begin);
                CreateBAMIndexFile(writer, indexStorage);
            }
        }
Example #16
0
        /// <summary>
        /// Format BAM file using IsequenceAlignment object.
        /// </summary>
        /// <param name="nodeName">Different xml nodes used for different test cases</param>
        /// <param name="BAMParserPam">BAM Format method parameters</param>
        /// <param name="WriteBAMIndexData">True if writting BAM index data to BAMIndex file,
        /// false otherwise</param>
        /// <param name="IsNotSupportedMethods">True if validating notsuportedMethods,
        /// false otherwise</param>
        void ValidateBAMFormatterWithSequenceAlignment(string nodeName,
            BAMParserParameters BAMParserPam, bool WriteBAMIndexData,
            bool IsNotSupportedMethods)
        {
            // Get input and output values from xml node.
            string BAMStoragePath = this.utilityObj.xmlUtil.GetTextValue(nodeName,
                Constants.FilePathNode);
            string expectedAlignedSeqFilePath = this.utilityObj.xmlUtil.GetTextValue(
                nodeName, Constants.ExpectedSequence);
            string alignedSeqCount = this.utilityObj.xmlUtil.GetTextValue(
                nodeName, Constants.AlignedSeqCountNode);

            BAMIndexStorage BAMIndexStorageObj = null;
            ISequenceAlignmentParser bamParserObj = new BAMParser();
            try
            {
                using (BAMParser bamSeqMapParserObj = new BAMParser())
                {
                    IEnumerable<ISequenceAlignment> seqList = bamParserObj.Parse(BAMStoragePath);

                    try
                    {
                        // Write BAm index data to BAM Index File.
                        if (WriteBAMIndexData)
                        {
                            BAMIndexStorageObj = new BAMIndexStorage(
                                File.Create(Constants.BAMTempIndexFileForSequenceAlignment));
                        }

                        // Create a BAM formatter object.
                        BAMFormatter formatterObj = new BAMFormatter
                                                    {
                                                        CreateSortedBAMFile = true,
                                                        CreateIndexFile = true
                                                    };
                        // Write/Format aligned sequences to BAM file.
                        switch (BAMParserPam)
                        {
                            case BAMParserParameters.StreamWriter:
                                try
                                {
                                    using (var writer = File.Create(Constants.BAMTempFileName))
                                    {
                                        foreach (ISequenceAlignment seq in seqList)
                                        {
                                            formatterObj.Format(writer, seq);
                                            Assert.Fail();
                                        }
                                    }
                                }
                                catch (NotSupportedException ex)
                                {
                                    string message = ex.Message;
                                    ApplicationLog.WriteLine(string.Format((IFormatProvider)null,
                                        "BAM Formatter P1 : Validated the exception {0} successfully"
                                        , message));
                                }
                                break;
                            case BAMParserParameters.Stream:
                                using (Stream stream = new
                                     FileStream(Constants.BAMTempFileName,
                                     FileMode.OpenOrCreate, FileAccess.ReadWrite))
                                {
                                    foreach (ISequenceAlignment seq in seqList)
                                    {
                                        formatterObj.Format(stream, seq);
                                    }
                                }
                                File.Exists(Constants.BAMTempFileName);
                                break;
                            case BAMParserParameters.FileName:
                                foreach (ISequenceAlignment seq in seqList)
                                {
                                    formatterObj.Format(seq, Constants.BAMTempFileName);
                                }
                                File.Exists(Constants.BAMTempFileName);
                                break;
                            case BAMParserParameters.StreamAndIndexFile:
                                using (Stream stream = new
                                     FileStream(Constants.BAMTempFileName,
                                     FileMode.Create, FileAccess.ReadWrite))
                                {
                                    foreach (ISequenceAlignment seq in seqList)
                                    {
                                        formatterObj.Format(stream, BAMIndexStorageObj, seq);
                                    }
                                }
                                File.Exists(Constants.BAMTempFileName);
                                break;
                            case BAMParserParameters.IndexFile:
                                foreach (ISequenceAlignment seq in seqList)
                                {
                                    formatterObj.Format(seq, Constants.BAMTempFileName,
                                        Constants.BAMTempIndexFile);
                                }
                                File.Exists(Constants.BAMTempFileName);
                                break;
                            default:
                                break;
                        }

                        if (!IsNotSupportedMethods)
                        {
                            // Parse formatted BAM file and validate aligned sequences.
                            SequenceAlignmentMap expectedSeqAlignmentMap = bamSeqMapParserObj.ParseOne<SequenceAlignmentMap>(
                                Constants.BAMTempFileName);

                            IList<SAMAlignedSequence> alignedSeqs = expectedSeqAlignmentMap.QuerySequences;

                            Assert.AreEqual(alignedSeqCount, alignedSeqs.Count.ToString((IFormatProvider)null));

                            // Get expected sequences
                            FastAParser parserObj = new FastAParser();
                            IEnumerable<ISequence> expectedSequences = parserObj.Parse(expectedAlignedSeqFilePath);
                            IList<ISequence> expectedSequencesList = expectedSequences.ToList();
                            // Validate aligned sequences from BAM file.
                            for (int index = 0; index < alignedSeqs.Count; index++)
                            {
                                Assert.AreEqual(new string(expectedSequencesList[index].Select(a => (char)a).ToArray()),
                                        new string(alignedSeqs[index].QuerySequence.Select(a => (char)a).ToArray()));

                                // Log to VSTest GUI.
                                ApplicationLog.WriteLine(string.Format((IFormatProvider)null,
                                    "BAM Formatter P1 : Validated Aligned sequence :{0} successfully",
                                    alignedSeqs[index].QuerySequence.ToString()));
                            }
                        }
                    }
                    finally
                    {
                        if (BAMIndexStorageObj != null)
                            BAMIndexStorageObj.Dispose();
                    }
                }
            }
            finally
            {
                (bamParserObj as BAMParser).Dispose();
                File.Delete(Constants.BAMTempFileName);
                File.Delete(Constants.BAMTempIndexFile);
            }
        }
Example #17
0
        public void InvalidateBAMIndexStorage()
        {
            //set source stream as null            
            try
            {
                var biFile = new BAMIndexStorage(null);
                Assert.Fail();
            }
            catch (ArgumentNullException ex)
            {
                ApplicationLog.Write("BAM P2 : Successfully caught ArgumentNullException : " + ex.Message);
            }

            try
            {
                string temp = null;
                using (var biFile = new BAMIndexStorage(File.Create(temp)))
                {
                    Assert.Fail();
                }
            }
            catch (ArgumentNullException ex)
            {
                ApplicationLog.Write("BAM P2 : Successfully caught ArgumentNullException : " + ex.Message);
            }
        }
Example #18
0
        /// <summary>
        /// Parses specified BAM file using index file.
        /// </summary>
        /// <param name="parser">BAM parser</param>
        /// <param name="fileName">BAM file name.</param>
        /// <param name="range">SequenceRange object which contains reference sequence name and start and end co-ordinates.</param>
        /// <returns>SequenceAlignmentMap object which contains alignments for specified reference sequence and for specified range.</returns>
        public static SequenceAlignmentMap ParseRange(this BAMParser parser, string fileName, SequenceRange range)
        {
            if (parser == null)
            {
                throw new ArgumentNullException("parser");
            }

            if (string.IsNullOrWhiteSpace(fileName))
            {
                throw new ArgumentNullException("fileName");
            }

            if (range == null)
            {
                throw new ArgumentNullException("range");
            }

            if (string.IsNullOrEmpty(range.ID))
            {
                throw new ArgumentException("Reference sequence name (range.ID) can't empty or null.");
            }

            int start = range.Start >= int.MaxValue ? int.MaxValue : (int)range.Start;
            int end = range.End >= int.MaxValue ? int.MaxValue : (int)range.End;

            using (FileStream bamStream = File.OpenRead(fileName))
            {
                string bamIndexFileName = GetBAMIndexFileName(fileName);
                using (FileStream bamIndexFile = File.OpenRead(bamIndexFileName))
                using (BAMIndexStorage bamIndexStorage = new BAMIndexStorage(bamIndexFile))
                {
                    if (start == 0 && end == int.MaxValue)
                        return parser.GetAlignment(bamStream, bamIndexStorage, range.ID);
                    return parser.GetAlignment(bamStream, bamIndexStorage, range.ID, start, end);

                }
            }
        }
Example #19
0
        /// <summary>
        ///     Format BAM file and validate.
        /// </summary>
        /// <param name="nodeName">Different xml nodes used for different test cases</param>
        private void InValidateBAMFormatter(string nodeName)
        {
            // Get input and output values from xml node.
            string bamFilePath = _utilityObj.xmlUtil.GetTextValue(nodeName, Constants.FilePathNode);

            using (var bamParserObj = new BAMParser())
            {
                using (var storage = new BAMIndexStorage(File.Create(Constants.BAMTempIndexFileForIndexData)))
                {
                    // Parse a BAM file.
                    var seqAlignment = bamParserObj.ParseOne <SequenceAlignmentMap>(bamFilePath);

                    // Create a BAM formatter object.
                    var formatterObj = new BAMFormatter();

                    // Null filename
                    try
                    {
                        formatterObj.Format(seqAlignment, null, Constants.BAMTempIndexFileForIndexData);
                    }
                    catch (ArgumentNullException ex)
                    {
                        ApplicationLog.WriteLine(string.Format("BAM Parser P2 : Validated Exception {0} successfully", ex.Message));
                    }

                    // Same filename
                    try
                    {
                        formatterObj.Format(seqAlignment, Constants.BAMTempFileName, Constants.BAMTempFileName);
                    }
                    catch (ArgumentException ex)
                    {
                        ApplicationLog.WriteLine(string.Format("BAM Parser P2 : Validated Exception {0} successfully", ex.Message));
                    }

                    // Null sequence
                    try
                    {
                        formatterObj.Format(null, bamFilePath, Constants.BAMTempIndexFileForIndexData);
                    }
                    catch (ArgumentNullException ex)
                    {
                        ApplicationLog.WriteLine(string.Format("BAM Parser P2 : Validated Exception {0} successfully", ex.Message));
                    }

                    // Null index
                    try
                    {
                        formatterObj.Format(seqAlignment, bamFilePath, null);
                    }
                    catch (ArgumentNullException ex)
                    {
                        ApplicationLog.WriteLine(string.Format("BAM Parser P2 : Validated Exception {0} successfully", ex.Message));
                    }

                    // Invalidate BAM Parser Format(SeqAlignmentMap, BamFileName)
                    try
                    {
                        formatterObj.Format(null as SequenceAlignmentMap,
                                            Constants.BAMTempFileName);
                    }
                    catch (ArgumentNullException ex)
                    {
                        ApplicationLog.WriteLine(string.Format("BAM Parser P2 : Validated Exception {0} successfully", ex.Message));
                    }

                    try
                    {
                        formatterObj.Format(seqAlignment, null as string);
                    }
                    catch (ArgumentNullException ex)
                    {
                        ApplicationLog.WriteLine(string.Format("BAM Parser P2 : Validated Exception {0} successfully", ex.Message));
                    }

                    // Invalidate Format(SequenceAlignmentMap, StreamWriter)
                    try
                    {
                        formatterObj.Format(null, seqAlignment);
                    }
                    catch (ArgumentNullException ex)
                    {
                        ApplicationLog.WriteLine(string.Format("BAM Parser P2 : Validated Exception {0} successfully", ex.Message));
                    }

                    Stream stream;
                    try
                    {
                        using (stream = new FileStream(Constants.BAMTempFileName, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                        {
                            formatterObj.Format(stream, null as ISequenceAlignment);
                        }
                    }
                    catch (ArgumentNullException ex)
                    {
                        ApplicationLog.WriteLine(string.Format("BAM Parser P2 : Validated Exception {0} successfully", ex.Message));
                    }

                    // Invalidate Format(SequenceAlignmentMap, StreamWriter, IndexFile)
                    try
                    {
                        formatterObj.Format(null, storage, seqAlignment);
                    }
                    catch (ArgumentNullException ex)
                    {
                        ApplicationLog.WriteLine(string.Format("BAM Parser P2 : Validated Exception {0} successfully", ex.Message));
                    }

                    try
                    {
                        using (stream = new FileStream(Constants.BAMTempFileName, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                        {
                            formatterObj.Format(stream, storage, null);
                        }
                    }
                    catch (ArgumentNullException ex)
                    {
                        ApplicationLog.WriteLine(string.Format("BAM Parser P2 : Validated Exception {0} successfully", ex.Message));
                    }

                    try
                    {
                        using (stream = new FileStream(Constants.BAMTempFileName, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                        {
                            formatterObj.Format(stream, null, seqAlignment);
                        }
                    }

                    catch (ArgumentNullException ex)
                    {
                        ApplicationLog.WriteLine(string.Format("BAM Parser P2 : Validated Exception {0} successfully", ex.Message));
                    }

                    formatterObj = null;
                }
            }
        }
Example #20
0
        /// <summary>
        ///     Format BAM file using IsequenceAlignment object.
        /// </summary>
        /// <param name="nodeName">Different xml nodes used for different test cases</param>
        private void InValidateBAMFormatterWithSequenceAlignment(string nodeName)
        {
            // Get input and output values from xml node.
            string bamFilePath = _utilityObj.xmlUtil.GetTextValue(nodeName, Constants.FilePathNode);

            ISequenceAlignmentParser bamParserObj = new BAMParser();
            IList<ISequenceAlignment> seqList = bamParserObj.Parse(bamFilePath).ToList();
            try
            {
                using (var BAMIndexStorageObj = new BAMIndexStorage(File.Create(Constants.BAMTempIndexFileForInvalidData)))
                {
                    // Create a BAM formatter object.
                    var formatterObj = new BAMFormatter();
                    InvalidateBAmFormatter(formatterObj, seqList);
                    InvalidateBAmFormatterWithWithInvalidValues(formatterObj,seqList, bamFilePath, BAMIndexStorageObj);
                    InvalidateBAmFormatterWithWithNullValues(formatterObj,seqList);
                }
            }
            finally
            {
                (bamParserObj as BAMParser).Dispose();
                File.Delete(Constants.BAMTempIndexFileForInvalidData);
            }
        }
Example #21
0
        /// <summary>
        /// Writes sequence alignment to specified stream.
        /// </summary>
        /// <param name="sequenceAlignment">Sequence alignment object</param>
        /// <param name="writer">Stream to write.</param>
        /// <param name="indexStorage">BAMIndex file.</param>
        private void WriteSequenceAlignment(ISequenceAlignment sequenceAlignment, Stream writer, BAMIndexStorage indexStorage)
        {
            // validate sequenceAlignment.
            SequenceAlignmentMap sequenceAlignmentMap = ValidateAlignment(sequenceAlignment);

            // write bam struct to temp file.
            using (var fstemp = PlatformManager.Services.CreateTempStream())
            {
                WriteUncompressed(sequenceAlignmentMap, fstemp, CreateSortedBAMFile);

                fstemp.Seek(0, SeekOrigin.Begin);

                // Compress and write to the specified stream.
                CompressBAMFile(fstemp, writer);
            }

            // if index file need to be created.
            if (indexStorage != null)
            {
                writer.Seek(0, SeekOrigin.Begin);
                CreateBAMIndexFile(writer, indexStorage);
            }
        }
Example #22
0
 /// <summary>
 /// Creates BAMIndex object from the specified BAM file and writes to specified BAMIndex file.
 /// </summary>
 /// <param name="compressedBAMStream"></param>
 /// <param name="indexStorage"></param>
 private static void CreateBAMIndexFile(Stream compressedBAMStream, BAMIndexStorage indexStorage)
 {
     var parser = new BAMParser();
     BAMIndex bamIndex = parser.GetIndexFromBAMStorage(compressedBAMStream);
     indexStorage.Write(bamIndex);
 }
Example #23
0
        /// <summary>
        ///     Invalidate BAMFormatter with invalid values.
        /// </summary>
        /// <param name="formatterObj">Bam formatter obj</param>
        /// <param name="seqList">List of sequences</param>
        private static void InvalidateBAmFormatterWithWithInvalidValues(BAMFormatter formatterObj,
                                                                        IList<ISequenceAlignment> seqList,
                                                                        string bamFilePath, BAMIndexStorage BAMIndexStorageObj)
        {
            try
            {
                formatterObj.Format(null as ISequenceAlignment, bamFilePath,
                                    Constants.BAMTempIndexFileForIndexData);
            }
            catch (ArgumentNullException ex)
            {
                ApplicationLog.WriteLine(string.Format("BAM Parser P2 : Validated Exception {0} successfully",
                                                       ex.Message));
            }

            try
            {
                foreach (ISequenceAlignment seq in seqList)
                {
                    formatterObj.Format(seq, bamFilePath, null);
                }
            }
            catch (ArgumentNullException ex)
            {
                ApplicationLog.WriteLine(string.Format("BAM Parser P2 : Validated Exception {0} successfully",
                                                       ex.Message));
            }

            // Invalidate Format(IseqAlignment, StreamWriter, IndexFile)
            try
            {
                foreach (ISequenceAlignment seq in seqList)
                {
                    formatterObj.Format(null, BAMIndexStorageObj, seq);
                }
            }
            catch (ArgumentNullException ex)
            {
                ApplicationLog.WriteLine(string.Format("BAM Parser P2 : Validated Exception {0} successfully",
                                                       ex.Message));
            }

            try
            {
                using (Stream stream = new
                    FileStream(Constants.BAMTempFileName,
                               FileMode.OpenOrCreate, FileAccess.ReadWrite))
                {
                    formatterObj.Format(stream, BAMIndexStorageObj, null as ISequenceAlignment);
                }
            }
            catch (ArgumentNullException ex)
            {
                ApplicationLog.WriteLine(string.Format("BAM Parser P2 : Validated Exception {0} successfully",
                                                       ex.Message));
            }
        }