Format() public method

Writes specified alignment object to a stream. The output is formatted according to the BAM specification.
public Format ( Stream writer, Bio.IO.BAM.BAMIndexStorage indexWriter, ISequenceAlignment sequenceAlignment ) : void
writer Stream Stream to write BAM data.
indexWriter Bio.IO.BAM.BAMIndexStorage BAMIndexFile to write index data.
sequenceAlignment ISequenceAlignment SequenceAlignmentMap object.
return void
Example #1
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 #2
0
        public void TestFormatter()
        {
            string filePath = @"TestUtils\BAM\SeqAlignment.bam";
            string outputfilePath = "BAMTests123.bam";
            BAMParser parser = null;
            try
            {
                parser = new BAMParser();
                BAMFormatter formatter = new BAMFormatter();
                SequenceAlignmentMap alignmentMap = parser.Parse(filePath);

                Assert.IsTrue(alignmentMap != null);
                Assert.AreEqual(alignmentMap.Header.GetReferenceSequencesInfoFromSQHeader().Count, 1);
                Assert.AreEqual(alignmentMap.Header.ReferenceSequences.Count, 1);
                Assert.AreEqual(alignmentMap.QuerySequences.Count, 2);

                formatter.Format(alignmentMap, outputfilePath);

                formatter.CreateSortedBAMFile = true;
                formatter.CreateIndexFile = true;
                alignmentMap = parser.Parse(filePath);
                formatter.Format(alignmentMap, outputfilePath);

                Assert.IsTrue(File.Exists("BAMTests123.bam.bai"));

                alignmentMap = parser.Parse(outputfilePath);

                Assert.IsTrue(alignmentMap != null);
                Assert.AreEqual(alignmentMap.Header.GetReferenceSequencesInfoFromSQHeader().Count, 1);
                Assert.AreEqual(alignmentMap.Header.ReferenceSequences.Count, 1);
                Assert.AreEqual(alignmentMap.QuerySequences.Count, 2);

                alignmentMap = parser.ParseRange("BAMTests123.bam", new SequenceRange("chr20", 0, int.MaxValue));

                Assert.IsTrue(alignmentMap != null);
                Assert.AreEqual(alignmentMap.Header.GetReferenceSequencesInfoFromSQHeader().Count, 1);
                Assert.AreEqual(alignmentMap.Header.ReferenceSequences.Count, 1);
                Assert.AreEqual(alignmentMap.QuerySequences.Count, 2);

                alignmentMap = parser.ParseRange("BAMTests123.bam", new SequenceRange("chr20", 0, 28833));

                Assert.IsTrue(alignmentMap != null);
                Assert.AreEqual(alignmentMap.Header.GetReferenceSequencesInfoFromSQHeader().Count, 1);
                Assert.AreEqual(alignmentMap.Header.ReferenceSequences.Count, 1);
                Assert.AreEqual(alignmentMap.QuerySequences.Count, 1);
            }
            finally
            {
                if (parser != null)
                    parser.Dispose();
            }
        }
Example #3
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 #4
0
        public void TestFormatter()
        {
            const string filePath = @"TestUtils\BAM\SeqAlignment.bam";
            const string outputfilePath = "BAMTests123.bam";
            string outputIndexFile = outputfilePath + ".bai";
            BAMParser parser = new BAMParser();
            SequenceAlignmentMap alignmentMap = parser.ParseOne<SequenceAlignmentMap>(filePath);

            Assert.IsNotNull(alignmentMap);
            Assert.IsNotNull(alignmentMap.Header);
            Assert.AreEqual(alignmentMap.Header.GetReferenceSequencesInfoFromSQHeader().Count, 1);
            Assert.AreEqual(alignmentMap.Header.ReferenceSequences.Count, 1);
            Assert.IsNotNull(alignmentMap.QuerySequences);
            Assert.AreEqual(alignmentMap.QuerySequences.Count, 2);

            BAMFormatter formatter = new BAMFormatter();
            formatter.Format(alignmentMap, outputfilePath);

            formatter.CreateSortedBAMFile = true;
            formatter.CreateIndexFile = true;
            formatter.Format(alignmentMap, outputfilePath);
            Assert.IsTrue(File.Exists("BAMTests123.bam.bai"));

            alignmentMap = parser.ParseOne<SequenceAlignmentMap>(outputfilePath);
            Assert.IsNotNull(alignmentMap);
            Assert.IsNotNull(alignmentMap.Header);
            Assert.AreEqual(alignmentMap.Header.GetReferenceSequencesInfoFromSQHeader().Count, 1);
            Assert.AreEqual(alignmentMap.Header.ReferenceSequences.Count, 1);
            Assert.AreEqual(alignmentMap.QuerySequences.Count, 2);

            alignmentMap = parser.ParseRange("BAMTests123.bam", new SequenceRange("chr20", 0, int.MaxValue));
            Assert.IsNotNull(alignmentMap);
            Assert.IsNotNull(alignmentMap.Header);
            Assert.AreEqual(alignmentMap.Header.GetReferenceSequencesInfoFromSQHeader().Count, 1);
            Assert.AreEqual(alignmentMap.Header.ReferenceSequences.Count, 1);
            Assert.AreEqual(alignmentMap.QuerySequences.Count, 2);

            alignmentMap = parser.ParseRange("BAMTests123.bam", new SequenceRange("chr20", 0, 28833));
            Assert.IsNotNull(alignmentMap);
            Assert.IsNotNull(alignmentMap.Header);
            Assert.AreEqual(alignmentMap.Header.GetReferenceSequencesInfoFromSQHeader().Count, 1);
            Assert.AreEqual(alignmentMap.Header.ReferenceSequences.Count, 1);
            Assert.AreEqual(alignmentMap.QuerySequences.Count, 1);

            File.Delete(outputfilePath);
            File.Delete(outputIndexFile);
        }
