ReportBuilder.scala 8.11 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.ToolCommandFuntion
import nl.lumc.sasc.biopet.utils.summary.Summary
Peter van 't Hof's avatar
Peter van 't Hof committed
21
import nl.lumc.sasc.biopet.utils.{ ToolCommand, Logging, IoUtils }
Peter van 't Hof's avatar
Peter van 't Hof committed
22
23
import org.broadinstitute.gatk.utils.commandline.Input
import org.fusesource.scalate.{ TemplateEngine, TemplateSource }
Peter van 't Hof's avatar
Peter van 't Hof committed
24
import scala.collection.mutable
25
26

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

33
  /** Report builder object */
34
35
  val builder: ReportBuilder

Peter van 't Hof's avatar
Peter van 't Hof committed
36
37
  def toolObject = builder

38
39
40
  @Input(required = true)
  var summaryFile: File = _

41
  /** OutputDir for the report  */
42
43
  var outputDir: File = _

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

47
48
  override def defaultCoreMemory = 4.0
  override def defaultThreads = 3
49

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

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

65
66
trait ReportBuilder extends ToolCommand {

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

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

81
  /** summary object internaly */
82
83
  private var setSummary: Summary = _

84
  /** Retrival of summary, read only */
85
86
  final def summary = setSummary

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

Peter van 't Hof's avatar
Peter van 't Hof committed
90
91
92
  private var done = 0
  private var total = 0

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

98
  /** Main function to for building the report */
99
100
101
102
103
104
105
106
107
  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
108
    cmdArgs.pageArgs.get("sampleId") match {
109
      case Some(s: String) =>
Peter van 't Hof's avatar
Peter van 't Hof committed
110
111
        cmdArgs.pageArgs += "sampleId" -> Some(s)
        _sampleId = Some(s)
Peter van 't Hof's avatar
Peter van 't Hof committed
112
      case _ =>
Peter van 't Hof's avatar
Peter van 't Hof committed
113
114
115
    }

    cmdArgs.pageArgs.get("libId") match {
116
      case Some(l: String) =>
Peter van 't Hof's avatar
Peter van 't Hof committed
117
118
        cmdArgs.pageArgs += "libId" -> Some(l)
        _libId = Some(l)
Peter van 't Hof's avatar
Peter van 't Hof committed
119
      case _ =>
Peter van 't Hof's avatar
Peter van 't Hof committed
120
121
    }

122
123
    logger.info("Copy Base files")

Peter van 't Hof's avatar
Peter van 't Hof committed
124
    // Static files that will be copied to the output folder, then file is added to [resourceDir] it's need to be added here also
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
    val extOutputDir: File = new File(cmdArgs.outputDir, "ext")
    val resourceDir: String = "/nl/lumc/sasc/biopet/core/report/ext/"
    val 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",
      "fonts/glyphicons-halflings-regular.woff",
      "fonts/glyphicons-halflings-regular.ttf",
      "fonts/glyphicons-halflings-regular.woff2"
    )

    for (resource <- extFiles.par) {
141
      IoUtils.copyStreamToFile(getClass.getResourceAsStream(resourceDir + resource), new File(extOutputDir, resource), createDirs = true)
142
    }
143

Peter van 't Hof's avatar
Peter van 't Hof committed
144
    logger.info("Parsing summary")
145
146
    setSummary = new Summary(cmdArgs.summary)

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

Peter van 't Hof's avatar
Peter van 't Hof committed
150
    logger.info("Generate pages")
Peter van 't Hof's avatar
Peter van 't Hof committed
151
    val jobs = generatePage(summary, indexPage, cmdArgs.outputDir,
Peter van 't Hof's avatar
Peter van 't Hof committed
152
      args = pageArgs ++ cmdArgs.pageArgs.toMap ++
153
        Map("summary" -> summary, "reportName" -> reportName, "indexPage" -> indexPage))
154

Peter van 't Hof's avatar
Peter van 't Hof committed
155
    logger.info(jobs + " Done")
156
157
  }

158
  /** This must be implemented, this will be the root page of the report */
159
160
  def indexPage: ReportPage

161
  /** This must be implemented, this will because the title of the report */
162
163
  def reportName: String

164
165
166
167
168
169
170
171
172
  /**
   * 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
   */
173
174
175
176
  def generatePage(summary: Summary,
                   page: ReportPage,
                   outputDir: File,
                   path: List[String] = Nil,
Peter van 't Hof's avatar
Peter van 't Hof committed
177
                   args: Map[String, Any] = Map()): Int = {
178

Peter van 't Hof's avatar
Peter van 't Hof committed
179
180
    val pageOutputDir = new File(outputDir, path.mkString(File.separator))
    pageOutputDir.mkdirs()
181
182
183
184
185
186
187
    val rootPath = "./" + Array.fill(path.size)("../").mkString("")
    val pageArgs = args ++ page.args ++
      Map("page" -> page,
        "path" -> path,
        "outputDir" -> pageOutputDir,
        "rootPath" -> rootPath
      )
188

189
190
191
192
193
    // 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
194
195
196
197
    val output = ReportBuilder.renderTemplate("/nl/lumc/sasc/biopet/core/report/main.ssp",
      pageArgs ++ Map("args" -> pageArgs))

    val file = new File(pageOutputDir, "index.html")
198
199
200
201
    val writer = new PrintWriter(file)
    writer.println(output)
    writer.close()

Peter van 't Hof's avatar
Peter van 't Hof committed
202
203
    done += 1
    if (done % 100 == 0) logger.info(done + " Done, " + (done.toDouble / total * 100) + "%")
204
    jobs.sum + 1
205
206
  }
}
Peter van 't Hof's avatar
Peter van 't Hof committed
207
208
209

object ReportBuilder {

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

213
  /** Cache of temp file for templates from the classpath / jar */
214
215
  private var templateCache: Map[String, File] = Map()

216
217
218
219
220
  /** 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
221
222
223
224
225
226
227
  /**
   * 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
228
229
    Logging.logger.info("Rendering: " + location)

230
231
    val templateFile: File = templateCache.get(location) match {
      case Some(template) => template
232
      case _ =>
233
        val tempFile = File.createTempFile("ssp-template", new File(location).getName)
234
        tempFile.deleteOnExit()
235
        IoUtils.copyStreamToFile(getClass.getResourceAsStream(location), tempFile)
236
237
238
239
240
        templateCache += location -> tempFile
        tempFile
    }
    engine.layout(TemplateSource.fromFile(templateFile), args)
  }
Peter van 't Hof's avatar
Peter van 't Hof committed
241
}