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

The following examples show how to use htsjdk.samtools.SAMRecord#getReadUnmappedFlag() . 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: UmiUtil.java    From picard with MIT License 6 votes vote down vote up
/**
 * Determines if the read represented by a SAM record belongs to the top or bottom strand
 * or if it cannot determine strand position due to one of the reads being unmapped.
 * Top strand is defined as having a read 1 unclipped 5' coordinate
 * less than the read 2 unclipped 5' coordinate.  If a read is unmapped
 * we do not attempt to determine the strand to which the read or its mate belongs.
 * If the mate belongs to a different contig from the read, then the reference
 * index for the read and its mate is used in leu of the unclipped 5' coordinate.
 * @param rec Record to determine top or bottom strand
 * @return Top or bottom strand, unknown if it cannot be determined.
 */
static ReadStrand getStrand(final SAMRecord rec) {
    if (rec.getReadUnmappedFlag() || rec.getMateUnmappedFlag()) {
        return ReadStrand.UNKNOWN;
    }

    // If the read pair are aligned to different contigs we use
    // the reference index to determine relative 5' coordinate ordering.
    // Both the read and its mate should not have their unmapped flag set to true.
    if (!rec.getReferenceIndex().equals(rec.getMateReferenceIndex())) {
        if (rec.getFirstOfPairFlag() == (rec.getReferenceIndex() < rec.getMateReferenceIndex())) {
            return ReadStrand.TOP;
        } else {
            return ReadStrand.BOTTOM;
        }
    }

    final int read5PrimeStart = (rec.getReadNegativeStrandFlag()) ? rec.getUnclippedEnd() : rec.getUnclippedStart();
    final int mate5PrimeStart = (rec.getMateNegativeStrandFlag()) ? SAMUtils.getMateUnclippedEnd(rec) : SAMUtils.getMateUnclippedStart(rec);

    if (rec.getFirstOfPairFlag() == (read5PrimeStart <= mate5PrimeStart)) {
        return ReadStrand.TOP;
    } else {
        return ReadStrand.BOTTOM;
    }
}
 
Example 2
Source File: SAMRecordUtils.java    From abra2 with MIT License 6 votes vote down vote up
/**
 * Calculates edit distance for the input read.
 * If the input c2r is not null, compare to the actual reference.
 * If c2r is null, check the input NM tag.
 */
public static int getEditDistance(SAMRecord read, CompareToReference2 c2r, boolean includeSoftClipping) {
	
	Integer distance = null;
	
	if (read.getReadUnmappedFlag()) {
		distance = read.getReadLength();
	} else if (c2r != null) {
		//distance = c2r.numMismatches(read) + getNumIndelBases(read);
		distance = c2r.numMismatches(read, includeSoftClipping) + getNumIndelBases(read);
	} else {
		distance = read.getIntegerAttribute("NM");
		
		if (distance == null) {
			// STAR format
			distance = read.getIntegerAttribute("nM");
		}
		
		if (distance == null) {
			distance = read.getReadLength();
		}
	}
			
	return distance;
}
 
Example 3
Source File: AdapterUtility.java    From picard with MIT License 6 votes vote down vote up
/**
 * Checks the first ADAPTER_MATCH_LENGTH bases of the read against known adapter sequences and returns
 * true if the read matches an adapter sequence with MAX_ADAPTER_ERRORS mismsatches or fewer.
 * <p>
 * Only unmapped reads and reads with MQ=0 are considers eligible for being adapter
 */

 public boolean isAdapter(final SAMRecord record) {

    // If the read mapped with mapping quality > 0 we do not consider it an adapter read.
    if (!record.getReadUnmappedFlag() && record.getMappingQuality() != 0) {
        return false;
    }

    // if the read is mapped and is aligned to the reverse strand, it needs to be
    // rev-comp'ed before calling isAdapterSequence.
    final boolean revComp = !record.getReadUnmappedFlag() &&
            record.getReadNegativeStrandFlag();

    final byte[] readBases = record.getReadBases();
    return isAdapterSequence(readBases, revComp);
}
 
