BammetricsReport.scala 21.5 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
import nl.lumc.sasc.biopet.core.report.{ReportBuilder, ReportBuilderExtension, ReportPage, ReportSection}
Peter van 't Hof's avatar
Peter van 't Hof committed
21
import nl.lumc.sasc.biopet.utils.ConfigUtils
22
import nl.lumc.sasc.biopet.utils.rscript.{LinePlot, StackedBarPlot}
Peter van 't Hof's avatar
Peter van 't Hof committed
23
import nl.lumc.sasc.biopet.utils.summary.db.SummaryDb
Peter van 't Hof's avatar
Peter van 't Hof committed
24 25
import nl.lumc.sasc.biopet.utils.summary.db.SummaryDb.Implicts._
import nl.lumc.sasc.biopet.utils.summary.db.SummaryDb._
26
import nl.lumc.sasc.biopet.utils.summary.db.Schema._
27

28
import scala.collection.mutable.ArrayBuffer
29
import scala.concurrent.{Await, Future}
Peter van 't Hof's avatar
Peter van 't Hof committed
30
import scala.concurrent.duration.Duration
31

Peter van 't Hof's avatar
Peter van 't Hof committed
32
class BammetricsReport(val parent: Configurable) extends ReportBuilderExtension {
33
  def builder = BammetricsReport
34
}
35

36
/**
37 38 39 40
  * Object to create a report for [[BamMetrics]]
  *
  * Created by pjvan_thof on 3/30/15.
  */
41
object BammetricsReport extends ReportBuilder {
42

43
  /** Name of report */
44 45
  val reportName = "Bam Metrics"

46 47
  def pipelineName = "bammetrics"

48
  /** Root page for single BamMetrcis report */
Peter van 't Hof's avatar
Peter van 't Hof committed
49 50
  def indexPage: Future[ReportPage] =
    bamMetricsPage(summary, sampleId, libId).map { bamMetricsPage =>
51 52 53 54 55 56 57 58 59 60 61 62 63
      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
64 65 66
        Map()
      )
    }
67

68
  /** Generates a page with alignment stats */
Peter van 't Hof's avatar
Peter van 't Hof committed
69 70 71
  def bamMetricsPage(summary: SummaryDb,
                     sampleId: Option[Int],
                     libId: Option[Int],
Peter van 't Hof's avatar
Peter van 't Hof committed
72
                     metricsTag: String = "bammetrics"): Future[ReportPage] = Future {
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
    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
93
      .exists(_._2.isDefined)
94

95 96 97 98 99 100 101 102
    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"))
    )
103
    val targets = (
Peter van 't Hof's avatar
Peter van 't Hof committed
104 105
      targetSettings("amplicon_name"),
      targetSettings("roi_name")
Peter van 't Hof's avatar
Peter van 't Hof committed
106
    ) match {
107 108 109 110
      case (Some(amplicon: String), Some(roi: List[_])) => amplicon :: roi.map(_.toString)
      case (_, Some(roi: List[_])) => roi.map(_.toString)
      case _ => Nil
    }
111 112

    ReportPage(
Peter van 't Hof's avatar
Peter van 't Hof committed
113
      if (targets.isEmpty) List()
114 115 116 117 118 119 120 121 122
      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()))),
123
      List(
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
        "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),
149
      Map("metricsTag" -> metricsTag)
150 151 152
    )
  }

153
  /**
154
    * Generates the lines for alignmentSummaryPlot
155 156 157
    *
    * @param summary Summary class
    * @param sampleId Default it selects all sampples, when sample is giving it limits to selected sample
158
    *                     * @param libraryLevel Default false, when set true plot will be based on library stats instead of sample stats
159
    */
160 161 162
  def alignmentSummaryPlotLines(summary: SummaryDb,
                       sampleId: Option[Int] = None,
                                libraryLevel: Boolean = false): Seq[String] = {
Peter van 't Hof's avatar
Peter van 't Hof committed
163 164 165 166 167 168 169 170
    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) {
171 172
      summary
        .getStatsForLibraries(runId,
173 174 175 176
          "bammetrics",
          "bamstats",
          sampleId = sampleId,
          keyValues = statsPaths)
177 178 179 180
        .map(x => (x._1._1, Some(x._1._2)) -> x._2)
    } else
      summary
        .getStatsForSamples(runId,
181 182 183 184
          "bammetrics",
          "bamstats",
          sample = sampleId.map(SampleId),
          keyValues = statsPaths)
185
        .map(x => (x._1, None) -> x._2)
