WriteSummary.scala 6.39 KB
Newer Older
bow's avatar
bow 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.summary

bow's avatar
bow committed
18
19
20
21
22
23
import java.io.{ File, PrintWriter }
import scala.collection.mutable
import scala.io.Source

import org.broadinstitute.gatk.queue.function.{ QFunction, InProcessFunction }
import org.broadinstitute.gatk.utils.commandline.{ Output, Input }
24

bow's avatar
bow committed
25
import nl.lumc.sasc.biopet.{ LastCommitHash, Version }
26
import nl.lumc.sasc.biopet.core.{ BiopetJavaCommandLineFunction, BiopetCommandLineFunction, BiopetCommandLineFunctionTrait, SampleLibraryTag }
27
import nl.lumc.sasc.biopet.core.config.Configurable
28
import nl.lumc.sasc.biopet.utils.ConfigUtils
29
30
31
32
33
34
35
36
37

/**
 * Created by pjvan_thof on 2/14/15.
 */
class WriteSummary(val root: Configurable) extends InProcessFunction with Configurable {
  this.analysisName = getClass.getSimpleName

  require(root.isInstanceOf[SummaryQScript], "root is not a SummaryQScript")

Peter van 't Hof's avatar
Peter van 't Hof committed
38
  /** To access qscript for this summary */
39
  val qscript = root.asInstanceOf[SummaryQScript]
40
41
42
43
44

  @Input(doc = "deps", required = false)
  var deps: List[File] = Nil

  @Output(doc = "Summary output", required = true)
45
  var out: File = qscript.summaryFile
46
47
48
49
50

  var md5sum: Boolean = config("summary_md5", default = true)
  //TODO: add more checksums types