Example 4
Source File: QualityScoreDistribution.java    From picard with MIT License 6 votes vote down vote up
@Override
protected void acceptRead(final SAMRecord rec, final ReferenceSequence ref) {
    // Skip unwanted records
    if (PF_READS_ONLY && rec.getReadFailsVendorQualityCheckFlag()) return;
    if (ALIGNED_READS_ONLY && rec.getReadUnmappedFlag()) return;
    if (rec.isSecondaryOrSupplementary()) return;

    final byte[] bases = rec.getReadBases();
    final byte[] quals = rec.getBaseQualities();
    final byte[] oq    = rec.getOriginalBaseQualities();

    final int length = quals.length;

    for (int i=0; i<length; ++i) {
        if (INCLUDE_NO_CALLS || !SequenceUtil.isNoCall(bases[i])) {
            qCounts[quals[i]]++;
            if (oq != null) oqCounts[oq[i]]++;
        }
    }
}
 
Example 5
Source File: SamRecordComparision.java    From cramtools with Apache License 2.0 6 votes vote down vote up
/**
 * This is supposed to check if the mates have valid pairing flags.
 * 
 * @param r1
 * @param r2
 * @return
 */
private boolean checkMateFlags(SAMRecord r1, SAMRecord r2) {
	if (!r1.getReadPairedFlag() || !r2.getReadPairedFlag())
		return false;

	if (r1.getReadUnmappedFlag() != r2.getMateUnmappedFlag())
		return false;
	if (r1.getReadNegativeStrandFlag() != r2.getMateNegativeStrandFlag())
		return false;
	if (r1.getProperPairFlag() != r2.getProperPairFlag())
		return false;
	if (r1.getFirstOfPairFlag() && r2.getFirstOfPairFlag())
		return false;
	if (r1.getSecondOfPairFlag() && r2.getSecondOfPairFlag())
		return false;

	if (r2.getReadUnmappedFlag() != r1.getMateUnmappedFlag())
		return false;
	if (r2.getReadNegativeStrandFlag() != r1.getMateNegativeStrandFlag())
		return false;

	return true;
}
 
Example 6
Source File: CleanSam.java    From picard with MIT License 5 votes vote down vote up
/**
 * Do the work after command line has been parsed.
 * RuntimeException may be thrown by this method, and are reported appropriately.
 *
 * @return program exit status.
 */
@Override
protected int doWork() {
    IOUtil.assertFileIsReadable(INPUT);
    IOUtil.assertFileIsWritable(OUTPUT);
    final SamReaderFactory factory = SamReaderFactory.makeDefault().referenceSequence(REFERENCE_SEQUENCE);
    if (VALIDATION_STRINGENCY == ValidationStringency.STRICT) {
        factory.validationStringency(ValidationStringency.LENIENT);
    }
    final SamReader reader = factory.open(INPUT);
    final SAMFileWriter writer = new SAMFileWriterFactory().makeSAMOrBAMWriter(reader.getFileHeader(), true, OUTPUT);
    final CloseableIterator<SAMRecord> it = reader.iterator();
    final ProgressLogger progress = new ProgressLogger(Log.getInstance(CleanSam.class));

    // If the read (or its mate) maps off the end of the alignment, clip it
    while (it.hasNext()) {
        final SAMRecord rec = it.next();

        // If the read (or its mate) maps off the end of the alignment, clip it
        AbstractAlignmentMerger.createNewCigarsIfMapsOffEndOfReference(rec);

        // check the read's mapping quality
        if (rec.getReadUnmappedFlag() && 0 != rec.getMappingQuality()) {
            rec.setMappingQuality(0);
        }

        writer.addAlignment(rec);
        progress.record(rec);
    }

    writer.close();
    it.close();
    CloserUtil.close(reader);
    return 0;
}
 
Example 7
Source File: CollectBaseDistributionByCycle.java    From picard with MIT License 5 votes vote down vote up
@Override
protected void acceptRead(final SAMRecord rec, final ReferenceSequence ref) {
    if ((PF_READS_ONLY) && (rec.getReadFailsVendorQualityCheckFlag())) {
        return;
    }
    if ((ALIGNED_READS_ONLY) && (rec.getReadUnmappedFlag())) {
        return;
    }
    if (rec.isSecondaryOrSupplementary()) {
        return;
    }
    hist.addRecord(rec);
}
 
