BammetricsReport.scala 22.3 KB
Newer Older
Peter van 't Hof's avatar
Peter van 't Hof committed
1
/**
2 3 4 5 6 7 8 9 10 11 12 13 14
  * Biopet is built on top of GATK Queue for building bioinformatic
  * pipelines. It is mainly intended to support LUMC SHARK cluster which is running
  * SGE. But other types of HPC that are supported by GATK Queue (such as PBS)
  * should also be able to execute Biopet tools and pipelines.
  *
  * Copyright 2014 Sequencing Analysis Support Core - Leiden University Medical Center
  *
  * Contact us at: sasc@lumc.nl
  *
  * A dual licensing mode is applied. The source code within this project is freely available for non-commercial use under an AGPL
  * license; For commercial users or users who do not want to follow the AGPL
  * license, please contact us to obtain a separate license.
  */
15 16
package nl.lumc.sasc.biopet.pipelines.bammetrics

17
import java.io.{File, PrintWriter}
18

Peter van 't Hof's avatar
Peter van 't Hof committed
19
import nl.lumc.sasc.biopet.utils.config.Configurable
20 21 22 23 24 25
import nl.lumc.sasc.biopet.core.report.{
  ReportBuilder,
  ReportBuilderExtension,
  ReportPage,
  ReportSection
}
Peter van 't Hof's avatar
Peter van 't Hof committed
26
import nl.lumc.sasc.biopet.utils.ConfigUtils
27
import nl.lumc.sasc.biopet.utils.rscript.{LinePlot, StackedBarPlot}
Peter van 't Hof's avatar
Peter van 't Hof committed
28
import nl.lumc.sasc.biopet.utils.summary.db.SummaryDb
Peter van 't Hof's avatar
Peter van 't Hof committed
29 30
import nl.lumc.sasc.biopet.utils.summary.db.SummaryDb.Implicts._
import nl.lumc.sasc.biopet.utils.summary.db.SummaryDb._
31
import nl.lumc.sasc.biopet.utils.summary.db.Schema._
32

33
import scala.collection.mutable.ArrayBuffer
34
import scala.concurrent.{Await, Future}
Peter van 't Hof's avatar
Peter van 't Hof committed
35
import scala.concurrent.duration.Duration
36

Peter van 't Hof's avatar
Peter van 't Hof committed
37
class BammetricsReport(val parent: Configurable) extends ReportBuilderExtension {
38
  def builder = BammetricsReport
39
}
40

41
/**
42 43 44 45
  * Object to create a report for [[BamMetrics]]
  *
  * Created by pjvan_thof on 3/30/15.
  */
