Java Code Examples for htsjdk.samtools.SAMRecord#setBaseQualityString()

The following examples show how to use htsjdk.samtools.SAMRecord#setBaseQualityString() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ReadContextCounterTest.java    From hmftools with GNU General Public License v3.0 6 votes vote down vote up
@NotNull
public static SAMRecord buildSamRecord(final int alignmentStart, @NotNull final String cigar, @NotNull final String readString,
        @NotNull final String qualities) {
    final SAMRecord record = new SAMRecord(null);
    record.setAlignmentStart(alignmentStart);
    record.setCigarString(cigar);
    record.setReadString(readString);
    record.setReadNegativeStrandFlag(false);
    record.setBaseQualityString(qualities);
    record.setMappingQuality(20);
    record.setDuplicateReadFlag(false);
    record.setReadUnmappedFlag(false);
    record.setProperPairFlag(true);
    record.setReadPairedFlag(true);
    return record;
}
 
Example 2
Source File: SmartSamWriterTest.java    From rtg-tools with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private static SAMRecord createRecord(int position, String ref) {
  final SAMFileHeader header = new SAMFileHeader();
  header.getSequenceDictionary().addSequence(new SAMSequenceRecord("A", 100000));
  header.getSequenceDictionary().addSequence(new SAMSequenceRecord("B", 100000));
  final SAMRecord rec = new SAMRecord(header);
  rec.setReferenceName(ref);
  rec.setReadName("read");
  rec.setReadString("ACGT");
  rec.setBaseQualityString("####");
  if (ref.equals(SAMRecord.NO_ALIGNMENT_REFERENCE_NAME)) {
    rec.setReadUnmappedFlag(true);
  } else {
    rec.setCigarString("4=");
    rec.setAlignmentStart(position);
  }
  return rec;
}
 
Example 3
Source File: SAMRecordsTest.java    From hmftools with GNU General Public License v3.0 5 votes vote down vote up
@NotNull
public static SAMRecord buildSamRecord(final int alignmentStart, @NotNull final String cigar, @NotNull final String readString,
        @NotNull final String qualities) {
    final SAMRecord record = new SAMRecord(null);
    record.setAlignmentStart(alignmentStart);
    record.setCigarString(cigar);
    record.setReadString(readString);
    record.setReadNegativeStrandFlag(false);
    record.setBaseQualityString(qualities);
    record.setMappingQuality(20);
    record.setDuplicateReadFlag(false);
    record.setReadUnmappedFlag(false);
    return record;
}
 
Example 4
Source File: RefSequenceTest.java    From hmftools with GNU General Public License v3.0 5 votes vote down vote up
@NotNull
public static SAMRecord buildSamRecord(final int alignmentStart, @NotNull final String cigar, @NotNull final String readString,
        @NotNull final String qualities) {
    final SAMRecord record = new SAMRecord(null);
    record.setAlignmentStart(alignmentStart);
    record.setCigarString(cigar);
    record.setReadString(readString);
    record.setReadNegativeStrandFlag(false);
    record.setBaseQualityString(qualities);
    record.setMappingQuality(20);
    record.setDuplicateReadFlag(false);
    record.setReadUnmappedFlag(false);
    return record;
}
 
Example 5
Source File: ReadContextFactoryTest.java    From hmftools with GNU General Public License v3.0 5 votes vote down vote up
@NotNull
static SAMRecord buildSamRecord(@NotNull final String cigar, @NotNull final String readString, @NotNull final String qualities) {
    final SAMRecord record = new SAMRecord(null);
    record.setAlignmentStart(1000);
    record.setCigarString(cigar);
    record.setReadString(readString);
    record.setReadNegativeStrandFlag(false);
    record.setBaseQualityString(qualities);
    record.setMappingQuality(20);
    record.setDuplicateReadFlag(false);
    record.setReadUnmappedFlag(false);
    return record;
}
 
