legacy.py 19.5 KB
Newer Older
1

2
from typing import cast, Dict, List, Union, Any, Set, Iterable, Tuple
3
import numpy as np
4
5
from pint.errors import UndefinedUnitError
import os.path
6
from jinja2 import Environment as JinjaEnvironment, PackageLoader, select_autoescape
7
import textwrap
8

9
from nomadcore.local_meta_info import loadJsonFile, InfoKindEl, InfoKindEnv
10
11
12
import nomad_meta_info

from nomad import utils
13
14
from nomad.metainfo import (
    Definition, SubSection, Package, Quantity, Category, Section, Reference, units,
15
    Environment, MEnum, MProxy)
16
17


18
logger = utils.get_logger(__name__)
19
20


21
22
23
_ignored_packages = [
    'meta_types.nomadmetainfo.json',
    'repository.nomadmetainfo.json']
24
25


26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
def python_package_mapping(metainfo_package_name: str) -> Tuple[str, str]:
    '''
    Compute the python package for the given metainfo package name. It returns
    a tuple containing a file path and a package name. The filepath denotes the file
    for this package within the nomad git project.
    '''

    split_mi_package_name = metainfo_package_name.split('_')
    prefix = split_mi_package_name[0]

    if prefix in ['common', 'general', 'public']:
        directory = 'nomad/datamodel/metainfo'
        python_package_name = 'nomad.datamodel.metainfo.%s' % metainfo_package_name

    else:
        directory = 'dependencies/parsers/%s/%sparser/metainfo' % (prefix, prefix)
        python_package_name = '%sparser.metainfo.%s' % (prefix, metainfo_package_name)

    path = '%s/%s.py' % (directory, metainfo_package_name)

    return python_package_name, path


49
class LegacyMetainfoEnvironment(Environment):
50
    '''
51
52
    A metainfo environment with functions to create a legacy metainfo version of
    the environment.
53
    '''
54
55
56

    legacy_package_name = Quantity(type=str)

57
    def legacy_info(self, definition: Definition, *args, **kwargs) -> InfoKindEl:
58
        ''' Creates a legacy metainfo objects for the given definition. '''
59
60
61
62
63
64
65
66
67
68
69
70
71
        super_names: List[str] = list()
        result: Dict[str, Any] = dict(
            name=definition.name,
            description=definition.description,
            superNames=super_names)

        for category in definition.categories:
            super_names.append(category.name)

        if isinstance(definition, Section):
            result['kindStr'] = 'type_section'
            result['repeats'] = any(
                sub_section.repeats
72
                for sub_section in self.resolve_definitions(definition.name, SubSection))
73

74
            for sub_section in self.resolve_definitions(definition.name, SubSection):
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
                super_names.append(sub_section.m_parent_as(Definition).name)

        elif isinstance(definition, Quantity):
            result['kindStr'] = 'document_content'
            result['shape'] = definition.shape
            dtype_str = None
            if definition.type == int:
                dtype_str = 'i'
            elif definition.type == float:
                dtype_str = 'f'
            elif definition.type == bool:
                dtype_str = 'b'
            elif definition.type == str:
                dtype_str = 'C'
            elif isinstance(definition.type, Reference):
                dtype_str = 'r'
91
92
93
94
95
                if isinstance(definition.type.target_section_def, MProxy):
                    proxy = definition.type.target_section_def
                    proxy.m_proxy_section = definition
                    proxy.m_proxy_quantity = Quantity.type
                    definition.type.target_section_def = proxy.m_proxy_resolve()
96
                result['referencedSections'] = [definition.type.target_section_def.name]
97
            elif isinstance(definition.type, MEnum):
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
                dtype_str = 'C'
            elif type(definition.type) == np.dtype:
                dtype_str = definition.type.name[0]
            elif definition.type == Any:
                dtype_str = 'D'
            else:
                raise TypeError(
                    'Unsupported quantity type %s in %s.' % (definition.type, definition))
            result['dtypeStr'] = dtype_str
            if definition.unit is not None:
                result['units'] = str(definition.unit)
            super_names.append(definition.m_parent_as(Definition).name)

        elif isinstance(definition, Category):
            result['kindStr'] = 'abstract_document_content'

        return InfoKindEl(*args, **result, **kwargs)

    def legacy_info_env(self, packages: List[Package] = None, *args, **kwargs) -> InfoKindEnv:
