ReportBuilder.scala 9.49 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
import scala.language.postfixOps
27
28

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

35
  /** Report builder object */
36
  def builder: ReportBuilder
37

Peter van 't Hof's avatar
Peter van 't Hof committed
38
39
  def toolObject = builder

40
  @Input(required = true)
41
42
43
  var summaryDbFile: File = _

  var runId: Option[Int] = None
44

45
  /** OutputDir for the report  */
46
47
  var outputDir: File = _

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

51
52
  override def defaultCoreMemory = 4.0
  override def defaultThreads = 3
53

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

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

70
71
trait ReportBuilder extends ToolCommand {

72
  case class Args(summaryDbFile: File = null,
73
                  outputDir: File = null,
74
                  runId: Int = 0,
75
                  pageArgs: mutable.Map[String, Any] = mutable.Map()) extends AbstractArgs
76
77

  class OptParser extends AbstractOptParser {
78
79
80
81
82
83
84

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

85
86
    opt[File]('s', "summaryDb") unbounded () required () maxOccurs 1 valueName "<file>" action { (x, c) =>
      c.copy(summaryDbFile = x)
87
88
89
90
    } 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
91
    opt[File]('o', "outputDir") unbounded () required () maxOccurs 1 valueName "<file>" action { (x, c) =>
92
      c.copy(outputDir = x)
93
94
    } text "Output HTML report files to this directory"

95
96
97
98
    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
99
    opt[Map[String, String]]('a', "args") unbounded () action { (x, c) =>
100
101
      c.copy(pageArgs = c.pageArgs ++ x)
    }
102
103
  }

104
  /** summary object internaly */
105
  private var setSummary: SummaryDb = _
106

107
  /** Retrival of summary, read only */
108
109
  final def summary = setSummary

110
111
112
113
  private var setRunId: Int = 0

  final def runId = setRunId

Peter van 't Hof's avatar
Peter van 't Hof committed
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
  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

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

Peter van 't Hof's avatar
Peter van 't Hof committed
133
134
135
  private var done = 0
  private var total = 0

Peter van 't Hof's avatar
Peter van 't Hof committed
136
  private var _sampleId: Option[String] = None
Peter van 't Hof's avatar
Peter van 't Hof committed
137
  protected[report] def sampleId = _sampleId
Peter van 't Hof's avatar
Peter van 't Hof committed
138
  private var _libId: Option[String] = None
Peter van 't Hof's avatar
Peter van 't Hof committed
139
  protected[report] def libId = _libId
Peter van 't Hof's avatar
Peter van 't Hof committed
140

141
142
  case class ExtFile(resourcePath: String, targetPath: String)

143
144
145
146
147
148
149
150
  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
151
    "js/d3.v3.5.5.min.js",
152
153
154
    "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
155
  ).map(x => ExtFile("/nl/lumc/sasc/biopet/core/report/ext/" + x, x))
156

157
  /** Main function to for building the report */
158
159
160
161
  def main(args: Array[String]): Unit = {
    logger.info("Start")

    val argsParser = new OptParser
Peter van 't Hof's avatar
Peter van 't Hof committed
162
    val cmdArgs: Args = argsParser.parse(args, Args()) getOrElse (throw new IllegalArgumentException)
163
164
165
166

    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
167
    cmdArgs.pageArgs.get("sampleId") match {
168
      case Some(s: String) =>
Peter van 't Hof's avatar
Peter van 't Hof committed
169
170
        cmdArgs.pageArgs += "sampleId" -> Some(s)
        _sampleId = Some(s)
Peter van 't Hof's avatar
Peter van 't Hof committed
171
      case _ =>
Peter van 't Hof's avatar
Peter van 't Hof committed
172
173
174
    }

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

181
182
    logger.info("Copy Base files")

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

186
187
188
189
190
191
192
193
    // 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)
    )
194

Peter van 't Hof's avatar
Peter van 't Hof committed
195
    logger.info("Parsing summary")
196
197
    setSummary = SummaryDb.openSqliteSummary(cmdArgs.summaryDbFile)
    setRunId = cmdArgs.runId
198

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

Peter van 't Hof's avatar
Peter van 't Hof committed
202
203
    done = 0

Peter van 't Hof's avatar
Peter van 't Hof committed
204
    logger.info("Generate pages")
Peter van 't Hof's avatar
Peter van 't Hof committed
205
    val jobs = generatePage(summary, indexPage, cmdArgs.outputDir,
Peter van 't Hof's avatar
Peter van 't Hof committed
206
      args = pageArgs ++ cmdArgs.pageArgs.toMap ++
207
        Map("summary" -> summary, "reportName" -> reportName, "indexPage" -> indexPage, "runId" -> cmdArgs.runId))
208

Peter van 't Hof's avatar
Peter van 't Hof committed
209
    logger.info(jobs + " Done")
210
211
  }

212
  /** This must be implemented, this will be the root page of the report */
213
214
  def indexPage: ReportPage

215
  /** This must be implemented, this will become the title of the report */
216
217
  def reportName: String

218
219
  /**
   * This method will render the page and the subpages recursivly
Peter van 't Hof's avatar
Peter van 't Hof committed
220
   *
221
222
223
224
225
226
227
   * @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
   */
228
  def generatePage(summary: SummaryDb,
229
230
231
                   page: ReportPage,
                   outputDir: File,
                   path: List[String] = Nil,
Peter van 't Hof's avatar
Peter van 't Hof committed
232
                   args: Map[String, Any] = Map()): Int = {
233

Peter van 't Hof's avatar
Peter van 't Hof committed
234
235
    val pageOutputDir = new File(outputDir, path.mkString(File.separator))
    pageOutputDir.mkdirs()
236
    val rootPath = "./" + Array.fill(path.size)("../").mkString
237
238
239
240
241
242
    val pageArgs = args ++ page.args ++
      Map("page" -> page,
        "path" -> path,
        "outputDir" -> pageOutputDir,
        "rootPath" -> rootPath
      )
243

244
    // Generating subpages
245
246
247
    val jobs = page.subPages.par.flatMap {
      case (name, subPage) => Some(generatePage(summary, subPage, outputDir, path ::: name :: Nil, pageArgs))
      case _               => None
248
249
    }

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

    val file = new File(pageOutputDir, "index.html")
254
255
256
257
    val writer = new PrintWriter(file)
    writer.println(output)
    writer.close()

Peter van 't Hof's avatar
Peter van 't Hof committed
258
259
    done += 1
    if (done % 100 == 0) logger.info(done + " Done, " + (done.toDouble / total * 100) + "%")
260
    jobs.sum + 1
261
262
  }
}
Peter van 't Hof's avatar
Peter van 't Hof committed
263
264
265

object ReportBuilder {

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

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

272
273
274
275
276
  /** 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
277
278
279
280
281
282
283
  /**
   * 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
284
285
    Logging.logger.info("Rendering: " + location)

286
287
    val templateFile: File = templateCache.get(location) match {
      case Some(template) => template
288
      case _ =>
289
        val tempFile = File.createTempFile("ssp-template", new File(location).getName)
290
        tempFile.deleteOnExit()
291
        IoUtils.copyStreamToFile(getClass.getResourceAsStream(location), tempFile)
292
293
294
295
296
        templateCache += location -> tempFile
        tempFile
    }
    engine.layout(TemplateSource.fromFile(templateFile), args)
  }
Peter van 't Hof's avatar
Peter van 't Hof committed
297
}