/** * Create a SAMTextWriter that is ready to receive SAMRecords. * * @param header entire header. Sort order is determined by the sortOrder property of this arg. * @param presorted if true, SAMRecords must be added to the SAMFileWriter in order that agrees with header.sortOrder. * @param outputFile where to write the output. */ public SAMFileWriter makeSAMWriter(final SAMFileHeader header, final boolean presorted, final File outputFile) { return makeSAMWriter(header, presorted, outputFile.toPath()); }
/** * Create a SAMTextWriter that is ready to receive SAMRecords. * * @param header entire header. Sort order is determined by the sortOrder property of this arg. * @param presorted if true, SAMRecords must be added to the SAMFileWriter in order that agrees with header.sortOrder. * @param outputFile where to write the output. */ public SAMFileWriter makeSAMWriter(final SAMFileHeader header, final boolean presorted, final File outputFile) { return makeSAMWriter(header, presorted, outputFile.toPath()); }
/** * Create either a SAM or a BAM writer based on examination of the outputPath extension. * * @param header entire header. Sort order is determined by the sortOrder property of this arg. * @param presorted presorted if true, SAMRecords must be added to the SAMFileWriter in order that agrees with header.sortOrder. * @param outputPath where to write the output. Must end with .sam or .bam. * @return SAM or BAM writer based on file extension of outputPath. */ public SAMFileWriter makeSAMOrBAMWriter(final SAMFileHeader header, final boolean presorted, final Path outputPath) { final String filename = outputPath.getFileName().toString(); if (filename.endsWith(BamFileIoUtils.BAM_FILE_EXTENSION)) { return makeBAMWriter(header, presorted, outputPath); } if (filename.endsWith(".sam")) { return makeSAMWriter(header, presorted, outputPath); } return makeBAMWriter(header, presorted, outputPath); }
/** * Create either a SAM or a BAM writer based on examination of the outputPath extension. * * @param header entire header. Sort order is determined by the sortOrder property of this arg. * @param presorted presorted if true, SAMRecords must be added to the SAMFileWriter in order that agrees with header.sortOrder. * @param outputPath where to write the output. Must end with .sam or .bam. * @return SAM or BAM writer based on file extension of outputPath. */ public SAMFileWriter makeSAMOrBAMWriter(final SAMFileHeader header, final boolean presorted, final Path outputPath) { final String filename = outputPath.getFileName().toString(); if (filename.endsWith(BamFileIoUtils.BAM_FILE_EXTENSION)) { return makeBAMWriter(header, presorted, outputPath); } if (filename.endsWith(".sam")) { return makeSAMWriter(header, presorted, outputPath); } return makeBAMWriter(header, presorted, outputPath); }
/** * Create either a SAM or a BAM writer based on examination of the outputFile extension. * @param header entire header. Sort order is determined by the sortOrder property of this arg. * @param presorted presorted if true, SAMRecords must be added to the SAMFileWriter in order that agrees with header.sortOrder. * @param outputFile where to write the output. Must end with .sam or .bam. * @return SAM or BAM writer based on file extension of outputFile. */ public SAMFileWriter makeSAMOrBAMWriter(final SAMFileHeader header, final boolean presorted, final File outputFile) { final String filename = outputFile.getName(); if (filename.endsWith(BamFileIoUtils.BAM_FILE_EXTENSION)) { return makeBAMWriter(header, presorted, outputFile); } if (filename.endsWith(".sam")) { return makeSAMWriter(header, presorted, outputFile); } return makeBAMWriter(header, presorted, outputFile); } }
/** * create an artificial sam file * * @param filename the filename to write to * @param numberOfChromosomes the number of chromosomes * @param startingChromosome where to start counting * @param chromosomeSize how large each chromosome is * @param readsPerChomosome how many reads to make in each chromosome. They'll be aligned from position 1 to x (which is the number of reads) */ public static void createArtificialSamFile(String filename, int numberOfChromosomes, int startingChromosome, int chromosomeSize, int readsPerChomosome) { SAMFileHeader header = createArtificialSamHeader(numberOfChromosomes, startingChromosome, chromosomeSize); File outFile = new File(filename); SAMFileWriter out = new SAMFileWriterFactory().makeSAMWriter(header, false, outFile); for (int x = startingChromosome; x < startingChromosome + numberOfChromosomes; x++) { for (int readNumber = 1; readNumber <= readsPerChomosome; readNumber++) { out.addAlignment(createArtificialRead(header, "Read_" + readNumber, x - startingChromosome, readNumber, 100)); } } out.close(); }
/** * filters a SAM using a reads file */ @Test(dataProvider = "dataTestReadFilter") public void testReadFilters(final FilterSamReads.Filter filterType, final List<String> readList, final int expectNumber) throws Exception { final File inputSam = File.createTempFile("testSam", ".sam", new File(TEST_DIR)); inputSam.deleteOnExit(); final File sortedSamIdx = new File(TEST_DIR, inputSam.getName() + ".idx"); sortedSamIdx.deleteOnExit(); try (final SAMFileWriter writer = new SAMFileWriterFactory() .setCreateIndex(true).makeSAMWriter(builder.getHeader(), false, inputSam)) { for (final SAMRecord record : builder) { writer.addAlignment(record); } } final File reads = File.createTempFile(TEST_DIR, "reads"); reads.deleteOnExit(); try (final FileWriter writer = new FileWriter(reads)) { writer.write(String.join("\n", readList)); } catch (IOException e) { e.printStackTrace(); } FilterSamReads filterTest = setupProgram(reads, inputSam, filterType); Assert.assertEquals(filterTest.doWork(), 0); long count = getReadCount(filterTest); Assert.assertEquals(count, expectNumber); }
public static SAMFileWriter createSAMTextWriter(SAMFileWriterFactory factoryOrNull, OutputStream os, SAMFileHeader header, boolean printHeader) throws IOException { SAMFileWriter writer = null; if (printHeader) { if (factoryOrNull == null) factoryOrNull = new SAMFileWriterFactory(); writer = factoryOrNull.makeSAMWriter(header, true, os); } else { SwapOutputStream sos = new SwapOutputStream(); final SAMTextWriter ret = new SAMTextWriter(sos); ret.setSortOrder(header.getSortOrder(), true); ret.setHeader(header); ret.getWriter().flush(); writer = ret; sos.delegate = os; } return writer; }
@Test(description="Read and then write SAM to verify header attribute ordering does not change depending on JVM version") public void samRoundTrip() throws Exception { final File input = new File(TEST_DATA_DIR, "roundtrip.sam"); final SamReader reader = SamReaderFactory.makeDefault().open(input); final File outputFile = File.createTempFile("roundtrip-out", ".sam"); outputFile.delete(); outputFile.deleteOnExit(); FileOutputStream os = new FileOutputStream(outputFile); final SAMFileWriterFactory factory = new SAMFileWriterFactory(); final SAMFileWriter writer = factory.makeSAMWriter(reader.getFileHeader(), false, os); for (SAMRecord rec : reader) { writer.addAlignment(rec); } writer.close(); os.close(); InputStream is = new FileInputStream(input); String originalsam = IOUtil.readFully(is); is.close(); is = new FileInputStream(outputFile); String writtensam = IOUtil.readFully(is); is.close(); Assert.assertEquals(writtensam, originalsam); }
@Test(description="Write SAM records with null SAMFileHeader") public void samNullHeaderRoundTrip() throws Exception { final File input = new File(TEST_DATA_DIR, "roundtrip.sam"); final SamReader reader = SamReaderFactory.makeDefault().open(input); final File outputFile = File.createTempFile("nullheader-out", ".sam"); outputFile.delete(); outputFile.deleteOnExit(); FileOutputStream os = new FileOutputStream(outputFile); final SAMFileWriterFactory factory = new SAMFileWriterFactory(); final SAMFileWriter writer = factory.makeSAMWriter(reader.getFileHeader(), false, os); for (SAMRecord rec : reader) { rec.setHeader(null); writer.addAlignment(rec); } writer.close(); os.close(); InputStream is = new FileInputStream(input); String originalsam = IOUtil.readFully(is); is.close(); is = new FileInputStream(outputFile); String writtensam = IOUtil.readFully(is); is.close(); Assert.assertEquals(writtensam, originalsam); }
/** * Creates samFileReader from the data in instance of this class * * @return SamReader */ public SamReader getSamReader() { final File tempFile; try { tempFile = File.createTempFile("temp", this.useBamFile ? ".bam" : ".sam"); tempFile.deleteOnExit(); } catch (final IOException e) { throw new RuntimeIOException("problems creating tempfile", e); } this.header.setAttribute("VN", "1.0"); try(final SAMFileWriter w = this.useBamFile ? new SAMFileWriterFactory().makeBAMWriter(this.header, true, tempFile) : new SAMFileWriterFactory().makeSAMWriter(this.header, true, tempFile)) { for (final SAMRecord r : this.getRecords()) { w.addAlignment(r); } } return SamReaderFactory.makeDefault().validationStringency(ValidationStringency.SILENT).open(tempFile); }
/** * Creates samFileReader from the data in instance of this class * * @return SamReader */ public SamReader getSamReader() { final File tempFile; try { tempFile = File.createTempFile("temp", this.useBamFile ? ".bam" : ".sam"); tempFile.deleteOnExit(); } catch (final IOException e) { throw new RuntimeIOException("problems creating tempfile", e); } this.header.setAttribute("VN", "1.0"); try(final SAMFileWriter w = this.useBamFile ? new SAMFileWriterFactory().makeBAMWriter(this.header, true, tempFile) : new SAMFileWriterFactory().makeSAMWriter(this.header, true, tempFile)) { for (final SAMRecord r : this.getRecords()) { w.addAlignment(r); } } return SamReaderFactory.makeDefault().validationStringency(ValidationStringency.SILENT).open(tempFile); }
inputSAM.getFileHeader().setAttribute(entry.getKey(), entry.getValue().toString()); final SAMFileWriter samWriter = new SAMFileWriterFactory().setSamFlagFieldOutput(samFlagField).makeSAMWriter(inputSAM.getFileHeader(), false, samFile); for (final SAMRecord samRecord : inputSAM) { samWriter.addAlignment(samRecord);
/** * filters a SAM using an interval filter */ @Test(dataProvider = "dataTestPairedIntervalFilter") public void testPairedIntervalFilter(final String intervalFilename, final int expectNumber) throws Exception { // Build a sam file for testing final File inputSam = VcfTestUtils.createTemporaryIndexedFile("testSam", ".bam"); final SAMFileWriter writer = new SAMFileWriterFactory() .setCreateIndex(true).makeSAMWriter(builder.getHeader(), false, inputSam); for (final SAMRecord record : builder) { writer.addAlignment(record); } writer.close(); final File intervalFile = new File(intervalFilename); FilterSamReads filterTest = setupProgram(intervalFile, inputSam, FilterSamReads.Filter.includePairedIntervals); Assert.assertEquals(filterTest.doWork(), 0); long count = getReadCount(filterTest); Assert.assertEquals(count, expectNumber); }
@Test(description="check that factory settings are propagated to writer") public void testFactorySettings() throws Exception { final SAMFileWriterFactory factory = new SAMFileWriterFactory(); factory.setCreateIndex(false); factory.setCreateMd5File(false); final File wontBeUsed = new File("wontBeUsed.tmp"); final int maxRecsInRam = 271828; factory.setMaxRecordsInRam(maxRecsInRam); factory.setTempDirectory(wontBeUsed); final SAMFileHeader header = new SAMFileHeader(); header.setSortOrder(SAMFileHeader.SortOrder.coordinate); header.addSequence(new SAMSequenceRecord("chr1", 123)); try (final SAMFileWriter writer = factory.makeBAMWriter(header, false, new ByteArrayOutputStream())) { Assert.assertEquals(maxRecsInRam, ((SAMFileWriterImpl) writer).getMaxRecordsInRam()); Assert.assertEquals(wontBeUsed, ((SAMFileWriterImpl) writer).getTempDirectory()); } try (final SAMFileWriter writer = factory.makeSAMWriter(header, false, new ByteArrayOutputStream())) { Assert.assertEquals(maxRecsInRam, ((SAMFileWriterImpl) writer).getMaxRecordsInRam()); Assert.assertEquals(wontBeUsed, ((SAMFileWriterImpl) writer).getTempDirectory()); } }
samFile.deleteOnExit(); final SAMFileWriter samWriter = new SAMFileWriterFactory().makeSAMWriter(builder.getHeader(), false, samFile); for (final SAMRecord rec : builder.getRecords()) samWriter.addAlignment(rec); samWriter.close();
/** * Colon separates fields of a text tag, but colon is also valid in a tag value, so assert that works properly. */ @Test public void testTagWithColon() { // Create a SAMRecord with a String tag containing a colon final SAMRecordSetBuilder samBuilder = new SAMRecordSetBuilder(); samBuilder.addUnmappedFragment("Hi,Mom!"); final SAMRecord rec = samBuilder.iterator().next(); final String valueWithColons = "A:B::C:::"; rec.setAttribute(SAMTag.CQ.name(), valueWithColons); // Write the record as SAM Text final ByteArrayOutputStream os = new ByteArrayOutputStream(); final SAMFileWriter textWriter = new SAMFileWriterFactory().makeSAMWriter(samBuilder.getHeader(), true, os); textWriter.addAlignment(rec); textWriter.close(); final SamReader reader = SamReaderFactory.makeDefault().open(SamInputResource.of(new ByteArrayInputStream(os.toByteArray()))); final SAMRecord recFromText = reader.iterator().next(); Assert.assertEquals(recFromText.getAttribute(SAMTag.CQ.name()), valueWithColons); CloserUtil.close(reader); }
switch (format) { case SAM: w = new SAMFileWriterFactory().makeSAMWriter(header, false, baos); break; case BAM:
this.writer = factory.makeSAMWriter( stub.getFileHeader(), stub.isPresorted(), stub.getOutputStream());
private void createSmallBamToOutputStream(final OutputStream outputStream,boolean binary) { final SAMFileWriterFactory factory = new SAMFileWriterFactory(); factory.setCreateIndex(false); factory.setCreateMd5File(false); final SAMFileHeader header = new SAMFileHeader(); // index only created if coordinate sorted header.setSortOrder(SAMFileHeader.SortOrder.coordinate); header.addSequence(new SAMSequenceRecord("chr1", 123)); try (final SAMFileWriter writer = (binary? factory.makeBAMWriter(header, false, outputStream): factory.makeSAMWriter(header, false, outputStream) )) { fillSmallBam(writer); } }