Merge pull request #539 from broadinstitute/eb_hard_clip_exon_overhangs_for_ami

Add the capability to the N-cigar splitter to also hard-clip off overhan...
This commit is contained in:
amilev 2014-03-03 12:23:11 -05:00
commit cecdd2f2c5
5 changed files with 720 additions and 142 deletions

View File

@ -0,0 +1,380 @@
/*
* 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.rnaseq;
import net.sf.samtools.SAMFileWriter;
import net.sf.samtools.SAMRecordCoordinateComparator;
import org.apache.log4j.Logger;
import org.broadinstitute.sting.utils.GenomeLoc;
import org.broadinstitute.sting.utils.GenomeLocParser;
import org.broadinstitute.sting.utils.clipping.ReadClipper;
import org.broadinstitute.sting.utils.fasta.CachingIndexedFastaSequenceFile;
import org.broadinstitute.sting.utils.sam.GATKSAMRecord;
import java.util.*;
/**
* The class manages reads and splices and tries to apply overhang clipping when appropriate.
* Important note: although for efficiency the manager does try to send reads to the underlying writer in coordinate
* sorted order, it does NOT guarantee that it will do so in every case! So unless there's a good reason not to,
* methods that instantiate this manager should pass in a writer that does not assume the reads are pre-sorted.
*/
public class OverhangFixingManager {
protected static final Logger logger = Logger.getLogger(OverhangFixingManager.class);
private static final boolean DEBUG = false;
// how many reads should we store in memory before flushing the queue?
private final int MAX_RECORDS_IN_MEMORY;
// how many mismatches do we tolerate in the overhangs?
private final int MAX_MISMATCHES_IN_OVERHANG;
// how many bases do we tolerate in the overhang before deciding not to clip?
private final int MAX_BASES_IN_OVERHANG;
// should we not bother fixing overhangs?
private final boolean doNotFixOverhangs;
// where we ultimately write out our records
private final SAMFileWriter writer;
// fasta reference reader to check overhanging edges in the exome reference sequence
private final CachingIndexedFastaSequenceFile referenceReader;
// the genome loc parser
private final GenomeLocParser genomeLocParser;
// the read cache
private final static int initialCapacity = 5000;
private PriorityQueue<SplitRead> waitingReads = new PriorityQueue<>(initialCapacity, new SplitReadComparator());
// the set of current splices to use
private final Set<Splice> splices = new TreeSet<>(new SpliceComparator());
protected static final int MAX_SPLICES_TO_KEEP = 1000;
/**
*
* @param writer actual writer
* @param genomeLocParser the GenomeLocParser object
* @param referenceReader the reference reader
* @param maxRecordsInMemory max records to keep in memory
* @param maxMismatchesInOverhangs max number of mismatches permitted in the overhangs before requiring clipping
* @param maxBasesInOverhangs max number of bases permitted in the overhangs before deciding not to clip
* @param doNotFixOverhangs if true, don't clip overhangs at all
*/
public OverhangFixingManager(final SAMFileWriter writer,
final GenomeLocParser genomeLocParser,
final CachingIndexedFastaSequenceFile referenceReader,
final int maxRecordsInMemory,
final int maxMismatchesInOverhangs,
final int maxBasesInOverhangs,
final boolean doNotFixOverhangs) {
this.writer = writer;
this.genomeLocParser = genomeLocParser;
this.referenceReader = referenceReader;
this.MAX_RECORDS_IN_MEMORY = maxRecordsInMemory;
this.MAX_MISMATCHES_IN_OVERHANG = maxMismatchesInOverhangs;
this.MAX_BASES_IN_OVERHANG = maxBasesInOverhangs;
this.doNotFixOverhangs = doNotFixOverhangs;
}
public final int getNReadsInQueue() { return waitingReads.size(); }
/**
* For testing purposes only
*
* @return the list of reads currently in the queue
*/
protected List<SplitRead> getReadsInQueueForTesting() {
return new ArrayList<>(waitingReads);
}
/**
* For testing purposes only
*
* @return the list of splices currently in the queue
*/
protected List<Splice> getSplicesForTesting() {
return new ArrayList<>(splices);
}
/**
* Add a new observed split to the list to use
*
* @param contig the contig
* @param start the start of the split, inclusive
* @param end the end of the split, inclusive
*/
public void addSplicePosition(final String contig, final int start, final int end) {
if ( doNotFixOverhangs )
return;
// is this a new splice? if not, we are done
final Splice splice = new Splice(contig, start, end);
if ( splices.contains(splice) )
return;
// initialize it with the reference context
// we don't want to do this until we know for sure that it's a new splice position
splice.initialize(referenceReader);
// clear the set of old split positions seen if we hit a new contig
final boolean sameContig = splices.isEmpty() || splices.iterator().next().loc.getContig().equals(contig);
if ( !sameContig )
splices.clear();
// run this position against the existing reads
for ( final SplitRead read : waitingReads )
fixSplit(read, splice);
splices.add(splice);
if ( splices.size() > MAX_SPLICES_TO_KEEP )
cleanSplices();
}
/**
* Add a read to the manager
*
* @param read the read to add
*/
public void addRead(final GATKSAMRecord read) {
if ( read == null ) throw new IllegalArgumentException("read added to manager is null, which is not allowed");
// if the new read is on a different contig or we have too many reads, then we need to flush the queue and clear the map
final boolean tooManyReads = getNReadsInQueue() >= MAX_RECORDS_IN_MEMORY;
final boolean encounteredNewContig = getNReadsInQueue() > 0 && !waitingReads.peek().read.getReferenceIndex().equals(read.getReferenceIndex());
if ( tooManyReads || encounteredNewContig ) {
if ( DEBUG ) logger.warn("Flushing queue on " + (tooManyReads ? "too many reads" : ("move to new contig: " + read.getReferenceName() + " from " + waitingReads.peek().read.getReferenceName())) + " at " + read.getAlignmentStart());
final int targetQueueSize = encounteredNewContig ? 0 : MAX_RECORDS_IN_MEMORY / 2;
// write the required number of waiting reads to disk
while ( getNReadsInQueue() > targetQueueSize )
writer.addAlignment(waitingReads.poll().read);
}
final SplitRead splitRead = new SplitRead(read);
// fix overhangs, as needed
for ( final Splice splice : splices)
fixSplit(splitRead, splice);
// add the new read to the queue
waitingReads.add(splitRead);
}
/**
* Clean up the list of splices
*/
private void cleanSplices() {
final int targetQueueSize = splices.size() / 2;
final Iterator<Splice> iter = splices.iterator();
for ( int i = 0; i < targetQueueSize; i++ ) {
iter.next();
iter.remove();
}
}
/**
* Try to fix the given read using the given split
*
* @param read the read to fix
* @param splice the split (bad region to clip out)
*/
private void fixSplit(final SplitRead read, final Splice splice) {
// if the read doesn't even overlap the split position then we can just exit
if ( !splice.loc.overlapsP(read.loc) )
return;
if ( isLeftOverhang(read.loc, splice.loc) ) {
final int overhang = splice.loc.getStop() - read.loc.getStart() + 1;
if ( overhangingBasesMismatch(read.read.getReadBases(), 0, splice.reference, splice.reference.length - overhang, overhang) ) {
final GATKSAMRecord clippedRead = ReadClipper.hardClipByReadCoordinates(read.read, 0, overhang - 1);
read.setRead(clippedRead);
}
}
else if ( isRightOverhang(read.loc, splice.loc) ) {
final int overhang = read.loc.getStop() - splice.loc.getStart() + 1;
if ( overhangingBasesMismatch(read.read.getReadBases(), read.read.getReadLength() - overhang, splice.reference, 0, overhang) ) {
final GATKSAMRecord clippedRead = ReadClipper.hardClipByReadCoordinates(read.read, read.read.getReadLength() - overhang, read.read.getReadLength() - 1);
read.setRead(clippedRead);
}
}
}
/**
* Is this a proper overhang on the left side of the read?
*
* @param readLoc the read's loc
* @param spliceLoc the split's loc
* @return true if it's a left side overhang
*/
protected static boolean isLeftOverhang(final GenomeLoc readLoc, final GenomeLoc spliceLoc) {
return readLoc.getStart() <= spliceLoc.getStop() && readLoc.getStart() > spliceLoc.getStart() && readLoc.getStop() > spliceLoc.getStop();
}
/**
* Is this a proper overhang on the right side of the read?
*
* @param readLoc the read's loc
* @param spliceLoc the split's loc
* @return true if it's a right side overhang
*/
protected static boolean isRightOverhang(final GenomeLoc readLoc, final GenomeLoc spliceLoc) {
return readLoc.getStop() >= spliceLoc.getStart() && readLoc.getStop() < spliceLoc.getStop() && readLoc.getStart() < spliceLoc.getStart();
}
/**
* Are there too many mismatches to the reference among the overhanging bases?
*
* @param read the read bases
* @param readStartIndex where to start on the read
* @param reference the reference bases
* @param referenceStartIndex where to start on the reference
* @param spanToTest how many bases to test
* @return true if too many overhanging bases mismatch, false otherwise
*/
protected boolean overhangingBasesMismatch(final byte[] read,
final int readStartIndex,
final byte[] reference,
final int referenceStartIndex,
final int spanToTest) {
// don't process too small a span, too large a span, or a span that is most of a read
if ( spanToTest < 1 || spanToTest > MAX_BASES_IN_OVERHANG || spanToTest > read.length / 2 )
return false;
int numMismatchesSeen = 0;
for ( int i = 0; i < spanToTest; i++ ) {
if ( read[readStartIndex + i] != reference[referenceStartIndex + i] ) {
if ( ++numMismatchesSeen > MAX_MISMATCHES_IN_OVERHANG )
return true;
}
}
// we can still mismatch overall if at least half of the bases mismatch
return numMismatchesSeen >= ((spanToTest+1)/2);
}
/**
* Close out the manager stream by clearing the read cache
*/
public void close() {
// write out all of the remaining reads
while ( ! waitingReads.isEmpty() )
writer.addAlignment(waitingReads.poll().read);
}
// class to represent the reads with their soft-clip-included GenomeLocs
protected final class SplitRead {
public GATKSAMRecord read;
public GenomeLoc loc;
public SplitRead(final GATKSAMRecord read) {
setRead(read);
}
public void setRead(final GATKSAMRecord read) {
if ( !read.isEmpty() ) {
this.read = read;
loc = genomeLocParser.createGenomeLoc(read.getReferenceName(), read.getSoftStart(), read.getSoftEnd());
}
}
}
// class to represent the comparator for the split reads
private final class SplitReadComparator implements Comparator<SplitRead> {
private final SAMRecordCoordinateComparator readComparator;
public SplitReadComparator() {
readComparator = new SAMRecordCoordinateComparator();
}
public int compare(final SplitRead read1, final SplitRead read2) {
return readComparator.compare(read1.read, read2.read);
}
}
// class to represent the split positions
protected final class Splice {
public final GenomeLoc loc;
public byte[] reference;
public Splice(final String contig, final int start, final int end) {
loc = genomeLocParser.createGenomeLoc(contig, start, end);
}
public void initialize(final CachingIndexedFastaSequenceFile referenceReader) {
reference = referenceReader.getSubsequenceAt(loc.getContig(), loc.getStart(), loc.getStop()).getBases();
}
@Override
public boolean equals(final Object other) {
return other != null && (other instanceof Splice) && this.loc.equals(((Splice)other).loc);
}
@Override
public int hashCode() {
return loc.hashCode();
}
}
// class to represent the comparator for the split reads
private final class SpliceComparator implements Comparator<Splice> {
public int compare(final Splice position1, final Splice position2) {
return position1.loc.compareTo(position2.loc);
}
}
}

