Bio.IO.BAM.BAMFormatter.WriteHeader C# (CSharp) Method

WriteHeader() public method

Writes BAM header to the specified stream in BAM format.
public WriteHeader ( Bio.IO.SAM.SAMAlignmentHeader header, Stream writer ) : void
header Bio.IO.SAM.SAMAlignmentHeader SAMAlignmentHeader object
writer Stream Stream to write.
return void
        public void WriteHeader(SAMAlignmentHeader header, Stream writer)
        {
            if (header == null)
            {
                throw new ArgumentNullException("header");
            }

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

            string samHeader;

            if (this.refSequences == null)
            {
                this.refSequences = header.GetReferenceSequenceRanges();
            }

            using (StringWriter strwriter = new StringWriter(CultureInfo.InvariantCulture))
            {
                SAMFormatter.WriteHeader(strwriter, header);
                samHeader = strwriter.ToString();
            }

            int samHeaderLen = samHeader.Length;
            byte[] bytes = Encoding.UTF8.GetBytes(samHeader);
            byte[] bamMagicNumber = { 66, 65, 77, 1 };

            // write BAM magic number
            writer.Write(bamMagicNumber, 0, 4);

            // Length of the header text
            writer.Write(Helper.GetLittleEndianByteArray(samHeaderLen), 0, 4);

            //Plain header text in SAM
            writer.Write(bytes, 0, bytes.Length);
            // number of reference sequences
            writer.Write(Helper.GetLittleEndianByteArray(this.refSequences.Count), 0, 4);

            foreach (SequenceRange range in this.refSequences)
            {
                int len = range.ID.Length;

                byte[] array = Encoding.UTF8.GetBytes(range.ID);
                writer.Write(Helper.GetLittleEndianByteArray(len + 1), 0, 4);
                writer.Write(array, 0, len);
                writer.WriteByte((byte)'\0');
                writer.Write(Helper.GetLittleEndianByteArray((int)range.End), 0, 4);
            }
        }

Usage Example

Ejemplo n.º 1
0
        /// <summary>
        /// Merge multiple sorted alignments.
        /// SAMUtil.exe out.bam in1.bam in2.bam
        /// </summary>
        public void DoMerge()
        {
            if (FilePaths == null)
            {
                throw new InvalidOperationException("FilePath");
            }

            if (FilePaths.Length < 2)
            {
                throw new InvalidOperationException(Resources.MergeHelp);
            }

            IList<IList<BAMSortedIndex>> sortedIndexes = new List<IList<BAMSortedIndex>>();
            IList<SequenceAlignmentMap> sequenceAlignmentMaps = new List<SequenceAlignmentMap>();
            Parallel.For(0, FilePaths.Length, (int index) =>
            {
                IList<BAMSortedIndex> sortedIndex;
                BAMParser parser = new BAMParser(); ;
                SequenceAlignmentMap map;
                if (index == 0)
                {
                    try
                    {
                        map = parser.ParseOne<SequenceAlignmentMap>(FilePaths[0]);
                    }
                    catch
                    {
                        throw new InvalidOperationException(Resources.InvalidBAMFile);
                    }

                    if (map == null)
                    {
                        throw new InvalidOperationException(Resources.EmptyFile);
                    }

                    if (string.IsNullOrEmpty(HeaderFile) && map.Header.RecordFields.Count == 0)
                    {
                        throw new InvalidOperationException(Resources.HeaderMissing);
                    }

                    if (!string.IsNullOrEmpty(HeaderFile))
                    {
                        SAMParser parse = new SAMParser();
                        SequenceAlignmentMap head;
                        try
                        {
                            head = parse.ParseOne<SequenceAlignmentMap>(HeaderFile);
                        }
                        catch
                        {
                            throw new InvalidOperationException(Resources.IncorrectHeaderFile);   
                        }

                        if (head == null)
                        {
                            throw new InvalidOperationException(Resources.EmptyFile);
                        }

                        header = head.Header;                       
                    }
                    else
                    {
                        header = map.Header;
                    }

                    sortedIndex = Sort(map, SortByReadName ? BAMSortByFields.ReadNames : BAMSortByFields.ChromosomeCoordinates);
                }
                else
                {
                    try
                    {
                        map = parser.ParseOne<SequenceAlignmentMap>(FilePaths[index]);
                    }
                    catch
                    {
                        throw new InvalidOperationException(Resources.InvalidBAMFile);
                    }
                    
                    if (map == null)
                    {
                        throw new InvalidOperationException(Resources.EmptyFile);
                    }

                    sortedIndex = Sort(map, SortByReadName ? BAMSortByFields.ReadNames : BAMSortByFields.ChromosomeCoordinates);
                }

                lock (sortedIndexes)
                {
                    sortedIndexes.Add(sortedIndex);
                    sequenceAlignmentMaps.Add(map);
                }
            });

            if (string.IsNullOrEmpty(OutputFilename))
            {
                OutputFilename = "out.bam";
                autoGeneratedOutputFilename = true;
            }

            string filePath = Path.GetTempFileName();
            using (FileStream fstemp = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite))
            {
                BAMFormatter formatter = new BAMFormatter();
                formatter.WriteHeader(header, fstemp);

                if (SortByReadName)
                {
                    IList<BAMSortedIndex> sortedIndex = sortedIndexes.Select(a => a.First()).ToList();
                    WriteMergeFileSortedByReadName(sortedIndex, fstemp, formatter, sequenceAlignmentMaps);
                }
                else
                {
                    WriteMergeFile(sortedIndexes, fstemp, formatter, sequenceAlignmentMaps);
                }

                using (FileStream fsoutput = new FileStream(OutputFilename, FileMode.Create, FileAccess.Write))
                {
                    fstemp.Seek(0, SeekOrigin.Begin);
                    formatter.CompressBAMFile(fstemp, fsoutput);
                }
            }

            File.Delete(filePath);

            if (autoGeneratedOutputFilename)
            {
                Console.WriteLine(Properties.Resources.SuccessMessageWithOutputFileName, OutputFilename);
            }
        }
All Usage Examples Of Bio.IO.BAM.BAMFormatter::WriteHeader