Example #5
0
        /// <summary>
        /// Public method to sort BAM file.
        /// SAMUtil.exe in.bam out.bam
        /// </summary>
        public void DoSort()
        {
            string sortExtension = ".sort";
            if (string.IsNullOrEmpty(InputFilename))
            {
                throw new InvalidOperationException(Resources.SortHelp);
            }

            BAMParser parse = new BAMParser();
            SequenceAlignmentMap map = null;

            try
            {
                map = parse.ParseOne<SequenceAlignmentMap>(InputFilename);
            }
            catch(Exception ex)
            {
                throw new InvalidOperationException(Resources.InvalidBAMFile, ex);
            }

            BAMFormatter format = new BAMFormatter
                                  {
                                      CreateSortedBAMFile = true,
                                      SortType =
                                          this.SortByReadName
                                              ? BAMSortByFields.ReadNames
                                              : BAMSortByFields.ChromosomeCoordinates
                                  };

            if (string.IsNullOrEmpty(OutputFilename))
            {
                OutputFilename = InputFilename + sortExtension;
                autoGeneratedOutputFilename = true;
            }

            format.Format(map, OutputFilename);

            if (autoGeneratedOutputFilename)
            {
                Console.WriteLine(Resources.SuccessMessageWithOutputFileName, OutputFilename);
            }
        }
Example #6
0
 /// <summary>
 /// Writes the SAM object to file in SAM/BAM format.
 /// </summary>
 private void PerformFormat()
 {
     if (_isSAM)
     {
         BAMFormatter format = new BAMFormatter();
         try
         {
             format.Format(_sequenceAlignmentMap, OutputFilename);
         }
         catch (Exception ex)
         {
             throw new InvalidOperationException(Resources.WriteBAM + Environment.NewLine + ex.Message);
         }
     }
     else
     {
         SAMFormatter format = new SAMFormatter();
         try
         {
             format.Format(_sequenceAlignmentMap, OutputFilename);
         }
         catch (Exception ex)
         {
             throw new InvalidOperationException(Resources.WriteSAM + Environment.NewLine + ex.Message);
         }
     }
 }
Example #7
0
        public void TestFormatterWithSort()
        {
            string inputFilePath = @"TestUtils\BAM\SeqAlignment.bam";
            string outputFilePath1 = "output1.bam";
            string outputFilePath2 = "output2.bam";
            BAMParser parser = null;
            try
            {
                parser = new BAMParser();
                BAMFormatter formatter = new BAMFormatter();
                SequenceAlignmentMap alignmentMap = parser.Parse(inputFilePath);

                Assert.IsTrue(alignmentMap != null);
                Assert.AreEqual(alignmentMap.Header.GetReferenceSequencesInfoFromSQHeader().Count, 1);
                Assert.AreEqual(alignmentMap.Header.ReferenceSequences.Count, 1);
                Assert.AreEqual(alignmentMap.QuerySequences.Count, 2);

                formatter.CreateSortedBAMFile = true;
                formatter.SortType = BAMSortByFields.ChromosomeCoordinates;
                formatter.Format(alignmentMap, outputFilePath1);

                alignmentMap = parser.Parse(inputFilePath);
                formatter.Format(alignmentMap, outputFilePath2);

                Assert.IsTrue(File.Exists(outputFilePath1));
                Assert.IsTrue(File.Exists(outputFilePath2));

                Assert.AreEqual(true, FileCompare(outputFilePath1, outputFilePath2));
            }
            finally
            {
                if (parser != null)
                    parser.Dispose();
            }
        }