Example 8
Source File: BestEndMapqPrimaryAlignmentStrategy.java    From picard with MIT License 5 votes vote down vote up
public int compare(final SAMRecord rec1, final SAMRecord rec2) {
    if (rec1.getReadUnmappedFlag()) {
        if (rec2.getReadUnmappedFlag()) return 0;
        else return 1;
    } else if (rec2.getReadUnmappedFlag()) {
        return -1;
    }
    return -SAMUtils.compareMapqs(rec1.getMappingQuality(), rec2.getMappingQuality());
}
 
Example 9
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 10
Source File: CollectJumpingLibraryMetrics.java    From picard with MIT License 5 votes vote down vote up
/**
 * Calculates the mode for outward-facing pairs, using the first SAMPLE_FOR_MODE
 * outward-facing pairs found in INPUT
 */
private double getOutieMode() {

    int samplePerFile = SAMPLE_FOR_MODE / INPUT.size();

    Histogram<Integer> histo = new Histogram<Integer>();

    for (File f : INPUT) {
        SamReader reader = SamReaderFactory.makeDefault().open(f);
        int sampled = 0;
        for (Iterator<SAMRecord> it = reader.iterator(); it.hasNext() && sampled < samplePerFile; ) {
            SAMRecord sam = it.next();
            if (!sam.getFirstOfPairFlag()) {
                continue;
            }
            // If we get here we've hit the end of the aligned reads
            if (sam.getReadUnmappedFlag() && sam.getReferenceIndex() == SAMRecord.NO_ALIGNMENT_REFERENCE_INDEX) {
                break;
            } else if (sam.getReadUnmappedFlag() || sam.getMateUnmappedFlag()) {
                continue;
            } else if ((sam.getAttribute(SAMTag.MQ.name()) == null ||
                    sam.getIntegerAttribute(SAMTag.MQ.name()) >= MINIMUM_MAPPING_QUALITY) &&
                    sam.getMappingQuality() >= MINIMUM_MAPPING_QUALITY &&
                    sam.getMateNegativeStrandFlag() != sam.getReadNegativeStrandFlag() &&
                    sam.getMateReferenceIndex().equals(sam.getReferenceIndex()) &&
                    SamPairUtil.getPairOrientation(sam) == PairOrientation.RF) {
                histo.increment(Math.abs(sam.getInferredInsertSize()));
                sampled++;
            }
        }
        CloserUtil.close(reader);
    }

    return histo.size() > 0 ? histo.getMode() : 0;
}
 
Example 11
Source File: SortedSAMWriter.java    From abra2 with MIT License 5 votes vote down vote up
public MateKey getOriginalReadInfo(SAMRecord read) {
		int pos = read.getAlignmentStart();
		boolean isUnmapped = read.getReadUnmappedFlag();
		boolean isRc = read.getReadNegativeStrandFlag();
		
		String yo = read.getStringAttribute("YO");
		
		if (yo != null) {
			if (yo.startsWith("N/A")) {
				// Original alignment was unmapped
				isUnmapped = true;
//				isRc = false;
				// Orientation is forced to be opposite of mate during realignment
				// regardless of the original alignment.
				isRc = !read.getMateNegativeStrandFlag();
			} else {
				String[] fields = yo.split(":");
				pos = Integer.parseInt(fields[1]);
				isUnmapped = false;
				isRc = fields[2].equals("-") ? true : false;
			}
		}
		
		int readNum = read.getFirstOfPairFlag() ? 1 : 2;
		
		return new MateKey(read.getReadName(), pos, isUnmapped, isRc, readNum, read.getAlignmentStart());
	}
 