46
object BammetricsReport extends ReportBuilder {
47

48
  /** Name of report */
49 50
  val reportName = "Bam Metrics"

51 52
  def pipelineName = "bammetrics"

53
  /** Root page for single BamMetrcis report */
Peter van 't Hof's avatar
Peter van 't Hof committed
54 55
  def indexPage: Future[ReportPage] =
    bamMetricsPage(summary, sampleId, libId).map { bamMetricsPage =>
56 57 58 59 60 61 62 63 64 65 66 67 68
      ReportPage(
        bamMetricsPage.subPages ::: List(
          "Versions" -> Future(
            ReportPage(List(),
                       List("Executables" -> ReportSection(
                         "/nl/lumc/sasc/biopet/core/report/executables.ssp")),
                       Map())),
          "Files" -> filesPage(sampleId, libId)
        ),
        List(
          "Report" -> ReportSection(
            "/nl/lumc/sasc/biopet/pipelines/bammetrics/bamMetricsFront.ssp")
        ) ::: bamMetricsPage.sections,
Peter van 't Hof's avatar
Peter van 't Hof committed
69 70 71
        Map()
      )
    }
72

73
  /** Generates a page with alignment stats */
Peter van 't Hof's avatar
Peter van 't Hof committed
74 75 76
  def bamMetricsPage(summary: SummaryDb,
                     sampleId: Option[Int],
                     libId: Option[Int],
Peter van 't Hof's avatar
Peter van 't Hof committed
77
                     metricsTag: String = "bammetrics"): Future[ReportPage] = Future {
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
    val wgsExecuted = summary.getStatsSize(runId,
                                           metricsTag,
                                           "wgs",
                                           sample = sampleId.map(SampleId),
                                           library = libId.map(LibraryId)) >= 1
    val rnaExecuted = summary.getStatsSize(runId,
                                           metricsTag,
                                           "rna",
                                           sample = sampleId.map(SampleId),
                                           library = libId.map(LibraryId)) >= 1

    val insertsizeMetrics = summary
      .getStatKeys(
        runId,
        metricsTag,
        "CollectInsertSizeMetrics",
        sampleId.map(SampleId).getOrElse(NoSample),
        libId.map(LibraryId).getOrElse(NoLibrary),
        Map("metrics" -> List("metrics"))
      )
Peter van 't Hof's avatar
Peter van 't Hof committed
98
      .exists(_._2.isDefined)
99

100 101 102 103 104 105 106 107
    val targetSettings = summary.getSettingKeys(
      runId,
      metricsTag,
      NoModule,
      sample = sampleId.map(SampleId).getOrElse(NoSample),
      library = libId.map(LibraryId).getOrElse(NoLibrary),
      Map("amplicon_name" -> List("amplicon_name"), "roi_name" -> List("roi_name"))
    )
108
    val targets = (
Peter van 't Hof's avatar
Peter van 't Hof committed
109 110
      targetSettings("amplicon_name"),
      targetSettings("roi_name")
Peter van 't Hof's avatar
Peter van 't Hof committed
111
    ) match {
112 113 114 115
      case (Some(amplicon: String), Some(roi: List[_])) => amplicon :: roi.map(_.toString)
      case (_, Some(roi: List[_])) => roi.map(_.toString)
      case _ => Nil
    }
116 117

    ReportPage(
Peter van 't Hof's avatar
Peter van 't Hof committed
118
      if (targets.isEmpty) List()
119 120 121 122 123 124 125 126 127
      else
        List(
          "Targets" -> Future.successful(
            ReportPage(
              List(),
              targets.map(t =>
                t -> ReportSection("/nl/lumc/sasc/biopet/pipelines/bammetrics/covstatsPlot.ssp",
                                   Map("target" -> Some(t)))),
              Map()))),
128
      List(
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
        "Summary" -> ReportSection(
          "/nl/lumc/sasc/biopet/pipelines/bammetrics/alignmentSummary.ssp"),
        "Mapping Quality" -> ReportSection(
          "/nl/lumc/sasc/biopet/pipelines/bammetrics/mappingQuality.ssp",
          Map("showPlot" -> true)),
        "Clipping" -> ReportSection("/nl/lumc/sasc/biopet/pipelines/bammetrics/clipping.ssp",
                                    Map("showPlot" -> true))
      ) ++
        (if (insertsizeMetrics)
           List(
             "Insert Size" -> ReportSection(
               "/nl/lumc/sasc/biopet/pipelines/bammetrics/insertSize.ssp",
               Map("showPlot" -> true)))
         else Nil) ++ (if (wgsExecuted)
                         List(
                           "Whole genome coverage" -> ReportSection(
                             "/nl/lumc/sasc/biopet/pipelines/bammetrics/wgsHistogram.ssp",
                             Map("showPlot" -> true)))
                       else Nil) ++
        (if (rnaExecuted)
           List(
             "Rna coverage" -> ReportSection(
               "/nl/lumc/sasc/biopet/pipelines/bammetrics/rnaHistogram.ssp",
               Map("showPlot" -> true)))
         else Nil),
154
      Map("metricsTag" -> metricsTag)
155 156 157
    )
  }

158
  /**
159
    * Generates the lines for alignmentSummaryPlot
160 161 162
    *
    * @param summary Summary class
    * @param sampleId Default it selects all sampples, when sample is giving it limits to selected sample
163
    *                     * @param libraryLevel Default false, when set true plot will be based on library stats instead of sample stats
164
    */
165
  def alignmentSummaryPlotLines(summary: SummaryDb,
166
                                sampleId: Option[Int] = None,
167
                                libraryLevel: Boolean = false): Seq[String] = {
Peter van 't Hof's avatar
Peter van 't Hof committed
168 169 170 171 172 173 174 175
    val statsPaths = Map(
      "Mapped" -> List("flagstats", "Mapped"),
      "Duplicates" -> List("flagstats", "Duplicates"),
      "All" -> List("flagstats", "All"),
      "NotPrimaryAlignment" -> List("flagstats", "NotPrimaryAlignment")
    )

    val results: Map[(Int, Option[Int]), Map[String, Option[Any]]] = if (libraryLevel) {
176 177
      summary
        .getStatsForLibraries(runId,
178 179 180 181
                              "bammetrics",
                              "bamstats",
                              sampleId = sampleId,
                              keyValues = statsPaths)
182 183 184 185
        .map(x => (x._1._1, Some(x._1._2)) -> x._2)
    } else
      summary
        .getStatsForSamples(runId,
186 187 188 189
                            "bammetrics",
                            "bamstats",
                            sample = sampleId.map(SampleId),
                            keyValues = statsPaths)
190
        .map(x => (x._1, None) -> x._2)
191
    val summaryPlotLines = ArrayBuffer[String]()
Peter van 't Hof's avatar
Peter van 't Hof committed
192

Peter van 't Hof's avatar
Peter van 't Hof committed
193
    for (((s, l), result) <- results) {
Peter van 't Hof's avatar
Peter van 't Hof committed
194
      val sampleName: String = summary.getSampleName(s).map(_.get)
195 196
      val libName: Option[String] =
        l.flatMap(x => Await.result(summary.getLibraryName(x), Duration.Inf))
197
      val sb = new StringBuffer()
198 199
      if (libName.isDefined) sb.append(sampleName + "-" + libName.get + "\t")
      else sb.append(sampleName + "\t")
Peter van 't Hof's avatar
Peter van 't Hof committed
200 201 202 203
      val mapped = ConfigUtils.any2long(result("Mapped"))
      val duplicates = ConfigUtils.any2long(result("Duplicates"))
      val total = ConfigUtils.any2long(result("All"))
      val secondary = ConfigUtils.any2long(result("NotPrimaryAlignment"))
Peter van 't Hof's avatar
Peter van 't Hof committed
204
      sb.append((mapped - duplicates - secondary) + "\t")
205
      sb.append(duplicates + "\t")
Peter van 't Hof's avatar
Peter van 't Hof committed
206
      sb.append((total - mapped) + "\t")
207
      sb.append(secondary)
208
      summaryPlotLines += sb.toString
209
    }
210 211 212 213 214 215 216 217 218 219 220 221 222 223
    summaryPlotLines
  }

