ReportBuilder.scala 9.18 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
114
115
  /** summary object internaly */
  private var setRunId: Int = 0

  /** Retrival of summary, read only */
  final def runId = setRunId

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

Peter van 't Hof's avatar
Peter van 't Hof committed
119
120
121
  private var done = 0
  private var total = 0

Peter van 't Hof's avatar
Peter van 't Hof committed
122
  private var _sampleId: Option[String] = None
Peter van 't Hof's avatar
Peter van 't Hof committed
123
  protected[report] def sampleId = _sampleId
Peter van 't Hof's avatar
Peter van 't Hof committed
124
  private var _libId: Option[String] = None
Peter van 't Hof's avatar
Peter van 't Hof committed
125
  protected[report] def libId = _libId
Peter van 't Hof's avatar
Peter van 't Hof committed
126

127
128
  case class ExtFile(resourcePath: String, targetPath: String)

129
130
131
132
133
134
135
136
  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
137
    "js/d3.v3.5.5.min.js",
138
139
140
    "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
141
  ).map(x => ExtFile("/nl/lumc/sasc/biopet/core/report/ext/" + x, x))
142

143
  /** Main function to for building the report */
144
145
146
147
  def main(args: Array[String]): Unit = {
    logger.info("Start")

    val argsParser = new OptParser
Peter van 't Hof's avatar
Peter van 't Hof committed
148
    val cmdArgs: Args = argsParser.parse(args, Args()) getOrElse (throw new IllegalArgumentException)
149
150
151
152

    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
153
    cmdArgs.pageArgs.get("sampleId") match {
154
      case Some(s: String) =>
Peter van 't Hof's avatar
Peter van 't Hof committed
155
156
        cmdArgs.pageArgs += "sampleId" -> Some(s)
        _sampleId = Some(s)
Peter van 't Hof's avatar
Peter van 't Hof committed
157
      case _ =>
Peter van 't Hof's avatar
Peter van 't Hof committed
158
159
160
    }

    cmdArgs.pageArgs.get("libId") match {
161
      case Some(l: String) =>
Peter van 't Hof's avatar
Peter van 't Hof committed
162
163
        cmdArgs.pageArgs += "libId" -> Some(l)
        _libId = Some(l)
Peter van 't Hof's avatar
Peter van 't Hof committed
164
      case _ =>
Peter van 't Hof's avatar
Peter van 't Hof committed
165
166
    }

167
168
    logger.info("Copy Base files")

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

172
173
174
175
176
177
178
179
    // 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)
    )
180

Peter van 't Hof's avatar
Peter van 't Hof committed
181
    logger.info("Parsing summary")
182
183
    setSummary = SummaryDb.openSqliteSummary(cmdArgs.summaryDbFile)
    setRunId = cmdArgs.runId
184

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

Peter van 't Hof's avatar
Peter van 't Hof committed
188
189
    done = 0

Peter van 't Hof's avatar
Peter van 't Hof committed
190
    logger.info("Generate pages")
Peter van 't Hof's avatar
Peter van 't Hof committed
191
    val jobs = generatePage(summary, indexPage, cmdArgs.outputDir,
Peter van 't Hof's avatar
Peter van 't Hof committed
192
      args = pageArgs ++ cmdArgs.pageArgs.toMap ++
193
        Map("summary" -> summary, "reportName" -> reportName, "indexPage" -> indexPage, "runId" -> cmdArgs.runId))
194

Peter van 't Hof's avatar
Peter van 't Hof committed
195
    logger.info(jobs + " Done")
196
197
  }

198
  /** This must be implemented, this will be the root page of the report */
199
200
  def indexPage: ReportPage

201
  /** This must be implemented, this will become the title of the report */
202
203
  def reportName: String

204
205
  /**
   * This method will render the page and the subpages recursivly
Peter van 't Hof's avatar
Peter van 't Hof committed
206
   *
207
208
209
210
211
212
213
   * @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
   */
214
  def generatePage(summary: SummaryDb,
215
216
217
                   page: ReportPage,
                   outputDir: File,
                   path: List[String] = Nil,
Peter van 't Hof's avatar
Peter van 't Hof committed
218
                   args: Map[String, Any] = Map()): Int = {
219

Peter van 't Hof's avatar
Peter van 't Hof committed
220
221
    val pageOutputDir = new File(outputDir, path.mkString(File.separator))
    pageOutputDir.mkdirs()
222
    val rootPath = "./" + Array.fill(path.size)("../").mkString
223
224
225
226
227
228
    val pageArgs = args ++ page.args ++
      Map("page" -> page,
        "path" -> path,
        "outputDir" -> pageOutputDir,
        "rootPath" -> rootPath
      )
229

230
    // Generating subpages
231
232
233
    val jobs = page.subPages.par.flatMap {
      case (name, subPage) => Some(generatePage(summary, subPage, outputDir, path ::: name :: Nil, pageArgs))
      case _               => None
234
235
    }

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

    val file = new File(pageOutputDir, "index.html")
240
241
242
243
    val writer = new PrintWriter(file)
    writer.println(output)
    writer.close()

Peter van 't Hof's avatar
Peter van 't Hof committed
244
245
    done += 1
    if (done % 100 == 0) logger.info(done + " Done, " + (done.toDouble / total * 100) + "%")
246
    jobs.sum + 1
247
248
  }
}
Peter van 't Hof's avatar
Peter van 't Hof committed
249
250
251

object ReportBuilder {

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

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

258
259
260
261
262
  /** 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
263
264
265
266
267
268
269
  /**
   * 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
270
271
    Logging.logger.info("Rendering: " + location)

272
273
    val templateFile: File = templateCache.get(location) match {
      case Some(template) => template
274
      case _ =>
275
        val tempFile = File.createTempFile("ssp-template", new File(location).getName)
276
        tempFile.deleteOnExit()
277
        IoUtils.copyStreamToFile(getClass.getResourceAsStream(location), tempFile)
278
279
280
281
282
        templateCache += location -> tempFile
        tempFile
    }
    engine.layout(TemplateSource.fromFile(templateFile), args)
  }
Peter van 't Hof's avatar
Peter van 't Hof committed
283
}