Example 6
Source File: TestUtils.java    From hmftools with GNU General Public License v3.0 5 votes vote down vote up
@NotNull
public static SAMRecord buildSamRecord(final int alignmentStart, @NotNull final String cigar, @NotNull final String readString,
        @NotNull final String qualities, final boolean negativeStrand) {
    final SAMRecord record = new SAMRecord(null);
    record.setAlignmentStart(alignmentStart);
    record.setCigarString(cigar);
    record.setReadString(readString);
    record.setReadNegativeStrandFlag(negativeStrand);
    record.setBaseQualityString(qualities);
    record.setMappingQuality(20);
    record.setDuplicateReadFlag(false);
    record.setReadUnmappedFlag(false);
    return record;
}
 
Example 7
Source File: SortedSAMWriter.java    From abra2 with MIT License 5 votes vote down vote up
public void addAlignment(int sampleIdx, SAMRecordWrapper samRecord, int chromosomeChunkIdx) {
	Feature chunk = this.chromosomeChunker.getChunks().get(chromosomeChunkIdx);
	
	SAMRecord read = samRecord.getSamRecord();
	
	// Only output reads with original start pos within specified chromosomeChunk
	// Avoids reads being written in 2 different chunks
	
	int origAlignmentStart = read.getAlignmentStart();
	String yo = read.getStringAttribute("YO");
	if (yo != null) {
		String[] fields = yo.split(":");
		origAlignmentStart = Integer.parseInt(fields[1]);
	}
	
	if (origAlignmentStart >= chunk.getStart() && origAlignmentStart <= chunk.getEnd()) {
		
		if (samRecord.isUnalignedRc() && read.getReadUnmappedFlag()) {
			// This read was reverse complemented, but not updated.
			// Change it back to its original state.
			read.setReadString(rc.reverseComplement(read.getReadString()));
			read.setBaseQualityString(rc.reverse(read.getBaseQualityString()));
			read.setReadNegativeStrandFlag(!read.getReadNegativeStrandFlag());
		}
		
		writers[sampleIdx][chromosomeChunkIdx].addAlignment(read);
	}
}
 
Example 8
Source File: SamOutputTest.java    From rtg-tools with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void test() throws IOException {
  final SAMFileHeader header = new SAMFileHeader();
  header.setSortOrder(SAMFileHeader.SortOrder.coordinate);
  header.getSequenceDictionary().addSequence(new SAMSequenceRecord("seq", 1000000));
  final SAMRecord rec = new SAMRecord(header);
  rec.setAlignmentStart(500000);
  rec.setReferenceName("seq");
  rec.setReadName("read");
  rec.setReadString("acgt");
  rec.setBaseQualityString("####");
  rec.setCigarString("4=");
  try (TestDirectory dir = new TestDirectory()) {
    final MemoryPrintStream mps = new MemoryPrintStream();
    try (SamOutput out = SamOutput.getSamOutput(new File(dir, "foo"), mps.outputStream(), header, true, true, null)) {
      out.getWriter().addAlignment(rec);
    }
    mNano.check("samoutput_expected_1.sam", MainResult.run(new ExtractCli(), "--header", new File(dir, "foo.bam").getPath(), "seq:500000+1").out());
    assertTrue(new File(dir, "foo.bam.bai").exists());
    assertEquals("", mps.toString());

    try (SamOutput out = SamOutput.getSamOutput(new File(dir, "foo.sam"), mps.outputStream(), header, true, true, null)) {
      out.getWriter().addAlignment(rec);
    }
    mNano.check("samoutput_expected_1.sam", MainResult.run(new ExtractCli(), "--header", new File(dir, "foo.sam.gz").getPath(), "seq:500000+1").out());
    assertTrue(new File(dir, "foo.sam.gz.tbi").exists());
    assertEquals("", mps.toString());

    try (SamOutput out = SamOutput.getSamOutput(new File(dir, "foo.sam"), mps.outputStream(), header, false, true, null)) {
      out.getWriter().addAlignment(rec);
    }
    mNano.check("samoutput_expected_1.sam", FileHelper.fileToString(new File(dir, "foo.sam")));
    assertFalse(new File(dir, "foo.sam.tbi").exists());
    assertEquals("", mps.toString());

    try (SamOutput out = SamOutput.getSamOutput(new File("-"), mps.outputStream(), header, true, true, null)) {
      out.getWriter().addAlignment(rec);
    }
    mNano.check("samoutput_expected_1.sam", mps.toString());
  }
}
 
