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

feat: output umi grouping metrics #1021

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 3 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
37 changes: 32 additions & 5 deletions src/main/scala/com/fulcrumgenomics/umi/GroupReadsByUmi.scala
Original file line number Diff line number Diff line change
Expand Up @@ -466,6 +466,20 @@ case class TagFamilySizeMetric(family_size: Int,
var fraction: Proportion = 0,
var fraction_gt_or_eq_family_size: Proportion = 0) extends Metric

/**
* Metrics produced by `GroupReadsByUmi` to describe reads passed through UMI grouping
* @param sam_records The number of SAM records accepted for grouping.
* @param filtered_non_pf The number of non-PF SAM records.
znorgaard marked this conversation as resolved.
Show resolved Hide resolved
* @param filtered_poor_alignment The number of SAM records discarded for poor alignment.
* @param filtered_ns_in_umi The number of SAM records discarded due to one or more Ns in the UMI.
* @param filtered_umis_to_short The number of SAM records discarded due to a shorter than expected UMI.
*/
case class UmiGroupingMetric(sam_records: Long,
filtered_non_pf: Long,
filtered_poor_alignment: Long,
filtered_ns_in_umi: Long,
filtered_umis_to_short: Long) extends Metric
znorgaard marked this conversation as resolved.
Show resolved Hide resolved

/** The strategies implemented by [[GroupReadsByUmi]] to identify reads from the same source molecule.*/
sealed trait Strategy extends EnumEntry {
def newStrategy(edits: Int, threads: Int): UmiAssigner
Expand Down Expand Up @@ -568,6 +582,7 @@ class GroupReadsByUmi
(@arg(flag='i', doc="The input BAM file.") val input: PathToBam = Io.StdIn,
@arg(flag='o', doc="The output BAM file.") val output: PathToBam = Io.StdOut,
@arg(flag='f', doc="Optional output of tag family size counts.") val familySizeHistogram: Option[FilePath] = None,
@arg(flag='g', doc="Optional output of UMI grouping metrics.") val groupingMetrics: Option[FilePath] = None,
@arg(flag='t', doc="The tag containing the raw UMI.") val rawTag: String = ConsensusTags.UmiBases,
@arg(flag='T', doc="The output tag for UMI grouping.") val assignTag: String = ConsensusTags.MolecularId,
@arg(flag='d', doc="Turn on duplicate marking mode.") val markDuplicates: Boolean = false,
Expand Down Expand Up @@ -742,14 +757,26 @@ class GroupReadsByUmi
ms.tails.foreach { tail => tail.headOption.foreach(m => m.fraction_gt_or_eq_family_size = tail.map(_.fraction).sum) }
Metric.write(p, ms)
}

// Write out UMI grouping metrics
this.groupingMetrics.foreach { path =>
val groupingMetrics = UmiGroupingMetric(
sam_records = kept,
filtered_non_pf = filteredNonPf,
filtered_poor_alignment = filteredPoorAlignment,
filtered_ns_in_umi = filteredNsInUmi,
filtered_umis_to_short = filterUmisTooShort,
)
znorgaard marked this conversation as resolved.
Show resolved Hide resolved
Metric.write(path, groupingMetrics)
}
}

private def logStats(): Unit = {
logger.info(f"Accepted $kept%,d reads for grouping.")
if (filteredNonPf > 0) logger.info(f"Filtered out $filteredNonPf%,d non-PF reads.")
logger.info(f"Filtered out $filteredPoorAlignment%,d reads due to mapping issues.")
logger.info(f"Filtered out $filteredNsInUmi%,d reads that contained one or more Ns in their UMIs.")
this.minUmiLength.foreach { _ => logger.info(f"Filtered out $filterUmisTooShort%,d reads that contained UMIs that were too short.") }
logger.info(f"Accepted $kept%,d SAM records for grouping.")
if (filteredNonPf > 0) logger.info(f"Filtered out $filteredNonPf%,d non-PF SAM records.")
logger.info(f"Filtered out $filteredPoorAlignment%,d SAM records due to mapping issues.")
logger.info(f"Filtered out $filteredNsInUmi%,d SAM records that contained one or more Ns in their UMIs.")
this.minUmiLength.foreach { _ => logger.info(f"Filtered out $filterUmisTooShort%,d SAM records that contained UMIs that were too short.") }
}

/** Consumes the next group of templates with all matching end positions and returns them. */
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ 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 com.fulcrumgenomics.util.Metric
import org.scalatest.{OptionValues, PrivateMethodTester}

import java.nio.file.Files
Expand Down Expand Up @@ -247,7 +248,8 @@ class GroupReadsByUmiTest extends UnitSpec with OptionValues with PrivateMethodT
val in = builder.toTempFile()
val out = Files.createTempFile("umi_grouped.", ".sam")
val hist = Files.createTempFile("umi_grouped.", ".histogram.txt")
val tool = new GroupReadsByUmi(input=in, output=out, familySizeHistogram=Some(hist), rawTag="RX", assignTag="MI", strategy=Strategy.Edit, edits=1, minMapQ=Some(30))
val metrics = Files.createTempFile("umi_grouped.", ".metrics.txt")
val tool = new GroupReadsByUmi(input=in, output=out, familySizeHistogram=Some(hist), groupingMetrics=Some(metrics), rawTag="RX", assignTag="MI", strategy=Strategy.Edit, edits=1, minMapQ=Some(30))
val logs = executeFgbioTool(tool)

val groups = readBamRecs(out).groupBy(_.name.charAt(0))
Expand All @@ -267,6 +269,10 @@ class GroupReadsByUmiTest extends UnitSpec with OptionValues with PrivateMethodT

hist.toFile.exists() shouldBe true

// TODO: Create a more comprehensive test case
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
// TODO: Create a more comprehensive test case
// TODO: Consider creating more unit tests that vary the following metric fields

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@znorgaard how about adding to existing tests? E.g.

it should "exclude reads that contain an N in the UMI" in {

Copy link
Contributor Author

@znorgaard znorgaard Dec 16, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@nh13, just add the metric generation and check to those other tests?

That would work. I generally like to see a "complex" test case where non-zero values are generated for each metric entry all at once. But, in this specific case we're pulling from existing variables, so individual tests might be good enough.

val expectedMetric = UmiGroupingMetric(sam_records = 10, filtered_non_pf = 0, filtered_poor_alignment = 2, filtered_ns_in_umi = 0, filtered_umis_to_short = 0)
Metric.read[UmiGroupingMetric](metrics) shouldEqual Seq(expectedMetric)

// Make sure that we skip sorting for TemplateCoordinate
val sortMessage = "Sorting the input to TemplateCoordinate order"
logs.exists(_.contains(sortMessage)) shouldBe (sortOrder != TemplateCoordinate)
Expand Down
Loading