Example 12
Source File: AbstractMarkDuplicatesCommandLineProgram.java    From picard with MIT License 5 votes vote down vote up
public static void addDuplicateReadToMetrics(final SAMRecord rec, final DuplicationMetrics metrics) {
    // only update duplicate counts for "decider" reads, not tag-a-long reads
    if (!rec.isSecondaryOrSupplementary() && !rec.getReadUnmappedFlag()) {
        // Update the duplication metrics
        if (!rec.getReadPairedFlag() || rec.getMateUnmappedFlag()) {
            ++metrics.UNPAIRED_READ_DUPLICATES;
        } else {
            ++metrics.READ_PAIR_DUPLICATES;// will need to be divided by 2 at the end
        }
    }
}
 
Example 13
Source File: AlignerInstance.java    From halvade with GNU General Public License v3.0 5 votes vote down vote up
public int writeSAMRecordToContext(SAMRecord sam, boolean useCompact) throws IOException, InterruptedException {
    int count = 0;
    if (!sam.getReadUnmappedFlag()){
        int read1Ref = sam.getReferenceIndex();
        context.getCounter(HalvadeCounters.OUT_BWA_READS).increment(1);
        writableRecord.set(sam);
        int beginpos = sam.getAlignmentStart();
        HashSet<Integer> keys = null;
        if (!mergeBam)
             keys = splitter.getRegions(sam, read1Ref);
        else {
            keys = new HashSet<>();
            keys.add(0);
        }
        for(Integer key : keys) {
            if(useCompact) {
                writeableCompactRegion.setRegion(key, beginpos);
                context.write(writeableCompactRegion, stub);
            } else {
                writableRegion.setChromosomeRegion(read1Ref, beginpos, key);
                context.write(writableRegion, writableRecord);
            }
            count++;
        }
    } else {
        context.getCounter(HalvadeCounters.OUT_UNMAPPED_READS).increment(1);
    }
    return count;
}
 
Example 14
Source File: Reader.java    From dataflow-java with Apache License 2.0 5 votes vote down vote up
/**
 * Checks if the record matches our filter.
 */
static boolean passesFilter(SAMRecord record, Filter filter,
    String referenceName) {
  // If we are looking for only mapped or only unmapped reads then we will use
  // the UnmappedFlag to decide if this read should be rejected.
  if (filter == Filter.UNMAPPED_ONLY && !record.getReadUnmappedFlag()) {
    return false;
  }

  if (filter == Filter.MAPPED_ONLY && record.getReadUnmappedFlag()) {
    return false;
  }

  // If we are looking for mapped reads, then we check the reference name
  // of the read matches the one we are looking for.
  final boolean referenceNameMismatch = referenceName != null &&
      !referenceName.isEmpty() &&
      !referenceName.equals(record.getReferenceName());

  // Note that unmapped mate pair of mapped read will have a reference
  // name set to the reference of its mapped mate.
  if ((filter == Filter.MAPPED_ONLY || filter == Filter.MAPPED_AND_UNMAPPED)
      && referenceNameMismatch) {
    return false;
  }

  return true;
}
 
Example 15
Source File: SAMSlicer.java    From hmftools with GNU General Public License v3.0 4 votes vote down vote up
private boolean samRecordMeetsQualityRequirements(@NotNull final SAMRecord record) {
    return record.getMappingQuality() >= minMappingQuality && !record.getReadUnmappedFlag()
            && (!record.getDuplicateReadFlag() || !dropDuplicates) && !record.isSecondaryOrSupplementary();
}
 
