ReportBuilder.scala 8.23 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
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
41
42
  @Input(required = true)
  var summaryFile: File = _

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

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

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

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

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

67
68
trait ReportBuilder extends ToolCommand {

Peter van 't Hof's avatar
Peter van 't Hof committed
69
  case class Args(summary: File = null, outputDir: File = null, pageArgs: mutable.Map[String, Any] = mutable.Map()) extends AbstractArgs
70
71

  class OptParser extends AbstractOptParser {
Peter van 't Hof's avatar
Peter van 't Hof committed
72
    opt[File]('s', "summary") unbounded () required () maxOccurs 1 valueName "<file>" action { (x, c) =>
73
74
      c.copy(summary = x)
    }
Peter van 't Hof's avatar
Peter van 't Hof committed
75
    opt[File]('o', "outputDir") unbounded () required () maxOccurs 1 valueName "<file>" action { (x, c) =>
76
77
      c.copy(outputDir = x)
    }
Peter van 't Hof's avatar
Peter van 't Hof committed
78
    opt[Map[String, String]]('a', "args") unbounded () action { (x, c) =>
79
80
      c.copy(pageArgs = c.pageArgs ++ x)
    }
81
82
  }

83
  /** summary object internaly */
84
85
  private var setSummary: Summary = _

86
  /** Retrival of summary, read only */
87
88
  final def summary = setSummary

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

Peter van 't Hof's avatar
Peter van 't Hof committed
92
93
94
  private var done = 0
  private var total = 0

Peter van 't Hof's avatar
Peter van 't Hof committed
95
  private var _sampleId: Option[String] = None
Peter van 't Hof's avatar
Peter van 't Hof committed
96
  protected[report] def sampleId = _sampleId
Peter van 't Hof's avatar
Peter van 't Hof committed
97
  private var _libId: Option[String] = None
Peter van 't Hof's avatar
Peter van 't Hof committed
98
  protected[report] def libId = _libId
Peter van 't Hof's avatar
Peter van 't Hof committed
99

100
101
  case class ExtFile(resourcePath: String, targetPath: String)

102
103
104
105
106
107
108
109
  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
110
    "js/d3.v3.5.5.min.js",
111
112
113
    "fonts/glyphicons-halflings-regular.woff",
    "fonts/glyphicons-halflings-regular.ttf",
    "fonts/glyphicons-halflings-regular.woff2"
114
  ).map(x => ExtFile("/nl/lumc/sasc/biopet/core/report/ext/" + x, x))
115

116
  /** Main function to for building the report */
117
118
119
120
121
122
123
124
125
  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
126
    cmdArgs.pageArgs.get("sampleId") match {
127
      case Some(s: String) =>
Peter van 't Hof's avatar
Peter van 't Hof committed
128
129
        cmdArgs.pageArgs += "sampleId" -> Some(s)
        _sampleId = Some(s)
Peter van 't Hof's avatar
Peter van 't Hof committed
130
      case _ =>
Peter van 't Hof's avatar
Peter van 't Hof committed
131
132
133
    }

    cmdArgs.pageArgs.get("libId") match {
134
      case Some(l: String) =>
Peter van 't Hof's avatar
Peter van 't Hof committed
135
136
        cmdArgs.pageArgs += "libId" -> Some(l)
        _libId = Some(l)
Peter van 't Hof's avatar
Peter van 't Hof committed
137
      case _ =>
Peter van 't Hof's avatar
Peter van 't Hof committed
138
139
    }

140
141
    logger.info("Copy Base files")

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

    for (resource <- extFiles.par) {
146
      IoUtils.copyStreamToFile(getClass.getResourceAsStream(resource.resourcePath), new File(extOutputDir, resource.targetPath), createDirs = true)
147
    }
148

Peter van 't Hof's avatar
Peter van 't Hof committed
149
    logger.info("Parsing summary")
150
151
    setSummary = new Summary(cmdArgs.summary)

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

Peter van 't Hof's avatar
Peter van 't Hof committed
155
156
    done = 0

Peter van 't Hof's avatar
Peter van 't Hof committed
157
    logger.info("Generate pages")
Peter van 't Hof's avatar
Peter van 't Hof committed
158
    val jobs = generatePage(summary, indexPage, cmdArgs.outputDir,
Peter van 't Hof's avatar
Peter van 't Hof committed
159
      args = pageArgs ++ cmdArgs.pageArgs.toMap ++
160
        Map("summary" -> summary, "reportName" -> reportName, "indexPage" -> indexPage))
161

Peter van 't Hof's avatar
Peter van 't Hof committed
162
    logger.info(jobs + " Done")
163
164
  }

165
  /** This must be implemented, this will be the root page of the report */
166
167
  def indexPage: ReportPage

168
  /** This must be implemented, this will because the title of the report */
169
170
  def reportName: String

171
172
173
174
175
176
177
178
179
  /**
   * This method will render the page and the subpages recursivly
   * @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
   */
180
181
182
183
  def generatePage(summary: Summary,
                   page: ReportPage,
                   outputDir: File,
                   path: List[String] = Nil,
Peter van 't Hof's avatar
Peter van 't Hof committed
184
                   args: Map[String, Any] = Map()): Int = {
185

Peter van 't Hof's avatar
Peter van 't Hof committed
186
187
    val pageOutputDir = new File(outputDir, path.mkString(File.separator))
    pageOutputDir.mkdirs()
188
189
190
191
192
193
194
    val rootPath = "./" + Array.fill(path.size)("../").mkString("")
    val pageArgs = args ++ page.args ++
      Map("page" -> page,
        "path" -> path,
        "outputDir" -> pageOutputDir,
        "rootPath" -> rootPath
      )
195

196
197
198
199
200
    // Generating subpages
    val jobs = for ((name, subPage) <- page.subPages.par) yield {
      generatePage(summary, subPage, outputDir, path ::: name :: Nil, pageArgs)
    }

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

    val file = new File(pageOutputDir, "index.html")
205
206
207
208
    val writer = new PrintWriter(file)
    writer.println(output)
    writer.close()

Peter van 't Hof's avatar
Peter van 't Hof committed
209
210
    done += 1
    if (done % 100 == 0) logger.info(done + " Done, " + (done.toDouble / total * 100) + "%")
211
    jobs.sum + 1
212
213
  }
}
Peter van 't Hof's avatar
Peter van 't Hof committed
214
215
216

object ReportBuilder {

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

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

223
224
225
226
227
  /** 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
228
229
230
231
232
233
234
  /**
   * 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
235
236
    Logging.logger.info("Rendering: " + location)

237
238
    val templateFile: File = templateCache.get(location) match {
      case Some(template) => template
239
      case _ =>
240
        val tempFile = File.createTempFile("ssp-template", new File(location).getName)
241
        tempFile.deleteOnExit()
242
        IoUtils.copyStreamToFile(getClass.getResourceAsStream(location), tempFile)
243
244
245
246
247
        templateCache += location -> tempFile
        tempFile
    }
    engine.layout(TemplateSource.fromFile(templateFile), args)
  }
Peter van 't Hof's avatar
Peter van 't Hof committed
248
}