186
    val summaryPlotLines = ArrayBuffer[String]()
Peter van 't Hof's avatar
Peter van 't Hof committed
187

Peter van 't Hof's avatar
Peter van 't Hof committed
188
    for (((s, l), result) <- results) {
Peter van 't Hof's avatar
Peter van 't Hof committed
189
      val sampleName: String = summary.getSampleName(s).map(_.get)
190 191
      val libName: Option[String] =
        l.flatMap(x => Await.result(summary.getLibraryName(x), Duration.Inf))
192
      val sb = new StringBuffer()
193 194
      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
195 196 197 198
      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
199
      sb.append((mapped - duplicates - secondary) + "\t")
200
      sb.append(duplicates + "\t")
Peter van 't Hof's avatar
Peter van 't Hof committed
201
      sb.append((total - mapped) + "\t")
202
      sb.append(secondary)
203
      summaryPlotLines += sb.toString
204
    }
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225
    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],
                           libraryLevel: Boolean = false
                           ): Unit = {
    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")
226

227 228 229
    for (line <- summaryPlotLines) {
      tsvWriter.println(line)
    }
230 231 232 233 234 235
    tsvWriter.close()

    val plot = new StackedBarPlot(null)
    plot.input = tsvFile
    plot.output = pngFile
    plot.ylabel = Some("Reads")
236
    plot.width = Some(200 + (summaryPlotLines.size * 10))
Peter van 't Hof's avatar
WIP  
Peter van 't Hof committed
237
    plot.title = Some("Aligned_reads")
238 239
    plot.runLocal()
  }
240 241 242 243 244 245 246 247 248 249 250
  /**
    * 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
    */
251 252
  def summaryForPlot(                                         summary: SummaryDb,
                      statsPaths: Map[String, List[String]],
253 254 255 256 257 258 259
                                        yKeyList: List[String],
                                        xKeyList: List[String],
                                        pipeline: PipelineQuery,
                                        module: ModuleQuery,
                                        libraryLevel: Boolean = false,
                     sampleId: Option[Int] = None,
                     libraryId: Option[Int] = None
260
                      ): Array[Map[String, Array[Any]]]= {
Peter van 't Hof's avatar
Peter van 't Hof committed
261
    val results: Map[(Int, Option[Int]), Map[String, Option[Array[Any]]]] = if (libraryLevel) {
262 263 264 265 266 267 268 269
      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,
270 271 272 273
          pipeline,
          module,
          sample = sampleId.map(SampleId),
          keyValues = statsPaths)
274
        .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
275 276
    val tables: Array[Map[String, Array[Any]]] = results.map {
      case ((sample, library), map) =>
277 278
        val sampleName = Await
          .result(summary.getSampleName(sample), Duration.Inf)
Peter van 't Hof's avatar
Peter van 't Hof committed
279
          .getOrElse(throw new IllegalStateException("Sample must be there"))
280 281
        val libraryName =
          library.flatMap(l => Await.result(summary.getLibraryName(l), Duration.Inf))
Peter van 't Hof's avatar
Peter van 't Hof committed
282 283
        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
284
        Map(
Peter van 't Hof's avatar
Peter van 't Hof committed
285 286 287 288
          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
289
        )
Peter van 't Hof's avatar
Peter van 't Hof committed
290
    }.toArray
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
    tables
  }

  /**
    * This is a generic method to create plots
    * @param outputDir Outputdir of the plot
    * @param prefix Files will start with this name
    * @param tables Tables to be written
    * @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,
                           tables: Array[Map[String, Array[Any]]],
                           yKeyList: List[String],
311
                           xKeyList: List[String],
312 313 314 315 316 317
                           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
318

319
    writeTableToTsv(tsvFile, mergeTables(tables, yKeyList.head), yKeyList.head)
Peter van 't Hof's avatar
Peter van 't Hof committed
320

321 322 323 324 325
    LinePlot(tsvFile,
             pngFile,
             xlabel = xlabel,
             ylabel = ylabel,
             title = title,
326
             hideLegend = tables.size > 40, /* changed from results.size. Original results in summaryForPlot*/
327
             removeZero = removeZero).runLocal()
Peter van 't Hof's avatar
Peter van 't Hof committed
328 329
  }