  override def freezeFieldValues(): Unit = {
51
52
    for (q <- qscript.summaryQScripts) deps :+= q.summaryFile
    for ((_, l) <- qscript.summarizables; s <- l) s match {
53
54
55
      case f: QFunction => deps :+= f.firstOutput
      case _            =>
    }
Peter van 't Hof's avatar
Peter van 't Hof committed
56
57
58

    jobOutputFile = new File(out.getParentFile, ".%s.%s.out".format(out.getName, analysisName))

59
60
61
    super.freezeFieldValues()
  }

Peter van 't Hof's avatar
Peter van 't Hof committed
62
  /** Function to create summary */
63
  def run(): Unit = {
64
    for (((name, sampleId, libraryId), summarizables) <- qscript.summarizables; summarizable <- summarizables) {
65
      summarizable.addToQscriptSummary(qscript, name)
66
67
    }

68
69
70
    val pipelineMap = {
      val files = parseFiles(qscript.summaryFiles)
      val settings = qscript.summarySettings
71
72
73
      val executables: Map[String, Any] = {
        (for (f <- qscript.functions if f.isInstanceOf[BiopetCommandLineFunctionTrait]) yield {
          f match {
74
            case f: BiopetJavaCommandLineFunction => {
75
              f.configName -> Map("version" -> f.getVersion.getOrElse(None),
76
77
78
79
                "java_md5" -> BiopetCommandLineFunctionTrait.executableMd5Cache.getOrElse(f.executable, None),
                "jar_md5" -> SummaryQScript.md5sumCache.getOrElse(f.jarFile, None))
            }
            case f: BiopetCommandLineFunction => {
Peter van 't Hof's avatar
Peter van 't Hof committed
80
              f.configName -> Map("version" -> f.getVersion.getOrElse(None),
81
82
83
84
85
86
                "md5" -> BiopetCommandLineFunctionTrait.executableMd5Cache.getOrElse(f.executable, None))
            }
            case _ => throw new IllegalStateException("This should not be possible")
          }

        }).toMap
87
88
89
90
91
92
93
94
95
96
97
98
99
      }

      val map = Map(qscript.summaryName -> ((if (settings.isEmpty) Map[String, Any]() else Map("settings" -> settings)) ++
        (if (files.isEmpty) Map[String, Any]() else Map("files" -> Map("pipeline" -> files))) ++
        (if (executables.isEmpty) Map[String, Any]() else Map("executables" -> executables.toMap))))

      qscript match {
        case tag: SampleLibraryTag => prefixSampleLibrary(map, tag.sampleId, tag.libId)
        case _                     => map
      }
    }

    val jobsMap = (for (
100
      ((name, sampleId, libraryId), summarizables) <- qscript.summarizables;
101
102
      summarizable <- summarizables
    ) yield {
103
      val map = Map(qscript.summaryName -> parseSummarizable(summarizable, name))
104

105
106
107
      (prefixSampleLibrary(map, sampleId, libraryId),
        (v1: Any, v2: Any, key: String) => summarizable.resolveSummaryConflict(v1, v2, key))
    }).foldRight(pipelineMap)((a, b) => ConfigUtils.mergeMaps(a._1, b, a._2))
108

bow's avatar
bow committed
109
110
    val combinedMap = Map("meta" -> Map(
      "last_commit_hash" -> LastCommitHash,
111
      "pipeline_version" -> Version,
112
113
      "pipeline_name" -> qscript.summaryName,
      "output_dir" -> qscript.outputDir
bow's avatar
bow committed
114
115
116
117
    )) ++
      (for (qscript <- qscript.summaryQScripts) yield {
        ConfigUtils.fileToConfigMap(qscript.summaryFile)
      }).foldRight(jobsMap)((a, b) => ConfigUtils.mergeMaps(a, b))
118

119
    val writer = new PrintWriter(out)
120
    writer.println(ConfigUtils.mapToJson(combinedMap).nospaces)
121
122
    writer.close()
  }
123

124
125
126
127
128
129
130
131
132
133
  def prefixSampleLibrary(map: Map[String, Any], sampleId: Option[String], libraryId: Option[String]): Map[String, Any] = {
    sampleId match {
      case Some(sampleId) => Map("samples" -> Map(sampleId -> (libraryId match {
        case Some(libraryId) => Map("libraries" -> Map(libraryId -> map))
        case _               => map
      })))
      case _ => map
    }
  }

Peter van 't Hof's avatar
Peter van 't Hof committed
134
135
136
137
138
139
  /**
   * Convert summarizable to a summary map
   * @param summarizable
   * @param name
   * @return
   */
140
  def parseSummarizable(summarizable: Summarizable, name: String) = {
Peter van 't Hof's avatar
Peter van 't Hof committed
141
    val stats = summarizable.summaryStats
142
143
    val files = parseFiles(summarizable.summaryFiles)

Peter van 't Hof's avatar
Peter van 't Hof committed
144
    (Map("stats" -> Map(name -> stats))) ++
145
      (if (files.isEmpty) Map[String, Any]() else Map("files" -> Map(name -> files)))
146
147
  }

Peter van 't Hof's avatar
Peter van 't Hof committed
148
149
150
151
152
  /**
   * Parse files map to summary map
   * @param files
   * @return
   */
153
  def parseFiles(files: Map[String, File]): Map[String, Map[String, Any]] = {
154
155
156
    for ((key, file) <- files) yield key -> parseFile(file)
  }

Peter van 't Hof's avatar
Peter van 't Hof committed
157
158
159
160
161
  /**
   * parse single file summary map
   * @param file
   * @return
   */
162
163
164
165
166
  def parseFile(file: File): Map[String, Any] = {
    val map: mutable.Map[String, Any] = mutable.Map()
    map += "path" -> file.getAbsolutePath
    if (md5sum) map += "md5" -> parseChecksum(SummaryQScript.md5sumCache(file))
    map.toMap
167
168
  }

Peter van 't Hof's avatar
Peter van 't Hof committed
169
170
171
172
173
  /**
   * Retrive checksum from file
   * @param checksumFile
   * @return
   */
Peter van 't Hof's avatar
Peter van 't Hof committed
174
  def parseChecksum(checksumFile: File): String = {
175
176
    Source.fromFile(checksumFile).getLines().toList.head.split(" ")(0)
  }
177
}