Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

GroupReadsByUmi optionally allows inter-contig pairs #648

Merged
merged 2 commits into from
Mar 1, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion src/main/scala/com/fulcrumgenomics/testing/SamBuilder.scala
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,7 @@ class SamBuilder(val readLength: Int=100,
quals1: String = defaultQuals,
quals2: String = defaultQuals,
contig: Int = 0,
contig2: Option[Int] = None,
start1: Int = SAMRecord.NO_ALIGNMENT_START,
start2: Int = SAMRecord.NO_ALIGNMENT_START,
unmapped1: Boolean = false,
Expand Down Expand Up @@ -159,7 +160,7 @@ class SamBuilder(val readLength: Int=100,
r2.name = name
r2.bases = bases2
r2.quals = quals2
r2.refIndex = if (start2 == SAMRecord.NO_ALIGNMENT_START) SAMRecord.NO_ALIGNMENT_REFERENCE_INDEX else contig
r2.refIndex = if (start2 == SAMRecord.NO_ALIGNMENT_START) SAMRecord.NO_ALIGNMENT_REFERENCE_INDEX else contig2.getOrElse(contig)
r2.start = start2
r2.positiveStrand = strand2 == Plus
r2.paired = true
Expand Down
39 changes: 21 additions & 18 deletions src/main/scala/com/fulcrumgenomics/umi/GroupReadsByUmi.scala
Original file line number Diff line number Diff line change
Expand Up @@ -83,23 +83,23 @@ object GroupReadsByUmi {
tmp
}
else {
val lib = library(rec)
val chrom = rec.refIndex
val recNeg = rec.negativeStrand
val recPos = if (recNeg) rec.unclippedEnd else rec.unclippedStart
val lib = library(rec)
val chrom = rec.refIndex
val mateChrom = rec.mateRefIndex
val recNeg = rec.negativeStrand
val recPos = if (recNeg) rec.unclippedEnd else rec.unclippedStart

val (mateNeg, matePos) = if (!rec.paired) (false, Int.MaxValue) else {
require(rec.refIndex == rec.mateRefIndex, s"Mate on different chrom for ${rec.name}.")
val neg = rec.mateNegativeStrand
val pos = if (neg) SAMUtils.getMateUnclippedEnd(rec.asSam) else SAMUtils.getMateUnclippedStart(rec.asSam)
(neg, pos)
}

val result = if (recPos < matePos || (recPos == matePos && !recNeg)) {
val result = if (chrom < mateChrom || (chrom == mateChrom && (recPos < matePos || (recPos == matePos && !recNeg)))) {
new ReadInfo(chrom, recPos, matePos, recNeg, mateNeg, lib)
}
else {
new ReadInfo(chrom, matePos, recPos, mateNeg, recNeg, lib)
new ReadInfo(mateChrom, matePos, recPos, mateNeg, recNeg, lib)
}

rec.transientAttrs(GroupReadsByUmi.ReadInfoTempAttributeName, result)
Expand Down Expand Up @@ -377,9 +377,9 @@ object Strategy extends FgBioEnum[Strategy] {
| 4. Read Name
|
|Reads are aggressively filtered out so that only high quality reads/mappings are taken forward. Single-end
|reads must have mapping quality >= `min-map-q`. Paired-end reads must have both reads mapped to the same
|chromosome with both reads having mapping quality >= `min-mapq`. (Note: the `MQ` tag is required on reads
|with mapped mates).
|reads must have mapping quality >= `min-map-q`. Paired-end reads must both have mapping quality >= `min-mapq`
|(Note: the `MQ` tag is required on reads with mapped mates). By default, paired-end reads must have both reads
|mapped to the same chromosome (to turn off this filter, use `--allow-inter-contig`).
|
|This is done with the expectation that the next step is building consensus reads, where
|it is undesirable to either:
Expand Down Expand Up @@ -430,7 +430,10 @@ class GroupReadsByUmi
@arg(flag='l', doc= """The minimum UMI length. If not specified then all UMIs must have the same length,
|otherwise discard reads with UMIs shorter than this length and allow for differing UMI lengths.
|""")
val minUmiLength: Option[Int] = None
val minUmiLength: Option[Int] = None,
@arg(flag='x', doc= """Allow read pairs with primary alignments on different contigs to be grouped when using the
|paired assigner (otherwise filtered out).""")
val allowInterContig: Boolean = false
)extends FgBioTool with LazyLogging {
import GroupReadsByUmi._

Expand Down Expand Up @@ -465,11 +468,11 @@ class GroupReadsByUmi
logger.info("Filtering and sorting input.")
in.iterator
.filter(r => !r.secondary && !r.supplementary)
.filter(r => (includeNonPfReads || r.pf) || { filteredNonPf += 1; false })
.filter(r => (r.mapped && (r.unpaired || r.mateMapped)) || { filteredPoorAlignment += 1; false })
.filter(r => (r.unpaired || r.refIndex == r.mateRefIndex) || { filteredPoorAlignment += 1; false })
.filter(r => mapqOk(r, this.minMapQ) || { filteredPoorAlignment += 1; false })
.filter(r => !r.get[String](rawTag).exists(_.contains('N')) || { filteredNsInUmi += 1; false })
.filter(r => (includeNonPfReads || r.pf) || { filteredNonPf += 1; false })
.filter(r => (r.mapped && (r.unpaired || r.mateMapped)) || { filteredPoorAlignment += 1; false })
.filter(r => (allowInterContig || r.unpaired || r.refIndex == r.mateRefIndex) || { filteredPoorAlignment += 1; false })
.filter(r => mapqOk(r, this.minMapQ) || { filteredPoorAlignment += 1; false })
.filter(r => !r.get[String](rawTag).exists(_.contains('N')) || { filteredNsInUmi += 1; false })
.filter { r =>
this.minUmiLength.forall { l =>
r.get[String](this.rawTag).forall { umi =>
Expand Down Expand Up @@ -583,10 +586,10 @@ class GroupReadsByUmi

(t.r1, t.r2, this.assigner) match {
case (Some(r1), Some(r2), paired: PairedUmiAssigner) =>
require(r1.refIndex == r2.refIndex, s"Mates on different references not supported: ${r1.name}")
if (!this.allowInterContig) require(r1.refIndex == r2.refIndex, s"Mates on different references not supported: ${r1.name}")
val pos1 = if (r1.positiveStrand) r1.unclippedStart else r1.unclippedEnd
val pos2 = if (r2.positiveStrand) r2.unclippedStart else r2.unclippedEnd
val r1Lower = pos1 < pos2 || pos1 == pos2 && r1.positiveStrand
val r1Lower = r1.refIndex < r2.refIndex || (r1.refIndex == r2.refIndex && (pos1 < pos2 || (pos1 == pos2 && r1.positiveStrand)))
val umis = umi.split('-')
require(umis.length == 2, s"Paired strategy used but umi did not contain 2 segments: $umi")

Expand Down
63 changes: 59 additions & 4 deletions src/test/scala/com/fulcrumgenomics/umi/GroupReadsByUmiTest.scala
Original file line number Diff line number Diff line change
Expand Up @@ -26,22 +26,22 @@
*/
package com.fulcrumgenomics.umi

import java.nio.file.Files

import com.fulcrumgenomics.bam.Template
import com.fulcrumgenomics.bam.api.SamOrder
import com.fulcrumgenomics.cmdline.FgBioMain.FailureException
import com.fulcrumgenomics.testing.SamBuilder.{Minus, Plus}
import com.fulcrumgenomics.testing.{SamBuilder, UnitSpec}
import com.fulcrumgenomics.umi.GroupReadsByUmi._
import org.scalatest.OptionValues
import org.scalatest.{OptionValues, PrivateMethodTester}

import java.nio.file.Files
import scala.collection.mutable

/**
* Tests for the tool that groups reads by position and UMI to attempt to identify
* read pairs that arose from the same original molecule.
*/
class GroupReadsByUmiTest extends UnitSpec with OptionValues {
class GroupReadsByUmiTest extends UnitSpec with OptionValues with PrivateMethodTester {
// Returns a List of the element 't' repeated 'n' times
private def n[T](t: T, n:Int =1): List[T] = List.tabulate(n)(x => t)

Expand Down Expand Up @@ -171,6 +171,34 @@ class GroupReadsByUmiTest extends UnitSpec with OptionValues {
}
}

"GroupReadsByUmi.umiForRead" should "correctly assign a/b for paired UMI prefixes" in {
val tool = new GroupReadsByUmi(rawTag="RX", assignTag="MI", strategy=Strategy.Paired, edits = 0, allowInterContig=true)
val builder = new SamBuilder(readLength=100)
val templates = Seq(
// These 4 should be a::AAA-b::TTT since contig1 is lower
builder.addPair(contig = 1, contig2 = Some(2), start1=100, start2=300, strand1=Plus, strand2=Minus, attrs=Map("RX" -> "AAA-TTT")),
builder.addPair(contig = 1, contig2 = Some(2), start1=300, start2=100, strand1=Plus, strand2=Minus, attrs=Map("RX" -> "AAA-TTT")),
builder.addPair(contig = 1, contig2 = Some(2), start1=100, start2=100, strand1=Plus, strand2=Minus, attrs=Map("RX" -> "AAA-TTT")),
builder.addPair(contig = 1, contig2 = Some(2), start1=100, start2=100, strand1=Minus, strand2=Plus, attrs=Map("RX" -> "AAA-TTT")),
// These 4 should be b::AAA-a::TTT since contig2 is lower
builder.addPair(contig = 2, contig2 = Some(1), start1=100, start2=300, strand1=Plus, strand2=Minus, attrs=Map("RX" -> "AAA-TTT")),
builder.addPair(contig = 2, contig2 = Some(1), start1=300, start2=100, strand1=Plus, strand2=Minus, attrs=Map("RX" -> "AAA-TTT")),
builder.addPair(contig = 2, contig2 = Some(1), start1=100, start2=100, strand1=Plus, strand2=Minus, attrs=Map("RX" -> "AAA-TTT")),
builder.addPair(contig = 2, contig2 = Some(1), start1=100, start2=100, strand1=Minus, strand2=Plus, attrs=Map("RX" -> "AAA-TTT")),
// Should be a::AAA-b::TTT since r1 pos < r2 pos
builder.addPair(contig = 1, start1=100, start2=300, strand1=Plus, strand2=Minus, attrs=Map("RX" -> "AAA-TTT")),
// Should be b::AAA-a::TTT since r1 pos < r2 pos
builder.addPair(contig = 1, start1=300, start2=100, strand1=Plus, strand2=Minus, attrs=Map("RX" -> "AAA-TTT")),
// Should be a::AAA-b::TTT since same contig/pos, r1 positive strand
builder.addPair(contig = 1, start1=100, start2=100, strand1=Plus, strand2=Minus, attrs=Map("RX" -> "AAA-TTT")),
// Should be b::AAA-a::TTT since same contig/pos, r2 positive strand
builder.addPair(contig = 1, start1=100, start2=100, strand1=Minus, strand2=Plus, attrs=Map("RX" -> "AAA-TTT")),
).map { pair => Template(r1 = pair.headOption, r2 = pair.lastOption) }
val expected = n("a::AAA-b::TTT", 4) ++ n("b::AAA-a::TTT", 4) ++ n("a::AAA-b::TTT", 1) ++ n("b::AAA-a::TTT", 1) ++ n("a::AAA-b::TTT", 1) ++ n("b::AAA-a::TTT", 1)
val umiForRead = PrivateMethod[String](Symbol("umiForRead"))
templates.map(t => tool invokePrivate umiForRead(t)) should contain theSameElementsInOrderAs expected
}

// Test for running the GroupReadsByUmi command line program with some sample input
"GroupReadsByUmi" should "group reads correctly" in {
val builder = new SamBuilder(readLength=100, sort=Some(SamOrder.Coordinate))
Expand Down Expand Up @@ -224,6 +252,33 @@ class GroupReadsByUmiTest extends UnitSpec with OptionValues {
aIds.head should not equal bIds.head
}

it should "correctly group reads with the paired assigner when the two UMIs are the same in cross-contig read pairs" in {
val builder = new SamBuilder(readLength=100, sort=Some(SamOrder.Coordinate))
builder.addPair(name="a01", contig = 1, contig2 = Some(2), start1=100, start2=300, strand1=Plus, strand2=Minus, attrs=Map("RX" -> "ACT-ACT"))
builder.addPair(name="a02", contig = 1, contig2 = Some(2), start1=100, start2=300, strand1=Plus, strand2=Minus, attrs=Map("RX" -> "ACT-ACT"))
builder.addPair(name="a03", contig = 1, contig2 = Some(2), start1=100, start2=300, strand1=Plus, strand2=Minus, attrs=Map("RX" -> "ACT-ACT"))
builder.addPair(name="a04", contig = 1, contig2 = Some(2), start1=100, start2=300, strand1=Plus, strand2=Minus, attrs=Map("RX" -> "ACT-ACT"))
builder.addPair(name="b01", contig = 2, contig2 = Some(1), start1=300, start2=100, strand1=Minus, strand2=Plus, attrs=Map("RX" -> "ACT-ACT"))
builder.addPair(name="b02", contig = 2, contig2 = Some(1), start1=300, start2=100, strand1=Minus, strand2=Plus, attrs=Map("RX" -> "ACT-ACT"))
builder.addPair(name="b03", contig = 2, contig2 = Some(1), start1=300, start2=100, strand1=Minus, strand2=Plus, attrs=Map("RX" -> "ACT-ACT"))
builder.addPair(name="b04", contig = 2, contig2 = Some(1), start1=300, start2=100, strand1=Minus, strand2=Plus, attrs=Map("RX" -> "ACT-ACT"))

val in = builder.toTempFile()
val out = Files.createTempFile("umi_grouped.", ".sam")
val hist = Files.createTempFile("umi_grouped.", ".histogram.txt")
new GroupReadsByUmi(input=in, output=out, familySizeHistogram=Some(hist), rawTag="RX", assignTag="MI", strategy=Strategy.Paired, edits=1, allowInterContig=true).execute()

val recs = readBamRecs(out)
val aIds = recs.filter(_.name.startsWith("a")).map(r => r[String]("MI")).distinct
val bIds = recs.filter(_.name.startsWith("b")).map(r => r[String]("MI")).distinct

aIds should have size 1
bIds should have size 1

aIds.head.takeWhile(_ != '/') shouldBe bIds.head.takeWhile(_ != '/')
aIds.head should not equal bIds.head
}

it should "correctly group together single-end reads with UMIs" in {
val builder = new SamBuilder(readLength=100, sort=Some(SamOrder.Coordinate))
builder.addFrag(name="a01", start=100, attrs=Map("RX" -> "AAAAAAAA"))
Expand Down