  /**
    * Generate a stackbar plot for alignment stats
    *
    * @param outputDir OutputDir for the tsv and png file
    * @param prefix Prefix of the tsv and png file
    * @param summaryPlotLines A sequence of strings written to the summary tsv
    * @param libraryLevel Default false, when set true plot will be based on library stats instead of sample stats
    */
  def alignmentSummaryPlot(outputDir: File,
                           prefix: String,
                           summaryPlotLines: Seq[String],
224
                           libraryLevel: Boolean = false): Unit = {
225 226 227 228 229
    val tsvFile = new File(outputDir, prefix + ".tsv")
    val pngFile = new File(outputDir, prefix + ".png")
    val tsvWriter = new PrintWriter(tsvFile)
    if (libraryLevel) tsvWriter.print("Library") else tsvWriter.print("Sample")
    tsvWriter.println("\tMapped\tDuplicates\tUnmapped\tSecondary")
230

231 232 233
    for (line <- summaryPlotLines) {
      tsvWriter.println(line)
    }
234 235 236 237 238 239
    tsvWriter.close()

    val plot = new StackedBarPlot(null)
    plot.input = tsvFile
    plot.output = pngFile
    plot.ylabel = Some("Reads")
240
    plot.width = Some(200 + (summaryPlotLines.size * 10))
Peter van 't Hof's avatar
WIP  
Peter van 't Hof committed
241
    plot.title = Some("Aligned_reads")
242 243
    plot.runLocal()
  }
244

245 246 247 248 249 250 251 252 253 254 255
  /**
    * This is a generic method to create plots
    * @param libraryLevel If enabled the plots will show data per library
    * @param sampleId If set only this sample is shown
    * @param libraryId If set onlt this library is shown
    * @param statsPaths Paths in summary where the tables can be found
    * @param yKeyList Keys to search from, first has prio over second one
    * @param xKeyList Keys to search from, first has prio over second one
    * @param pipeline Query for the pipeline
    * @param module Query for the module
    */
256 257 258 259 260 261 262
  def summaryForPlot(summary: SummaryDb,
                     statsPaths: Map[String, List[String]],
                     yKeyList: List[String],
                     xKeyList: List[String],
                     pipeline: PipelineQuery,
                     module: ModuleQuery,
                     libraryLevel: Boolean = false,
263
                     sampleId: Option[Int] = None,
264
                     libraryId: Option[Int] = None): Array[Map[String, Array[Any]]] = {
Peter van 't Hof's avatar
Peter van 't Hof committed
265
    val results: Map[(Int, Option[Int]), Map[String, Option[Array[Any]]]] = if (libraryLevel) {
266 267 268 269 270 271 272 273
      summary
        .getStatsForLibraries(runId, pipeline, module, sampleId = sampleId, keyValues = statsPaths)
        .map(x =>
          (x._1._1, Some(x._1._2)) -> x._2.map(x =>
            x._1 -> x._2.map(ConfigUtils.any2list(_).toArray)))
    } else
      summary
        .getStatsForSamples(runId,
274 275 276 277
                            pipeline,
                            module,
                            sample = sampleId.map(SampleId),
                            keyValues = statsPaths)
278
        .map(x => (x._1, None) -> x._2.map(x => x._1 -> x._2.map(ConfigUtils.any2list(_).toArray)))
Peter van 't Hof's avatar
Peter van 't Hof committed
279 280
    val tables: Array[Map[String, Array[Any]]] = results.map {
      case ((sample, library), map) =>
281 282
        val sampleName = Await
          .result(summary.getSampleName(sample), Duration.Inf)
Peter van 't Hof's avatar
Peter van 't Hof committed
283
          .getOrElse(throw new IllegalStateException("Sample must be there"))
284 285
        val libraryName =
          library.flatMap(l => Await.result(summary.getLibraryName(l), Duration.Inf))
Peter van 't Hof's avatar
Peter van 't Hof committed
286 287
        val yKey = yKeyList.find(x => map.contains(x) && map(x).isDefined).getOrElse("none")
        val xKey = xKeyList.find(x => map.contains(x) && map(x).isDefined).getOrElse("none")
Peter van 't Hof's avatar
Peter van 't Hof committed
288
        Map(
Peter van 't Hof's avatar
Peter van 't Hof committed
289 290 291 292
          yKeyList.head -> map.getOrElse(yKey, None).getOrElse(Array()),
          (sampleName + libraryName.map("-" + _).getOrElse("")) -> map
            .getOrElse(xKey, None)
            .getOrElse(Array())
Peter van 't Hof's avatar
Peter van 't Hof committed
293
        )
Peter van 't Hof's avatar
Peter van 't Hof committed
294
    }.toArray
295 296 297 298 299 300 301
    tables
  }