Example 9
Source File: FastqRead.java    From cramtools with Apache License 2.0 5 votes vote down vote up
public SAMRecord toSAMRecord(SAMFileHeader header) {
	SAMRecord record = new SAMRecord(header);
	String name = null;
	if (data[nameLen - 1] == '/' && Character.isDigit(data[nameLen]))
		name = new String(data, 1, nameLen - 2);
	else
		name = new String(data, 1, nameLen - 2);
	record.setReadName(name);
	int readLen = (data.length - this.nameLen - 4 - 1) / 2;
	byte[] bases = Arrays.copyOfRange(data, nameLen + 2, nameLen + 2 + readLen);
	record.setReadBases(bases);

	byte[] scores = Arrays.copyOfRange(data, nameLen + 3 + 1 + readLen + 1, nameLen + 3 + 1 + 2 * readLen + 1);
	record.setBaseQualityString(new String(scores));

	record.setReadUnmappedFlag(true);
	switch (templateIndex) {
	case 0:
		record.setReadPairedFlag(false);
		break;
	case 1:
		record.setReadPairedFlag(true);
		record.setFirstOfPairFlag(true);
		break;
	case 2:
		record.setReadPairedFlag(true);
		record.setSecondOfPairFlag(true);
		break;

	default:
		break;
	}
	return record;
}
 
Example 10
Source File: BAMRecordViewTest.java    From cramtools with Apache License 2.0 5 votes vote down vote up
@Test
public void test() {
	SAMFileHeader header = new SAMFileHeader();
	SAMRecord r1 = new SAMRecord(header);
	r1.setReadName("readName");
	r1.setFlags(4);
	r1.setReferenceIndex(SAMRecord.NO_ALIGNMENT_REFERENCE_INDEX);
	r1.setAlignmentStart(SAMRecord.NO_ALIGNMENT_START);
	r1.setMappingQuality(SAMRecord.NO_MAPPING_QUALITY);
	r1.setCigar(new Cigar());
	r1.setMateReferenceIndex(SAMRecord.NO_ALIGNMENT_REFERENCE_INDEX);
	r1.setMateAlignmentStart(SAMRecord.NO_ALIGNMENT_START);
	r1.setReadBases("A".getBytes());
	r1.setBaseQualityString("!");

	BAMRecordView view = new BAMRecordView(new byte[1024]);
	translate(r1, view);
	r1.setReadName("2");
	translate(r1, view);

	List<SAMRecord> list = toSAMRecord(view, header);
	assertEquals(2, list.size());

	Iterator<SAMRecord> iterator = list.iterator();
	SAMRecord r2 = iterator.next();
	r1.setReadName("readName");
	compare(r1, r2);

	r1.setReadName("2");
	r2 = iterator.next();
	compare(r1, r2);
}
 
Example 11
Source File: MergeBamAlignmentTest.java    From picard with MIT License 4 votes vote down vote up
/**
 * Confirm that paired reads are rejected by PrimaryAlignmentStrategy.EarliestFragment.
 */