View File

@ -47,30 +47,28 @@
package org.broadinstitute.sting.gatk.walkers.rnaseq;
import net.sf.samtools.*;
import org.broadinstitute.sting.commandline.Advanced;
import org.broadinstitute.sting.commandline.Argument;
import org.broadinstitute.sting.commandline.Hidden;
import org.broadinstitute.sting.commandline.Output;
import org.broadinstitute.sting.gatk.CommandLineGATK;
import org.broadinstitute.sting.gatk.GenomeAnalysisEngine;
import org.broadinstitute.sting.gatk.contexts.ReferenceContext;
import org.broadinstitute.sting.gatk.io.StingSAMFileWriter;
import org.broadinstitute.sting.gatk.iterators.ReadTransformer;
import org.broadinstitute.sting.gatk.iterators.ReadTransformersMode;
import org.broadinstitute.sting.gatk.refdata.RefMetaDataTracker;
import org.broadinstitute.sting.gatk.walkers.BAQMode;
import org.broadinstitute.sting.gatk.walkers.DataSource;
import org.broadinstitute.sting.gatk.walkers.ReadWalker;
import org.broadinstitute.sting.gatk.walkers.Requires;
import org.broadinstitute.sting.utils.Utils;
import org.broadinstitute.sting.utils.baq.BAQ;
import org.broadinstitute.sting.utils.clipping.ReadClipper;
import org.broadinstitute.sting.utils.exceptions.UserException;
import org.broadinstitute.sting.utils.fasta.CachingIndexedFastaSequenceFile;
import org.broadinstitute.sting.utils.help.DocumentedGATKFeature;
import org.broadinstitute.sting.utils.help.HelpConstants;
import org.broadinstitute.sting.utils.sam.CigarUtils;
import org.broadinstitute.sting.utils.sam.GATKSAMRecord;
import java.io.PrintStream;
import java.util.*;
import java.io.FileNotFoundException;
/**
*
@ -88,119 +86,138 @@ import java.util.*;
@DocumentedGATKFeature( groupName = HelpConstants.DOCS_CAT_DATA, extraDocs = {CommandLineGATK.class} )
@Requires({DataSource.READS, DataSource.REFERENCE})
public class SplitNCigarReads extends ReadWalker<List<GATKSAMRecord>, SAMFileWriter> {
public class SplitNCigarReads extends ReadWalker<GATKSAMRecord, OverhangFixingManager> {
// The name that will go in the @PG tag
public static final String PROGRAM_RECORD_NAME = "GATK SplitNCigarReads";
@Output(doc="Write output to this BAM filename instead of STDOUT")
StingSAMFileWriter out;
@Argument(required = false)
PrintStream splitPositionsOutput = System.out;
@Argument(fullName="outputAsBED", shortName="bed", doc="Output as BED file", required=false)
boolean outputAsBED = false;
@Argument(fullName="printSplitPositions", shortName="splitPosition", doc="print the split positions", required=false)
boolean printSplitPositions = false;
public static final String PROGRAM_RECORD_NAME = "GATK SplitNCigarReads"; // The name that will go in the @PG tag
// public static SplitPositions splitPositions = null;
public static String results = "";
protected StingSAMFileWriter writer;
/**
* The initialize function.
* For expert users only! To minimize memory consumption you can lower this number, but then the tool may skip
* overhang fixing in regions with too much coverage. Just make sure to give Java enough memory! 4Gb should be
* enough with the default value.
*/
@Advanced
@Argument(fullName="maxReadsInMemory", shortName="maxInMemory", doc="max reads allowed to be kept in memory at a time by the BAM writer", required=false)
protected int MAX_RECORDS_IN_MEMORY = 150000;
/**
* If there are more than this many mismatches within the overhang regions, the whole overhang will get hard-clipped out.
* It is still possible in some cases that the overhang could get clipped if the number of mismatches do not exceed this
* value, e.g. if most of the overhang mismatches.
*/
@Advanced
@Argument(fullName="maxMismatchesInOverhang", shortName="maxMismatches", doc="max number of mismatches allowed in the overhang", required=false)
protected int MAX_MISMATCHES_IN_OVERHANG = 1;
/**
* If there are more than this many bases in the overhang, we won't try to hard-clip them out
*/
@Advanced
@Argument(fullName="maxBasesInOverhang", shortName="maxOverhang", doc="max number of bases allowed in the overhang", required=false)
protected int MAX_BASES_TO_CLIP = 40;
@Argument(fullName="doNotFixOverhangs", shortName="doNotFixOverhangs", doc="do not have the walker hard-clip overhanging sections of the reads", required=false)
protected boolean doNotFixOverhangs = false;
@Hidden
@Argument(fullName = "no_pg_tag", shortName = "npt", doc = "Necessary for integration tests", required = false)
protected boolean NO_PG_TAG = false;
/**
* This stores all of the already-split reads and manages any processing (e.g. clipping overhangs) that happens to them.
* It will emit reads to the underlying writer as needed so we don't need to worry about any of that in this class.
*/
protected OverhangFixingManager overhangManager;
@Override
public void initialize() {
final GenomeAnalysisEngine toolkit = getToolkit();
final boolean preSorted = false;
if (getToolkit() != null) {
Utils.setupWriter(out, toolkit, toolkit.getSAMFileHeader(), preSorted, this, PROGRAM_RECORD_NAME);
if ( !NO_PG_TAG ) {
// we don't want to assume that reads will be written in order by the manager because in deep, deep pileups it won't work
Utils.setupWriter(writer, toolkit, toolkit.getSAMFileHeader(), false, this, PROGRAM_RECORD_NAME);
}
try {
final CachingIndexedFastaSequenceFile referenceReader = new CachingIndexedFastaSequenceFile(toolkit.getArguments().referenceFile);
overhangManager = new OverhangFixingManager(writer, toolkit.getGenomeLocParser(), referenceReader, MAX_RECORDS_IN_MEMORY, MAX_MISMATCHES_IN_OVERHANG, MAX_BASES_TO_CLIP, doNotFixOverhangs);
}
catch (FileNotFoundException ex) {
throw new UserException.CouldNotReadInputFile(toolkit.getArguments().referenceFile, ex);
}
out.setPresorted(preSorted);
// splitPositions = new SplitPositions();
}
/**
* The reads map function.
*
* @param ref the reference bases that correspond to our read, if a reference was provided
* @param read the read itself, as a GATKSAMRecord
*
* @return a list of split read if there are N's in the cigar string, or the read itself.
*/
public List<GATKSAMRecord> map(final ReferenceContext ref,final GATKSAMRecord read,final RefMetaDataTracker metaDataTracker) {
return splitNCigarRead(read);
@Override
public GATKSAMRecord map(final ReferenceContext ref, final GATKSAMRecord read, final RefMetaDataTracker metaDataTracker) {
return read;
}
@Override
public OverhangFixingManager reduceInit() {
return overhangManager;
}
@Override
public OverhangFixingManager reduce(final GATKSAMRecord read, final OverhangFixingManager manager) {
splitNCigarRead(read, manager);
return manager;
}
@Override
public void onTraversalDone(final OverhangFixingManager manager) {
manager.close();
}
/**
* Goes through the cigar string of the read and create new reads for each consecutive non-N elements (while hard clipping the rest of the read).
* For example: for a read with cigar '1H2M2D1M2N1M2I1N1M2S' 3 new reads will be created with cigar strings: 1H2M2D1M, 1M2I and 1M2S
*
* @param read the read to split, as a GATKSAMRecord
* @return a list of split read if there are N's in the cigar string, or the read itself.
* @param read the read to split
* @param manager the output manager
*/
public static void splitNCigarRead(final GATKSAMRecord read, final OverhangFixingManager manager) {
final int numCigarElements = read.getCigar().numCigarElements();
public static List<GATKSAMRecord> splitNCigarRead(final GATKSAMRecord read){
final List<GATKSAMRecord> splitReads = new ArrayList<>();
int firstCigarIndex = 0;
for (int i = 0; i < read.getCigar().numCigarElements(); i ++){
for ( int i = 0; i < numCigarElements; i++ ) {
final CigarElement cigarElement = read.getCigar().getCigarElement(i);
if(cigarElement.getOperator() == CigarOperator.N){
final boolean addToSplitPositions = true;
splitReads.add(splitReadBasedOnCigar(read,firstCigarIndex,i, addToSplitPositions));
if (cigarElement.getOperator() == CigarOperator.N) {
manager.addRead(splitReadBasedOnCigar(read, firstCigarIndex, i, manager));
firstCigarIndex = i+1;
}
}
//if there are no N's in the read
if (firstCigarIndex == 0)
splitReads.add(read);
// if there are no N's in the read
if (firstCigarIndex == 0) {
manager.addRead(read);
}
//add the last section of the read: from the last N to the the end of the read
// (it will be done for all the usual cigar string that does not end with N)
else if(firstCigarIndex < read.getCigar().numCigarElements()){
final boolean addToSplitPositions = false;
splitReads.add(splitReadBasedOnCigar(read,firstCigarIndex,read.getCigar().numCigarElements(), addToSplitPositions));
else if (firstCigarIndex < numCigarElements) {
manager.addRead(splitReadBasedOnCigar(read, firstCigarIndex, numCigarElements, null));
}
return splitReads;
}
/**
* reduceInit is called once before any calls to the map function. We use it here to setup the splitPositionsOutput
* bam file, if it was specified on the command line
*
* @return SAMFileWriter, set to the BAM splitPositionsOutput file if the command line option was set, null otherwise
*/
public SAMFileWriter reduceInit() {
return out;
}
/**
* given a read and a splitPositionsOutput location, reduce by emitting the read
* Pull out an individual split position for a read
*
* @param reads the split reads itself
* @param output the splitPositionsOutput source
* @return the SAMFileWriter, so that the next reduce can emit to the same source
* @param read the read being split
* @param cigarStartIndex the index of the first cigar element to keep
* @param cigarEndIndex the index of the last cigar element to keep
* @param forSplitPositions the manager for keeping track of split positions; can be null
* @return a non-null read representing the section of the original read being split out
*/
public SAMFileWriter reduce(final List<GATKSAMRecord> reads,final SAMFileWriter output ) {
for (final GATKSAMRecord read: reads)
output.addAlignment(read);
return output;
}
public void onTraversalDone(SAMFileWriter readResult) {
super.onTraversalDone(readResult);
if(printSplitPositions)
splitPositionsOutput.println(results);
// splitPositionsOutput.println(splitPositions);
}
private static GATKSAMRecord splitReadBasedOnCigar(final GATKSAMRecord read, final int cigarStartIndex, final int cigarEndIndex, final boolean addToSplitPositions){
private static GATKSAMRecord splitReadBasedOnCigar(final GATKSAMRecord read, final int cigarStartIndex, final int cigarEndIndex, final OverhangFixingManager forSplitPositions) {
int cigarFirstIndex = cigarStartIndex;
int cigarSecondIndex = cigarEndIndex;
//in case a section of the read is end or start with D (for example the first section in 1M1D1N1M is 1M1D), we should trim this cigar element
// it can be if, but it was kept as while to make sure the code can work with Cigar string that were not "cleaned"
//in case a section of the read ends or starts with D (for example the first section in 1M1D1N1M is 1M1D), we should trim this cigar element
// it can be 'if', but it was kept as 'while' to make sure the code can work with Cigar strings that were not "cleaned"
while(read.getCigar().getCigarElement(cigarFirstIndex).getOperator().equals(CigarOperator.D))
cigarFirstIndex++;
while(read.getCigar().getCigarElement(cigarSecondIndex-1).getOperator().equals(CigarOperator.D))
@ -213,54 +230,13 @@ public class SplitNCigarReads extends ReadWalker<List<GATKSAMRecord>, SAMFileWri
final int startRefIndex = read.getOriginalAlignmentStart() + CigarUtils.countRefBasesBasedOnCigar(read,0,cigarFirstIndex); //goes through the prefix of the cigar (up to cigarStartIndex) and move the reference index.
final int stopRefIndex = startRefIndex + CigarUtils.countRefBasesBasedOnCigar(read,cigarFirstIndex,cigarSecondIndex)-1; //goes through a consecutive non-N section of the cigar (up to cigarEndIndex) and move the reference index.
if(addToSplitPositions){
final int splitPosition = startRefIndex + CigarUtils.countRefBasesBasedOnCigar(read,cigarFirstIndex,cigarEndIndex); //we use cigarEndIndex instead of cigarSecondIndex so we won't take into account the D's at the end.
if ( forSplitPositions != null ) {
final String contig = read.getReferenceName();
// results += String.format("%s:%d-%d\n", contig, splitPosition, splitPosition );
// splitPositions.addSplitPosition(contig,splitPosition);
final int splitStart = startRefIndex + CigarUtils.countRefBasesBasedOnCigar(read,cigarFirstIndex,cigarEndIndex); //we use cigarEndIndex instead of cigarSecondIndex so we won't take into account the D's at the end.
final int splitEnd = splitStart + read.getCigar().getCigarElement(cigarEndIndex).getLength() - 1;
forSplitPositions.addSplicePosition(contig, splitStart, splitEnd);
}
return ReadClipper.hardClipToRegionIncludingClippedBases(read, startRefIndex, stopRefIndex);
}
private class SplitPosition {
public final String contig;
public final int start;
public final int end;
public SplitPosition(final String c, final int position) {
contig = c;
start = position;
end = position;
}
}
private class SplitPositions {
private final HashSet<SplitPosition> splitPositions;
public SplitPositions() {
splitPositions = new HashSet<>();
}
public void addSplitPosition(final String contig, final int position) {
final SplitPosition newSplitPosition = new SplitPosition(contig, position);
splitPositions.add(newSplitPosition);
}
public String toString() {
String result = ""; // = "Contig\tstart\tstop\n";
for (SplitPosition position: splitPositions) {
if (outputAsBED)
result += String.format("%s\t%d\t%d\n", position.contig, position.start-1, position.end );
else
result += String.format("%s:%d-%d\n", position.contig, position.start, position.end );
}
return result;
}
}
}

View File

@ -0,0 +1,172 @@
/*
* 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.rnaseq;
import org.broadinstitute.sting.BaseTest;
import org.broadinstitute.sting.utils.GenomeLoc;
import org.broadinstitute.sting.utils.GenomeLocParser;
import org.broadinstitute.sting.utils.fasta.CachingIndexedFastaSequenceFile;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class OverhangFixingManagerUnitTest extends BaseTest {
private CachingIndexedFastaSequenceFile referenceReader;
private GenomeLocParser genomeLocParser;
@BeforeClass
public void setup() throws FileNotFoundException {
referenceReader = new CachingIndexedFastaSequenceFile(new File(b37KGReference));
genomeLocParser = new GenomeLocParser(referenceReader.getSequenceDictionary());
}
@Test
public void testCleanSplices() {
final OverhangFixingManager manager = new OverhangFixingManager(null, genomeLocParser, referenceReader, 10000, 1, 40, false);
final int offset = 10;
for ( int i = 0; i < OverhangFixingManager.MAX_SPLICES_TO_KEEP + 1; i++ )
manager.addSplicePosition("20", offset + i, offset + 1 + i);
final List<OverhangFixingManager.Splice> splices = manager.getSplicesForTesting();
Assert.assertEquals(splices.size(), (OverhangFixingManager.MAX_SPLICES_TO_KEEP / 2) + 1);
final int minStartPos = (OverhangFixingManager.MAX_SPLICES_TO_KEEP / 2) + offset;
for ( final OverhangFixingManager.Splice splice : splices )
Assert.assertTrue(splice.loc.getStart() >= minStartPos);
}
@DataProvider(name = "OverhangTest")
public Object[][] makeOverhangData() {
final List<Object[]> tests = new ArrayList<>();
for ( int leftRead : Arrays.asList(10, 20, 30, 40) ) {
for ( int rightRead : Arrays.asList(20, 30, 40, 50) ) {
if ( leftRead >= rightRead )
continue;
for ( int leftSplice : Arrays.asList(10, 20, 30) ) {
for ( int rightSplice : Arrays.asList(20, 30, 40) ) {
if ( leftSplice >= rightSplice )
continue;
final GenomeLoc readLoc = genomeLocParser.createGenomeLoc("1", leftRead, rightRead);
final GenomeLoc spliceLoc = genomeLocParser.createGenomeLoc("1", leftSplice, rightSplice);
tests.add(new Object[]{readLoc, spliceLoc});
}
}
}
}
return tests.toArray(new Object[][]{});
}
@Test(dataProvider = "OverhangTest")
public void testLeftOverhangs(final GenomeLoc readLoc, final GenomeLoc spliceLoc) {
final boolean isValidOverhang = readLoc.getStart() <= spliceLoc.getStop() &&
readLoc.getStop() > spliceLoc.getStop() &&
readLoc.getStart() > spliceLoc.getStart();
Assert.assertEquals(OverhangFixingManager.isLeftOverhang(readLoc, spliceLoc), isValidOverhang, readLoc + " vs. " + spliceLoc);
}
@Test(dataProvider = "OverhangTest")
public void testRightOverhangs(final GenomeLoc readLoc, final GenomeLoc spliceLoc) {
final boolean isValidOverhang = readLoc.getStop() >= spliceLoc.getStart() &&
readLoc.getStop() < spliceLoc.getStop() &&
readLoc.getStart() < spliceLoc.getStart();
Assert.assertEquals(OverhangFixingManager.isRightOverhang(readLoc, spliceLoc), isValidOverhang, readLoc + " vs. " + spliceLoc);
}
@DataProvider(name = "MismatchEdgeConditionTest")
public Object[][] makeMismatchEdgeConditionData() {
final List<Object[]> tests = new ArrayList<>();
tests.add(new Object[]{null, 1, null, 1, 0});
tests.add(new Object[]{null, 1, null, 1, 100});
tests.add(new Object[]{new byte[4], 1, null, 1, 3});
return tests.toArray(new Object[][]{});
}
@Test(dataProvider = "MismatchEdgeConditionTest")
public void testMismatchEdgeCondition(final byte[] read, final int readStart, final byte[] ref, final int refStart, final int overhang) {
final OverhangFixingManager manager = new OverhangFixingManager(null, genomeLocParser, referenceReader, 10000, 1, 40, false);
Assert.assertFalse(manager.overhangingBasesMismatch(read, readStart, ref, refStart, overhang));
}
@DataProvider(name = "MismatchTest")
public Object[][] makeMismatchData() {
final List<Object[]> tests = new ArrayList<>();
final byte[] AAAA = new byte[]{(byte)'A', (byte)'A', (byte)'A', (byte)'A'};
final byte[] AAAC = new byte[]{(byte)'A', (byte)'A', (byte)'A', (byte)'C'};
final byte[] AAAAAA = new byte[]{(byte)'A', (byte)'A', (byte)'A', (byte)'A', (byte)'A', (byte)'A'};
final byte[] AAAACA = new byte[]{(byte)'A', (byte)'A', (byte)'A', (byte)'A', (byte)'C', (byte)'A'};
final byte[] AAAACC = new byte[]{(byte)'A', (byte)'A', (byte)'A', (byte)'A', (byte)'C', (byte)'C'};
tests.add(new Object[]{AAAA, 2, AAAA, 2, 2, false});
tests.add(new Object[]{AAAA, 2, AAAC, 2, 2, true});
tests.add(new Object[]{AAAAAA, 3, AAAACA, 3, 3, false});
tests.add(new Object[]{AAAAAA, 3, AAAACC, 3, 3, true});
tests.add(new Object[]{AAAAAA, 4, AAAACC, 4, 2, true});
tests.add(new Object[]{AAAAAA, 2, AAAACC, 2, 3, false});
return tests.toArray(new Object[][]{});
}
@Test(dataProvider = "MismatchTest")
public void testMismatch(final byte[] read, final int readStart, final byte[] ref, final int refStart, final int overhang, final boolean expected) {
final OverhangFixingManager manager = new OverhangFixingManager(null, genomeLocParser, referenceReader, 10000, 1, 40, false);
Assert.assertEquals(manager.overhangingBasesMismatch(read, readStart, ref, refStart, overhang), expected, new String(read) + " vs. " + new String(ref) + " @" + overhang);
}
}

View File

@ -48,7 +48,6 @@ package org.broadinstitute.sting.gatk.walkers.rnaseq;
import org.broadinstitute.sting.WalkerTest;
import org.testng.annotations.Test;
import org.broadinstitute.sting.BaseTest;
import java.util.Arrays;
/**
@ -57,27 +56,57 @@ import java.util.Arrays;
* Date: 12/5/13
* Time: 1:04 PM
*/
public class SplitNCigarReadsIntegrationTests extends WalkerTest {
public class SplitNCigarReadsIntegrationTest extends WalkerTest {
@Test
@Test(enabled = false)
// contain reads without N's, with N's and with N's and I's
// TODO -- Ami: please put the bam file in the repo
public void testSplitWithInsertions() {
WalkerTest.WalkerTestSpec spec = new WalkerTest.WalkerTestSpec(
"-T SplitNCigarReads -R " + BaseTest.b37KGReference + " -I " + BaseTest.privateTestDir + "SplitNCigarReads.integrationTest.unsplitReads.withI.bam -o %s -U ALLOW_N_CIGAR_READS", 1,
"-T SplitNCigarReads -R " + b37KGReference + " -I " + privateTestDir + "SplitNCigarReads.integrationTest.unsplitReads.withI.bam -o %s --no_pg_tag -U ALLOW_N_CIGAR_READS", 1,
Arrays.asList("037c72fe1572efb63cccbe0a8dda3cb1"));
executeTest("test split N cigar reads with insertions", spec);
}
@Test
@Test(enabled = false)
// contain reads without N's, with N's and with N's and D's, and also with more then one N element in the cigar.
// TODO -- Ami: please put the bam file in the repo
public void testSplitWithDeletions() {
WalkerTest.WalkerTestSpec spec = new WalkerTest.WalkerTestSpec(
"-T SplitNCigarReads -R " + BaseTest.b37KGReference + " -I " + BaseTest.privateTestDir + "SplitNCigarReads.integrationTest.unsplitReads.withD.bam -o %s -U ALLOW_N_CIGAR_READS", 1,
"-T SplitNCigarReads -R " + b37KGReference + " -I " + privateTestDir + "SplitNCigarReads.integrationTest.unsplitReads.withD.bam -o %s --no_pg_tag -U ALLOW_N_CIGAR_READS", 1,
Arrays.asList("8472005c16353715025353d6d453faf4"));
executeTest("test split N cigar reads with deletions", spec);
}
@Test
public void testSplitsWithOverhangs() {
WalkerTest.WalkerTestSpec spec = new WalkerTest.WalkerTestSpec(
"-T SplitNCigarReads -R " + b37KGReference + " -I " + privateTestDir + "NA12878.RNAseq.bam -o %s --no_pg_tag -U ALLOW_N_CIGAR_READS", 1,
Arrays.asList("2832abc680c6b5a0219702ad5bf22f01"));
executeTest("test splits with overhangs", spec);
}
@Test
public void testSplitsWithOverhangsNotClipping() {
WalkerTest.WalkerTestSpec spec = new WalkerTest.WalkerTestSpec(
"-T SplitNCigarReads --doNotFixOverhangs -R " + b37KGReference + " -I " + privateTestDir + "NA12878.RNAseq.bam -o %s --no_pg_tag -U ALLOW_N_CIGAR_READS", 1,
Arrays.asList("59783610006bf7a1ccae57ee2016123b"));
executeTest("test splits with overhangs not clipping", spec);
}
@Test
public void testSplitsWithOverhangs0Mismatches() {
WalkerTest.WalkerTestSpec spec = new WalkerTest.WalkerTestSpec(
"-T SplitNCigarReads --maxMismatchesInOverhang 0 -R " + b37KGReference + " -I " + privateTestDir + "NA12878.RNAseq.bam -o %s --no_pg_tag -U ALLOW_N_CIGAR_READS", 1,
Arrays.asList("7547a5fc41ebfd1bbe62ce854b37b6ef"));
executeTest("test splits with overhangs 0 mismatches", spec);
}
@Test
public void testSplitsWithOverhangs5BasesInOverhang() {
WalkerTest.WalkerTestSpec spec = new WalkerTest.WalkerTestSpec(
"-T SplitNCigarReads --maxBasesInOverhang 5 -R " + b37KGReference + " -I " + privateTestDir + "NA12878.RNAseq.bam -o %s --no_pg_tag -U ALLOW_N_CIGAR_READS", 1,
Arrays.asList("f222eb02b003c08d4a606ab1bcb7931b"));
executeTest("test splits with overhangs 5 bases in overhang", spec);
}
}

View File

@ -49,12 +49,17 @@ package org.broadinstitute.sting.gatk.walkers.rnaseq;
import net.sf.samtools.Cigar;
import net.sf.samtools.CigarElement;
import net.sf.samtools.CigarOperator;
import org.broadinstitute.sting.gatk.walkers.rnaseq.SplitNCigarReads;
import org.broadinstitute.sting.BaseTest;
import org.broadinstitute.sting.utils.GenomeLocParser;
import org.broadinstitute.sting.utils.clipping.ReadClipperTestUtils;
import org.broadinstitute.sting.utils.fasta.CachingIndexedFastaSequenceFile;
import org.broadinstitute.sting.utils.sam.GATKSAMRecord;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
@ -69,7 +74,7 @@ import java.util.List;
* Date: 11/14/13
* Time: 6:49 PM
*/
public class SplitNCigarReadsUnitTest {
public class SplitNCigarReadsUnitTest extends BaseTest {
final static CigarElement[] cigarElements = {
new CigarElement(1, CigarOperator.HARD_CLIP),
new CigarElement(1, CigarOperator.SOFT_CLIP),
@ -79,6 +84,21 @@ public class SplitNCigarReadsUnitTest {
new CigarElement(1, CigarOperator.SKIPPED_REGION)
};
private CachingIndexedFastaSequenceFile referenceReader;
private GenomeLocParser genomeLocParser;
@BeforeClass
public void setup() throws FileNotFoundException {
referenceReader = new CachingIndexedFastaSequenceFile(new File(hg18Reference));
genomeLocParser = new GenomeLocParser(referenceReader.getSequenceDictionary());
}
private final class TestManager extends OverhangFixingManager {
public TestManager() {
super(null, genomeLocParser, referenceReader, 10000, 1, 40, false);
}
}
@Test(enabled = true)
public void splitReadAtN() {
final int cigarStringLength = 10;
@ -94,26 +114,27 @@ public class SplitNCigarReadsUnitTest {
for(Cigar cigar: cigarList){
final int numOfSplits = numOfNElements(cigar.getCigarElements());
if(numOfSplits != 0 && isCigarDoesNotHaveEmptyRegionsBetweenNs(cigar)){
final TestManager manager = new TestManager();
GATKSAMRecord read = ReadClipperTestUtils.makeReadFromCigar(cigar);
List<GATKSAMRecord> splitReads = SplitNCigarReads.splitNCigarRead(read);
SplitNCigarReads.splitNCigarRead(read, manager);
List<OverhangFixingManager.SplitRead> splitReads = manager.getReadsInQueueForTesting();
final int expectedReads = numOfSplits+1;
Assert.assertEquals(splitReads.size(),expectedReads,"wrong number of reads after split read with cigar: "+cigar+" at Ns [expected]: "+expectedReads+" [actual value]: "+splitReads.size());
final List<Integer> readLengths = consecutiveNonNElements(read.getCigar().getCigarElements());
int index = 0;
int offsetFromStart = 0;
for(GATKSAMRecord splitRead: splitReads){
for(final OverhangFixingManager.SplitRead splitRead: splitReads){
int expectedLength = readLengths.get(index);
Assert.assertTrue(splitRead.getReadLength() == expectedLength,
Assert.assertTrue(splitRead.read.getReadLength() == expectedLength,
"the "+index+" (starting with 0) split read has a wrong length.\n" +
"cigar of original read: "+cigar+"\n"+
"expected length: "+expectedLength+"\n"+
"actual length: "+splitRead.getReadLength()+"\n");
assertBases(splitRead.getReadBases(), read.getReadBases(), offsetFromStart);
"actual length: "+splitRead.read.getReadLength()+"\n");
assertBases(splitRead.read.getReadBases(), read.getReadBases(), offsetFromStart);
index++;
offsetFromStart += expectedLength;
}