RepoTagsNormalizer.scala 7.29 KB
Newer Older
1
/*
2
3
4
5
6
7
8
9
10
11
12
13
14
 * Copyright 2017-2018 Jungho Shin, Fawzi Mohamed
 * 
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 * 
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
15
 */
16

Jungho Shin's avatar
Jungho Shin committed
17
18
19
20
21
22
23
package eu.nomad_lab.normalizers

import eu.{ nomad_lab => lab }
import eu.nomad_lab.DefaultPythonInterpreter
import org.{ json4s => jn }
import scala.collection.breakOut
import eu.nomad_lab.normalize.ExternalNormalizerGenerator
24
import eu.nomad_lab.normalize.Normalizer
Jungho Shin's avatar
Jungho Shin committed
25
import eu.nomad_lab.meta
26
import eu.nomad_lab.ref.ObjectKind
Jungho Shin's avatar
Jungho Shin committed
27
28
29
30
import eu.nomad_lab.query
import eu.nomad_lab.resolve._
import eu.nomad_lab.h5.EmitJsonVisitor
import eu.nomad_lab.h5.H5EagerScanner
31
import eu.nomad_lab.h5.SectionH5
Jungho Shin's avatar
Jungho Shin committed
32
33
import eu.nomad_lab.parsers.ExternalParserWrapper
import eu.nomad_lab.JsonUtils
34
import eu.nomad_lab.H5Lib
Jungho Shin's avatar
Jungho Shin committed
35
import scala.collection.mutable.StringBuilder
36
import util.control.NonFatal
Jungho Shin's avatar
Jungho Shin committed
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55