@Test(expectedExceptions = UnsupportedOperationException.class)
public void testEarliestFragmentStrategyPaired() throws Exception {
    final File output = File.createTempFile("mergeTest", ".sam");
    output.deleteOnExit();

    final File unmappedSam = File.createTempFile("unmapped.", ".sam");
    unmappedSam.deleteOnExit();
    final SAMFileWriterFactory factory = new SAMFileWriterFactory();
    final SAMFileHeader header = new SAMFileHeader();
    header.setSortOrder(SAMFileHeader.SortOrder.queryname);
    final String cigar = "16M";

    final SAMRecord firstOfPair = new SAMRecord(header);
    firstOfPair.setReadName("theRead");
    firstOfPair.setReadString("ACGTACGTACGTACGT");
    firstOfPair.setBaseQualityString("5555555555555555");
    firstOfPair.setReadUnmappedFlag(true);
    firstOfPair.setReadPairedFlag(true);
    firstOfPair.setFirstOfPairFlag(true);

    final SAMRecord secondOfPair = new SAMRecord(header);
    secondOfPair.setReadName("theRead");
    secondOfPair.setReadString("ACGTACGTACGTACGT");
    secondOfPair.setBaseQualityString("5555555555555555");
    secondOfPair.setReadUnmappedFlag(true);
    secondOfPair.setReadPairedFlag(true);
    secondOfPair.setSecondOfPairFlag(true);
    SamPairUtil.setMateInfo(firstOfPair, secondOfPair);

    final SAMFileWriter unmappedWriter = factory.makeSAMWriter(header, false, unmappedSam);
    unmappedWriter.addAlignment(firstOfPair);
    unmappedWriter.addAlignment(secondOfPair);
    unmappedWriter.close();

    final File alignedSam = File.createTempFile("aligned.", ".sam");
    alignedSam.deleteOnExit();

    // Populate the header with SAMSequenceRecords
    header.setSequenceDictionary(SAMSequenceDictionaryExtractor.extractDictionary(sequenceDict2.toPath()));

    // Create 2 alignments for each end of pair
    final SAMFileWriter alignedWriter = factory.makeSAMWriter(header, false, alignedSam);
    for (int i = 1; i <= 2; ++i) {
        final SAMRecord firstOfPairAligned = new SAMRecord(header);
        firstOfPairAligned.setReadName(firstOfPair.getReadName());
        firstOfPairAligned.setReadBases(firstOfPair.getReadBases());
        firstOfPairAligned.setBaseQualities(firstOfPair.getBaseQualities());
        firstOfPairAligned.setReferenceName("chr1");
        firstOfPairAligned.setAlignmentStart(i);
        firstOfPairAligned.setCigarString(cigar);
        firstOfPairAligned.setMappingQuality(100);
        firstOfPairAligned.setReadPairedFlag(true);
        firstOfPairAligned.setFirstOfPairFlag(true);
        firstOfPairAligned.setAttribute(SAMTag.HI.name(), i);

        final SAMRecord secondOfPairAligned = new SAMRecord(header);
        secondOfPairAligned.setReadName(secondOfPair.getReadName());
        secondOfPairAligned.setReadBases(secondOfPair.getReadBases());
        secondOfPairAligned.setBaseQualities(secondOfPair.getBaseQualities());
        secondOfPairAligned.setReferenceName("chr1");
        secondOfPairAligned.setAlignmentStart(i + 10);
        secondOfPairAligned.setCigarString(cigar);
        secondOfPairAligned.setMappingQuality(100);
        secondOfPairAligned.setReadPairedFlag(true);
        secondOfPairAligned.setSecondOfPairFlag(true);
        secondOfPairAligned.setAttribute(SAMTag.HI.name(), i);

        SamPairUtil.setMateInfo(firstOfPairAligned, secondOfPairAligned);

        alignedWriter.addAlignment(firstOfPairAligned);
        alignedWriter.addAlignment(secondOfPairAligned);
    }
    alignedWriter.close();

    doMergeAlignment(unmappedSam, Collections.singletonList(alignedSam),
            null, null, null, null,
            false, true, false, 1,
            "0", "1.0", "align!", "myAligner",
            true,
            fasta, output,
            SamPairUtil.PairOrientation.FR,
            MergeBamAlignment.PrimaryAlignmentStrategy.EarliestFragment,
            null, null, null, null);

    Assert.fail("Exception was not thrown");
}
 
