Skip to content

Instantly share code, notes, and snippets.

@clintval
Created September 2, 2021 00:16
Show Gist options
  • Save clintval/e2927178162e081bdc0ee3d140c12bd5 to your computer and use it in GitHub Desktop.
Save clintval/e2927178162e081bdc0ee3d140c12bd5 to your computer and use it in GitHub Desktop.
import com.fulcrumgenomics.bam.api.SamSource
import com.fulcrumgenomics.commons.CommonsDef._
/** Namespace for SAM/BAM source utilities. */
object SamSourceUtil {
/** Return the only sample in this SAM/BAM source otherwise raise an exception. */
def onlySample(source: SamSource): String = {
validateHasSingleSample(source)
source.header.getReadGroups.map(_.getSample).toSeq.head
}
/** Return the only sample in this SAM/BAM file otherwise raise an exception. */
def onlySample(bam: PathToBam): String = {
val source = SamSource(bam)
yieldAndThen(onlySample(source))(source.safelyClose())
}
/** The sample names from the input SAM/BAM source. */
def samples(source: SamSource): Seq[String] = {
source.header.getReadGroups.map(_.getSample).distinct.toSeq
}
/** The sample names from the input SAM/BAM file. */
def samples(sam: PathToBam): Seq[String] = {
val source = SamSource(sam)
yieldAndThen(samples(source))(source.safelyClose())
}
/** Validate that a SAM/BAM source has a single sample's reads. */
def validateHasSingleSample(source: SamSource): Unit = {
val names = samples(source)
val n = names.length
if (n != 1) {
source.safelyClose()
throw new IllegalArgumentException(s"SAM/BAM is not single-sample and has $n samples: ${names.mkString(", ")}")
}
}
/** Validate that a SAM/BAM file has a single sample's reads. */
def validateHasSingleSample(sam: PathToBam): Unit = {
val source = SamSource(sam)
yieldAndThen(validateHasSingleSample(source))(source.safelyClose())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment