encyclopedia.py 13.5 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# Copyright 2018 Markus Scheidgen
#
# 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.

from typing import Any

17
from nomad.normalizing.normalizer import Normalizer
18
from nomad.metainfo.encyclopedia import (
19
    section_encyclopedia,
20
21
22
23
24
    Material,
    Method,
    Properties,
    Calculation,
)
25
from nomad.parsing.legacy import Backend
26
27
28
29
from nomad.normalizing.encyclopedia.context import Context
from nomad.normalizing.encyclopedia.material import MaterialBulkNormalizer, Material2DNormalizer, Material1DNormalizer
from nomad.normalizing.encyclopedia.method import MethodDFTNormalizer, MethodGWNormalizer
from nomad.normalizing.encyclopedia.properties import PropertiesNormalizer
30
31
32
33
from nomad import config, files
from nomad.archive import query_archive
from nomad.datamodel import EntryArchive
# from nomad.datamodel.metainfo.public import section_run
34
35
36
37
38
39
40
41

J_to_Ry = 4.587425e+17


class EncyclopediaNormalizer(Normalizer):
    """
    This normalizer emulates the functionality of the old Encyclopedia backend.
    The data used by the encyclopedia have been assigned under new metainfo
42
    within a new section called "encyclopedia". In the future these separate
43
44
    metainfos could be absorbed into the existing metainfo hiearchy.
    """
45
    def __init__(self, backend: Backend):
46
        super().__init__(backend)
47
        self.backend: Backend = backend
48
49
50
51
52
53
54
55
56

    def calc_type(self, calc: Calculation) -> str:
        """Decides what type of calculation this is: single_point, md,
        geometry_optimization, etc.
        """
        calc_enums = Calculation.calculation_type.type
        calc_type = calc_enums.unavailable

        try:
57
            sccs = self.section_run.section_single_configuration_calculation
58
59
60
        except Exception:
            sccs = []
        try:
61
            frame_sequences = self.section_run.section_frame_sequence
62
63
64
65
66
67
68
69
        except Exception:
            frame_sequences = []

        n_scc = len(sccs)
        n_frame_seq = len(frame_sequences)

        # No sequences, only a few calculations
        if n_scc <= 3 and n_frame_seq == 0:
70
            program_name = self.section_run.program_name
71
72
73
74
75
76
77
78
79
80
81
82
            if program_name == "elastic":
                # TODO move to taylor expansion as soon as data is correct in archive
                calc_type = calc_enums.elastic_constants
            else:
                calc_type = calc_enums.single_point

        # One sequence. Currently calculations with multiple sequences are
        # unsupported.
        elif n_frame_seq == 1:
            frame_seq = frame_sequences[0]

            # See if sampling_method is present
83
84
            section_sampling_method = frame_seq.frame_sequence_to_sampling_ref
            if section_sampling_method is None:
85
86
87
88
89
90
91
                self.logger.info(
                    "Cannot determine encyclopedia run type because missing "
                    "value for frame_sequence_to_sampling_ref."
                )
                return calc_type

            # See if local frames are present
92
93
            frames = frame_seq.frame_sequence_local_frames_ref
            if not frames:
94
95
96
                self.logger.info("No frames referenced in section_frame_sequence_local_frames.")
                return calc_type

97
            sampling_method = section_sampling_method.sampling_method
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113

            if sampling_method == "molecular_dynamics":
                calc_type = calc_enums.molecular_dynamics
            if sampling_method == "geometry_optimization":
                calc_type = calc_enums.geometry_optimization
            if sampling_method == "taylor_expansion":
                calc_type = calc_enums.phonon_calculation

        calc.calculation_type = calc_type
        return calc_type

    def material_type(self, material: Material) -> tuple:
        # Try to fetch representative system
        system = None
        material_type = config.services.unavailable_value
        material_enums = Material.material_type.type
114
        try:
115
            system_idx = self.section_run.m_cache["representative_system_idx"]
116
117
118
        except (AttributeError, KeyError):
            pass
        else:
119
120
            # Try to find system type information from backend for the selected system.
            try:
121
122
                system = self.section_run.section_system[system_idx]
                stype = system.system_type
123
124
125
126
127
128
129
130
            except KeyError:
                pass
            else:
                if stype == material_enums.one_d or stype == material_enums.two_d:
                    material_type = stype
                # For bulk systems we also ensure that the symmetry information is available
                if stype == material_enums.bulk:
                    try:
131
                        system.section_symmetry[0]
132
133
134
135
136
137
138
139
                    except (KeyError, IndexError):
                        self.logger.info("Symmetry information is not available for a bulk system. No Encylopedia entry created.")
                    else:
                        material_type = stype

        material.material_type = material_type
        return system, material_type

140
    def method_type(self, method: Method, run_type: str) -> tuple:
141
142
        repr_method = None
        method_id = config.services.unavailable_value
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173

        # Special handling for phonon calculations. This simply assumes that
        # the method information can be retrieved from the first referenced
        # calculation. TODO: Once we have standardized approach to handling
        # references between entries, this implementation should change.
        calc_enums = Calculation.calculation_type.type
        if run_type == calc_enums.phonon_calculation:
            try:
                # The reference is given as an absolute path in the host
                # machine. We take the path that is relative to the upload
                # root.
                ref = self.section_run.section_single_configuration_calculation[0].section_calculation_to_calculation_refs[0].calculation_to_calculation_external_url
                ref = ref.split("/", 6)[6]

                # We get the referenced archive as an ArchiveReader object and get sec
                upload_id = self.backend.entry_archive.section_metadata.upload_id
                upload_files = files.StagingUploadFiles(upload_id, is_authorized=lambda: True)
                calc_id = upload_files.calc_id(ref)
                with upload_files.read_archive(calc_id) as archive:
                    arch = query_archive(archive, {calc_id: calc_id})[calc_id]
                    ref_archive = EntryArchive.m_from_dict(arch)
                    methods = ref_archive.section_run[0].section_method
            except Exception:
                self.logger.warn(
                    "Could not retrieve the method information from a "
                    "referenced archive within a phonon calculation."
                )
                methods = []
        else:
            methods = self.section_run.section_method

