ReportBuilder.scala 10.1 KB
Newer Older
Peter van 't Hof's avatar
Peter van 't Hof committed
1
2
3
4
5
6
7
8
9
10
/**
 * 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
 *
11
 * A dual licensing mode is applied. The source code within this project is freely available for non-commercial use under an AGPL
Peter van 't Hof's avatar
Peter van 't Hof committed
12
13
14
 * 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.core.report

17
import java.io._
18

19
import nl.lumc.sasc.biopet.core.ToolCommandFunction
20
21
import nl.lumc.sasc.biopet.utils.summary.db.SummaryDb
import nl.lumc.sasc.biopet.utils.{IoUtils, Logging, ToolCommand}
Peter van 't Hof's avatar
Peter van 't Hof committed
22
import org.broadinstitute.gatk.utils.commandline.Input
23
import org.fusesource.scalate.{TemplateEngine, TemplateSource}
24

Peter van 't Hof's avatar
Peter van 't Hof committed
25
import scala.collection.mutable
26
27
import scala.concurrent.Await
import scala.concurrent.duration.Duration
28
import scala.language.postfixOps
29
30

/**
31
32
33
 * This trait is meant to make an extension for a report object
 *
 * @author pjvan_thof
34
 */
35
trait ReportBuilderExtension extends ToolCommandFunction {
36

37
  /** Report builder object */
38
  def builder: ReportBuilder
39

Peter van 't Hof's avatar
Peter van 't Hof committed
40
41
  def toolObject = builder

42
  @Input(required = true)
43
44
45
  var summaryDbFile: File = _

  var runId: Option[Int] = None
46

47
  /** OutputDir for the report  */
48
49
  var outputDir: File = _

50
  /** Arguments that are passed on the commandline */
51
52
  var args: Map[String, String] = Map()

53
54
  override def defaultCoreMemory = 4.0
  override def defaultThreads = 3
55

56
57
  override def beforeGraph(): Unit = {
    super.beforeGraph()
58
59
60
61
    jobOutputFile = new File(outputDir, ".report.log.out")
    javaMainClass = builder.getClass.getName.takeWhile(_ != '$')
  }

62
  /** Command to generate the report */
63
64
  override def cmdLine: String = {
    super.cmdLine +
65
66
      required("--summaryDb", summaryDbFile) +
      optional("--runId", runId) +
67
      required("--outputDir", outputDir) +
Peter van 't Hof's avatar
Peter van 't Hof committed
68
      args.map(x => required("-a", x._1 + "=" + x._2)).mkString
69
70
71
  }
}

72
73
trait ReportBuilder extends ToolCommand {

74
75
  implicit def toOption[T](x: T) : Option[T] = Option(x)

76
  case class Args(summaryDbFile: File = null,
77
                  outputDir: File = null,
78
                  runId: Int = 0,
79
                  pageArgs: mutable.Map[String, Any] = mutable.Map()) extends AbstractArgs
80
81

  class OptParser extends AbstractOptParser {
82
83
84
85
86
87
88

    head(
      s"""
         |$commandName - Generate HTML formatted report from a biopet summary.json
       """.stripMargin
    )

89
90
    opt[File]('s', "summaryDb") unbounded () required () maxOccurs 1 valueName "<file>" action { (x, c) =>
      c.copy(summaryDbFile = x)
91
92
93
94
    } validate {
      x => if (x.exists) success else failure("Summary JSON file not found!")
    } text "Biopet summary JSON file"

Peter van 't Hof's avatar
Peter van 't Hof committed
95
    opt[File]('o', "outputDir") unbounded () required () maxOccurs 1 valueName "<file>" action { (x, c) =>
96
      c.copy(outputDir = x)
97
98
    } text "Output HTML report files to this directory"

99
100
101
102
    opt[Int]("runId") unbounded () maxOccurs 1 valueName "<int>" action { (x, c) =>
      c.copy(runId = x)
    }

Peter van 't Hof's avatar
Peter van 't Hof committed
103
    opt[Map[String, String]]('a', "args") unbounded () action { (x, c) =>
104
105
      c.copy(pageArgs = c.pageArgs ++ x)
    }
106
107
  }

108
  /** summary object internaly */
109
  private var setSummary: SummaryDb = _
110

111
  /** Retrival of summary, read only */
112
113
  final def summary = setSummary

114
115
116
117
  private var setRunId: Int = 0

  final def runId = setRunId

Peter van 't Hof's avatar
Peter van 't Hof committed
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
  private var setSampleCache: Map[String, Int] = _

  final def sampleCache = setSampleCache

  private var setLibraryCache: Map[(String, String), Int] = _

  final def libraryCache = setSampleCache

  private var setPipelineCache: Map[String, Int] = _

  final def pipelineCache = setPipelineCache

  private var setModuleCache: Map[String, Int] = _