117
        ''' Creates a legacy metainfo environment with all definitions from the given packages. '''
118
        if packages is None:
119
            packages = self.packages
120
121
122
123

        env = InfoKindEnv(*args, **kwargs)
        for package in packages:
            for definition in package.all_definitions.values():
124
125
126
                if not (isinstance(definition, Section) and definition.extends_base_section):
                    env.addInfoKindEl(self.legacy_info(definition))

127
128
129
130
131
132
                if isinstance(definition, Section):
                    for quantity in definition.quantities:
                        env.addInfoKindEl(self.legacy_info(quantity))

        return env

133

134
135
136
137
138
139
140
141
142
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
class EnvironmentConversion:
    def __init__(self, legacy_env_or_path: Union[InfoKindEnv, str]):
        if isinstance(legacy_env_or_path, str):
            legacy_env_or_path = os.path.normpath(os.path.join(
                os.path.dirname(nomad_meta_info.__file__), legacy_env_or_path))
            self.legacy_env, _ = loadJsonFile(filePath=legacy_env_or_path)

        else:
            self.legacy_env = cast(InfoKindEnv, legacy_env_or_path)

        self.__fix_legacy_super_names()

        self.package_conversions: Dict[str, PackageConversion] = {}

        for legacy_def in self.legacy_env.infoKindEls():
            if legacy_def.package in _ignored_packages:
                continue
            legacy_def.package = legacy_def.package.replace('.nomadmetainfo.json', '').replace('.', '_')
            package_conversion = self.package_conversions.get(legacy_def.package)
            if package_conversion is None:
                package_conversion = PackageConversion(self, legacy_def.package)
                self.package_conversions[legacy_def.package] = package_conversion

            package_conversion.legacy_defs.append(legacy_def)

        for package_conversion in self.package_conversions.values():
            package_conversion.create_definitions()

        for package_conversion in self.package_conversions.values():
            package_conversion.set_super_names()

        for package_conversion in self.package_conversions.values():
            package_conversion.init_definitions()

    def create_env(self) -> LegacyMetainfoEnvironment:
        env = LegacyMetainfoEnvironment()
170
        env.legacy_package_name = self.legacy_env.name.replace('.nomadmetainfo.json', '').replace('.', '_')
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
        for package_conv in self.package_conversions.values():
            package = package_conv.package
            errors, warnings = package.m_all_validate()
            if len(errors) > 0:
                logger.error(
                    '%s. There are %d more errors in converted legacy package %s' %
                    (errors[0], len(errors) - 1, package))
            if len(warnings) > 0:
                logger.warn(
                    '%s. There are %d more warnings in converted legacy package %s' %
                    (warnings[0], len(warnings) - 1, package))
            env.m_add_sub_section(Environment.packages, package)
            package.init_metainfo()
        return env

    def __fix_legacy_super_names(self):

        def get_super_names(legacy_def: InfoKindEl, super_categories: Set[str] = None):
            super_section: str = None
            if super_categories is None:
                super_categories = set()

            for super_name in legacy_def.superNames:
                super_def = self.legacy_env.infoKindEl(super_name)

                if super_def.kindStr == 'type_section':
                    super_section = super_def.name

                elif super_def.kindStr == 'type_abstract_document_content':
                    super_categories.add(super_def.name)
                    super_super_section, _ = get_super_names(super_def, super_categories=super_categories)
202

203
204
                    if super_super_section is None:
                        pass
205

206
207
                    elif super_section is None:
                        super_section = super_super_section
208

209
210
                    elif super_section == super_super_section:
                        pass
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
                    else:
                        logger.error('conflicting parent sections %s, %s for %s' % (
                            super_section, super_def.name, legacy_def.name))

            return super_section, super_categories

        for legacy_def in self.legacy_env.infoKindEls():
            super_section, super_categories = get_super_names(legacy_def)

            if super_section is None:
                legacy_def.superNames = list(super_categories)

            else:
                legacy_def.superNames = [super_section] + list(super_categories)

    def resolve(self, name: str) -> Iterable[Definition]:
        for package_conversion in self.package_conversions.values():
            definition = package_conversion.package.all_definitions.get(name)
            if definition is not None:
                yield definition


class PackageConversion:

    def __init__(self, env_conversion: EnvironmentConversion, name: str):
        self.env_conversion = env_conversion
        self.legacy_defs: List[InfoKindEl] = []