174
175
176
177
        n_methods = len(methods)

        if n_methods == 1:
            repr_method = methods[0]
178
179
180
            method_id = repr_method.electronic_structure_method
            if method_id is None:
                method_id = config.services.unavailable_value
181
        elif n_methods > 1:
182
            for sec_method in methods:
183
                # GW
184
                electronic_structure_method = sec_method.electronic_structure_method
185
186
187
188
189
190
191
192
193
                if electronic_structure_method in {"G0W0", "scGW"}:
                    repr_method = sec_method
                    method_id = "GW"
                    break

                # Methods linked to each other through references. Get all
                # linked methods, try to get electronic_structure_method from
                # each.
                try:
194
                    refs = sec_method.section_method_to_method_refs
195
196
197
198
199
                except KeyError:
                    pass
                else:
                    linked_methods = [sec_method]
                    for ref in refs:
200
201
                        method_to_method_kind = ref.method_to_method_kind
                        method_to_method_ref = ref.method_to_method_ref
202
                        if method_to_method_kind == "core_settings":
203
                            linked_methods.append(method_to_method_ref)
204
205

                    for i_method in linked_methods:
206
207
                        electronic_structure_method = i_method.electronic_structure_method
                        if electronic_structure_method is not None:
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
                            repr_method = sec_method
                            method_id = electronic_structure_method

        method.method_type = method_id
        return repr_method, method_id

    def fill(self, context: Context):
        # Fill structure related metainfo
        struct: Any = None
        if context.material_type == Material.material_type.type.bulk:
            struct = MaterialBulkNormalizer(self.backend, self.logger)
        elif context.material_type == Material.material_type.type.two_d:
            struct = Material2DNormalizer(self.backend, self.logger)
        elif context.material_type == Material.material_type.type.one_d:
            struct = Material1DNormalizer(self.backend, self.logger)
        if struct is not None:
            struct.normalize(context)

        # Fill method related metainfo
        method = None
        if context.method_type == Method.method_type.type.DFT or context.method_type == Method.method_type.type.DFTU:
            method = MethodDFTNormalizer(self._backend, self.logger)
        elif context.method_type == Method.method_type.type.GW:
            method = MethodGWNormalizer(self._backend, self.logger)
        if method is not None:
            method.normalize(context)

        # Fill properties related metainfo
        properties = PropertiesNormalizer(self.backend, self.logger)
        properties.normalize(context)

    def normalize(self, logger=None) -> None:
        """The caller will automatically log if the normalizer succeeds or ends
        up with an exception.
        """
243
244
245
246
247
248
249
250
251
        # Do nothing if section_run is not present
        if self.section_run is None:
            self.logger.info(
                "Required data is missing or is invalid.",
                enc_status="invalid_data",
                invalid_metainfo="section_run",
            )
            return

252
253
254
255
        try:
            super().normalize(logger)

            # Initialise metainfo structure
256
            # sec_enc = self._backend.openSection("section_encyclopedia", return_section=True)
257
            sec_enc = self.backend.entry_archive.m_create(section_encyclopedia)
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
            material = sec_enc.m_create(Material)
            method = sec_enc.m_create(Method)
            sec_enc.m_create(Properties)
            calc = sec_enc.m_create(Calculation)

            # Determine run type, stop if unknown
            calc_type = self.calc_type(calc)
            if calc_type == config.services.unavailable_value:
                self.logger.info(
                    "Unsupported run type for encyclopedia, encyclopedia metainfo not created.",
                    enc_status="unsupported_calc_type",
                )
                return

            # Get the system type, stop if unknown
            material_enums = Material.material_type.type
            representative_system, material_type = self.material_type(material)
            if material_type != material_enums.bulk and material_type != material_enums.two_d and material_type != material_enums.one_d:
                self.logger.info(
277
                    "Unsupported material type for encyclopedia, encyclopedia metainfo not created.",
278
279
280
281
                    enc_status="unsupported_material_type",
                )
                return

282
283
            # Get the method type. For now, we allow unknown method type.
            # Mostly to allow phonon calculations through.
284
            representative_method, method_type = self.method_type(method, calc_type)
285
286
287

            # Get representative scc
            try:
288
289
                representative_scc_idx = self.section_run.m_cache["representative_scc_idx"]
                representative_scc = self.section_run.section_single_configuration_calculation[representative_scc_idx]
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
            except (KeyError, IndexError):
                representative_scc = None
                representative_scc_idx = None

            # Create one context that holds all details
            context = Context(
                material_type=material_type,
                method_type=method_type,
                calc_type=calc_type,
                representative_system=representative_system,
                representative_method=representative_method,
                representative_scc=representative_scc,
                representative_scc_idx=representative_scc_idx,
            )

            # Put the encyclopedia section into backend
            self.fill(context)
307

308
309
310
311
312
313
314
315
316
317
318
        except Exception:
            self.logger.error(
                "Failed to create an Encyclopedia entry due to an unhandlable exception.",
                enc_status="failure",
            )
            raise  # Reraise for the caller to log the exception as well
        else:
            self.logger.info(
                "Successfully created metainfo for Encyclopedia.",
                enc_status="success",
            )