ReportBuilder.scala 8.75 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
15
/**
 * 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 that are
 * not part of GATK Queue 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.
 */
16
17
package nl.lumc.sasc.biopet.core.report

18
import java.io._
19

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

Peter van 't Hof's avatar
Peter van 't Hof committed
26
import scala.collection.mutable
27
import scala.language.postfixOps
28
29

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

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

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

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

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

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

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

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

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

68
69
trait ReportBuilder extends ToolCommand {

70
71
72
  case class Args(summary: File = null,
                  outputDir: File = null,
                  pageArgs: mutable.Map[String, Any] = mutable.Map()) extends AbstractArgs
73
74

  class OptParser extends AbstractOptParser {
75
76
77
78
79
80
81

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

Peter van 't Hof's avatar
Peter van 't Hof committed
82
    opt[File]('s', "summary") unbounded () required () maxOccurs 1 valueName "<file>" action { (x, c) =>
83
      c.copy(summary = x)
84
85
86
87
    } 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
88
    opt[File]('o', "outputDir") unbounded () required () maxOccurs 1 valueName "<file>" action { (x, c) =>
89
      c.copy(outputDir = x)
90
91
    } text "Output HTML report files to this directory"

Peter van 't Hof's avatar
Peter van 't Hof committed
92
    opt[Map[String, String]]('a', "args") unbounded () action { (x, c) =>
93
94
      c.copy(pageArgs = c.pageArgs ++ x)
    }
95
96
  }

97
  /** summary object internaly */
98
99
  private var setSummary: Summary = _

100
  /** Retrival of summary, read only */
101
102
  final def summary = setSummary

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

Peter van 't Hof's avatar
Peter van 't Hof committed
106
107
108
  private var done = 0
  private var total = 0

Peter van 't Hof's avatar
Peter van 't Hof committed
109
  private var _sampleId: Option[String] = None
Peter van 't Hof's avatar
Peter van 't Hof committed
110
  protected[report] def sampleId = _sampleId
Peter van 't Hof's avatar
Peter van 't Hof committed
111
  private var _libId: Option[String] = None
Peter van 't Hof's avatar
Peter van 't Hof committed
112
  protected[report] def libId = _libId
Peter van 't Hof's avatar
Peter van 't Hof committed
113

114
115
  case class ExtFile(resourcePath: String, targetPath: String)

116
117
118
119
120
121
122
123
  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
124
    "js/d3.v3.5.5.min.js",
125
126
127
    "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
128
  ).map(x => ExtFile("/nl/lumc/sasc/biopet/core/report/ext" + x, x))
129

130
  /** Main function to for building the report */
131
132
133
134
135
136
137
138
139
  def main(args: Array[String]): Unit = {
    logger.info("Start")

    val argsParser = new OptParser
    val cmdArgs: Args = argsParser.parse(args, Args()) getOrElse sys.exit(1)

    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
140
    cmdArgs.pageArgs.get("sampleId") match {
141
      case Some(s: String) =>
Peter van 't Hof's avatar
Peter van 't Hof committed
142
143
        cmdArgs.pageArgs += "sampleId" -> Some(s)
        _sampleId = Some(s)
Peter van 't Hof's avatar
Peter van 't Hof committed
144
      case _ =>
Peter van 't Hof's avatar
Peter van 't Hof committed
145
146
147
    }

    cmdArgs.pageArgs.get("libId") match {
148
      case Some(l: String) =>
Peter van 't Hof's avatar
Peter van 't Hof committed
149
150
        cmdArgs.pageArgs += "libId" -> Some(l)
        _libId = Some(l)
Peter van 't Hof's avatar
Peter van 't Hof committed
151
      case _ =>
Peter van 't Hof's avatar
Peter van 't Hof committed
152
153
    }

154
155
    logger.info("Copy Base files")

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

159
160
161
162
163
164
165
166
    // 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)
    )
167

Peter van 't Hof's avatar
Peter van 't Hof committed
168
    logger.info("Parsing summary")
169
170
    setSummary = new Summary(cmdArgs.summary)

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

Peter van 't Hof's avatar
Peter van 't Hof committed
174
175
    done = 0

Peter van 't Hof's avatar
Peter van 't Hof committed
176
    logger.info("Generate pages")
Peter van 't Hof's avatar
Peter van 't Hof committed
177
    val jobs = generatePage(summary, indexPage, cmdArgs.outputDir,
Peter van 't Hof's avatar
Peter van 't Hof committed
178
      args = pageArgs ++ cmdArgs.pageArgs.toMap ++
179
        Map("summary" -> summary, "reportName" -> reportName, "indexPage" -> indexPage))
180

Peter van 't Hof's avatar
Peter van 't Hof committed
181
    logger.info(jobs + " Done")
182
183
  }

184
  /** This must be implemented, this will be the root page of the report */
185
186
  def indexPage: ReportPage

187
  /** This must be implemented, this will become the title of the report */
188
189
  def reportName: String

190
191
  /**
   * This method will render the page and the subpages recursivly
Peter van 't Hof's avatar
Peter van 't Hof committed
192
 *
193
194
195
196
197
198
199
   * @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
   */
200
201
202
203
  def generatePage(summary: Summary,
                   page: ReportPage,
                   outputDir: File,
                   path: List[String] = Nil,
Peter van 't Hof's avatar
Peter van 't Hof committed
204
                   args: Map[String, Any] = Map()): Int = {
205

Peter van 't Hof's avatar
Peter van 't Hof committed
206
207
    val pageOutputDir = new File(outputDir, path.mkString(File.separator))
    pageOutputDir.mkdirs()
Peter van 't Hof's avatar
Peter van 't Hof committed
208
    val rootPath = "./" + Array.fill(path.size)("src/main").mkString("")
209
210
211
212
213
214
    val pageArgs = args ++ page.args ++
      Map("page" -> page,
        "path" -> path,
        "outputDir" -> pageOutputDir,
        "rootPath" -> rootPath
      )
215

216
    // Generating subpages
217
218
219
    val jobs = page.subPages.par.flatMap {
      case (name, subPage) => Some(generatePage(summary, subPage, outputDir, path ::: name :: Nil, pageArgs))
      case _               => None
220
221
    }

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

    val file = new File(pageOutputDir, "index.html")
226
227
228
229
    val writer = new PrintWriter(file)
    writer.println(output)
    writer.close()

Peter van 't Hof's avatar
Peter van 't Hof committed
230
231
    done += 1
    if (done % 100 == 0) logger.info(done + " Done, " + (done.toDouble / total * 100) + "%")
232
    jobs.sum + 1
233
234
  }
}
Peter van 't Hof's avatar
Peter van 't Hof committed
235
236
237

object ReportBuilder {

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

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

244
245
246
247
248
  /** 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
249
250
251
252
253
254
255
  /**
   * 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
256
257
    Logging.logger.info("Rendering: " + location)

258
259
    val templateFile: File = templateCache.get(location) match {
      case Some(template) => template
260
      case _ =>
261
        val tempFile = File.createTempFile("ssp-template", new File(location).getName)
262
        tempFile.deleteOnExit()
263
        IoUtils.copyStreamToFile(getClass.getResourceAsStream(location), tempFile)
264
265
266
267
268
        templateCache += location -> tempFile
        tempFile
    }
    engine.layout(TemplateSource.fromFile(templateFile), args)
  }
Peter van 't Hof's avatar
Peter van 't Hof committed
269
}