330
  /**
331 332 333 334 335 336 337 338
    * Generate a line plot for insertsize
    *
    * @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
339
  def insertSizePlot(outputDir: File,
Peter van 't Hof's avatar
Peter van 't Hof committed
340
                     prefix: String,
341
                     tables: Array[Map[String, Array[Any]]],
Peter van 't Hof's avatar
Peter van 't Hof committed
342
                     libraryLevel: Boolean = false,
Peter van 't Hof's avatar
Peter van 't Hof committed
343
                     sampleId: Option[Int] = None,
Peter van 't Hof's avatar
Peter van 't Hof committed
344
                     libraryId: Option[Int] = None): Unit = {
Peter van 't Hof's avatar
Peter van 't Hof committed
345 346
    val statsPaths = Map(
      "insert_size" -> List("histogram", "insert_size"),
Peter van 't Hof's avatar
Peter van 't Hof committed
347
      "count" -> List("histogram", "All_Reads.fr_count")
Peter van 't Hof's avatar
Peter van 't Hof committed
348
    )
Peter van 't Hof's avatar
Peter van 't Hof committed
349

350 351 352
    writePlotFromSummary(
      outputDir,
      prefix,
353
      tables,
354 355 356 357
      libraryLevel,
      sampleId,
      libraryId,
      statsPaths,
358 359
      "insert_size" :: Nil,
      "count" :: Nil,
360 361 362 363 364 365
      "bammetrics",
      "CollectInsertSizeMetrics",
      "Insert size",
      "Reads",
      "Insert size"
    )
Peter van 't Hof's avatar
Peter van 't Hof committed
366
  }
Peter van 't Hof's avatar
Peter van 't Hof committed
367

368 369
  def mappingQualityPlotSummary(summary: SummaryDb,
                               ): Unit = {
Peter van 't Hof's avatar
Peter van 't Hof committed
370 371 372
    val statsPaths = Map(
      "mapping_quality" -> List("mapping_quality", "histogram", "values"),
      "count" -> List("mapping_quality", "histogram", "counts")
373
    )
374
    val plotSummary: Array[Map[String, Array[Any]]] = summaryForPlot(summary, statsPaths,
375 376 377 378
      "mapping_quality" :: Nil,
      "count" :: Nil,
      "bammetrics",
      "bamstats"
379
    )
380
    plotSummary
381 382
  }

383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399
    def mappingQualityPlot(outputDir: File,
                           prefix: String,
                           mappingQualityPlotSummary: Array[Map[String, Array[Any]]],
                           libraryLevel: Boolean = false,
                           sampleId: Option[Int] = None,
                           libraryId: Option[Int] = None): Unit = {
      val statsPaths = Map(
        "mapping_quality" -> List("mapping_quality", "histogram", "values"),
        "count" -> List("mapping_quality", "histogram", "counts")
      )
      writePlotFromSummary(outputDir,
        prefix,
        mappingQualityPlotSummary,
        "mapping_quality" :: Nil,
        "count" :: Nil,"Mapping Quality", "Reads","Mapping Quality")
    }

400
  def clippingPlot(outputDir: File,
Peter van 't Hof's avatar
Peter van 't Hof committed
401
                   prefix: String,
402
                   tables: Array[Map[String, Array[Any]]],
Peter van 't Hof's avatar
Peter van 't Hof committed
403
                   libraryLevel: Boolean = false,
Peter van 't Hof's avatar
Peter van 't Hof committed
404
                   sampleId: Option[Int] = None,
Peter van 't Hof's avatar
Peter van 't Hof committed
405 406 407 408
                   libraryId: Option[Int] = None): Unit = {
    val statsPaths = Map(
      "clipping" -> List("clipping", "histogram", "values"),
      "count" -> List("clipping", "histogram", "counts")
409 410
    )

411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426
    writePlotFromSummary(
      outputDir,
      prefix,
      summary,
      libraryLevel,
      sampleId,
      libraryId,
      statsPaths,
      "clipping" :: Nil,
      "count" :: Nil,
      "bammetrics",
      "bamstats",
      "Clipping",
      "Reads",
      "Clipping"
    )
427 428
  }

429
  /**
430 431 432 433 434 435 436 437
    * 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
438
  def wgsHistogramPlot(outputDir: File,
Peter van 't Hof's avatar
Peter van 't Hof committed
439
                       prefix: String,
440
                       tables: Array[Map[String, Array[Any]]],
Peter van 't Hof's avatar
Peter van 't Hof committed
441
                       libraryLevel: Boolean = false,
Peter van 't Hof's avatar
Peter van 't Hof committed
442
                       sampleId: Option[Int] = None,
Peter van 't Hof's avatar
Peter van 't Hof committed
443 444
                       libraryId: Option[Int] = None): Unit = {
    val statsPaths = Map(
Peter van 't Hof's avatar
Peter van 't Hof committed
445
      "coverage" -> List("histogram", "coverage"),
446 447
      "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
448
    )
Peter van 't Hof's avatar
Peter van 't Hof committed
449

450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465
    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
466
  }
Peter van 't Hof's avatar
Peter van 't Hof committed
467 468

  /**
469 470 471 472 473 474 475 476
    * 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
477 478
  def rnaHistogramPlot(outputDir: File,
                       prefix: String,
479
                       tables: Array[Map[String, Array[Any]]],
Peter van 't Hof's avatar
Peter van 't Hof committed
480
                       libraryLevel: Boolean = false,
Peter van 't Hof's avatar
Peter van 't Hof committed
481 482 483
                       sampleId: Option[Int] = None,
                       libraryId: Option[Int] = None): Unit = {
    val statsPaths = Map(
Peter van 't Hof's avatar
Peter van 't Hof committed
484 485
      "position" -> List("histogram", "normalized_position"),
      "count" -> List("histogram", "All_Reads.normalized_coverage")
Peter van 't Hof's avatar
Peter van 't Hof committed
486
    )
Peter van 't Hof's avatar
Peter van 't Hof committed
487

488 489 490 491 492 493 494 495
    writePlotFromSummary(
      outputDir,
      prefix,
      summary,
      libraryLevel,
      sampleId,
      libraryId,
      statsPaths,
496 497
      "position" :: Nil,
      "count" :: Nil,
498 499 500 501 502 503
      "bammetrics",
      "rna",
      "Relative position",
      "Coverage",
      "Rna coverage"
    )
Peter van 't Hof's avatar
Peter van 't Hof committed
504 505
  }

Peter van 't Hof's avatar
Peter van 't Hof committed
506
  def mergeTables(tables: Array[Map[String, Array[Any]]],
507 508
                  mergeColumn: String,
                  defaultValue: Any = 0): Map[String, Array[Any]] = {
Peter van 't Hof's avatar
Peter van 't Hof committed
509 510
    val keys = tables.flatMap(x => x(mergeColumn)).distinct
    (for (table <- tables; (columnKey, columnValues) <- table if columnKey != mergeColumn) yield {
511 512
      columnKey -> keys.map(x =>
        table(mergeColumn).zip(columnValues).toMap.getOrElse(x, defaultValue))
Peter van 't Hof's avatar
Peter van 't Hof committed
513 514 515 516
    }).toMap + (mergeColumn -> keys)
  }

  def writeTableToTsv(tsvFile: File, table: Map[String, Array[Any]], firstColumn: String): Unit = {
517
    require(table.map(_._2.length).toList.distinct.size == 1,
518
            "Not all values has the same number or rows")
Peter van 't Hof's avatar
Peter van 't Hof committed
519 520 521
    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
522 523 524
    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
525 526 527
    }
    writer.close()
  }
528
}
529

530
object BamMetricsAlignmentReport {
531 532 533 534 535
  def values(summary: SummaryDb,
             runId: Int,
             allSamples: Seq[Sample],
             allLibraries: Seq[Library],
             sampleId: Option[Int] = None,
536 537 538 539 540
             libId: Option[Int] = None,
             sampleLevel: Boolean = false,
             showPlot: Boolean = false,
             showIntro: Boolean = true,
             showTable: Boolean = true): Map[String,Any] = {
541 542 543 544 545 546 547 548

    val statsPaths = Map(
        "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)
549 550 551 552
    val alignmentSummaryPlotLines: Option[Seq[String]] =
      if (showPlot)
        Some(BammetricsReport.alignmentSummaryPlotLines(summary,sampleId,!sampleLevel))
      else None
553 554
  Map(
    "alignmentSummaryResults" -> alignmentSummaryResults,
555 556 557 558 559 560 561
    "alignmentSummaryPlotLines" -> alignmentSummaryPlotLines,
    "sampleLevel" -> sampleLevel,
    "showPlot" -> showPlot,
    "showIntro" -> showIntro,
    "showTable" -> showTable,
    "sampleId" -> sampleId,
    "libId" -> libId
562 563 564
  )
  }
}
565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583
object BamMetricsMappingQuality {
  def values(summary: SummaryDb,
             runId: Int,
             allSamples: Seq[Sample],
             allLibraries: Seq[Library],
             sampleId: Option[Int],
             libId: Option[Int],
             sampleLevel: Boolean= false,
             showPlot: Boolean = false,
             showIntro: Boolean = true,
             showTable: Boolean = true): Map[String,Any] = {

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