Example 12
Source File: MergeBamAlignmentTest.java    From picard with MIT License 4 votes vote down vote up
/**
 * @return a 2-element array in which the first element is the unmapped SAM, and the second the mapped SAM.
 */
private File[] createSamFilesToBeMerged(final MultipleAlignmentSpec[] specs) {
    try {
        final File unmappedSam = File.createTempFile("unmapped.", ".sam");
        unmappedSam.deleteOnExit();
        final SAMFileWriterFactory factory = new SAMFileWriterFactory();
        final SAMFileHeader header = new SAMFileHeader();
        header.setSortOrder(SAMFileHeader.SortOrder.queryname);
        final SAMRecord unmappedRecord = new SAMRecord(header);

        unmappedRecord.setReadName("theRead");
        unmappedRecord.setReadString("ACGTACGTACGTACGT");
        unmappedRecord.setBaseQualityString("5555555555555555");
        unmappedRecord.setReadUnmappedFlag(true);

        final SAMFileWriter unmappedWriter = factory.makeSAMWriter(header, false, unmappedSam);
        unmappedWriter.addAlignment(unmappedRecord);
        unmappedWriter.close();

        final File alignedSam = File.createTempFile("aligned.", ".sam");
        alignedSam.deleteOnExit();

        final String sequence = "chr1";
        // Populate the header with SAMSequenceRecords
        header.setSequenceDictionary(SAMSequenceDictionaryExtractor.extractDictionary(sequenceDict2.toPath()));

        final SAMFileWriter alignedWriter = factory.makeSAMWriter(header, false, alignedSam);
        for (final MultipleAlignmentSpec spec : specs) {
            final SAMRecord alignedRecord = new SAMRecord(header);
            alignedRecord.setReadName(unmappedRecord.getReadName());
            alignedRecord.setReadBases(unmappedRecord.getReadBases());
            alignedRecord.setBaseQualities(unmappedRecord.getBaseQualities());
            alignedRecord.setReferenceName(sequence);
            alignedRecord.setAlignmentStart(1);
            alignedRecord.setReadNegativeStrandFlag(spec.reverseStrand);
            alignedRecord.setCigarString(spec.cigar);
            alignedRecord.setMappingQuality(spec.mapQ);
            if (spec.oneOfTheBest) {
                alignedRecord.setAttribute(ONE_OF_THE_BEST_TAG, 1);
            }
            alignedWriter.addAlignment(alignedRecord);
        }
        alignedWriter.close();

        return new File[]{unmappedSam, alignedSam};
    } catch (IOException e) {
        throw new PicardException(e.getMessage(), e);
    }
}
 