Example 16
Source File: MostDistantPrimaryAlignmentSelectionStrategy.java    From gatk with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public void pickPrimaryAlignment(final HitsForInsert hitsForInsert) {
    final BestEndAlignmentsAccumulator firstEndBest = new BestEndAlignmentsAccumulator();
    final BestEndAlignmentsAccumulator secondEndBest = new BestEndAlignmentsAccumulator();
    final CollectionUtil.MultiMap<Integer, SAMRecord> firstEndBySequence =
            new CollectionUtil.MultiMap<>();
    final BestPairAlignmentsAccumulator pairBest = new BestPairAlignmentsAccumulator();

    for (final SAMRecord rec : hitsForInsert.firstOfPairOrFragment) {
        if (rec.getReadUnmappedFlag()) throw new IllegalStateException();
        firstEndBest.considerBest(rec);
        firstEndBySequence.append(rec.getReferenceIndex(), rec);
    }

    for (final SAMRecord secondEnd: hitsForInsert.secondOfPair) {
        if (secondEnd.getReadUnmappedFlag()) throw new IllegalStateException();
        secondEndBest.considerBest(secondEnd);
        final Collection<SAMRecord> firstEnds = firstEndBySequence.get(secondEnd.getReferenceIndex());
        if (firstEnds != null) {
            for (final SAMRecord firstEnd : firstEnds) {
                pairBest.considerBest(firstEnd, secondEnd);
            }
        }
    }

    final SAMRecord bestFirstEnd;
    final SAMRecord bestSecondEnd;
    if (pairBest.hasBest()) {
        final Map.Entry<SAMRecord, SAMRecord> pairEntry = pickRandomlyFromList(pairBest.bestAlignmentPairs);
        bestFirstEnd = pairEntry.getKey();
        bestSecondEnd = pairEntry.getValue();
    } else {
        if (firstEndBest.hasBest()) {
            bestFirstEnd = pickRandomlyFromList(firstEndBest.bestAlignments);
        } else {
            bestFirstEnd = null;
        }
        if (secondEndBest.hasBest()) {
            bestSecondEnd = pickRandomlyFromList(secondEndBest.bestAlignments);
        } else {
            bestSecondEnd = null;
        }
    }

    if (hitsForInsert.firstOfPairOrFragment.isEmpty() != (bestFirstEnd == null)) {
        throw new IllegalStateException("Should not happen");
    }
    if (hitsForInsert.secondOfPair.isEmpty() != (bestSecondEnd == null)) {
        throw new IllegalStateException("Should not happen");
    }
    if (bestFirstEnd != null) {
        moveToHead(hitsForInsert.firstOfPairOrFragment, bestFirstEnd);
    }
    if (bestSecondEnd != null) {
        moveToHead(hitsForInsert.secondOfPair, bestSecondEnd);
    }
    hitsForInsert.setPrimaryAlignment(0);

    // For non-primary alignments, de-correlate them so that the mate fields don't point at some
    // arbitrary alignment for the other end.

    // No non-primary alignments for one of the ends so nothing to do.
    if (hitsForInsert.firstOfPairOrFragment.size() <= 1 || hitsForInsert.secondOfPair.size() <= 1) return;
    final int amountToSlide = hitsForInsert.firstOfPairOrFragment.size() - 1;
    for (int i = 0; i < amountToSlide; ++i) {
        hitsForInsert.secondOfPair.add(1, null);
    }


}
 