240
241
242
        python_package, python_path = python_package_mapping(name)

        self.package = Package(name=name, a_python=(python_package, python_path))
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
        self.quantities: Dict[str, Quantity] = {}

        self.logger = logger.bind(package=name)

    def create_definitions(self):
        for legacy_def in self.legacy_defs:
            name = legacy_def.name

            if legacy_def.kindStr == 'type_abstract_document_content':
                self.package.m_create(Category, name=name)

            elif legacy_def.kindStr == 'type_section':
                self.package.m_create(Section, name=name)

            elif legacy_def.kindStr in ['type_dimension', 'type_document_content']:
                definition = Quantity(name=name)
                self.quantities[name] = (definition)

            else:
                logger.error('unknown kindStr %s for %s' % (legacy_def.kindStr, name))

    def __resolve(self, name: str, create_extends: bool = False):
        definition: Definition = self.package.all_definitions.get(name)
        if definition is None:
            definition = self.quantities.get(name)

        if definition is not None:
            if not (isinstance(definition, Section) and definition.extends_base_section) or create_extends:
                return definition

        for definition in self.env_conversion.resolve(name):
            if isinstance(definition, Section) and definition.extends_base_section:
                continue

            if create_extends and isinstance(definition, Section):
                extending_def = self.package.m_create(Section, name=definition.name)
                extending_def.base_sections = [definition]
                extending_def.extends_base_section = True
                return extending_def

            return definition

        assert False, 'definition %s must be created now' % name

    def set_super_names(self):
        for legacy_def in self.legacy_defs:
            definition = self.__resolve(legacy_def.name)
            assert definition is not None, 'definition %s must exist' % legacy_def.name

            if isinstance(definition, Section):
                parent_section: Section = None
                for super_name in legacy_def.superNames:
                    super_def = self.__resolve(super_name, create_extends=True)
                    if isinstance(super_def, Section):
                        parent_section = cast(Section, super_def)

                if parent_section is not None:
                    sub_section = parent_section.m_create(SubSection, name=definition.name)
                    sub_section.sub_section = definition
                    sub_section.repeats = legacy_def.repeats is None or legacy_def.repeats

            if isinstance(definition, Quantity):
                parent_section: Section = None
                for super_name in legacy_def.superNames:
                    super_def = self.__resolve(super_name, create_extends=True)
                    if isinstance(super_def, Section):
                        parent_section = cast(Section, super_def)

                parent_section.m_add_sub_section(Section.quantities, definition)

    def init_definitions(self):
        for legacy_def in self.legacy_defs:
            definition = self.__resolve(legacy_def.name)
            assert definition is not None, 'definition %s must exist' % legacy_def.name
            logger = self.logger.bind(definition=definition.name)

            # common properties
            definition.description = legacy_def.description

            if isinstance(definition, Definition):
                # deal with categories
                categories: List[Category] = []
                for super_name in legacy_def.superNames:
                    super_def = self.__resolve(super_name)
                    if isinstance(super_def, Category):
                        categories.append(super_def)

                definition.categories = categories

            if isinstance(definition, Quantity):
                # type
                referenced_sections = legacy_def.extra_args.get('referencedSections', [])
                if len(referenced_sections) == 1:
                    referenced_section = self.__resolve(referenced_sections[0])
                    if referenced_section is None:
                        logger.error('could not find referencedSection %s of %s' % (
                            referenced_sections[0], definition.name))
                        definition.type = int
                    else:
                        definition.type = Reference(referenced_section)

                elif len(referenced_sections) > 1:
                    logger.error(
                        'higher dimensional references not yet supported: %s' % legacy_def.name)
                    definition.type = np.dtype(int)

                elif legacy_def.kindStr == 'type_dimension':
                    definition.type = int
                elif legacy_def.dtypeStr == 'D':
                    definition.type = Any
                elif legacy_def.dtypeStr == 'C':
                    definition.type = str
                elif legacy_def.dtypeStr == 'r':
                    logger.error('r typed quantity %s  doesn\'t have referencedSections' % legacy_def.name)
                    definition.type = int
                elif legacy_def.dtypeStr == 'b':
                    definition.type = bool
                elif legacy_def.dtypeStr == 'i64':
                    definition.type = np.dtype(np.int64)
                elif legacy_def.dtypeStr == 'f':
                    definition.type = np.dtype(np.float64)
                else:
                    definition.type = np.dtype(legacy_def.dtypeStr)

                # shapes
                legacy_shape = legacy_def.shape
                if legacy_shape is None:
                    legacy_shape = []

                definition.shape = legacy_shape
                if len(definition.shape) > 1 and definition.type == str:
                    # Usually only np types have higher shapes in old metainfo;
                    # str is one exception.
                    definition.type = np.dtype('U')

                # units
                if legacy_def.units is not None:
                    try:
                        definition.unit = units.parse_units(legacy_def.units)
                    except UndefinedUnitError:
                        logger.error('unknown unit %s' % legacy_def.units)
                    except ValueError as e:
                        logger.error('cannot parse unit %s' % legacy_def.units, exc_info=e)