Example 13
Source File: MergeBamAlignmentTest.java    From picard with MIT License 4 votes vote down vote up
private void testBestFragmentMapqStrategy(final String testName, final int[] firstMapQs, final int[] secondMapQs,
                                          final boolean includeSecondary, final int expectedFirstMapq,
                                          final int expectedSecondMapq) throws Exception {
    final File unmappedSam = File.createTempFile("unmapped.", ".sam");
    unmappedSam.deleteOnExit();
    final SAMFileWriterFactory factory = new SAMFileWriterFactory();
    final SAMFileHeader header = new SAMFileHeader();
    header.setSortOrder(SAMFileHeader.SortOrder.queryname);

    final String readName = "theRead";
    final SAMRecord firstUnmappedRead = new SAMRecord(header);
    firstUnmappedRead.setReadName(readName);
    firstUnmappedRead.setReadString("ACGTACGTACGTACGT");
    firstUnmappedRead.setBaseQualityString("5555555555555555");
    firstUnmappedRead.setReadUnmappedFlag(true);
    firstUnmappedRead.setMateUnmappedFlag(true);
    firstUnmappedRead.setReadPairedFlag(true);
    firstUnmappedRead.setFirstOfPairFlag(true);

    final SAMRecord secondUnmappedRead = new SAMRecord(header);
    secondUnmappedRead.setReadName(readName);
    secondUnmappedRead.setReadString("TCGAACGTTCGAACTG");
    secondUnmappedRead.setBaseQualityString("6666666666666666");
    secondUnmappedRead.setReadUnmappedFlag(true);
    secondUnmappedRead.setMateUnmappedFlag(true);
    secondUnmappedRead.setReadPairedFlag(true);
    secondUnmappedRead.setSecondOfPairFlag(true);

    final SAMFileWriter unmappedWriter = factory.makeSAMWriter(header, false, unmappedSam);
    unmappedWriter.addAlignment(firstUnmappedRead);
    unmappedWriter.addAlignment(secondUnmappedRead);
    unmappedWriter.close();

    final File alignedSam = File.createTempFile("aligned.", ".sam");
    alignedSam.deleteOnExit();

    final String sequence = "chr1";
    // Populate the header with SAMSequenceRecords
    header.setSequenceDictionary(SAMSequenceDictionaryExtractor.extractDictionary(sequenceDict2.toPath()));

    final SAMFileWriter alignedWriter = factory.makeSAMWriter(header, false, alignedSam);

    addAlignmentsForBestFragmentMapqStrategy(alignedWriter, firstUnmappedRead, sequence, firstMapQs);
    addAlignmentsForBestFragmentMapqStrategy(alignedWriter, secondUnmappedRead, sequence, secondMapQs);
    alignedWriter.close();

    final File output = File.createTempFile("testBestFragmentMapqStrategy." + testName, ".sam");
    output.deleteOnExit();
    doMergeAlignment(unmappedSam, Collections.singletonList(alignedSam),
            null, null, null, null,
            false, true, false, 1,
            "0", "1.0", "align!", "myAligner",
            true,
            fasta, output,
            SamPairUtil.PairOrientation.FR,
            MergeBamAlignment.PrimaryAlignmentStrategy.BestEndMapq,
            null, includeSecondary, null, null);
    final SamReader reader = SamReaderFactory.makeDefault().open(output);

    int numFirstRecords = 0;
    int numSecondRecords = 0;
    int firstPrimaryMapq = -1;
    int secondPrimaryMapq = -1;
    for (final SAMRecord rec: reader) {
        Assert.assertTrue(rec.getReadPairedFlag());
        if (rec.getFirstOfPairFlag()) ++numFirstRecords;
        else if (rec.getSecondOfPairFlag()) ++ numSecondRecords;
        else Assert.fail("unpossible!");
        if (!rec.getReadUnmappedFlag() && !rec.getNotPrimaryAlignmentFlag()) {
            if (rec.getFirstOfPairFlag()) {
                Assert.assertEquals(firstPrimaryMapq, -1);
                firstPrimaryMapq = rec.getMappingQuality();
            } else {
                Assert.assertEquals(secondPrimaryMapq, -1);
                secondPrimaryMapq = rec.getMappingQuality();
            }
        } else if (rec.getNotPrimaryAlignmentFlag()) {
            Assert.assertTrue(rec.getMateUnmappedFlag());
        }
    }
    reader.close();
    Assert.assertEquals(firstPrimaryMapq, expectedFirstMapq);
    Assert.assertEquals(secondPrimaryMapq, expectedSecondMapq);
    if (!includeSecondary) {
        Assert.assertEquals(numFirstRecords, 1);
        Assert.assertEquals(numSecondRecords, 1);
    } else {
        // If no alignments for an end, there will be a single unmapped record
        Assert.assertEquals(numFirstRecords, Math.max(1, firstMapQs.length));
        Assert.assertEquals(numSecondRecords, Math.max(1, secondMapQs.length));
    }
}