  final def moduleCache = setModuleCache

134
  /** default args that are passed to all page withing the report */
135
136
  def pageArgs: Map[String, Any] = Map()

Peter van 't Hof's avatar
Peter van 't Hof committed
137
138
139
  private var done = 0
  private var total = 0

Peter van 't Hof's avatar
Peter van 't Hof committed
140
  private var _sampleId: Option[String] = None
Peter van 't Hof's avatar
Peter van 't Hof committed
141
  protected[report] def sampleId = _sampleId
Peter van 't Hof's avatar
Peter van 't Hof committed
142
  private var _libId: Option[String] = None
Peter van 't Hof's avatar
Peter van 't Hof committed
143
  protected[report] def libId = _libId
Peter van 't Hof's avatar
Peter van 't Hof committed
144

145
146
  case class ExtFile(resourcePath: String, targetPath: String)

147
148
149
150
151
152
153
154
  def extFiles = List(
    "css/bootstrap_dashboard.css",
    "css/bootstrap.min.css",
    "css/bootstrap-theme.min.css",
    "css/sortable-theme-bootstrap.css",
    "js/jquery.min.js",
    "js/sortable.min.js",
    "js/bootstrap.min.js",
Peter van 't Hof's avatar
Peter van 't Hof committed
155
    "js/d3.v3.5.5.min.js",
156
157
158
    "fonts/glyphicons-halflings-regular.woff",
    "fonts/glyphicons-halflings-regular.ttf",
    "fonts/glyphicons-halflings-regular.woff2"
Peter van 't Hof's avatar
Peter van 't Hof committed
159
  ).map(x => ExtFile("/nl/lumc/sasc/biopet/core/report/ext/" + x, x))
160

161
  /** Main function to for building the report */
162
163
164
165
  def main(args: Array[String]): Unit = {
    logger.info("Start")

    val argsParser = new OptParser
Peter van 't Hof's avatar
Peter van 't Hof committed
166
    val cmdArgs: Args = argsParser.parse(args, Args()) getOrElse (throw new IllegalArgumentException)
167
168
169
170

    require(cmdArgs.outputDir.exists(), "Output dir does not exist")
    require(cmdArgs.outputDir.isDirectory, "Output dir is not a directory")

Peter van 't Hof's avatar
Peter van 't Hof committed
171
    cmdArgs.pageArgs.get("sampleId") match {
172
      case Some(s: String) =>
Peter van 't Hof's avatar
Peter van 't Hof committed
173
174
        cmdArgs.pageArgs += "sampleId" -> Some(s)
        _sampleId = Some(s)
Peter van 't Hof's avatar
Peter van 't Hof committed
175
      case _ =>
Peter van 't Hof's avatar
Peter van 't Hof committed
176
177
178
    }

    cmdArgs.pageArgs.get("libId") match {
179
      case Some(l: String) =>
Peter van 't Hof's avatar
Peter van 't Hof committed
180
181
        cmdArgs.pageArgs += "libId" -> Some(l)
        _libId = Some(l)
Peter van 't Hof's avatar
Peter van 't Hof committed
182
      case _ =>
Peter van 't Hof's avatar
Peter van 't Hof committed
183
184
    }

185
186
    logger.info("Copy Base files")

Peter van 't Hof's avatar
Peter van 't Hof committed
187
    // Static files that will be copied to the output folder, then file is added to [resourceDir] it's need to be added here also
188
189
    val extOutputDir: File = new File(cmdArgs.outputDir, "ext")

190
191
192
193
194
195
196
197
    // Copy each resource files out to the report destination
    extFiles.par.foreach(
      resource =>
        IoUtils.copyStreamToFile(
          getClass.getResourceAsStream(resource.resourcePath),
          new File(extOutputDir, resource.targetPath),
          createDirs = true)
    )
198

Peter van 't Hof's avatar
Peter van 't Hof committed
199
    logger.info("Parsing summary")
200
201
    setSummary = SummaryDb.openSqliteSummary(cmdArgs.summaryDbFile)
    setRunId = cmdArgs.runId
202
203
204
205
    setSampleCache = Await.result(summary.getSamples(runId = Some(runId)), Duration.Inf).map(r => r.name -> r.id).toMap
    setLibraryCache = Await.result(summary.getLibraries(runId = Some(runId)), Duration.Inf).map(r => (setSampleCache.find(_._2 == r.sampleId).get._1, r.name) -> r.id).toMap
    setPipelineCache = Await.result(summary.getPipelines(runId = Some(runId)), Duration.Inf).map(r => r.name -> r.id).toMap
    setModuleCache = Await.result(summary.getModules(runId = Some(runId)), Duration.Inf).map(r => r.name -> r.id).toMap
206

207
    total = ReportBuilder.countPages(indexPage)
Peter van 't Hof's avatar
Peter van 't Hof committed
208
209
    logger.info(total + " pages to be generated")

Peter van 't Hof's avatar
Peter van 't Hof committed
210
211
    done = 0

Peter van 't Hof's avatar
Peter van 't Hof committed
212
    logger.info("Generate pages")
Peter van 't Hof's avatar
Peter van 't Hof committed
213
    val jobs = generatePage(summary, indexPage, cmdArgs.outputDir,
Peter van 't Hof's avatar
Peter van 't Hof committed
214
      args = pageArgs ++ cmdArgs.pageArgs.toMap ++
215
        Map("summary" -> summary, "reportName" -> reportName, "indexPage" -> indexPage, "runId" -> cmdArgs.runId))
216

Peter van 't Hof's avatar
Peter van 't Hof committed
217
    logger.info(jobs + " Done")
218
219
  }

220
  /** This must be implemented, this will be the root page of the report */
221
222
  def indexPage: ReportPage

223
  /** This must be implemented, this will become the title of the report */
224
225
  def reportName: String

226
227
  /**
   * This method will render the page and the subpages recursivly
Peter van 't Hof's avatar
Peter van 't Hof committed
228
   *
229
230
231
232
233
234
235
   * @param summary The summary object
   * @param page Page to render
   * @param outputDir Root output dir of the report
   * @param path Path from root to current page
   * @param args Args to add to this sub page, are args from current page are passed automaticly
   * @return Number of pages including all subpages that are rendered
   */
236
  def generatePage(summary: SummaryDb,
237
238
239
                   page: ReportPage,
                   outputDir: File,
                   path: List[String] = Nil,
Peter van 't Hof's avatar
Peter van 't Hof committed
240
                   args: Map[String, Any] = Map()): Int = {
241

Peter van 't Hof's avatar
Peter van 't Hof committed
242
243
    val pageOutputDir = new File(outputDir, path.mkString(File.separator))
    pageOutputDir.mkdirs()
244
    val rootPath = "./" + Array.fill(path.size)("../").mkString
245
246
247
248
249
250
    val pageArgs = args ++ page.args ++
      Map("page" -> page,
        "path" -> path,
        "outputDir" -> pageOutputDir,
        "rootPath" -> rootPath
      )
251

252
    // Generating subpages
253
254
255
    val jobs = page.subPages.par.flatMap {
      case (name, subPage) => Some(generatePage(summary, subPage, outputDir, path ::: name :: Nil, pageArgs))
      case _               => None
256
257
    }

Peter van 't Hof's avatar
Peter van 't Hof committed
258
259
260
261
    val output = ReportBuilder.renderTemplate("/nl/lumc/sasc/biopet/core/report/main.ssp",
      pageArgs ++ Map("args" -> pageArgs))

    val file = new File(pageOutputDir, "index.html")
262
263
264
265
    val writer = new PrintWriter(file)
    writer.println(output)
    writer.close()

Peter van 't Hof's avatar
Peter van 't Hof committed
266
267
    done += 1
    if (done % 100 == 0) logger.info(done + " Done, " + (done.toDouble / total * 100) + "%")
268
    jobs.sum + 1
269
270
  }
}
Peter van 't Hof's avatar
Peter van 't Hof committed
271
272
273