  /**
    * This is a generic method to create plots
    * @param outputDir Outputdir of the plot
    * @param prefix Files will start with this name
Ruben Vorderman's avatar
Ruben Vorderman committed
302
    * @param plotTables Tables to be written
303 304 305 306 307 308 309 310 311
    * @param yKeyList Keys to search from, first has prio over second one
    * @param xKeyList Keys to search from, first has prio over second one
    * @param xlabel X label shown on the plot
    * @param ylabel Y label shown on the plot
    * @param title Title of the plot
    * @param removeZero
    */
  def writePlotFromSummary(outputDir: File,
                           prefix: String,
Ruben Vorderman's avatar
Ruben Vorderman committed
312
                           plotTables: Array[Map[String, Array[Any]]],
313
                           yKeyList: List[String],
314
                           xKeyList: List[String],
315 316 317 318 319 320
                           xlabel: Option[String] = None,
                           ylabel: Option[String] = None,
                           title: Option[String] = None,
                           removeZero: Boolean = true): Unit = {
    val tsvFile = new File(outputDir, prefix + ".tsv")
    val pngFile = new File(outputDir, prefix + ".png")
Peter van 't Hof's avatar
Peter van 't Hof committed
321

Ruben Vorderman's avatar
Ruben Vorderman committed
322
    writeTableToTsv(tsvFile, mergeTables(plotTables, yKeyList.head), yKeyList.head)
Peter van 't Hof's avatar
Peter van 't Hof committed
323

324 325 326 327 328 329
    LinePlot(
      tsvFile,
      pngFile,
      xlabel = xlabel,
      ylabel = ylabel,
      title = title,
Ruben Vorderman's avatar
Ruben Vorderman committed
330
      hideLegend = plotTables.size > 40,
331 332 333
      /* changed from results.size. Original results in summaryForPlot*/
      removeZero = removeZero
    ).runLocal()
Peter van 't Hof's avatar
Peter van 't Hof committed
334 335
  }

336 337 338
  def insertSizePlotTables(summary: SummaryDb,
                           libraryLevel: Boolean = false,
                           sampleId: Option[Int] = None,
Ruben Vorderman's avatar
Ruben Vorderman committed
339 340 341 342 343 344 345 346 347 348 349 350
                           libraryId: Option[Int] = None): Array[Map[String, Array[Any]]] = {
    val statsPaths = Map(
      "insert_size" -> List("histogram", "insert_size"),
      "count" -> List("histogram", "All_Reads.fr_count")
    )
    val plotTables = summaryForPlot(summary,
      statsPaths,
      "insert_size" :: Nil,
      "count" :: Nil,      "bammetrics",
      "CollectInsertSizeMetrics",libraryLevel,sampleId,libraryId)
    plotTables
  }
351

352
  /**
353 354 355 356
    * Generate a line plot for insertsize
    *
    * @param outputDir OutputDir for the tsv and png file
    * @param prefix Prefix of the tsv and png file
Ruben Vorderman's avatar
Ruben Vorderman committed
357
    * @param insertSizePlotTables
358
    */
Peter van 't Hof's avatar
Peter van 't Hof committed
359
  def insertSizePlot(outputDir: File,
Peter van 't Hof's avatar
Peter van 't Hof committed
360
                     prefix: String,
361
                     insertSizePlotTables: Array[Map[String, Array[Any]]]): Unit = {
362 363 364
    writePlotFromSummary(
      outputDir,
      prefix,
365
      insertSizePlotTables,
366 367
      "insert_size" :: Nil,
      "count" :: Nil,
Ruben Vorderman's avatar
Ruben Vorderman committed
368 369 370
    "Insert size",
    "Reads",
      "Insert size")
Peter van 't Hof's avatar
Peter van 't Hof committed
371
  }
Peter van 't Hof's avatar
Peter van 't Hof committed
372

373 374 375 376
  def mappingQualityPlotTables(summary: SummaryDb,
                               libraryLevel: Boolean = false,
                               sampleId: Option[Int] = None,
                               libraryId: Option[Int] = None): Array[Map[String, Array[Any]]] = {
Peter van 't Hof's avatar
Peter van 't Hof committed
377 378 379
    val statsPaths = Map(
      "mapping_quality" -> List("mapping_quality", "histogram", "values"),
      "count" -> List("mapping_quality", "histogram", "counts")
380
    )
Ruben Vorderman's avatar
Ruben Vorderman committed
381
    val plotTables = summaryForPlot(summary,
382 383 384 385 386 387 388 389 390
                                                                    statsPaths,
                                                                    "mapping_quality" :: Nil,
                                                                    "count" :: Nil,
                                                                    "bammetrics",
                                                                    "bamstats",
                                                                    libraryLevel,
                                                                    sampleId,
                                                                    libraryId)
    plotTables
391 392
  }

393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408
  def mappingQualityPlot(outputDir: File,
                         prefix: String,
                         mappingQualityPlotTables: Array[Map[String, Array[Any]]]): Unit = {
    writePlotFromSummary(outputDir,
                         prefix,
                         mappingQualityPlotTables,
                         "mapping_quality" :: Nil,
                         "count" :: Nil,
                         "Mapping Quality",
                         "Reads",
                         "Mapping Quality")
  }
  def clippingPlotTables(summary: SummaryDb,
                         libraryLevel: Boolean = false,
                         sampleId: Option[Int] = None,
                         libraryId: Option[Int] = None): Array[Map[String, Array[Any]]] = {}
409
  def clippingPlot(outputDir: File,
Peter van 't Hof's avatar
Peter van 't Hof committed
410
                   prefix: String,
411
                   clippingPlotTables: Array[Map[String, Array[Any]]],
Peter van 't Hof's avatar
Peter van 't Hof committed
412
                   libraryLevel: Boolean = false,
Peter van 't Hof's avatar
Peter van 't Hof committed
413
                   sampleId: Option[Int] = None,
Peter van 't Hof's avatar
Peter van 't Hof committed
414 415 416 417
                   libraryId: Option[Int] = None): Unit = {
    val statsPaths = Map(
      "clipping" -> List("clipping", "histogram", "values"),
      "count" -> List("clipping", "histogram", "counts")
418 419
    )

420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
    writePlotFromSummary(
      outputDir,
      prefix,
      summary,
      libraryLevel,
      sampleId,
      libraryId,
      statsPaths,
      "clipping" :: Nil,
      "count" :: Nil,
      "bammetrics",
      "bamstats",
      "Clipping",
      "Reads",
      "Clipping"
    )
436 437
  }

438
  /**
439 440 441 442 443 444 445 446
    * Generate a line plot for wgs coverage
    *
    * @param outputDir OutputDir for the tsv and png file
    * @param prefix Prefix of the tsv and png file
    * @param summary Summary class
    * @param libraryLevel Default false, when set true plot will be based on library stats instead of sample stats
    * @param sampleId Default it selects all sampples, when sample is giving it limits to selected sample
    */
Peter van 't Hof's avatar
Peter van 't Hof committed
447
  def wgsHistogramPlot(outputDir: File,
Peter van 't Hof's avatar
Peter van 't Hof committed
448
                       prefix: String,
449
                       tables: Array[Map[String, Array[Any]]],
Peter van 't Hof's avatar
Peter van 't Hof committed
450
                       libraryLevel: Boolean = false,
Peter van 't Hof's avatar
Peter van 't Hof committed
451
                       sampleId: Option[Int] = None,
Peter van 't Hof's avatar
Peter van 't Hof committed
452 453
                       libraryId: Option[Int] = None): Unit = {
    val statsPaths = Map(
Peter van 't Hof's avatar
Peter van 't Hof committed
454
      "coverage" -> List("histogram", "coverage"),
455 456
      "count" -> List("histogram", "count"),
      "high_quality_coverage_count" -> List("histogram", "high_quality_coverage_count")
Peter van 't Hof's avatar
Peter van 't Hof committed
457
    )
Peter van 't Hof's avatar
Peter van 't Hof committed
458

459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474
    writePlotFromSummary(
      outputDir,
      prefix,
      summary,
      libraryLevel,
      sampleId,
      libraryId,
      statsPaths,
      "coverage" :: Nil,
      "count" :: "high_quality_coverage_count" :: Nil,
      "bammetrics",
      "wgs",
      "Coverage",
      "Bases",
      "Whole genome coverage"
    )
Peter van 't Hof's avatar
Peter van 't Hof committed
475
  }
Peter van 't Hof's avatar
Peter van 't Hof committed
476 477

