ReportBuilder.scala 8.16 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
37
  val builder: ReportBuilder

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
96
97
98
99
  private var _sampleId: Option[String] = None
  protected def sampleId = _sampleId
  private var _libId: Option[String] = None
  protected def libId = _libId

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

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

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

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

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

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

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

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

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

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

Peter van 't Hof's avatar
Peter van 't Hof committed
159
    logger.info(jobs + " Done")
160
161
  }

162
  /** This must be implemented, this will be the root page of the report */
163
164
  def indexPage: ReportPage

165
  /** This must be implemented, this will because the title of the report */
166
167
  def reportName: String

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

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

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

    val file = new File(pageOutputDir, "index.html")
202
203
204
205
    val writer = new PrintWriter(file)
    writer.println(output)
    writer.close()

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

object ReportBuilder {

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

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

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

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