Example #8
0
        /// <summary>
        ///     Validate formatted BAM file.
        /// </summary>
        /// <param name="nodeName">Different xml nodes used for different test cases</param>
        /// <param name="BAMParserPam">BAM Format method parameters</param>
        private void ValidateBAMFormatter(string nodeName,
                                          BAMParserParameters BAMParserPam)
        {
            // Get input and output values from xml node.
            string bamFilePath = 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);

            using (var bamParserObj = new BAMParser())
            {
                // Parse a BAM file.
                var seqAlignment = bamParserObj.ParseOne<SequenceAlignmentMap>(bamFilePath);
                // Create a BAM formatter object.
                var formatterObj = new BAMFormatter();
                // Write/Format aligned sequences to BAM file.
                switch (BAMParserPam)
                {
                    case BAMParserParameters.StreamWriter:
                        Stream stream;
                        using (stream = new FileStream(Constants.BAMTempFileName, FileMode.Create, FileAccess.Write))
                        {
                            formatterObj.Format(stream, seqAlignment);
                        }
                        break;
                    case BAMParserParameters.FileName:
                        formatterObj.Format(seqAlignment, Constants.BAMTempFileName);
                        break;
                    case BAMParserParameters.IndexFile:
                        formatterObj.Format(seqAlignment, Constants.BAMTempFileName, Constants.BAMTempIndexFile);
                        File.Exists(Constants.BAMTempIndexFile);
                        break;
                    default:
                        break;
                }

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

                // Validate Parsed BAM file Header record fileds.
                this.ValidateBAMHeaderRecords(nodeName, expectedSeqAlignmentMap);
                IList<SAMAlignedSequence> alignedSeqs = expectedSeqAlignmentMap.QuerySequences;
                Assert.AreEqual(alignedSeqCount, alignedSeqs.Count.ToString((IFormatProvider) null));

                // Get expected sequences
                var 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("BAM Formatter BVT : Validated Aligned sequence :{0} successfully", alignedSeqs[index].QuerySequence));
                    }
                }
            }
            File.Delete(Constants.BAMTempFileName);
            File.Delete(Constants.BAMTempIndexFile);
        }
Example #9
0
        public void ValidateSAMToBAMConversion()
        {
            // Get values from xml config file.
            string expectedBamFilePath = this.utilityObj.xmlUtil.GetTextValue(
                Constants.BAMToSAMConversionNode, Constants.FilePathNode);
            string samFilePath = this.utilityObj.xmlUtil.GetTextValue(
                Constants.BAMToSAMConversionNode, Constants.FilePathNode1);

            // Parse expected BAM file.
            var bamParserObj = new BAMParser();
            SequenceAlignmentMap expextedBamAlignmentObj = bamParserObj.ParseOne<SequenceAlignmentMap>(expectedBamFilePath);

            // Parse a SAM file.
            var samParserObj = new SAMParser();
            SequenceAlignmentMap samSeqAlignment = samParserObj.ParseOne<SequenceAlignmentMap>(samFilePath);

            try
            {
                // Format SAM sequenceAlignment object to BAM file.
                var bamFormatterObj = new BAMFormatter();
                bamFormatterObj.Format(samSeqAlignment, Constants.BAMTempFileName);

                // Parse a formatted BAM file.
                SequenceAlignmentMap bamSeqAlignment = bamParserObj.ParseOne<SequenceAlignmentMap>(Constants.BAMTempFileName);

                // Validate converted BAM file with expected BAM file.
                Assert.IsTrue(CompareSequencedAlignmentHeader(bamSeqAlignment, expextedBamAlignmentObj));

                // Validate BAM file aligned sequences.
                Assert.IsTrue(CompareAlignedSequences(bamSeqAlignment, expextedBamAlignmentObj));
            }
            finally
            {
                // Delete temporary file.
                File.Delete(Constants.BAMTempFileName);
            }
        }
