ReportBuilder.scala 7.23 KB
Newer Older
1
2
package nl.lumc.sasc.biopet.core.report

3
import java.io._
4

5
import nl.lumc.sasc.biopet.core.{ ToolCommandFuntion, ToolCommand }
6
import nl.lumc.sasc.biopet.core.summary.Summary
7
import org.broadinstitute.gatk.utils.commandline.Input
8
import org.fusesource.scalate.{ TemplateSource, TemplateEngine }
9
import nl.lumc.sasc.biopet.utils.IoUtils
Peter van 't Hof's avatar
Peter van 't Hof committed
10
import scala.collection.mutable
11
12
13
14

/**
 * Created by pjvan_thof on 3/27/15.
 */
15
trait ReportBuilderExtension extends ToolCommandFuntion {
16

17
  /** Report builder object */
18
19
20
21
22
  val builder: ReportBuilder

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

23
  /** OutputDir for the report  */
24
25
  var outputDir: File = _

26
  /** Arguments that are passed on the commandline */
27
28
  var args: Map[String, String] = Map()

29
30
  override val defaultCoreMemory = 3.0

31
32
33
34
35
36
  override def beforeGraph: Unit = {
    super.beforeGraph
    jobOutputFile = new File(outputDir, ".report.log.out")
    javaMainClass = builder.getClass.getName.takeWhile(_ != '$')
  }

37
  /** Command to generate the report */
38
39
40
41
  override def commandLine: String = {
    super.commandLine +
      required("--summary", summaryFile) +
      required("--outputDir", outputDir) +
Peter van 't Hof's avatar
Peter van 't Hof committed
42
      args.map(x => required("-a", x._1 + "=" + x._2)).mkString
43
44
45
  }
}

46
47
trait ReportBuilder extends ToolCommand {

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

  class OptParser extends AbstractOptParser {
Peter van 't Hof's avatar
Peter van 't Hof committed
51
    opt[File]('s', "summary") unbounded () required () maxOccurs 1 valueName "<file>" action { (x, c) =>
52
53
      c.copy(summary = x)
    }
Peter van 't Hof's avatar
Peter van 't Hof committed
54
    opt[File]('o', "outputDir") unbounded () required () maxOccurs 1 valueName "<file>" action { (x, c) =>
55
56
      c.copy(outputDir = x)
    }
Peter van 't Hof's avatar
Peter van 't Hof committed
57
    opt[Map[String, String]]('a', "args") unbounded () action { (x, c) =>
58
59
      c.copy(pageArgs = c.pageArgs ++ x)
    }
60
61
  }

62
  /** summary object internaly */
63
64
  private var setSummary: Summary = _

65
  /** Retrival of summary, read only */
66
67
  final def summary = setSummary

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

Peter van 't Hof's avatar
Peter van 't Hof committed
71
72
73
  private var done = 0
  private var total = 0

Peter van 't Hof's avatar
Peter van 't Hof committed
74
75
76
77
78
  private var _sampleId: Option[String] = None
  protected def sampleId = _sampleId
  private var _libId: Option[String] = None
  protected def libId = _libId

79
  /** Main function to for building the report */
80
81
82
83
84
85
86
87
88
  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
89
    cmdArgs.pageArgs.get("sampleId") match {
Peter van 't Hof's avatar
Peter van 't Hof committed
90
91
92
93
      case Some(s: String) => {
        cmdArgs.pageArgs += "sampleId" -> Some(s)
        _sampleId = Some(s)
      }
Peter van 't Hof's avatar
Peter van 't Hof committed
94
      case _ =>
Peter van 't Hof's avatar
Peter van 't Hof committed
95
96
97
    }

