WriteSummary.scala 5.52 KB
Newer Older
1
2
package nl.lumc.sasc.biopet.core.summary

3
import java.io.{ FileInputStream, PrintWriter, File }
4
import java.security.MessageDigest
5

6
import nl.lumc.sasc.biopet.core.{ BiopetJavaCommandLineFunction, BiopetCommandLineFunction, BiopetCommandLineFunctionTrait, SampleLibraryTag }
7
import nl.lumc.sasc.biopet.core.config.Configurable
8
import nl.lumc.sasc.biopet.utils.ConfigUtils
9
10
11
import org.broadinstitute.gatk.queue.function.{ QFunction, InProcessFunction }
import org.broadinstitute.gatk.utils.commandline.{ Output, Input }

12
13
14
import scala.collection.mutable
import scala.io.Source

15
16
17
18
19
20
21
22
/**
 * 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
23
  /** To access qscript for this summary */
24
  val qscript = root.asInstanceOf[SummaryQScript]
25
26
27
28
29

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

  @Output(doc = "Summary output", required = true)
30
  var out: File = qscript.summaryFile
31
32
33
34
35

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

  override def freezeFieldValues(): Unit = {
36
37
    for (q <- qscript.summaryQScripts) deps :+= q.summaryFile
    for ((_, l) <- qscript.summarizables; s <- l) s match {
38
39
40
      case f: QFunction => deps :+= f.firstOutput
      case _            =>
    }
Peter van 't Hof's avatar
Peter van 't Hof committed
41
42
43

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

44
45
46
    super.freezeFieldValues()
  }

Peter van 't Hof's avatar
Peter van 't Hof committed
47
  /** Function to create summary */
48
  def run(): Unit = {
49
    for (((name, sampleId, libraryId), summarizables) <- qscript.summarizables; summarizable <- summarizables) {
50
      summarizable.addToQscriptSummary(qscript, name)
51
52
    }

53
54
55
    val pipelineMap = {
      val files = parseFiles(qscript.summaryFiles)
      val settings = qscript.summarySettings
56
57
58
      val executables: Map[String, Any] = {
        (for (f <- qscript.functions if f.isInstanceOf[BiopetCommandLineFunctionTrait]) yield {
          f match {
59
            case f: BiopetJavaCommandLineFunction => {
60
              f.configName -> Map("version" -> f.getVersion.getOrElse(None),
61
62
63
64
                "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
65
              f.configName -> Map("version" -> f.getVersion.getOrElse(None),
66
67
68
69
70
71
                "md5" -> BiopetCommandLineFunctionTrait.executableMd5Cache.getOrElse(f.executable, None))
            }
            case _ => throw new IllegalStateException("This should not be possible")
          }

        }).toMap
72
73
74
75
76
77
78
79
80
81
82
83
84
      }

      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 (
85
      ((name, sampleId, libraryId), summarizables) <- qscript.summarizables;
86
87
      summarizable <- summarizables
    ) yield {
88
      val map = Map(qscript.summaryName -> parseSummarizable(summarizable, name))
89

90
91
92
      (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))
93

94
    val combinedMap = (for (qscript <- qscript.summaryQScripts) yield {
95
      ConfigUtils.fileToConfigMap(qscript.summaryFile)
96
    }).foldRight(jobsMap)((a, b) => ConfigUtils.mergeMaps(a, b))
97

98
    val writer = new PrintWriter(out)
Peter van 't Hof's avatar
Peter van 't Hof committed
99
    writer.println(ConfigUtils.mapToJson(combinedMap).spaces4)
100
101
    writer.close()
  }
102

103
104
105
106
107
108
109
110
111
112
  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
113
114
115
116
117
118
  /**
   * Convert summarizable to a summary map
   * @param summarizable
   * @param name
   * @return
   */
119
  def parseSummarizable(summarizable: Summarizable, name: String) = {
Peter van 't Hof's avatar
Peter van 't Hof committed
120
    val stats = summarizable.summaryStats
121
122
    val files = parseFiles(summarizable.summaryFiles)

Peter van 't Hof's avatar
Peter van 't Hof committed
123
    (if (stats.isEmpty) Map[String, Any]() else Map("stats" -> Map(name -> stats))) ++
124
      (if (files.isEmpty) Map[String, Any]() else Map("files" -> Map(name -> files)))
125
126
  }

Peter van 't Hof's avatar
Peter van 't Hof committed
127
128
129
130
131
  /**
   * Parse files map to summary map
   * @param files
   * @return
   */
132
  def parseFiles(files: Map[String, File]): Map[String, Map[String, Any]] = {
133
134
135
    for ((key, file) <- files) yield key -> parseFile(file)
  }

Peter van 't Hof's avatar
Peter van 't Hof committed
136
137
138
139
140
  /**
   * parse single file summary map
   * @param file
   * @return
   */
141
142
143
144
145
  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
146
147
  }

Peter van 't Hof's avatar
Peter van 't Hof committed
148
149
150
151
152
  /**
   * Retrive checksum from file
   * @param checksumFile
   * @return
   */
Peter van 't Hof's avatar
Peter van 't Hof committed
153
  def parseChecksum(checksumFile: File): String = {
154
155
    Source.fromFile(checksumFile).getLines().toList.head.split(" ")(0)
  }
156
}