object RepoTagsNormalizer extends ExternalNormalizerGenerator(
  name = "RepoTagsNormalizer",
  info = jn.JObject(
    ("name" -> jn.JString("RepoTagsNormalizer")) ::
      ("parserId" -> jn.JString("RepoTagsNormalizer" + lab.RepoTagsVersionInfo.version)) ::
      ("versionInfo" -> jn.JObject(
        ("nomadCoreVersion" -> jn.JObject(lab.NomadCoreVersionInfo.toMap.map {
          case (k, v) => k -> jn.JString(v.toString)
        }(breakOut): List[(String, jn.JString)])) ::
          (lab.RepoTagsVersionInfo.toMap.map {
            case (key, value) =>
              (key -> jn.JString(value.toString))
          }(breakOut): List[(String, jn.JString)])
      )) :: Nil
  ),
  context = "calculation_context",
  filter = query.CompiledQuery(query.QueryExpression("program_name and atom_positions"), meta.KnownMetaInfoEnvs.all),
  cmd = Seq(DefaultPythonInterpreter.pythonExe(), "${envDir}/normalizers/repo-tags/normalizer/normalizer-repo-tags/calculate_repo_tags.py",
56
    "${contextUri}", "${archivePath}"),
Jungho Shin's avatar
Jungho Shin committed
57
58
  resList = Seq(
    "normalizer-repo-tags/calculate_repo_tags.py",
Jungho Shin's avatar
Jungho Shin committed
59
    "normalizer-repo-tags/extract_from_repo.py",
Jungho Shin's avatar
Jungho Shin committed
60
    "normalizer-repo-tags/setup_paths.py",
Jungho Shin's avatar
Jungho Shin committed
61
    "normalizer-repo-tags/setting.json",
Jungho Shin's avatar
Jungho Shin committed
62
63
64
65
66
67
68
69
70
71
72
73
74
75
    "nomad_meta_info/public.nomadmetainfo.json",
    "nomad_meta_info/common.nomadmetainfo.json",
    "nomad_meta_info/meta_types.nomadmetainfo.json",
    "nomad_meta_info/stats.nomadmetainfo.json"
  ) ++ DefaultPythonInterpreter.commonFiles(),
  dirMap = Map(
    "normalizer-repo-tags" -> "normalizers/repo-tags/normalizer/normalizer-repo-tags",
    "nomad_meta_info" -> "nomad-meta-info/meta_info/nomad_meta_info",
    "python" -> "python-common/common/python/nomadcore"
  ) ++ DefaultPythonInterpreter.commonDirMapping(),
  metaInfoEnv = lab.meta.KnownMetaInfoEnvs.all
) {

  override def stdInHandler(context: ResolvedRef)(wrapper: ExternalParserWrapper)(pIn: java.io.OutputStream): Unit = {
76
77
    val trace = Normalizer.trace
    val out: java.io.Writer =
Jungho Shin's avatar
Jungho Shin committed
78
      new java.io.BufferedWriter(new java.io.OutputStreamWriter(pIn));
79
80
    val stringBuilder = if (trace)
      new StringBuilder
Jungho Shin's avatar
Jungho Shin committed
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
    else
      null
    def writeOut(s: String): Unit = {
      out.write(s)
      if (trace) stringBuilder ++= s
    }
    def flush(): Unit = {
      out.flush()
      if (trace) {
        logger.info(stringBuilder.result())
        stringBuilder.clear()
      }
    }
    writeOut("[")
    var isFirst = true
    try {
      context match {
        case Calculation(archiveSet, c) =>
          val programNames: Set[String] = (for (v <- c.valueTable(Seq("section_run", "program_name"))) yield (v.stringValue))(breakOut)
          val programVersions: Set[String] = (for (v <- c.valueTable(Seq("section_run", "program_version"))) yield (v.stringValue))(breakOut)
101
          val xcFunctionals: Set[String] = (for (v <- c.valueTable(Seq("section_run", "section_method", "section_XC_functionals", "XC_functional_name"))) yield (v.stringValue))(breakOut)
Jungho Shin's avatar
Jungho Shin committed
102
          val electronicStructureMethods: Set[String] = (for (v <- c.valueTable(Seq("section_run", "section_method", "electronic_structure_method"))) yield (v.stringValue))(breakOut)
103
          val singleConfSections = c.sectionTable(Seq("section_run", "section_single_configuration_calculation"))
Jungho Shin's avatar
Jungho Shin committed
104
          val nEnergyEvaluations = singleConfSections.lengthL
105
          var lastGeometry: Option[SectionH5] = None
Jungho Shin's avatar
Jungho Shin committed
106
          var lastEnergy: Option[Double] = None
107
108
109
110
111
112
113
114
115
116
117
118
119
          val cGroup = c.calculationGroup
          val mainFileUris: Seq[String] = try {
            val mainFileAttr: Long = H5Lib.attributeOpen(
              cGroup,
              attributeName = "mainFileUri", attributeType = "C"
            )
            val mainFiles: Array[String] = H5Lib.attributeReadStr(mainFileAttr)
            H5Lib.attributeClose(mainFileAttr)
            mainFiles.toSeq
          } catch {
            case NonFatal(e) =>
              Seq()
          }
Jungho Shin's avatar
Jungho Shin committed
120
          if (nEnergyEvaluations > 0) {
121
122
            val lastEnergyEval: SectionH5 = singleConfSections(nEnergyEvaluations - 1)
            lastGeometry = lastEnergyEval.maybeValue("single_configuration_calculation_to_system_ref").map(_.longValue) match {
Jungho Shin's avatar
Jungho Shin committed
123
              case Some(idx) =>
124
                val sysSections = c.sectionTable(Seq("section_run", "section_system"))
Jungho Shin's avatar
Jungho Shin committed
125
126
127
128
129
130
                Some(sysSections(idx))
              case None =>
                None
            }
            lastEnergy = lastEnergyEval.maybeValue("energy_total").map(_.doubleValue)
          }
131
          val repoInfo = c.sectionTable(Seq("section_repository_info"))
Jungho Shin's avatar
Jungho Shin committed
132
          writeOut(s"""{
133
134
135
136
  "program_name": ${JsonUtils.normalizedStr(jn.JArray(programNames.map(jn.JString(_))(breakOut)))},
  "program_version": ${JsonUtils.normalizedStr(jn.JArray(programVersions.map(jn.JString(_))(breakOut)))},
  "XC_functional_name": ${JsonUtils.normalizedStr(jn.JArray(xcFunctionals.map(jn.JString(_))(breakOut)))},
  "electronic_structure_method": ${JsonUtils.normalizedStr(jn.JArray(electronicStructureMethods.map(jn.JString(_))(breakOut)))},
Jungho Shin's avatar
Jungho Shin committed
137
  "section_single_confguration_calculation.length": ${nEnergyEvaluations},
138
  "energy_total.last": ${lastEnergy.getOrElse("null")},
139
  "main_file_uri": ${JsonUtils.normalizedStr(jn.JArray(mainFileUris.map(jn.JString(_))(breakOut)))},
Jungho Shin's avatar
Jungho Shin committed
140
141
142
143
  "section_system.last": """)
          lastGeometry match {
            case None => "null"
            case Some(geo) =>
144
145
146
              val visitor = new EmitJsonVisitor(
                writeOut = writeOut
              )
Jungho Shin's avatar
Jungho Shin committed
147
148
149
              val scanner = new H5EagerScanner
              scanner.scanResolvedRef(Section(archiveSet, geo), visitor)
          }
150
151
152
153
154
155
156
          writeOut(""",
  "section_repository_info.uri": """)
          if (repoInfo.isEmpty)
            writeOut("null")
          else
            writeOut(JsonUtils.escapeString(repoInfo(0).toRef.toUriStr(ObjectKind.NormalizedData)))
          writeOut("}]\n")
Jungho Shin's avatar
Jungho Shin committed
157
          flush()
158
        case r =>
Jungho Shin's avatar
Jungho Shin committed
159
160
161
162
163
164
          throw new Exception(s"RepoTagsNormalizer expected a calculation as context, but got $r")
      }
    } finally {
      out.close()
      pIn.close()
      wrapper.sendStatus = ExternalParserWrapper.SendStatus.Finished
165
    }
Jungho Shin's avatar
Jungho Shin committed
166
167
  }
}