    cmdArgs.pageArgs.get("libId") match {
Peter van 't Hof's avatar
Peter van 't Hof committed
98
99
100
101
      case Some(l: String) => {
        cmdArgs.pageArgs += "libId" -> Some(l)
        _libId = Some(l)
      }
Peter van 't Hof's avatar
Peter van 't Hof committed
102
      case _ =>
Peter van 't Hof's avatar
Peter van 't Hof committed
103
104
    }

105
106
    logger.info("Copy Base files")

Peter van 't Hof's avatar
Peter van 't Hof committed
107
    // Static files that will be copied to the output folder, then file is added to [resourceDir] it's need to be added here also
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
    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) {
124
      IoUtils.copyStreamToFile(getClass.getResourceAsStream(resourceDir + resource), new File(extOutputDir, resource), true)
125
    }
126

Peter van 't Hof's avatar
Peter van 't Hof committed
127
    logger.info("Parsing summary")
128
129
    setSummary = new Summary(cmdArgs.summary)

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

Peter van 't Hof's avatar
Peter van 't Hof committed
133
    logger.info("Generate pages")
Peter van 't Hof's avatar
Peter van 't Hof committed
134
    val jobs = generatePage(summary, indexPage, cmdArgs.outputDir,
Peter van 't Hof's avatar
Peter van 't Hof committed
135
      args = pageArgs ++ cmdArgs.pageArgs.toMap ++
136
        Map("summary" -> summary, "reportName" -> reportName, "indexPage" -> indexPage))
137

Peter van 't Hof's avatar
Peter van 't Hof committed
138
    logger.info(jobs + " Done")
139
140
  }

141
  /** This must be implemented, this will be the root page of the report */
142
143
  def indexPage: ReportPage

144
  /** This must be implemented, this will because the title of the report */
145
146
  def reportName: String

147
148
149
150
151
152
153
154
155
  /**
   * 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
   */
156
157
158
159
  def generatePage(summary: Summary,
                   page: ReportPage,
                   outputDir: File,
                   path: List[String] = Nil,
Peter van 't Hof's avatar
Peter van 't Hof committed
160
                   args: Map[String, Any] = Map()): Int = {
161

Peter van 't Hof's avatar
Peter van 't Hof committed
162
163
    val pageOutputDir = new File(outputDir, path.mkString(File.separator))
    pageOutputDir.mkdirs()
164
165
166
167
168
169
170
    val rootPath = "./" + Array.fill(path.size)("../").mkString("")
    val pageArgs = args ++ page.args ++
      Map("page" -> page,
        "path" -> path,
        "outputDir" -> pageOutputDir,
        "rootPath" -> rootPath
      )
171

172
173
174
175
176
    // 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
177
178
179
180
    val output = ReportBuilder.renderTemplate("/nl/lumc/sasc/biopet/core/report/main.ssp",
      pageArgs ++ Map("args" -> pageArgs))

    val file = new File(pageOutputDir, "index.html")
181
182
183
184
    val writer = new PrintWriter(file)
    writer.println(output)
    writer.close()

Peter van 't Hof's avatar
Peter van 't Hof committed
185
186
    done += 1
    if (done % 100 == 0) logger.info(done + " Done, " + (done.toDouble / total * 100) + "%")
Peter van 't Hof's avatar
Peter van 't Hof committed
187
    jobs.fold(0)(_ + _) + 1
188
189
  }
}
Peter van 't Hof's avatar
Peter van 't Hof committed
190
191
192

object ReportBuilder {

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

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

199
200
201
202
203
  /** 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
204
205
206
207
208
209
210
  /**
   * 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 = {
211
212
213
214
    val templateFile: File = templateCache.get(location) match {
      case Some(template) => template
      case _ => {
        val tempFile = File.createTempFile("ssp-template", new File(location).getName)
215
        IoUtils.copyStreamToFile(getClass.getResourceAsStream(location), tempFile)
216
217
218
219
220
221
        templateCache += location -> tempFile
        tempFile
      }
    }
    engine.layout(TemplateSource.fromFile(templateFile), args)
  }
Peter van 't Hof's avatar
Peter van 't Hof committed
222
}