Setting the reduce reads count tag was all wrong in a previous commit; fixing.

RR counts are represented as offsets from the first count, but that wasn't being done
correctly when counts are adjusted on the fly.  Also, we were triggering the expensive
conversion and writing to binary tags even when we weren't going to write the read
to disk.

The code has been updated so that unconverted counts are passed to the GATKSAMRecord
and it knows how to encode the tag correctly.  Also, there are now methods to write
to the reduced counts array without forcing the conversion (and methods that do force
the conversion).

Also:
1. counts are now maintained as ints whenever possible.  Only the GATKSAMRecord knows
about the internal encoding.
2. as discussed in meetings today, we updated the encoding so that it can now handle
a range of values that extends to 255 instead of 127 (and is backwards compatible).
3. tests have been moved from SyntheticReadUnitTest to GATKSAMRecordUnitTest accordingly.
This commit is contained in:
Eric Banks 2013-04-29 11:17:38 -04:00
parent 15266da51c
commit 58424e56be
12 changed files with 188 additions and 240 deletions

View File

@ -47,13 +47,11 @@
package org.broadinstitute.sting.gatk.walkers.compression.reducereads;
import com.google.java.contract.Requires;
import it.unimi.dsi.fastutil.bytes.ByteArrayList;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import net.sf.samtools.Cigar;
import net.sf.samtools.CigarElement;
import net.sf.samtools.CigarOperator;
import net.sf.samtools.SAMFileHeader;
import org.broadinstitute.sting.utils.MathUtils;
import org.broadinstitute.sting.utils.exceptions.ReviewedStingException;
import org.broadinstitute.sting.utils.recalibration.EventType;
import org.broadinstitute.sting.utils.sam.GATKSAMReadGroupRecord;
@ -89,12 +87,12 @@ public class SyntheticRead {
// Rather than storing a separate list for each attribute in SingleBaseInfo, store one list to reduce memory footprint.
private static class SingleBaseInfo {
byte baseIndexOrdinal; // enum BaseIndex.ordinal
byte count;
int count;
byte qual;
byte insertionQual;
byte deletionQual;
SingleBaseInfo(byte baseIndexOrdinal, byte count, byte qual, byte insertionQual, byte deletionQual) {
SingleBaseInfo(byte baseIndexOrdinal, int count, byte qual, byte insertionQual, byte deletionQual) {
this.baseIndexOrdinal = baseIndexOrdinal;
this.count = count;
this.qual = qual;
@ -170,22 +168,6 @@ public class SyntheticRead {
this.strandType = strandType;
}
public SyntheticRead(ObjectArrayList<BaseIndex> bases, ByteArrayList counts, ByteArrayList quals, ByteArrayList insertionQuals, ByteArrayList deletionQuals, double mappingQuality, SAMFileHeader header, GATKSAMReadGroupRecord readGroupRecord, String contig, int contigIndex, String readName, int refStart, boolean hasIndelQualities, StrandType strandType) {
basesCountsQuals = new ObjectArrayList<SingleBaseInfo>(bases.size());
for (int i = 0; i < bases.size(); ++i) {
basesCountsQuals.add(new SingleBaseInfo(bases.get(i).getOrdinalByte(), counts.get(i), quals.get(i), insertionQuals.get(i), deletionQuals.get(i)));
}
this.mappingQuality = mappingQuality;
this.header = header;
this.readGroupRecord = readGroupRecord;
this.contig = contig;
this.contigIndex = contigIndex;
this.readName = readName;
this.refStart = refStart;
this.hasIndelQualities = hasIndelQualities;
this.strandType = strandType;
}
/**
* Easy access to keep adding to a running consensus that has already been
* initialized with the correct read name and refStart
@ -194,7 +176,7 @@ public class SyntheticRead {
* @param count number of reads with this base
*/
@Requires("count <= Byte.MAX_VALUE")
public void add(BaseIndex base, byte count, byte qual, byte insQual, byte delQual, double mappingQuality) {
public void add(BaseIndex base, int count, byte qual, byte insQual, byte delQual, double mappingQuality) {
basesCountsQuals.add(new SingleBaseInfo(base.getOrdinalByte(), count, qual, insQual, delQual));
this.mappingQuality += mappingQuality;
}
@ -285,22 +267,14 @@ public class SyntheticRead {
});
}
protected byte [] convertBaseCounts() {
byte[] countsArray = convertVariableGivenBases(new SingleBaseInfoIterator() {
public Byte next() {
return it.next().count;
}
});
if (countsArray.length == 0)
throw new ReviewedStingException("Reduced read has counts array of length 0");
byte[] compressedCountsArray = new byte [countsArray.length];
compressedCountsArray[0] = countsArray[0];
for (int i = 1; i < countsArray.length; i++)
compressedCountsArray[i] = (byte) MathUtils.bound(countsArray[i] - compressedCountsArray[0], Byte.MIN_VALUE, Byte.MAX_VALUE);
return compressedCountsArray;
protected int[] convertBaseCounts() {
int[] variableArray = new int[getReadLengthWithNoDeletions()];
int i = 0;
for (final SingleBaseInfo singleBaseInfo : basesCountsQuals) {
if (singleBaseInfo.baseIndexOrdinal != BaseIndex.D.getOrdinalByte())
variableArray[i++] = singleBaseInfo.count;
}
return variableArray;
}
private byte [] convertReadBases() {
@ -376,7 +350,6 @@ public class SyntheticRead {
variableArray[i++] = count;
}
return variableArray;
}
/**

View File

@ -277,7 +277,7 @@ public class DeBruijnAssembler extends LocalAssemblyEngine {
for( final GATKSAMRecord read : reads ) {
final byte[] sequence = read.getReadBases();
final byte[] qualities = read.getBaseQualities();
final byte[] reducedReadCounts = read.getReducedReadCounts(); // will be null if read is not reduced
final int[] reducedReadCounts = read.getReducedReadCounts(); // will be null if read is not reduced
if ( sequence.length > kmerLength + KMER_OVERLAP ) {
int lastGood = -1; // the index of the last good base we've seen
for( int end = 0; end < sequence.length; end++ ) {

View File

@ -1,127 +0,0 @@
/*
* By downloading the PROGRAM you agree to the following terms of use:
*
* BROAD INSTITUTE - SOFTWARE LICENSE AGREEMENT - FOR ACADEMIC NON-COMMERCIAL RESEARCH PURPOSES ONLY
*
* This Agreement is made between the Broad Institute, Inc. with a principal address at 7 Cambridge Center, Cambridge, MA 02142 (BROAD) and the LICENSEE and is effective at the date the downloading is completed (EFFECTIVE DATE).
*
* WHEREAS, LICENSEE desires to license the PROGRAM, as defined hereinafter, and BROAD wishes to have this PROGRAM utilized in the public interest, subject only to the royalty-free, nonexclusive, nontransferable license rights of the United States Government pursuant to 48 CFR 52.227-14; and
* WHEREAS, LICENSEE desires to license the PROGRAM and BROAD desires to grant a license on the following terms and conditions.
* NOW, THEREFORE, in consideration of the promises and covenants made herein, the parties hereto agree as follows:
*
* 1. DEFINITIONS
* 1.1 PROGRAM shall mean copyright in the object code and source code known as GATK2 and related documentation, if any, as they exist on the EFFECTIVE DATE and can be downloaded from http://www.broadinstitute/GATK on the EFFECTIVE DATE.
*
* 2. LICENSE
* 2.1 Grant. Subject to the terms of this Agreement, BROAD hereby grants to LICENSEE, solely for academic non-commercial research purposes, a non-exclusive, non-transferable license to: (a) download, execute and display the PROGRAM and (b) create bug fixes and modify the PROGRAM.
* The LICENSEE may apply the PROGRAM in a pipeline to data owned by users other than the LICENSEE and provide these users the results of the PROGRAM provided LICENSEE does so for academic non-commercial purposes only. For clarification purposes, academic sponsored research is not a commercial use under the terms of this Agreement.
* 2.2 No Sublicensing or Additional Rights. LICENSEE shall not sublicense or distribute the PROGRAM, in whole or in part, without prior written permission from BROAD. LICENSEE shall ensure that all of its users agree to the terms of this Agreement. LICENSEE further agrees that it shall not put the PROGRAM on a network, server, or other similar technology that may be accessed by anyone other than the LICENSEE and its employees and users who have agreed to the terms of this agreement.
* 2.3 License Limitations. Nothing in this Agreement shall be construed to confer any rights upon LICENSEE by implication, estoppel, or otherwise to any computer software, trademark, intellectual property, or patent rights of BROAD, or of any other entity, except as expressly granted herein. LICENSEE agrees that the PROGRAM, in whole or part, shall not be used for any commercial purpose, including without limitation, as the basis of a commercial software or hardware product or to provide services. LICENSEE further agrees that the PROGRAM shall not be copied or otherwise adapted in order to circumvent the need for obtaining a license for use of the PROGRAM.
*
* 3. OWNERSHIP OF INTELLECTUAL PROPERTY
* LICENSEE acknowledges that title to the PROGRAM shall remain with BROAD. The PROGRAM is marked with the following BROAD copyright notice and notice of attribution to contributors. LICENSEE shall retain such notice on all copies. LICENSEE agrees to include appropriate attribution if any results obtained from use of the PROGRAM are included in any publication.
* Copyright 2012 Broad Institute, Inc.
* Notice of attribution: The GATK2 program was made available through the generosity of Medical and Population Genetics program at the Broad Institute, Inc.
* LICENSEE shall not use any trademark or trade name of BROAD, or any variation, adaptation, or abbreviation, of such marks or trade names, or any names of officers, faculty, students, employees, or agents of BROAD except as states above for attribution purposes.
*
* 4. INDEMNIFICATION
* LICENSEE shall indemnify, defend, and hold harmless BROAD, and their respective officers, faculty, students, employees, associated investigators and agents, and their respective successors, heirs and assigns, (Indemnitees), against any liability, damage, loss, or expense (including reasonable attorneys fees and expenses) incurred by or imposed upon any of the Indemnitees in connection with any claims, suits, actions, demands or judgments arising out of any theory of liability (including, without limitation, actions in the form of tort, warranty, or strict liability and regardless of whether such action has any factual basis) pursuant to any right or license granted under this Agreement.
*
* 5. NO REPRESENTATIONS OR WARRANTIES
* THE PROGRAM IS DELIVERED AS IS. BROAD MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND CONCERNING THE PROGRAM OR THE COPYRIGHT, EXPRESS OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT OR OTHER DEFECTS, WHETHER OR NOT DISCOVERABLE. BROAD EXTENDS NO WARRANTIES OF ANY KIND AS TO PROGRAM CONFORMITY WITH WHATEVER USER MANUALS OR OTHER LITERATURE MAY BE ISSUED FROM TIME TO TIME.
* IN NO EVENT SHALL BROAD OR ITS RESPECTIVE DIRECTORS, OFFICERS, EMPLOYEES, AFFILIATED INVESTIGATORS AND AFFILIATES BE LIABLE FOR INCIDENTAL OR CONSEQUENTIAL DAMAGES OF ANY KIND, INCLUDING, WITHOUT LIMITATION, ECONOMIC DAMAGES OR INJURY TO PROPERTY AND LOST PROFITS, REGARDLESS OF WHETHER BROAD SHALL BE ADVISED, SHALL HAVE OTHER REASON TO KNOW, OR IN FACT SHALL KNOW OF THE POSSIBILITY OF THE FOREGOING.
*
* 6. ASSIGNMENT
* This Agreement is personal to LICENSEE and any rights or obligations assigned by LICENSEE without the prior written consent of BROAD shall be null and void.
*
* 7. MISCELLANEOUS
* 7.1 Export Control. LICENSEE gives assurance that it will comply with all United States export control laws and regulations controlling the export of the PROGRAM, including, without limitation, all Export Administration Regulations of the United States Department of Commerce. Among other things, these laws and regulations prohibit, or require a license for, the export of certain types of software to specified countries.
* 7.2 Termination. LICENSEE shall have the right to terminate this Agreement for any reason upon prior written notice to BROAD. If LICENSEE breaches any provision hereunder, and fails to cure such breach within thirty (30) days, BROAD may terminate this Agreement immediately. Upon termination, LICENSEE shall provide BROAD with written assurance that the original and all copies of the PROGRAM have been destroyed, except that, upon prior written authorization from BROAD, LICENSEE may retain a copy for archive purposes.
* 7.3 Survival. The following provisions shall survive the expiration or termination of this Agreement: Articles 1, 3, 4, 5 and Sections 2.2, 2.3, 7.3, and 7.4.
* 7.4 Notice. Any notices under this Agreement shall be in writing, shall specifically refer to this Agreement, and shall be sent by hand, recognized national overnight courier, confirmed facsimile transmission, confirmed electronic mail, or registered or certified mail, postage prepaid, return receipt requested. All notices under this Agreement shall be deemed effective upon receipt.
* 7.5 Amendment and Waiver; Entire Agreement. This Agreement may be amended, supplemented, or otherwise modified only by means of a written instrument signed by all parties. Any waiver of any rights or failure to act in a specific instance shall relate only to such instance and shall not be construed as an agreement to waive any rights or fail to act in any other instance, whether or not similar. This Agreement constitutes the entire agreement among the parties with respect to its subject matter and supersedes prior agreements or understandings between the parties relating to its subject matter.
* 7.6 Binding Effect; Headings. This Agreement shall be binding upon and inure to the benefit of the parties and their respective permitted successors and assigns. All headings are for convenience only and shall not affect the meaning of any provision of this Agreement.
* 7.7 Governing Law. This Agreement shall be construed, governed, interpreted and applied in accordance with the internal laws of the Commonwealth of Massachusetts, U.S.A., without regard to conflict of laws principles.
*/
package org.broadinstitute.sting.gatk.walkers.compression.reducereads;
import it.unimi.dsi.fastutil.bytes.ByteArrayList;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import net.sf.samtools.SAMFileHeader;
import org.broadinstitute.sting.BaseTest;
import org.broadinstitute.sting.utils.sam.ArtificialSAMUtils;
import org.broadinstitute.sting.utils.sam.GATKSAMReadGroupRecord;
import org.broadinstitute.sting.utils.sam.GATKSAMRecord;
import org.testng.Assert;
import org.testng.annotations.Test;
public class SyntheticReadUnitTest extends BaseTest {
final SAMFileHeader artificialSAMHeader = ArtificialSAMUtils.createArtificialSamHeader(1, 1, 1);
final GATKSAMReadGroupRecord artificialGATKRG = new GATKSAMReadGroupRecord("synthetic");
final String artificialContig = "1";
final int artificialContigIndex = 0;
final String artificialReadName = "synth";
final int artificialRefStart = 1;
final double artificialMappingQuality = 60;
@Test
public void testBaseCounts() {
BaseIndex [] bases = new BaseIndex[] {BaseIndex.A,BaseIndex.A,BaseIndex.A,BaseIndex.A};
byte[] quals = new byte[] {20, 20, 20, 20 };
TestRead [] testReads = new TestRead [] {
new TestRead(bases, quals, new byte[] {100, 100, 100, 101}, new byte [] {100, 0, 0, 1}),
new TestRead(bases, quals, new byte[] {1, 100, 100, 0}, new byte [] {1, 99, 99, -1}),
new TestRead(bases, quals, new byte[] {127, 100, 0, 1}, new byte [] {127, -27, -127, -126}),
new TestRead(bases, quals, new byte[] {1, 127, 51, 126}, new byte [] {1, 126, 50, 125})};
for (TestRead testRead : testReads) {
SyntheticRead syntheticRead = new SyntheticRead(new ObjectArrayList<BaseIndex>(testRead.getBases()), new ByteArrayList(testRead.getCounts()), new ByteArrayList(testRead.getQuals()), new ByteArrayList(testRead.getInsQuals()), new ByteArrayList(testRead.getDelQuals()), artificialMappingQuality, artificialSAMHeader, artificialGATKRG, artificialContig, artificialContigIndex, artificialReadName, artificialRefStart, false, SyntheticRead.StrandType.STRANDLESS);
Assert.assertEquals(syntheticRead.convertBaseCounts(), testRead.getExpectedCounts());
}
}
private class TestRead {
BaseIndex[] bases;
byte[] quals;
byte[] insQuals;
byte[] delQuals;
byte[] counts;
byte[] expectedCounts;
private TestRead(BaseIndex[] bases, byte[] quals, byte[] counts, byte[] expectedCounts) {
this.bases = bases;
this.quals = quals;
this.insQuals = quals;
this.delQuals = quals;
this.counts = counts;
this.expectedCounts = expectedCounts;
}
public BaseIndex[] getBases() {
return bases;
}
public byte[] getQuals() {
return quals;
}
public byte[] getInsQuals() {
return insQuals;
}
public byte[] getDelQuals() {
return delQuals;
}
public byte[] getCounts() {
return counts;
}
public byte[] getExpectedCounts() {
return expectedCounts;
}
}
}

View File

@ -63,13 +63,13 @@ public class UnifiedGenotyperReducedReadsIntegrationTest extends WalkerTest {
public void testReducedBam() {
WalkerTest.WalkerTestSpec spec = new WalkerTest.WalkerTestSpec(
"-T UnifiedGenotyper --disableDithering -R " + b37KGReference + " --no_cmdline_in_header -I " + privateTestDir + "bamExample.ReducedRead.ADAnnotation.bam -o %s -L 1:67,225,396-67,288,518", 1,
Arrays.asList("da3fd775c8add1f7962baabf06b7d372"));
Arrays.asList("e6565060b44a7804935973efcd56e596"));
executeTest("test calling on a ReducedRead BAM", spec);
}
@Test
public void testReducedBamSNPs() {
testReducedCalling("SNP", "76244ab1be60814f1412e6cd09e546cc");
testReducedCalling("SNP", "ab776d74c41ce2b859e2b2466a76204a");
}
@Test

View File

@ -698,7 +698,7 @@ public class MathUtils {
return maxI;
}
public static byte arrayMax(final byte[] array) {
public static int arrayMax(final int[] array) {
return array[maxElementIndex(array)];
}

View File

@ -380,7 +380,7 @@ public class ClippingOp {
}
if (read.isReducedRead()) {
final byte[] reducedCounts = new byte[newLength];
final int[] reducedCounts = new int[newLength];
System.arraycopy(read.getReducedReadCounts(), copyStart, reducedCounts, 0, newLength);
hardClippedRead.setReducedReadCounts(reducedCounts);
}

View File

@ -322,6 +322,8 @@ public class PileupElement implements Comparable<PileupElement> {
* Adjusts the representative count of this pileup element.
* Throws an exception if this element does not represent a reduced read.
*
* See GATKSAMRecord.adjustReducedCount() for warnings on the permanency of this operation.
*
* @param adjustmentFactor how much to adjust the representative count (can be positive or negative)
*/
public void adjustRepresentativeCount(final int adjustmentFactor) {

View File

@ -27,6 +27,7 @@ package org.broadinstitute.sting.utils.sam;
import com.google.java.contract.Ensures;
import net.sf.samtools.*;
import org.broadinstitute.sting.utils.MathUtils;
import org.broadinstitute.sting.utils.NGSPlatform;
import org.broadinstitute.sting.utils.exceptions.ReviewedStingException;
import org.broadinstitute.sting.utils.recalibration.EventType;
@ -69,7 +70,7 @@ public class GATKSAMRecord extends BAMRecord {
// the SAMRecord data we're caching
private String mReadString = null;
private GATKSAMReadGroupRecord mReadGroup = null;
private byte[] reducedReadCounts = null;
private int[] reducedReadCounts = null;
private final static int UNINITIALIZED = -1;
private int softStart = UNINITIALIZED;
private int softEnd = UNINITIALIZED;
@ -360,18 +361,34 @@ public class GATKSAMRecord extends BAMRecord {
*
* as one might expect.
*
* @return a byte[] holding the depth of the bases in this reduced read, or null if this isn't a reduced read
* @return a int[] holding the depth of the bases in this reduced read, or null if this isn't a reduced read
*/
public byte[] getReducedReadCounts() {
public int[] getReducedReadCounts() {
if ( ! retrievedReduceReadCounts ) {
final byte[] tag = getByteArrayAttribute(REDUCED_READ_CONSENSUS_TAG);
if ( tag != null ) reducedReadCounts = decodeReadReadCounts(tag);
if ( tag != null ) reducedReadCounts = decodeReduceReadCounts(tag);
retrievedReduceReadCounts = true;
}
return reducedReadCounts;
}
/**
* The number of bases corresponding the i'th base of the reduced read.
*
* @param i the read based coordinate inside the read
* @return the number of bases corresponding to the i'th base of the reduced read
*/
public final int getReducedCount(final int i) {
if ( !isReducedRead() )
throw new IllegalArgumentException("error trying to retrieve the reduced count from a read that is not reduced");
if ( i < 0 || i >= getReadBases().length )
throw new IllegalArgumentException("illegal offset used when retrieving reduced counts: " + i);
final int[] reducedCounts = getReducedReadCounts();
return reducedCounts[i];
}
/**
* Is this read a reduced read?
* @return true if yes
@ -381,65 +398,69 @@ public class GATKSAMRecord extends BAMRecord {
}
/**
* Set the reduced read counts tag for this record to counts
*
* WARNING -- this function assumes that counts is encoded as a difference in value count
* of count[i] - count[0]. It is not a straight counting of the bases in the read.
* Set the reduced read counts tag for this record.
* Note that this method is slightly expensive as it converts to the correct reduced counts representation and sets the
* appropriate binary tag. If you want to modify the reduced count in place without triggering the permanent conversion
* internally, use the #setReducedCount() method.
*
* @param counts the count array
*/
public void setReducedReadCountsTag(final byte[] counts) {
retrievedReduceReadCounts = false;
setAttribute(REDUCED_READ_CONSENSUS_TAG, counts);
public void setReducedReadCountsTag(final int[] counts) {
setAttribute(REDUCED_READ_CONSENSUS_TAG, encodeReduceReadCounts(counts));
retrievedReduceReadCounts = false; // need to force new decode in case we had to handle precision problems with the counts
}
/**
* @see #setReducedReadCountsTag() and uses the currently stored values of the internal array.
* Useful if you've been using #setReducedCount() to modify the reduced count and now want to trigger the expensive conversion.
*/
public void setReducedReadCountsTag() {
if ( !retrievedReduceReadCounts )
throw new IllegalStateException("Trying to write the reduced reads counts using an uninitialized internal array of counts");
setReducedReadCountsTag(reducedReadCounts);
}
/**
* Sets the reduced read count corresponding the i'th base of the reduced read.
*
* WARNING: does not actually write this value permanently to the binary tags for this read. To trigger the conversion
* and push that value into the read's binary tags, use #setReducedReadCountsTag().
*
* @param i the read based coordinate inside the read
* @param count the new count
*/
public final void setReducedCount(final int i, final int count) {
if ( count < 0 )
throw new IllegalArgumentException("the reduced count cannot be set to a negative value");
if ( !isReducedRead() )
throw new IllegalArgumentException("error trying to set the reduced count for a read that is not reduced");
if ( i < 0 || i >= getReadBases().length )
throw new IllegalArgumentException("illegal offset used when setting the reduced count: " + i);
// force the initialization of the counts array if it hasn't happened yet
getReducedReadCounts()[i] = count;
}
/**
* Set the reduced read counts tag for this record to counts
*
* Note that this function does not set the REDUCED_READ_CONSENSUS_TAG value, it's purely for manipulating
* the underlying reduced reads count
*
* TODO -- this function needs to be fixed when the RR spec is set to 2.0
* WARNING: does not actually write this value permanently to the binary tags for this read. To trigger the conversion
* and push that value into the read's binary tags, use #setReducedReadCountsTag().
*
* @param counts the count array
*/
public void setReducedReadCounts(final byte[] counts) {
if ( counts.length != getReadBases().length ) throw new IllegalArgumentException("Reduced counts length " + counts.length + " != bases length " + getReadBases().length);
public void setReducedReadCounts(final int[] counts) {
if ( counts.length != getReadBases().length )
throw new IllegalArgumentException("Reduced counts length " + counts.length + " != bases length " + getReadBases().length);
retrievedReduceReadCounts = true;
reducedReadCounts = counts;
}
/**
* The number of bases corresponding the i'th base of the reduced read.
*
* @param i the read based coordinate inside the read
* @return the number of bases corresponding to the i'th base of the reduced read
*/
public final byte getReducedCount(final int i) {
if ( !isReducedRead() )
throw new IllegalArgumentException("error trying to retrieve the reduced count from a read that is not reduced");
final byte[] reducedCounts = getReducedReadCounts();
return reducedCounts[i];
}
/**
* Sets the number of bases corresponding the i'th base of the reduced read.
*
* @param i the read based coordinate inside the read
* @param count the new count
*/
public final void setReducedCount(final int i, final byte count) {
if ( count < 0 )
throw new IllegalArgumentException("the reduced count cannot be set to a negative value");
if ( !isReducedRead() )
throw new IllegalArgumentException("error trying to set the reduced count for a read that is not reduced");
final byte[] reducedCounts = getReducedReadCounts();
reducedCounts[i] = count;
setReducedReadCountsTag(reducedCounts);
}
/**
* Sets the number of bases corresponding the i'th base of the reduced read.
* WARNING: does not actually write this value permanently to the binary tags for this read. To trigger the conversion
* and push that value into the read's binary tags, use #setReducedReadCountsTag().
*
* @param i the read based coordinate inside the read
* @param adjustmentFactor how much to add/subtract to the current count
@ -447,9 +468,10 @@ public class GATKSAMRecord extends BAMRecord {
public final void adjustReducedCount(final int i, final int adjustmentFactor) {
if ( !isReducedRead() )
throw new IllegalArgumentException("error trying to set the reduced count for a read that is not reduced");
final byte[] reducedCounts = getReducedReadCounts();
final byte newCount = (byte)(reducedCounts[i] + adjustmentFactor);
setReducedCount(i, newCount);
if ( i < 0 || i >= getReadBases().length )
throw new IllegalArgumentException("illegal offset used when setting the reduced count: " + i);
setReducedCount(i, getReducedReadCounts()[i] + adjustmentFactor);
}
/**
@ -462,21 +484,43 @@ public class GATKSAMRecord extends BAMRecord {
* as one might expect.
*
* @param countsFromTag a non-null byte[] containing the tag encoded reduce reads counts
* @return a non-null byte[] containing the true depth values for the vector
* @return a non-null int[] containing the true depth values for the vector
*/
private byte[] decodeReadReadCounts(final byte[] countsFromTag) {
protected static int[] decodeReduceReadCounts(final byte[] countsFromTag) {
final int n = countsFromTag.length;
final byte[] result = new byte[n];
final byte firstCount = countsFromTag[0];
final int[] result = new int[n];
final int firstCount = countsFromTag[0] & 0xff; // unsigned byte
result[0] = firstCount;
for ( int i = 1; i < n; i++) {
final byte offsetCount = countsFromTag[i];
result[i] = (byte) Math.min(firstCount + offsetCount, Byte.MAX_VALUE);
for ( int i = 1; i < n; i++ ) {
final int offsetCount = countsFromTag[i] & 0xff; // unsigned byte
result[i] = (firstCount + offsetCount) % 256;
}
return result;
}
/**
* Converts int array from straight counts to the appropriate reduce reads representation in BAM (offset from first value)
*
* @param counts the counts array
* @return non-null converted byte array
*/
protected static byte[] encodeReduceReadCounts(final int[] counts) {
if ( counts.length == 0 )
throw new IllegalArgumentException("Trying to write a reduced read with a counts array of length 0");
final byte[] compressedCountsArray = new byte[counts.length];
final int firstCount = (int) MathUtils.bound(counts[0], 0, 255); // we want an unsigned byte capped at max byte representation
compressedCountsArray[0] = (byte)firstCount;
for ( int i = 1; i < counts.length; i++ ) {
final int count = (int) MathUtils.bound(counts[i], 0, 255);
final byte offset = (byte)(count - firstCount + (count >= firstCount ? 0 : 256)); // unsigned byte
compressedCountsArray[i] = offset;
}
return compressedCountsArray;
}
///////////////////////////////////////////////////////////////////////////////
// *** GATKSAMRecord specific methods ***//
///////////////////////////////////////////////////////////////////////////////
@ -694,7 +738,7 @@ public class GATKSAMRecord extends BAMRecord {
emptyRead.setCigarString("");
emptyRead.setReadBases(new byte[0]);
emptyRead.setBaseQualities(new byte[0]);
if ( read.isReducedRead() ) emptyRead.setReducedReadCounts(new byte[0]);
if ( read.isReducedRead() ) emptyRead.setReducedReadCounts(new int[0]);
SAMReadGroupRecord samRG = read.getReadGroup();
emptyRead.clearAttributes();
@ -728,7 +772,7 @@ public class GATKSAMRecord extends BAMRecord {
/**
* A caching version of ReadUtils.getAdaptorBoundary()
*
* @see ReadUtils.getAdaptorBoundary(SAMRecord) for more information about the meaning of this function
* see #ReadUtils.getAdaptorBoundary(SAMRecord) for more information about the meaning of this function
*
* WARNING -- this function caches a value depending on the inferred insert size and alignment starts
* and stops of this read and its mate. Changing these values in any way will invalidate the cached value.

View File

@ -62,7 +62,7 @@ public class ReadUtils {
return 1;
// compute mean representative read counts
final byte[] counts = read.getReducedReadCounts();
final int[] counts = read.getReducedReadCounts();
return (int)Math.round((double)MathUtils.sum(counts)/counts.length);
}

View File

@ -150,7 +150,7 @@ public class AlleleBiasedDownsamplingUtilsUnitTest extends BaseTest {
}
if ( originalReducedCount > 0 ) {
final GATKSAMRecord read = ArtificialSAMUtils.createArtificialRead(header, "read", 0, 1, 1);
read.setReducedReadCountsTag(new byte[]{(byte)originalReducedCount});
read.setReducedReadCountsTag(new int[]{originalReducedCount});
elements.add(indexToPutReducedRead, new PileupElement(read, 0, new CigarElement(1, CigarOperator.M), 0, 0));
}

View File

@ -352,15 +352,15 @@ public class ReadClipperUnitTest extends BaseTest {
@Test(enabled = true)
public void testHardClipReducedRead() {
GATKSAMRecord read = ReadClipperTestUtils.makeReadFromCigar("10M");
final byte[] counts = new byte[read.getReadLength()];
for ( int i = 0; i < counts.length; i++ ) counts[i] = (byte)i;
final int[] counts = new int[read.getReadLength()];
for ( int i = 0; i < counts.length; i++ ) counts[i] = i;
read.setReducedReadCounts(counts);
int alnStart = read.getAlignmentStart();
int alnEnd = read.getAlignmentEnd();
int readLength = read.getReadLength();
for (int i = 0; i < readLength / 2; i++) {
GATKSAMRecord clippedRead = ReadClipper.hardClipBothEndsByReferenceCoordinates(read, alnStart + i, alnEnd - i);
final byte[] expectedReducedCounts = Arrays.copyOfRange(counts, i + 1, readLength - i - 1);
final int[] expectedReducedCounts = Arrays.copyOfRange(counts, i + 1, readLength - i - 1);
Assert.assertEquals(clippedRead.getReducedReadCounts(), expectedReducedCounts);
}
}

View File

@ -31,15 +31,18 @@ import org.broadinstitute.sting.utils.locusiterator.LocusIteratorByState;
import org.broadinstitute.sting.utils.pileup.PileupElement;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import java.util.ArrayList;
import java.util.List;
public class GATKSAMRecordUnitTest extends BaseTest {
GATKSAMRecord read, reducedRead;
final static String BASES = "ACTG";
final static String QUALS = "!+5?";
final private static byte[] REDUCED_READ_COUNTS = new byte[]{10, 20, 30, 40, 1};
final private static byte[] REDUCED_READ_COUNTS_OFFSETS = new byte[]{10, 10, 20, 30, -9}; // just the offsets
final private static int[] REDUCED_READ_COUNTS = new int[]{10, 20, 30, 40, 1};
@BeforeClass
public void init() {
@ -52,11 +55,13 @@ public class GATKSAMRecordUnitTest extends BaseTest {
reducedRead = ArtificialSAMUtils.createArtificialRead(header, "reducedRead", 0, 1, BASES.length());
reducedRead.setReadBases(BASES.getBytes());
reducedRead.setBaseQualityString(QUALS);
reducedRead.setReducedReadCountsTag(REDUCED_READ_COUNTS_OFFSETS);
reducedRead.setReducedReadCountsTag(REDUCED_READ_COUNTS);
}
@Test
public void testReducedReads() {
reducedRead.setReducedReadCountsTag(REDUCED_READ_COUNTS);
Assert.assertFalse(read.isReducedRead(), "isReducedRead is false for normal read");
Assert.assertEquals(read.getReducedReadCounts(), null, "No reduced read tag in normal read");
@ -73,16 +78,17 @@ public class GATKSAMRecordUnitTest extends BaseTest {
@Test(expectedExceptions = IllegalArgumentException.class)
public void testSetReducedTagOnNormalRead() {
read.setReducedCount(0, (byte)2);
read.setReducedCount(0, 2);
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void testSetReducedCountToNegativeNumber() {
reducedRead.setReducedCount(0, (byte)1000);
public void testAdjustReducedCountToNegativeNumber() {
reducedRead.setReducedCount(0, 1);
reducedRead.adjustReducedCount(0, -2);
}
@Test
public void testSetReducedTagOnReducedRead() {
public void testSetReducedCountOnReducedRead() {
for (int i = 0; i < reducedRead.getReadLength(); i++) {
final byte newCount = (byte)i;
reducedRead.setReducedCount(i, newCount);
@ -96,8 +102,35 @@ public class GATKSAMRecordUnitTest extends BaseTest {
}
}
@Test
public void testReducedReadEncodeAndDecode() {
// encode
byte[] encoded = GATKSAMRecord.encodeReduceReadCounts(REDUCED_READ_COUNTS);
// decode
int[] decoded = GATKSAMRecord.decodeReduceReadCounts(encoded);
// for the heck of it, let's encode and decode again!
encoded = GATKSAMRecord.encodeReduceReadCounts(decoded);
decoded = GATKSAMRecord.decodeReduceReadCounts(encoded);
for (int i = 0; i < decoded.length; i++)
Assert.assertEquals(decoded[i], REDUCED_READ_COUNTS[i]);
}
@Test
public void testByteBoundsOnReducedTag() {
reducedRead.setReducedCount(0, 1000);
reducedRead.setReducedReadCountsTag();
reducedRead.adjustReducedCount(0, -255);
Assert.assertEquals(reducedRead.getReducedCount(0), 0);
}
@Test
public void testReducedReadPileupElement() {
reducedRead.setReducedReadCountsTag(REDUCED_READ_COUNTS);
PileupElement readp = LocusIteratorByState.createPileupForReadAndOffset(read, 0);
PileupElement reducedreadp = LocusIteratorByState.createPileupForReadAndOffset(reducedRead, 0);
@ -167,9 +200,32 @@ public class GATKSAMRecordUnitTest extends BaseTest {
@Test
public void testGetReducedCountsIsCorrect() {
final byte[] counts = reducedRead.getReducedReadCounts();
final int[] counts = reducedRead.getReducedReadCounts();
Assert.assertNotSame(counts, reducedRead.getAttribute(GATKSAMRecord.REDUCED_READ_CONSENSUS_TAG));
for ( int i = 0; i < counts.length; i++ )
Assert.assertEquals(counts[i], reducedRead.getReducedCount(i), "Reduced counts vector not equal to getReducedCount(i) at " + i);
}
@DataProvider(name = "ReducedReadCountConversionProvider")
public Object[][] ReducedReadCountConversionTestData() {
List<Object[]> tests = new ArrayList<Object[]>();
tests.add(new Object[]{new int[] {100, 100, 100, 101}, new byte[] {100, 0, 0, 1}});
tests.add(new Object[]{new int[] {1, 100, 100, 0}, new byte[] {1, 99, 99, -1}});
tests.add(new Object[]{new int[] {127, 100, 0, 1}, new byte[] {127, -27, -127, -126}});
tests.add(new Object[]{new int[] {1, 127, 51, 126}, new byte[] {1, 126, 50, 125}});
tests.add(new Object[]{new int[] {300, 127, 1, 255}, new byte[] {-1, -128, 2, 0}});
tests.add(new Object[]{new int[] {1, 300, 51, 126}, new byte[] {1, -2, 50, 125}});
return tests.toArray(new Object[][]{});
}
@Test(dataProvider = "ReducedReadCountConversionProvider", enabled = true)
public void reducedReadCountConversionTest(final int[] counts, final byte[] expectedConversion) {
reducedRead.setReducedReadCountsTag(counts);
final byte[] actualConversion = reducedRead.getByteArrayAttribute(GATKSAMRecord.REDUCED_READ_CONSENSUS_TAG);
for ( int i = 0; i < actualConversion.length; i++ )
Assert.assertEquals(actualConversion[i], expectedConversion[i], "Conversion differs at position " + i + ": " + actualConversion[i] + " vs. " + expectedConversion[i]);
}
}