  /**
478 479 480 481 482 483 484 485
    * Generate a line plot for rna coverage
    *
    * @param outputDir OutputDir for the tsv and png file
    * @param prefix Prefix of the tsv and png file
    * @param summary Summary class
    * @param libraryLevel Default false, when set true plot will be based on library stats instead of sample stats
    * @param sampleId Default it selects all sampples, when sample is giving it limits to selected sample
    */
Peter van 't Hof's avatar
Peter van 't Hof committed
486 487
  def rnaHistogramPlot(outputDir: File,
                       prefix: String,
488
                       tables: Array[Map[String, Array[Any]]],
Peter van 't Hof's avatar
Peter van 't Hof committed
489
                       libraryLevel: Boolean = false,
Peter van 't Hof's avatar
Peter van 't Hof committed
490 491 492
                       sampleId: Option[Int] = None,
                       libraryId: Option[Int] = None): Unit = {
    val statsPaths = Map(
Peter van 't Hof's avatar
Peter van 't Hof committed
493 494
      "position" -> List("histogram", "normalized_position"),
      "count" -> List("histogram", "All_Reads.normalized_coverage")
Peter van 't Hof's avatar
Peter van 't Hof committed
495
    )
Peter van 't Hof's avatar
Peter van 't Hof committed
496

497 498 499 500 501 502 503 504
    writePlotFromSummary(
      outputDir,
      prefix,
      summary,
      libraryLevel,
      sampleId,
      libraryId,
      statsPaths,
505 506
      "position" :: Nil,
      "count" :: Nil,
507 508 509 510 511 512
      "bammetrics",
      "rna",
      "Relative position",
      "Coverage",
      "Rna coverage"
    )
Peter van 't Hof's avatar
Peter van 't Hof committed
513 514
  }

Peter van 't Hof's avatar
Peter van 't Hof committed
515
  def mergeTables(tables: Array[Map[String, Array[Any]]],
516 517
                  mergeColumn: String,
                  defaultValue: Any = 0): Map[String, Array[Any]] = {
Peter van 't Hof's avatar
Peter van 't Hof committed
518 519
    val keys = tables.flatMap(x => x(mergeColumn)).distinct
    (for (table <- tables; (columnKey, columnValues) <- table if columnKey != mergeColumn) yield {
520 521
      columnKey -> keys.map(x =>
        table(mergeColumn).zip(columnValues).toMap.getOrElse(x, defaultValue))
Peter van 't Hof's avatar
Peter van 't Hof committed
522 523 524 525
    }).toMap + (mergeColumn -> keys)
  }