def convert(metainfo_path: str) -> LegacyMetainfoEnvironment:
    return EnvironmentConversion(metainfo_path).create_env()


392
def generate_metainfo_code(metainfo_env: LegacyMetainfoEnvironment):
393
394
395
396
397
398
    '''
    Generates python code with metainfo definitions for all packages in the given
    environement

    Arguments:
        env: The metainfo environment.
399
400
401
        python_package_path: An optional directory path. The directory must exist. Default
            is the working directory. The path will be used to form the module prefix
            for generated Python modules.
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
    '''

    def format_description(description, indent=0, width=90):
        paragraphs = [paragraph.strip() for paragraph in description.split('\n')]

        def format_paragraph(paragraph, first):
            lines = textwrap.wrap(text=paragraph, width=width - indent * 4)
            lines = [l.replace('\\', '\\\\') for l in lines]
            return textwrap.indent(
                '\n'.join(lines), ' ' * 4 * indent, lambda x: not (first and x.startswith(lines[0])))

        return '\n\n'.join([
            format_paragraph(p, i == 0)
            for i, p in enumerate(paragraphs) if p != ''])

417
    def format_type(pkg, mi_type):
418
419
420
421
422
        if type(mi_type) == np.dtype:
            return 'np.dtype(np.%s)' % mi_type
        if mi_type in [int, float, str, bool]:
            return mi_type.__name__
        if isinstance(mi_type, Reference):
423
424
425
426
427
428
429
            if pkg == mi_type.target_section_def.m_parent:
                return "Reference(SectionProxy('%s'))" % mi_type.target_section_def.name

            else:
                python_pkg, _ = mi_type.target_section_def.m_parent.a_python
                return '%s.%s' % (python_pkg.split('.')[-1], mi_type.target_section_def.name)

430
431
432
433
434
435
436
437
438
439
        else:
            return str(mi_type)

    def format_unit(unit):
        return "'%s'" % unit

    def format_definition_refs(pkg, definitions):
        def format_definition_ref(definition: Definition):
            if pkg == definition.m_parent:
                return definition.name
440
            else:
441
442
                python_pkg, _ = definition.m_parent.a_python
                return '%s.%s' % (python_pkg.split('.')[-1], definition.name)
443
444
445

        return ', '.join([format_definition_ref(definition) for definition in definitions])

446
447
448
449
450
    def fromat_package_import(pkg):
        python_package, _ = pkg.a_python
        packages = python_package.split('.')
        return 'from %s import %s' % ('.'.join(packages[:-1]), packages[-1])

451
452
453
454
455
456
457
    env = JinjaEnvironment(
        loader=PackageLoader('nomad.metainfo', 'templates'),
        autoescape=select_autoescape(['python']))
    env.globals.update(
        format_description=format_description,
        format_type=format_type,
        format_unit=format_unit,
458
459
        format_definition_refs=format_definition_refs,
        fromat_package_import=fromat_package_import)
460
461

    for package in metainfo_env.packages:
462
463
464
465
466
        _, path = package.a_python
        if not os.path.exists(os.path.dirname(path)):
            os.makedirs(os.path.dirname(path))

        with open(path, 'wt') as f:
467
468
469
470
471
            code = env.get_template('package.j2').render(pkg=package)
            code = '\n'.join([
                line.rstrip() if line.strip() != '' else ''
                for line in code.split('\n')])
            f.write(code)
472

473
474
    _, path = python_package_mapping(metainfo_env.legacy_package_name)
    with open(os.path.join(os.path.dirname(path), '__init__.py'), 'wt') as f:
475

476
477
478
479
480
        code = env.get_template('environment.j2').render(env=metainfo_env)
        code = '\n'.join([
            line.rstrip() if line.strip() != '' else ''
            for line in code.split('\n')])
        f.write(code)