Example #10
0
        /// <summary>
        ///     Invalidate BAMFormatter with null values.
        /// </summary>
        /// <param name="formatterObj">Bam formatter obj</param>
        /// <param name="seqList">List of sequences</param>
        private static void InvalidateBAmFormatterWithWithNullValues(BAMFormatter formatterObj,
                                                                     IList<ISequenceAlignment> seqList)
        {
            try
            {
                using (Stream stream = new
                    FileStream(Constants.BAMTempFileName,
                               FileMode.OpenOrCreate, FileAccess.ReadWrite))
                {
                    foreach (ISequenceAlignment seq in seqList)
                    {
                        formatterObj.Format(stream, null, seq);
                    }
                }
            }

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

            // Invalidate Format(IseqAlignment, StreamWriter)
            try
            {
                foreach (ISequenceAlignment seq in seqList)
                {
                    formatterObj.Format(null as Stream, 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, null as ISequenceAlignment);
                }
            }
            catch (ArgumentNullException ex)
            {
                ApplicationLog.WriteLine(string.Format("BAM Parser P2 : Validated Exception {0} successfully",
                                                       ex.Message));
            }
        }
Example #11
0
        /// <summary>
        ///     Invalidate BAMFormatter.
        /// </summary>
        /// <param name="formatterObj">Bam formatter obj</param>
        /// <param name="seqList">List of sequences</param>
        private static void InvalidateBAmFormatter(BAMFormatter formatterObj,
                                                   IList<ISequenceAlignment> seqList)
        {
            // Invalidate BAM Parser Format(SeqAlignment, BamFileName)
            try
            {
                formatterObj.Format(null as ISequenceAlignment,
                                    Constants.BAMTempFileName);
            }
            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, null as string);
                }
            }
            catch (ArgumentNullException ex)
            {
                ApplicationLog.WriteLine(string.Format("BAM Parser P2 : Validated Exception {0} successfully", ex.Message));
            }

            // Invalidate Format(IseqAlignment, BAMFile, IndexFile)
            try
            {
                foreach (ISequenceAlignment seq in seqList)
                {
                    formatterObj.Format(seq, null,
                                        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, Constants.BAMTempFileName,
                                        Constants.BAMTempFileName);
                }
            }
            catch (ArgumentException ex)
            {
                ApplicationLog.WriteLine(string.Format("BAM Parser P2 : Validated Exception {0} successfully", ex.Message));
            }
        }
Example #12
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 #13
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 #14
0
        /// <summary>
        /// Validate SAM to BAM conversion.
        /// </summary>
        /// <param name="nodeName">Different xml node name used for different test cases</param>
        void ValidateSAMToBAMConversion(string nodeName)
        {
            // Get values from xml config file.
            string expectedBAMStoragePath = this.utilityObj.xmlUtil.GetTextValue(nodeName,
                Constants.FilePathNode);
            string samFilePath = this.utilityObj.xmlUtil.GetTextValue(nodeName,
                Constants.FilePathNode1);

            BAMParser bamParserObj = new BAMParser();
            SAMParser samParserObj = new SAMParser();
            BAMFormatter bamFormatterObj = new BAMFormatter { CreateSortedBAMFile = true, CreateIndexFile = true };
            SequenceAlignmentMap samSeqAlignment = null;
            SequenceAlignmentMap bamSeqAlignment = null;

            // Parse expected BAM file.
            SequenceAlignmentMap expextedBamAlignmentObj = bamParserObj.ParseOne<SequenceAlignmentMap>(expectedBAMStoragePath);

            // Parse a SAM file.
            samSeqAlignment = samParserObj.ParseOne<SequenceAlignmentMap>(samFilePath);

            try
            {
                // Format SAM sequenceAlignment object to BAM file.
                bamFormatterObj.Format(samSeqAlignment, Constants.BAMTempFileName);

                // Parse a formatted BAM file.
                bamSeqAlignment = bamParserObj.ParseOne<SequenceAlignmentMap>(Constants.BAMTempFileName);

                // Validate converted BAM file with expected BAM file.
                Assert.IsTrue(CompareSequencedAlignmentHeader(bamSeqAlignment,
                    expextedBamAlignmentObj));

                // Validate BAM file aligned sequences.
                Assert.IsTrue(CompareAlignedSequences(bamSeqAlignment,
                    expextedBamAlignmentObj));

                // Log message to VSTest GUI.
                ApplicationLog.WriteLine(string.Format((IFormatProvider)null,
                    "BAM Parser P1 : Validated the SAM->BAM conversion successfully"));
            }
            finally
            {
                // Delete temporary file.
                File.Delete(Constants.BAMTempFileName);
                ApplicationLog.WriteLine("Deleted the temp file created.");
            }
        }