  def writeTableToTsv(tsvFile: File, table: Map[String, Array[Any]], firstColumn: String): Unit = {
526
    require(table.map(_._2.length).toList.distinct.size == 1,
527
            "Not all values has the same number or rows")
Peter van 't Hof's avatar
Peter van 't Hof committed
528 529 530
    val keys = table.keys.filterNot(_ == firstColumn).toList.sorted
    val writer = new PrintWriter(tsvFile)
    writer.println((firstColumn :: keys).mkString("\t"))
Peter van 't Hof's avatar
Peter van 't Hof committed
531 532 533
    table(firstColumn).zipWithIndex.foreach {
      case (c, i) =>
        writer.println((c :: keys.map(x => table(x)(i))).mkString("\t"))
Peter van 't Hof's avatar
Peter van 't Hof committed
534 535 536
    }
    writer.close()
  }
537
}
538

539
object BamMetricsAlignmentReport {
540 541 542 543 544
  def values(summary: SummaryDb,
             runId: Int,
             allSamples: Seq[Sample],
             allLibraries: Seq[Library],
             sampleId: Option[Int] = None,
545 546 547 548
             libId: Option[Int] = None,
             sampleLevel: Boolean = false,
             showPlot: Boolean = false,
             showIntro: Boolean = true,
549
             showTable: Boolean = true): Map[String, Any] = {
550 551

    val statsPaths = Map(
552 553 554 555 556 557 558
      "All" -> List("flagstats", "All"),
      "Mapped" -> List("flagstats", "Mapped"),
      "Duplicates" -> List("flagstats", "Duplicates"),
      "NotPrimaryAlignment" -> List("flagstats", "NotPrimaryAlignment")
    )
    val alignmentSummaryResults =
      summary.getStatsForLibraries(runId, "bammetrics", "bamstats", sampleId, statsPaths)
559 560
    val alignmentSummaryPlotLines: Option[Seq[String]] =
      if (showPlot)
561
        Some(BammetricsReport.alignmentSummaryPlotLines(summary, sampleId, !sampleLevel))
562
      else None
563 564 565 566 567 568 569 570 571 572
    Map(
      "alignmentSummaryResults" -> alignmentSummaryResults,
      "alignmentSummaryPlotLines" -> alignmentSummaryPlotLines,
      "sampleLevel" -> sampleLevel,
      "showPlot" -> showPlot,
      "showIntro" -> showIntro,
      "showTable" -> showTable,
      "sampleId" -> sampleId,
      "libId" -> libId
    )
573 574
  }
}
575 576 577 578 579 580 581
object BamMetricsMappingQuality {
  def values(summary: SummaryDb,
             runId: Int,
             allSamples: Seq[Sample],
             allLibraries: Seq[Library],
             sampleId: Option[Int],
             libId: Option[Int],
582
             sampleLevel: Boolean = false,
583 584
             showPlot: Boolean = false,
             showIntro: Boolean = true,
585
             showTable: Boolean = true): Map[String, Any] = {
586 587 588 589 590 591

    val samples = sampleId match {
      case Some(id) => allSamples.filter(_.id == id).toList
      case _ => allSamples.toList
    }
  }
592
}