Example 17
Source File: MostDistantPrimaryAlignmentSelectionStrategy.java    From picard with MIT License 4 votes vote down vote up
@Override
public void pickPrimaryAlignment(final HitsForInsert hitsForInsert) {
    final BestEndAlignmentsAccumulator firstEndBest = new BestEndAlignmentsAccumulator();
    final BestEndAlignmentsAccumulator secondEndBest = new BestEndAlignmentsAccumulator();
    final CollectionUtil.MultiMap<Integer, SAMRecord> firstEndBySequence =
            new CollectionUtil.MultiMap<Integer, SAMRecord>();
    final BestPairAlignmentsAccumulator pairBest = new BestPairAlignmentsAccumulator();

    for (final SAMRecord rec : hitsForInsert.firstOfPairOrFragment) {
        if (rec.getReadUnmappedFlag()) throw new IllegalStateException();
        firstEndBest.considerBest(rec);
        firstEndBySequence.append(rec.getReferenceIndex(), rec);
    }

    for (final SAMRecord secondEnd: hitsForInsert.secondOfPair) {
        if (secondEnd.getReadUnmappedFlag()) throw new IllegalStateException();
        secondEndBest.considerBest(secondEnd);
        final Collection<SAMRecord> firstEnds = firstEndBySequence.get(secondEnd.getReferenceIndex());
        if (firstEnds != null) {
            for (final SAMRecord firstEnd : firstEnds) {
                pairBest.considerBest(firstEnd, secondEnd);
            }
        }
    }

    final SAMRecord bestFirstEnd;
    final SAMRecord bestSecondEnd;
    if (pairBest.hasBest()) {
        final Map.Entry<SAMRecord, SAMRecord> pairEntry = pickRandomlyFromList(pairBest.bestAlignmentPairs);
        bestFirstEnd = pairEntry.getKey();
        bestSecondEnd = pairEntry.getValue();
    } else {
        if (firstEndBest.hasBest()) {
            bestFirstEnd = pickRandomlyFromList(firstEndBest.bestAlignments);
        } else {
            bestFirstEnd = null;
        }
        if (secondEndBest.hasBest()) {
            bestSecondEnd = pickRandomlyFromList(secondEndBest.bestAlignments);
        } else {
            bestSecondEnd = null;
        }
    }

    if (hitsForInsert.firstOfPairOrFragment.isEmpty() != (bestFirstEnd == null)) {
        throw new IllegalStateException("Should not happen");
    }
    if (hitsForInsert.secondOfPair.isEmpty() != (bestSecondEnd == null)) {
        throw new IllegalStateException("Should not happen");
    }
    if (bestFirstEnd != null) {
        moveToHead(hitsForInsert.firstOfPairOrFragment, bestFirstEnd);
    }
    if (bestSecondEnd != null) {
        moveToHead(hitsForInsert.secondOfPair, bestSecondEnd);
    }
    hitsForInsert.setPrimaryAlignment(0);

    // For non-primary alignments, de-correlate them so that the mate fields don't point at some
    // arbitrary alignment for the other end.

    // No non-primary alignments for one of the ends so nothing to do.
    if (hitsForInsert.firstOfPairOrFragment.size() <= 1 || hitsForInsert.secondOfPair.size() <= 1) return;
    final int amountToSlide = hitsForInsert.firstOfPairOrFragment.size() - 1;
    for (int i = 0; i < amountToSlide; ++i) {
        hitsForInsert.secondOfPair.add(1, null);
    }


}
 
Example 18
Source File: MergeBamAlignmentTest.java    From picard with MIT License 4 votes vote down vote up
/**
 * Minimal test of merging data from separate read 1 and read 2 alignments
 */
@Test(dataProvider="separateTrimmed")
public void testMergingFromSeparatedReadTrimmedAlignments(final File unmapped, final List<File> r1Align, final List<File> r2Align, final int r1Trim, final int r2Trim, final String testName) throws Exception {
     final File output = File.createTempFile("mergeMultipleAlignmentsTest", ".sam");
     output.deleteOnExit();

    doMergeAlignment(unmapped, null, r1Align, r2Align, r1Trim, r2Trim,
            false, true, false, 1,
            "0", "1.0", "align!", "myAligner",
            true, fasta, output,
            SamPairUtil.PairOrientation.FR, null, null, null, null, null);

    SamReaderFactory factory = SamReaderFactory.makeDefault();
    final SamReader result = factory.open(output);
     for (final SAMRecord sam : result) {
        // Get the alignment record
        final List<File> rFiles = sam.getFirstOfPairFlag() ? r1Align : r2Align;
        SAMRecord alignment = null;
        for (final File f : rFiles) {
            for (final SAMRecord tmp : factory.open(f)) {
                if (tmp.getReadName().equals(sam.getReadName())) {
                    alignment = tmp;
                    break;
                }
            }
            if (alignment != null) break;
        }

        final int trim = sam.getFirstOfPairFlag() ? r1Trim : r2Trim;
        final int notWrittenToFastq = sam.getReadLength() - (trim + alignment.getReadLength());
        final int beginning = sam.getReadNegativeStrandFlag() ? notWrittenToFastq : trim;
        final int end = sam.getReadNegativeStrandFlag() ? trim : notWrittenToFastq;

        if (!sam.getReadUnmappedFlag()) {
            final CigarElement firstMergedCigarElement = sam.getCigar().getCigarElement(0);
            final CigarElement lastMergedCigarElement = sam.getCigar().getCigarElement(sam.getCigar().getCigarElements().size() - 1);
            final CigarElement firstAlignedCigarElement = alignment.getCigar().getCigarElement(0);
            final CigarElement lastAlignedCigarElement = alignment.getCigar().getCigarElement(alignment.getCigar().getCigarElements().size() - 1);

            if (beginning > 0) {
                Assert.assertEquals(firstMergedCigarElement.getOperator(), CigarOperator.S, "First element is not a soft clip");
                Assert.assertEquals(firstMergedCigarElement.getLength(), beginning + ((firstAlignedCigarElement.getOperator() == CigarOperator.S) ? firstAlignedCigarElement.getLength() : 0));
            }
            if (end > 0) {
                Assert.assertEquals(lastMergedCigarElement.getOperator(), CigarOperator.S, "Last element is not a soft clip");
                Assert.assertEquals(lastMergedCigarElement.getLength(), end + ((lastAlignedCigarElement.getOperator() == CigarOperator.S) ? lastAlignedCigarElement.getLength() : 0));
            }
        }
    }

}
 
Example 19
Source File: CgSamBamSequenceDataSource.java    From rtg-tools with BSD 2-Clause "Simplified" License 4 votes vote down vote up
/**
 * Unroll both the read bases and quality data for a CG alignment
 * @param rec the alignment
 * @return the unrolled read
 */
public static SamSequence unrollCgRead(SAMRecord rec) {
  final int projectedSplit = rec.getAlignmentStart() * ((rec.getFlags() & SamBamConstants.SAM_MATE_IS_REVERSE) != 0 ? 1 : -1);
  final byte flags = SamSequence.getFlags(rec);
  final byte[] expandedRead;
  final byte[] expandedQual;
  if (rec.getReadUnmappedFlag()) {
    expandedRead = rec.getReadBases();
    expandedQual = rec.getBaseQualities();
  } else {
    final String gc = rec.getStringAttribute(SamUtils.ATTRIBUTE_CG_RAW_READ_INSTRUCTIONS);
    if (gc == null) {
      throw new NoTalkbackSlimException("SAM Record does not contain CGI read reconstruction attribute: " + rec.getSAMString());
    }
    final byte[] gq = FastaUtils.asciiToRawQuality(SamUtils.allowEmpty(rec.getStringAttribute(SamUtils.ATTRIBUTE_CG_OVERLAP_QUALITY)));
    final byte[] gs = SamUtils.allowEmpty(rec.getStringAttribute(SamUtils.ATTRIBUTE_CG_OVERLAP_BASES)).getBytes();
    final boolean legacyLegacy = gq.length == gs.length / 2;
    expandedRead = unrollLegacyRead(rec.getReadBases(), gs, gc);
    if (expandedRead == null) {
      throw new NoTalkbackSlimException("Could not reconstruct read bases for record: " + rec.getSAMString());
    }
    if (rec.getBaseQualities().length == 0) {
      expandedQual = rec.getBaseQualities();
    } else {
      if (!legacyLegacy && gq.length != gs.length) {
        throw new NoTalkbackSlimException("Unexpected length of CG quality information: " + rec.getSAMString());
      }
      final byte[] samQualities = rec.getBaseQualities();
      if (legacyLegacy) {
        expandedQual = unrollLegacyLegacyQualities(samQualities, gq, gc);
      } else {
        final byte[] bytes = unrollLegacyRead(samQualities, gq, gc);
        expandedQual = bytes;
      }
    }
  }

  final byte[] readBytes = CgUtils.unPad(expandedRead, !rec.getReadNegativeStrandFlag());
  final byte[] readQual = CgUtils.unPad(expandedQual, !rec.getReadNegativeStrandFlag());

  return new SamSequence(rec.getReadName(), readBytes, readQual, flags, projectedSplit);
}
 
Example 20
Source File: CompareToReference2.java    From abra2 with MIT License 3 votes vote down vote up
public int numMismatches(SAMRecord read, boolean includeSoftClipping) {
	int mismatches = 0;
	
	if (!read.getReadUnmappedFlag()) {
		
		mismatches = numDifferences(read, 0, includeSoftClipping);
	}

	return mismatches;
}