object ReportBuilder {

274
  /** Single template render engine, this will have a cache for all compile templates */
Peter van 't Hof's avatar
Peter van 't Hof committed
275
276
  protected val engine = new TemplateEngine()

277
  /** Cache of temp file for templates from the classpath / jar */
Peter van 't Hof's avatar
Peter van 't Hof committed
278
  private[report] var templateCache: Map[String, File] = Map()
279

280
281
282
283
284
  /** This will give the total number of pages including all nested pages */
  def countPages(page: ReportPage): Int = {
    page.subPages.map(x => countPages(x._2)).fold(1)(_ + _)
  }

Peter van 't Hof's avatar
Peter van 't Hof committed
285
286
287
288
289
290
291
  /**
   * This method will render a template that is located in the classpath / jar
   * @param location location in the classpath / jar
   * @param args Additional arguments, not required
   * @return Rendered result of template
   */
  def renderTemplate(location: String, args: Map[String, Any] = Map()): String = {
Peter van 't Hof's avatar
Peter van 't Hof committed
292
293
    Logging.logger.info("Rendering: " + location)

294
295
    val templateFile: File = templateCache.get(location) match {
      case Some(template) => template
296
      case _ =>
297
        val tempFile = File.createTempFile("ssp-template", new File(location).getName)
298
        tempFile.deleteOnExit()
299
        IoUtils.copyStreamToFile(getClass.getResourceAsStream(location), tempFile)
300
301
302
303
304
        templateCache += location -> tempFile
        tempFile
    }
    engine.layout(TemplateSource.fromFile(templateFile), args)
  }
Peter van 't Hof's avatar
Peter van 't Hof committed
305
}