metainfo.py 47.8 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
# 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.
14

15
16
17
18
"""
The NOMAD meta-info allows to define physics data quantities. These definitions are
necessary for all computer representations of respective data (e.g. in Python,
search engines, data-bases, and files).
19

20
This modules provides various Python interfaces for
21

22
23
24
- defining meta-info data
- to create and manipulate data that follows these definitions
- to (de-)serialize meta-info data in JSON (i.e. represent data in JSON formatted files)
25

26
27
28
29
Here is a simple example that demonstrates the definition of System related quantities:

.. code-block:: python

Markus Scheidgen's avatar
Markus Scheidgen committed
30
    class System(MSection):
31
32
33
34
35
        \"\"\"
        A system section includes all quantities that describe a single a simulated
        system (a.k.a. geometry).
        \"\"\"

36
37
38
39
        n_atoms = Quantity(
            type=int, description='''
            A Defines the number of atoms in the system.
            ''')
40

41
42
43
44
        atom_labels = Quantity(type=Enum(ase.data.chemical_symbols), shape['n_atoms'])
        atom_positions = Quantity(type=float, shape=['n_atoms', 3], unit=Units.m)
        simulation_cell = Quantity(type=float, shape=[3, 3], unit=Units.m)
        pbc = Quantity(type=bool, shape=[3])
45

46
47
48
    class Run(MSection):
        systems = SubSection(sub_section=System, repeats=True)

49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
Here, we define a `section` called ``System``. The section mechanism allows to organize
related data into, well, sections. Sections form containment hierarchies. Here
containment is a parent-child (whole-part) relationship. In this example many ``Systems``,
are part of one ``Run``. Each ``System`` can contain values for the defined quantities:
``n_atoms``, ``atom_labels``, ``atom_positions``, ``simulation_cell``, and ``pbc``.
Quantities allow to state type, shape, and physics unit to specify possible quantity
values.

Here is an example, were we use the above definition to create, read, and manipulate
data that follows these definitions:

.. code-bock:: python

    run = Run()
    system = run.m_create(System)
    system.n_atoms = 3
    system.atom_labels = ['H', 'H', 'O']

    print(system.atom_labels)
    print(run.m_to_json(ident=2))

This last statement, will produce the following JSON:

.. code-block:: JSON

    {
75
        "m_def" = "Run",
76
77
        "System": [
            {
78
                "m_def" = "System",
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
                "m_parent_index" = 0,
                "n_atoms" = 3,
                "atom_labels" = [
                    "H",
                    "H",
                    "O"
                ]
            }
        ]
    }

This is the JSON representation, a serialized version of the Python representation in
the example above.

Sections can be extended with new quantities outside the original section definition.
This provides the key mechanism to extend commonly defined parts with (code) specific
quantities:

.. code-block:: Python

    class Method(nomad.metainfo.common.Method):
        x_vasp_incar_ALGO=Quantity(
            type=Enum(['Normal', 'VeryFast', ...]),
            links=['https://cms.mpi.univie.ac.at/wiki/index.php/ALGO'])
        \"\"\"
        A convenient option to specify the electronic minimisation algorithm (as of VASP.4.5)
        and/or to select the type of GW calculations.
        \"\"\"


All meta-info definitions and classes for meta-info data objects (i.e. section instances)
110
inherit from :class:` MSection`. This base-class provides common functions and properties
111
112
113
114
115
116
for all meta-info data objects. Names of these common parts are prefixed with ``m_``
to distinguish them from user defined quantities. This also constitute's the `reflection`
interface (in addition to Python's build in ``getattr``, ``setattr``) that allows to
create and manipulate meta-info data, without prior program time knowledge of the underlying
definitions.

Markus Scheidgen's avatar
Markus Scheidgen committed
117
.. autoclass:: MSection
118
119
120

The following classes can be used to define and structure meta-info data:

Markus Scheidgen's avatar
Markus Scheidgen committed
121
- sections are defined by sub-classes :class:`MSection` and using :class:`Section` to
122
  populate the classattribute `m_def`
123
124
125
126
127
128
129
130
131
132
133
134
- quantities are defined by assigning classattributes of a section with :class:`Quantity`
  instances
- references (from one section to another) can be defined with quantities that use
  section definitions as type
- dimensions can use defined by simply using quantity names in shapes
- categories (former `abstract type definitions`) can be given in quantity definitions
  to assign quantities to additional specialization-generalization hierarchies

See the reference of classes :class:`Section` and :class:`Quantities` for details.

.. autoclass:: Section
.. autoclass:: Quantity
135
136
"""

137
138
# TODO validation

139
140
from typing import Type, TypeVar, Union, Tuple, Iterable, List, Any, Dict, Set, Callable, cast
from collections.abc import Iterable as IterableABC
141
import sys
142
import inspect
143
import re
144
import json
145
import itertools
146
import time
147

148
import numpy as np
149
150
from pint.unit import _Unit
from pint import UnitRegistry
151

152
start_time = time.time()
Markus Scheidgen's avatar
Markus Scheidgen committed
153
154
is_bootstrapping = True
MSectionBound = TypeVar('MSectionBound', bound='MSection')
155
T = TypeVar('T')
156

157

158
159
160
161
162
class MetainfoError(Exception):
    """ An error within the definition for metainfo data. """
    pass


163
# Reflection
164

165
class Enum(list):
166
    """ Allows to define str types with values limited to a pre-set list of possible values. """
167
168
169
    pass


170
171
172
173
174
175
176
177
class DataType:
    """
    Allows to define custom data types that can be used in the meta-info.

    The metainfo supports most types out of the box. These includes the python build-in
    primitive types (int, bool, str, float, ...), references to sections, and enums.
    However, in some occasions you need to add custom data types.
    """
Markus Scheidgen's avatar
Markus Scheidgen committed
178
    def type_check(self, section, value):
179
        """ Checks the given value before it is set to the given section. Can modify the value. """
180
181
        return value

Markus Scheidgen's avatar
Markus Scheidgen committed
182
    def to_json_serializable(self, section, value):
183
184
        return value

Markus Scheidgen's avatar
Markus Scheidgen committed
185
    def from_json_serializable(self, section, value):
186
187
188
189
        return value


class Dimension(DataType):
190
    def type_check(self, section, value):
191
        if isinstance(value, int):
Markus Scheidgen's avatar
Markus Scheidgen committed
192
            return value
193
194
195

        if isinstance(value, str):
            if value.isidentifier():
Markus Scheidgen's avatar
Markus Scheidgen committed
196
                return value
197
            if re.match(r'(\d)\.\.(\d|\*)', value):
Markus Scheidgen's avatar
Markus Scheidgen committed
198
                return value
199
200

        if isinstance(value, Section):
Markus Scheidgen's avatar
Markus Scheidgen committed
201
            return value
202

203
        if isinstance(value, type) and hasattr(value, 'm_def'):
Markus Scheidgen's avatar
Markus Scheidgen committed
204
            return value
205
206
207
208

        raise TypeError('%s is not a valid dimension' % str(value))


Markus Scheidgen's avatar
Markus Scheidgen committed
209
210
211
212
213
214
215
216
217
218
219
220
class Reference(DataType):
    """ A datatype class that can be used to define reference types based on section definitions.

    A quantity can be used to define possible references between sections. Instantiate
    this class to create a reference type that specified that a quantity with this type
    is actually a reference (or references, depending on shape) to a section of the
    given definition.
    """
    def __init__(self, section: 'Section'):
        self.section = section


221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
class Unit(DataType):
    def type_check(self, section, value):
        if isinstance(value, str):
            value = units.parse_units(value)

        elif not isinstance(value, _Unit):
            raise TypeError('Units must be given as str or pint Unit instances.')

        return value

    def to_json_serializable(self, section, value):
        return value.__str__()

    def from_json_serializable(self, section, value):
        return units.parse_units(value)

237
238
239
# TODO class Datetime(DataType)


240
class MObjectMeta(type):
241

242
243
    def __new__(self, cls_name, bases, dct):
        cls = super().__new__(self, cls_name, bases, dct)
Markus Scheidgen's avatar
Markus Scheidgen committed
244

Markus Scheidgen's avatar
Markus Scheidgen committed
245
246
        init = getattr(cls, '__init_cls__')
        if init is not None and not is_bootstrapping:
247
248
            init()
        return cls
249
250


251
Content = Tuple['MSection', int, 'SubSection', 'MSection']
252
253
254
255
256
257
258
259
260
261
262

SectionDef = Union[str, 'Section', 'SubSection', Type[MSectionBound]]
""" Type for section definition references.

This can either be :

- the name of the section
- the section definition itself
- the definition of a sub section
- or the section definition Python class
"""
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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
class MData:
    """ An interface for low-level metainfo data objects.

    Metainfo data objects store the data of a single section instance. This interface
    constitutes the minimal functionality for accessing and modifying section data.
    Different implementations of this interface, can realize different storage backends,
    or include different rigorosity of type and shape checks.

    All section instances will implement this interface, usually be delegating calls to
    a standalone implementation of this interface. This allows to configure various
    data backends on section instance creation.
    """

    def __getitem__(self, key):
        raise NotImplementedError()

    def __setitem__(self, key, value):
        raise NotImplementedError()

    def m_set(self, section: 'MSection', quantity_def: 'Quantity', value: Any) -> None:
        """ Set the given value for the given quantity. """
        raise NotImplementedError()

    def m_get(self, section: 'MSection', quantity_def: 'Quantity') -> Any:
        """ Retrieve the given value for the given quantity. """
        raise NotImplementedError()

    def m_is_set(self, section: 'MSection', quantity_def: 'Quantity') -> bool:
        """ True iff this quantity was explicitely set. """
        raise NotImplementedError()

    def m_add_values(
            self, section: 'MSection', quantity_def: 'Quantity', values: Any,
            offset: int) -> None:
        """ Add (partial) values for the given quantity of higher dimensionality. """
        raise NotImplementedError()

    def m_add_sub_section(
            self, section: 'MSection', sub_section_def: 'SubSection',
            sub_section: 'MSection') -> None:
        """ Adds the given section instance as a sub section of the given sub section definition. """
        raise NotImplementedError()

    def m_get_sub_section(
            self, section: 'MSection', sub_section_def: 'SubSection',
            index: int) -> 'MSection':
        """ Retrieves a single sub section of the given sub section definition. """
        raise NotImplementedError()

    def m_get_sub_sections(
            self, section: 'MSection', sub_section_def: 'SubSection') -> Iterable['MSection']:
        """ Retrieves  all sub sections of the given sub section definition. """
        raise NotImplementedError()

    def m_sub_section_count(self, section: 'MSection', sub_section_def: 'SubSection') -> int:
        """ Returns the number of sub sections for the given sub section definition. """
        raise NotImplementedError()


class MDataDelegating(MData):
    """ A simple delgating implementation of :class:`MData`. """
    def __init__(self, m_data: MData):
        self.m_data = m_data

    def __getitem__(self, key):
        return self.m_data[key]

    def __setitem__(self, key, value):
        self.m_data[key] = value

    def m_set(self, section: 'MSection', quantity_def: 'Quantity', value: Any) -> None:
        self.m_data.m_set(section, quantity_def, value)

    def m_get(self, section: 'MSection', quantity_def: 'Quantity') -> Any:
        return self.m_data.m_get(section, quantity_def)

    def m_is_set(self, section: 'MSection', quantity_def: 'Quantity') -> bool:
        return self.m_data.m_is_set(section, quantity_def)

    def m_add_values(
            self, section: 'MSection', quantity_def: 'Quantity', values: Any,
            offset: int) -> None:
        self.m_data.m_add_values(section, quantity_def, values, offset)

    def m_add_sub_section(
            self, section: 'MSection', sub_section_def: 'SubSection',
            sub_section: 'MSection') -> None:
        self.m_data.m_add_sub_section(section, sub_section_def, sub_section)

    def m_get_sub_section(
            self, section: 'MSection', sub_section_def: 'SubSection',
            index: int) -> 'MSection':
        return self.m_data.m_get_sub_section(section, sub_section_def, index)

    def m_get_sub_sections(
            self, section: 'MSection', sub_section_def: 'SubSection') -> Iterable['MSection']:
        return self.m_data.m_get_sub_sections(section, sub_section_def)

    def m_sub_section_count(self, section: 'MSection', sub_section_def: 'SubSection') -> int:
        return self.m_data.m_sub_section_count(section, sub_section_def)


class MDataDict(MData):
    """ A simple dict backed implementaton of :class:`MData`. """

    def __init__(self, dct: Dict[str, Any] = None):
        if dct is None:
            dct = {}

        self.dct = dct

    def __getitem__(self, key):
        return self.dct[key]

    def __setitem__(self, key, value):
        self.dct[key] = value

    def m_set(self, section: 'MSection', quantity_def: 'Quantity', value: Any) -> None:
        self.dct[quantity_def.name] = value

    def m_get(self, section: 'MSection', quantity_def: 'Quantity') -> Any:
        quantity_name = quantity_def.name
        if quantity_name not in self.dct:
            return quantity_def.default
        else:
            return self.dct[quantity_name]

    def m_is_set(self, section: 'MSection', quantity_def: 'Quantity') -> bool:
        return quantity_def.name in self.dct

    def m_add_values(
            self, section: 'MSection', quantity_def: 'Quantity', values: Any,
            offset: int) -> None:

        # TODO
        raise NotImplementedError()

    def m_add_sub_section(
            self, section: 'MSection', sub_section_def: 'SubSection',
            sub_section: 'MSection') -> None:

        sub_section_name = sub_section_def.name
        if sub_section_def.repeats:
            sub_section_lst = self.dct.get(sub_section_name, None)
            if sub_section_lst is None:
                sub_section_lst = self.dct.setdefault(sub_section_name, [])

            sub_section_lst.append(sub_section)

        else:
            self.dct[sub_section_name] = sub_section

    def m_get_sub_section(
            self, section: 'MSection', sub_section_def: 'SubSection',
            index: int) -> 'MSection':

        if sub_section_def.repeats:
            return self.dct[sub_section_def.name][index]

        else:
            return self.dct.get(sub_section_def.name, None)

    def m_get_sub_sections(
            self, section: 'MSection', sub_section_def: 'SubSection') -> Iterable['MSection']:
        return self.dct.get(sub_section_def.name, [])

    def m_sub_section_count(self, section: 'MSection', sub_section_def: 'SubSection') -> int:
        sub_section_name = sub_section_def.name
        if sub_section_name not in self.dct:
            return 0

        if not sub_section_def.repeats:
            return 1

        return len(self.dct[sub_section_name])


class MDataTypeAndShapeChecks(MDataDelegating):
    """ A :class:`MData` implementation that delegates to another :class:`MData`
    instance after applying rigorous type/checks. It might also resolve potential
    duck typed values, depending on quantity :class:`DataType`s.
    """

    def __init__(self, m_data: MData):
        self.m_data = m_data

    def __check_np(self, quantity_ref: 'Quantity', value: np.ndarray) -> np.ndarray:
        # TODO
        return value

    def __check_single(
            self, section: 'MSection', quantity_def: 'Quantity', value: Any) -> Any:

        if isinstance(quantity_def.type, DataType):
            return quantity_def.type.type_check(section, value)

        elif isinstance(quantity_def.type, Section):
            if not isinstance(value, MSection):
                raise TypeError(
                    'The value %s for reference quantity %s is not a section instance.' %
                    (value, quantity_def))

            if not value.m_follows(quantity_def.type):
                raise TypeError(
                    'The value %s for quantity %s does not follow %s' %
                    (value, quantity_def, quantity_def.type))

        elif isinstance(quantity_def.type, Enum):
            if value not in quantity_def.type:
                raise TypeError(
                    'The value %s is not an enum value for quantity %s.' %
                    (value, quantity_def))

        elif quantity_def == Quantity.type:
            # TODO check this special case of values used as quantity types
            pass

        elif quantity_def.type == Any:
            pass

        else:
            if type(value) != quantity_def.type:
                raise TypeError(
                    'The value %s with type %s for quantity %s is not of type %s' %
                    (value, type(value), quantity_def, quantity_def.type))

        return value

    def m_set(self, section: 'MSection', quantity_def: 'Quantity', value: Any) -> None:
        if type(quantity_def.type) == np.dtype:
            if type(value) != np.ndarray:
                try:
                    value = np.asarray(value)
                except TypeError:
                    raise TypeError(
                        'Could not convert value %s of %s to a numpy array' %
                        (value, quantity_def))

            value = self.__check_np(quantity_def, value)

        else:
            dimensions = len(quantity_def.shape)
            if dimensions == 0:
                value = self.__check_single(section, quantity_def, value)

            elif dimensions == 1:
                if type(value) == str or not isinstance(value, IterableABC):
                    raise TypeError(
                        'The shape of %s requires an iterable value, but %s is not iterable.' %
                        (quantity_def, value))

                value = list(self.__check_single(section, quantity_def, item) for item in value)

            else:
                raise MetainfoError(
                    'Only numpy arrays and dtypes can be used for higher dimensional '
                    'quantities.')

        self.m_data.m_set(section, quantity_def, value)


Markus Scheidgen's avatar
Markus Scheidgen committed
526
527
class MSection(metaclass=MObjectMeta):
    """Base class for all section instances on all meta-info levels.
528

Markus Scheidgen's avatar
Markus Scheidgen committed
529
530
531
    All metainfo objects instantiate classes that inherit from ``MSection``. Each
    section or quantity definition is an ``MSection``, each actual (meta-)data carrying
    section is an ``MSection``. This class consitutes the reflection interface of the
532
533
534
535
536
537
538
539
540
541
542
543
544
    meta-info, since it allows to manipulate sections (and therefore all meta-info data)
    without having to know the specific sub-class.

    It also carries all the data for each section. All sub-classes only define specific
    sections in terms of possible sub-sections and quantities. The data is managed here.

    The reflection insterface for reading and manipulating quantity values consists of
    Pythons build in ``getattr``, ``setattr``, and ``del``, as well as member functions
    :func:`m_add_value`, and :func:`m_add_values`.

    Sub-sections and parent sections can be read and manipulated with :data:`m_parent`,
    :func:`m_sub_section`, :func:`m_create`.

545
546
547
548
549
    .. code-block:: python

        system = run.m_create(System)
        assert system.m_parent == run
        assert run.m_sub_section(System, system.m_parent_index) == system
550
551

    Attributes:
552
        m_def: The section definition that defines this sections, its possible
553
554
            sub-sections and quantities.
        m_parent: The parent section instance that this section is a sub-section of.
555
        m_parent_sub_section: The sub section definition that holds this section in the parent.
556
557
558
559
560
561
562
563
564
        m_parent_index: For repeatable sections, parent keep a list of sub-sections for
            each section definition. This is the index of this section in the respective
            parent sub-section list.
        m_data: The dictionary that holds all data of this section. It keeps the quantity
            values and sub-section. It should only be read directly (and never manipulated)
            if you are know what you are doing. You should always use the reflection interface
            if possible.
    """

565
    m_def: 'Section' = None
566

567
568
    def __init__(self, m_def: 'Section' = None, m_data: MData = None, **kwargs):

569
        self.m_def: 'Section' = m_def
570
571
        self.m_parent: 'MSection' = None
        self.m_parent_sub_section: 'SubSection' = None
572
        self.m_parent_index = -1
573

574
        # get missing m_def from class
575
        cls = self.__class__
576
577
        if self.m_def is None:
            self.m_def = cls.m_def
578

579
580
        if cls.m_def is not None:
            assert self.m_def == cls.m_def, \
581
582
                'Section class and section definition must match'

583
        # get annotations from kwargs
584
        self.m_annotations: Dict[str, Any] = {}
Markus Scheidgen's avatar
Markus Scheidgen committed
585
        rest = {}
586
587
588
589
        for key, value in kwargs.items():
            if key.startswith('a_'):
                self.m_annotations[key[2:]] = value
            else:
Markus Scheidgen's avatar
Markus Scheidgen committed
590
591
                rest[key] = value

592
593
594
595
        # initialize data
        self.m_data = m_data
        if self.m_data is None:
            self.m_data = MDataTypeAndShapeChecks(MDataDict())
596

597
598
599
        # set remaining kwargs
        if is_bootstrapping:
            self.m_data.m_data.dct.update(**rest)  # type: ignore
Markus Scheidgen's avatar
Markus Scheidgen committed
600
        else:
601
            self.m_update(**rest)
602

603
    @classmethod
Markus Scheidgen's avatar
Markus Scheidgen committed
604
    def __init_cls__(cls):
605
606
        # ensure that the m_def is defined
        m_def = cls.m_def
Markus Scheidgen's avatar
Markus Scheidgen committed
607
        if m_def is None:
608
609
            m_def = Section()
            setattr(cls, 'm_def', m_def)
610

611
612
        # transfer name and description to m_def
        m_def.name = cls.__name__
613
        if cls.__doc__ is not None:
614
            m_def.description = inspect.cleandoc(cls.__doc__).strip()
615
        m_def.section_cls = cls
616

617
        for name, attr in cls.__dict__.items():
618
619
            # transfer names and descriptions for properties
            if isinstance(attr, Property):
620
                attr.name = name
621
                if attr.description is not None:
622
                    attr.description = inspect.cleandoc(attr.description).strip()
623
                    attr.__doc__ = attr.description
624

625
                if isinstance(attr, Quantity):
626
                    m_def.m_add_sub_section(Section.quantities, attr)
627
                elif isinstance(attr, SubSection):
628
                    m_def.m_add_sub_section(Section.sub_sections, attr)
629
630
                else:
                    raise NotImplementedError('Unknown property kind.')
631

Markus Scheidgen's avatar
Markus Scheidgen committed
632
633
634
        # add base sections
        for base_cls in cls.__bases__:
            if base_cls != MSection:
635
636
                base_section = getattr(base_cls, 'm_def')
                if base_section is None:
Markus Scheidgen's avatar
Markus Scheidgen committed
637
638
639
640
                    raise TypeError(
                        'Section defining classes must have MSection or a decendant as '
                        'base classes.')

641
642
643
                base_sections = list(m_def.m_get(Section.base_sections))
                base_sections.append(base_section)
                m_def.m_set(Section.base_sections, base_sections)
Markus Scheidgen's avatar
Markus Scheidgen committed
644

645
646
647
        # add section cls' section to the module's package
        module_name = cls.__module__
        pkg = Package.from_module(module_name)
648
        pkg.m_add_sub_section(Package.section_definitions, cls.m_def)
649

650
651
652
653
    def __resolve_synonym(self, quantity_def: 'Quantity') -> 'Quantity':
        if quantity_def.synonym_for is not None:
            return self.m_def.all_quantities[quantity_def.synonym_for]
        return quantity_def
654

655
656
657
658
    def m_set(self, quantity_def: 'Quantity', value: Any) -> None:
        """ Set the given value for the given quantity. """
        quantity_def = self.__resolve_synonym(quantity_def)
        self.m_data.m_set(self, quantity_def, value)
659

660
661
662
663
    def m_get(self, quantity_def: 'Quantity') -> Any:
        """ Retrieve the given value for the given quantity. """
        quantity_def = self.__resolve_synonym(quantity_def)
        return self.m_data.m_get(self, quantity_def)
664

665
666
667
    def m_is_set(self, quantity_def: 'Quantity') -> bool:
        quantity_def = self.__resolve_synonym(quantity_def)
        return self.m_data.m_is_set(self, quantity_def)
Markus Scheidgen's avatar
Markus Scheidgen committed
668

669
670
671
    def m_add_values(self, quantity_def: 'Quantity', values: Any, offset: int) -> None:
        """ Add (partial) values for the given quantity of higher dimensionality. """
        self.m_data.m_add_values(self, quantity_def, values, offset)
672

673
674
    def m_add_sub_section(self, sub_section_def: 'SubSection', sub_section: 'MSection') -> None:
        """ Adds the given section instance as a sub section of the given sub section definition. """
Markus Scheidgen's avatar
Markus Scheidgen committed
675

676
        parent_index = -1
677
        if sub_section_def.repeats:
678
679
680
681
            parent_index = self.m_sub_section_count(sub_section_def)
        sub_section.m_parent = self
        sub_section.m_parent_sub_section = sub_section_def
        sub_section.m_parent_index = parent_index
682

683
        self.m_data.m_add_sub_section(self, sub_section_def, sub_section)
684

685
686
687
    def m_get_sub_section(self, sub_section_def: 'SubSection', index: int) -> 'MSection':
        """ Retrieves a single sub section of the given sub section definition. """
        return self.m_data.m_get_sub_section(self, sub_section_def, index)
688

689
690
691
    def m_get_sub_sections(self, sub_section_def: 'SubSection') -> Iterable['MSection']:
        """ Retrieves  all sub sections of the given sub section definition. """
        return self.m_data.m_get_sub_sections(self, sub_section_def)
692

693
694
695
    def m_sub_section_count(self, sub_section_def: 'SubSection') -> int:
        """ Returns the number of sub sections for the given sub section definition. """
        return self.m_data.m_sub_section_count(self, sub_section_def)
696

697
698
699
    def m_create(self, section_cls: Type[MSectionBound], **kwargs) -> MSectionBound:
        """ Creates a section instance and adds it to this section provided there is a
        corresponding sub section.
700
        """
701

702
703
704
705
        section_def = section_cls.m_def
        sub_section_def = self.m_def.all_sub_sections_by_section.get(section_def, None)
        if sub_section_def is None:
            raise TypeError('There is not sub section for %s in %s.' % (section_def, self))
706

707
708
        sub_section = section_cls(**kwargs)
        self.m_add_sub_section(sub_section_def, sub_section)
709

710
        return cast(MSectionBound, sub_section)
711

712
713
714
    def m_update(self, **kwargs):
        """ Updates all quantities and sub-sections with the given arguments. """
        for name, value in kwargs.items():
715
716
            prop = self.m_def.all_properties.get(name, None)
            if prop is None:
717
                raise KeyError('%s is not an attribute of this section %s' % (name, self))
718

719
720
            if isinstance(prop, SubSection):
                if prop.repeats:
721
722
                    if isinstance(value, List):
                        for item in value:
723
                            self.m_add_sub_section(prop, item)
724
                    else:
725
                        raise TypeError('Sub section %s repeats, but no list was given' % prop.name)
726
                else:
727
                    self.m_add_sub_section(prop, item)
728
729

            else:
730
                self.m_set(prop, value)
731

732
    def m_follows(self, definition: 'Section') -> bool:
733
        """ Determines if this section's definition is or is derived from the given definition. """
734
735
        return self.m_def == definition or self.m_def in definition.all_base_sections

736
737
    def m_to_dict(self) -> Dict[str, Any]:
        """Returns the data of this section as a json serializeable dictionary. """
738
739

        def items() -> Iterable[Tuple[str, Any]]:
740
            yield 'm_def', self.m_def.name
741
            if self.m_parent_index != -1:
742
                yield 'm_parent_index', self.m_parent_index
743

744
745
746
747
748
749
            for name, sub_section_def in self.m_def.all_sub_sections.items():
                if sub_section_def.repeats:
                    if self.m_sub_section_count(sub_section_def) > 0:
                        yield name, [
                            item.m_to_dict()
                            for item in self.m_get_sub_sections(sub_section_def)]
750
                else:
751
752
753
                    sub_section = self.m_get_sub_section(sub_section_def, -1)
                    if sub_section is not None:
                        yield name, sub_section.m_to_dict()
754

755
            for name, quantity in self.m_def.all_quantities.items():
756
757
                if self.m_is_set(quantity):
                    to_json_serializable: Callable[[Any], Any] = str
758
                    if isinstance(quantity.type, DataType):
759
760
761
762
763

                        def serialize(v):
                            quantity.type.to_json_serializable(self, v)

                        to_json_serializable = serialize
764
765
766
767

                    elif isinstance(quantity.type, Section):
                        # TODO
                        to_json_serializable = str
768
769
770
                    elif quantity.type in [str, int, float, bool]:
                        to_json_serializable = quantity.type

771
772
773
774
                    else:
                        # TODO
                        pass

775
                    value = getattr(self, name)
776

777
                    if hasattr(value, 'tolist'):
778
779
780
781
782
783
784
785
786
787
788
                        serializable_value = value.tolist()

                    else:
                        if len(quantity.shape) == 0:
                            serializable_value = to_json_serializable(value)
                        elif len(quantity.shape) == 1:
                            serializable_value = [to_json_serializable(i) for i in value]
                        else:
                            raise NotImplementedError('Higher shapes (%s) not supported: %s' % (quantity.shape, quantity))

                    yield name, serializable_value
789
790

        return {key: value for key, value in items()}
791

792
    @classmethod
Markus Scheidgen's avatar
Markus Scheidgen committed
793
    def m_from_dict(cls: Type[MSectionBound], dct: Dict[str, Any]) -> MSectionBound:
794
795
796
797
798
799
800
        """ Creates a section from the given data dictionary.

        This is the 'oposite' of :func:`m_to_dict`. It takes a deserialized dict, e.g
        loaded from JSON, and turns it into a proper section, i.e. instance of the given
        section class.
        """

801
        section_def = cls.m_def
802

803
804
        # remove m_def and m_parent_index, they set themselves automatically
        assert section_def.name == dct.pop('m_def', None)
805
806
807
        dct.pop('m_parent_index', -1)

        def items():
808
            for name, sub_section_def in section_def.all_sub_sections.items():
809
810
811
812
                if name in dct:
                    sub_section_value = dct.pop(name)
                    if sub_section_def.repeats:
                        yield name, [
813
                            sub_section_def.sub_section.section_cls.m_from_dict(sub_section_dct)
814
815
                            for sub_section_dct in sub_section_value]
                    else:
816
                        yield name, sub_section_def.sub_section.section_cls.m_from_dict(sub_section_value)
817
818
819
820
821

            for key, value in dct.items():
                yield key, value

        dct = {key: value for key, value in items()}
Markus Scheidgen's avatar
Markus Scheidgen committed
822
        section_instance = cast(MSectionBound, section_def.section_cls())
823
824
825
        section_instance.m_update(**dct)
        return section_instance

826
    def m_to_json(self, **kwargs):
827
        """Returns the data of this section as a json string. """
828
        return json.dumps(self.m_to_dict(), **kwargs)
829

830
    def m_all_contents(self) -> Iterable[Content]:
831
        """Returns an iterable over all sub and sub subs sections. """
832
833
834
        for content in self.m_contents():
            for sub_content in content[0].m_all_contents():
                yield sub_content
835

836
            yield content
837

838
    def m_contents(self) -> Iterable[Content]:
839
        """Returns an iterable over all direct subs sections. """
840
841
842
843
844
845
        for sub_section_def in self.m_def.all_sub_sections.values():
            if sub_section_def.repeats:
                index = 0
                for sub_section in self.m_get_sub_sections(sub_section_def):
                    yield sub_section, index, sub_section_def, self
                    index += 1
846

847
848
849
            else:
                sub_section = self.m_get_sub_section(sub_section_def, -1)
                yield sub_section, -1, sub_section_def, self
850

851
    def __repr__(self):
852
        m_section_name = self.m_def.name
853
854
855
856
        # name_quantity_def = self.m_def.all_quantities.get('name', None)
        # if name_quantity_def is not None:
        #     name = self.m_get(name_quantity_def)
        try:
857
            name = self.m_data['name']
858
859
        except KeyError:
            name = '<noname>'
860
861

        return '%s:%s' % (name, m_section_name)
862
863


Markus Scheidgen's avatar
Markus Scheidgen committed
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
class MCategory(metaclass=MObjectMeta):

    m_def: 'Category' = None

    @classmethod
    def __init_cls__(cls):
        # ensure that the m_def is defined
        m_def = cls.m_def
        if m_def is None:
            m_def = Category()
            setattr(cls, 'm_def', m_def)

        # transfer name and description to m_def
        m_def.name = cls.__name__
        if cls.__doc__ is not None:
879
            m_def.description = inspect.cleandoc(cls.__doc__).strip()
Markus Scheidgen's avatar
Markus Scheidgen committed
880
881
882
883

        # add section cls' section to the module's package
        module_name = cls.__module__
        pkg = Package.from_module(module_name)
884
        pkg.m_add_sub_section(Package.category_definitions, cls.m_def)
Markus Scheidgen's avatar
Markus Scheidgen committed
885
886


887
888
889
890
891
892
893
# M3, the definitions that are used to write definitions. These are the section definitions
# for sections Section and Quantity.They define themselves; i.e. the section definition
# for Section is the same section definition.
# Due to this circular nature (hen-egg-problem), the classes for sections Section and
# Quantity do only contain placeholder for their own section and quantity definitions.
# These placeholder are replaced, once the necessary classes are defined. This process
# is referred to as 'bootstrapping'.
894

895
896
897
_definition_change_counter = 0


898
899
class cached_property:
    """ A property that allows to cache the property value.
900
901
902
903
904

    The cache will be invalidated whenever a new definition is added. Once all definitions
    are loaded, the cache becomes stable and complex derived results become available
    instantaneous.
    """
905
906
907
908
909
    def __init__(self, f):
        self.__doc__ = getattr(f, "__doc__")
        self.f = f
        self.change = -1
        self.values: Dict[type(self), Any] = {}
910

911
912
913
914
915
916
917
    def __get__(self, obj, cls):
        if obj is None:
            return self

        global _definition_change_counter
        if self.change != _definition_change_counter:
            self.values = {}
918

919
920
921
922
        value = self.values.get(obj, None)
        if value is None:
            value = self.f(obj)
            self.values[obj] = value
923
924
925
926

        return value


Markus Scheidgen's avatar
Markus Scheidgen committed
927
class Definition(MSection):
928

Markus Scheidgen's avatar
Markus Scheidgen committed
929
    __all_definitions: Dict[Type[MSection], List[MSection]] = {}
930

931
932
933
    name: 'Quantity' = None
    description: 'Quantity' = None
    links: 'Quantity' = None
934
    categories: 'Quantity' = None
935

936
937
938
939
940
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        global _definition_change_counter
        _definition_change_counter += 1

941
942
943
944
945
        for cls in self.__class__.mro() + [self.__class__]:
            definitions = Definition.__all_definitions.setdefault(cls, [])
            definitions.append(self)

    @classmethod
Markus Scheidgen's avatar
Markus Scheidgen committed
946
    def all_definitions(cls: Type[MSectionBound]) -> Iterable[MSectionBound]:
947
        """ Returns all definitions of this definition class. """
Markus Scheidgen's avatar
Markus Scheidgen committed
948
        return cast(Iterable[MSectionBound], Definition.__all_definitions.get(cls, []))
949

950
951
952
953
    @cached_property
    def all_categories(self):
        """ All categories of this definition and its categories. """
        all_categories = list(self.categories)
Markus Scheidgen's avatar
Markus Scheidgen committed
954
        for category in self.categories:  # pylint: disable=not-an-iterable
955
956
957
958
959
            for super_category in category.all_categories:
                all_categories.append(super_category)

        return all_categories

960

961
962
963
964
965
class Property(Definition):
    pass


class Quantity(Property):
966
967
968
969
970
971
972
973
974
975
976
    """Used to define quantities that store a certain piece of (meta-)data.

    Quantities are the basic building block with meta-info data. The Quantity class is
    used to define quantities within sections. A quantity definition
    is a (physics) quantity with name, type, shape, and potentially a unit.

    In Python terms, quantities are descriptors. Descriptors define how to get, set, and
    delete values for a object attribute. Meta-info descriptors ensure that
    type and shape fit the set values.
    """

977
978
    type: 'Quantity' = None
    shape: 'Quantity' = None
979
980
    unit: 'Quantity' = None
    default: 'Quantity' = None
Markus Scheidgen's avatar
Markus Scheidgen committed
981
    synonym_for: 'Quantity' = None
982
983
984
985
986

    # TODO derived_from = Quantity(type=Quantity, shape=['0..*'])
    # TODO categories = Quantity(type=Category, shape=['0..*'])
    # TODO converter = Quantity(type=Converter), a class with set of functions for
    #      normalizing, (de-)serializing values.
987

988
    def __get__(self, obj, cls):
989
990
991
992
        if obj is None:
            # class (def) attribute case
            return self

993
        return obj.m_get(self)
994

995
    def __set__(self, obj, value):
996
997
998
999
1000
        if obj is None:
            # class (def) case
            raise KeyError('Cannot overwrite quantity definition. Only values can be set.')

        # object (instance) case
1001
        obj.m_set(self, value)
Markus Scheidgen's avatar
Markus Scheidgen committed
1002

1003
1004
1005
1006
    def __delete__(self, obj):
        if obj is None:
            # class (def) case
            raise KeyError('Cannot delete quantity definition. Only values can be deleted.')
1007

1008
1009
        # object (instance) case
        raise NotImplementedError('Deleting quantity values is not supported.')
1010

1011

1012
1013
class DirectQuantity(Quantity):
    """ Used for quantities that would cause indefinite loops due to bootstrapping. """
1014

1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.__name = kwargs.get('name')
        self.__default = kwargs.get('default')

    def __get__(self, obj, cls):
        if obj is None:
            # class (def) attribute case
            return self

        try:
            return obj.m_data[self.__name]
        except KeyError:
            return self.__default

    def __set__(self, obj, value):
1031
1032
        if obj is None:
            # class (def) case
1033
            raise KeyError('Cannot overwrite quantity definition. Only values can be set.')
1034
1035

        # object (instance) case
1036
        obj.m_data[self.__name] = value
1037
1038


1039
1040
1041
1042
1043
1044
class SubSection(Property):
    """ Allows to assign a section class as a sub-section to another section class. """

    sub_section: 'Quantity' = None
    repeats: 'Quantity' = None

1045
    def __get__(self, obj, type=None):
1046
1047
1048
1049
1050
1051
        if obj is None:
            # the class attribute case
            return self

        else:
            # the object attribute case
1052
1053
1054
1055
            if self.repeats:
                return obj.m_get_sub_sections(self)
            else:
                return obj.m_get_sub_section(self, -1)
1056

1057
    def __set__(self, obj, value):
1058
1059
1060
        raise NotImplementedError('Sub sections cannot be set directly. Use m_create.')

    def __delete__(self, obj):
1061
        raise NotImplementedError('Deleting sub sections is not supported.')
1062
1063


1064
class Section(Definition):
1065
1066
1067
    """Used to define section that organize meta-info data into containment hierarchies.

    Section definitions determine what quantities and sub-sections can appear in a section
1068
    instance.
1069

1070
    In Python terms, sections are classes. Sub-sections and quantities are attributes of
1071
1072
1073
1074
1075
1076
    respective instantiating objects. For each section class there is a corresponding
    :class:`Section` instance that describes this class as a section. This instance
    is referred to as 'section definition' in contrast to the Python class that we call
    'section class'.
    """

Markus Scheidgen's avatar
Markus Scheidgen committed
1077
    section_cls: Type[MSection] = None
1078
1079
    """ The section class that corresponse to this section definition. """

1080
1081
    quantities: 'SubSection' = None
    sub_sections: 'SubSection' = None
1082

Markus Scheidgen's avatar
Markus Scheidgen committed
1083
    base_sections: 'Quantity' = None
1084
1085
    # TODO extends = Quantity(type=bool), denotes this section as a container for
    #      new quantities that belong to the base-class section definitions
1086
1087
1088
1089
    @cached_property
    def all_base_sections(self) -> Set['Section']:
        all_base_sections: Set['Section'] = set()
        for base_section in self.base_sections:  # pylint: disable=not-an-iterable
1090
1091
            all_base_sections.add(base_section)

1092
1093
1094
1095
            for base_base_section in base_section.all_base_sections:
                all_base_sections.add(base_base_section)

        return all_base_sections
1096

1097
    @cached_property
1098
    def all_properties(self) -> Dict[str, Union['SubSection', Quantity]]:
1099
        """ All attribute (sub section and quantity) definitions. """
1100

1101
1102
1103
        properties: Dict[str, Union[SubSection, Quantity]] = dict(**self.all_quantities)
        properties.update(**self.all_sub_sections)
        return properties
1104

1105
    @cached_property
1106
    def all_quantities(self) -> Dict[str, Quantity]:
1107
        """ All quantity definition in the given section definition. """
1108

Markus Scheidgen's avatar
Markus Scheidgen committed
1109
        all_quantities: Dict[str, Quantity] = {}
1110
        for section in itertools.chain(self.all_base_sections, [self]):
1111
            for quantity in section.m_get_sub_sections(Section.quantities):
Markus Scheidgen's avatar
Markus Scheidgen committed
1112
1113
1114
                all_quantities[quantity.name] = quantity

        return all_quantities
1115

1116
    @cached_property
1117
1118
    def all_sub_sections(self) -> Dict[str, 'SubSection']:
        """ All sub section definitions for this section definition by name. """
1119

1120
1121
1122
1123
1124
1125
        all_sub_sections: Dict[str, SubSection] = {}
        for section in itertools.chain(self.all_base_sections, [self]):
            for sub_section in section.m_get_sub_sections(Section.sub_sections):
                all_sub_sections[sub_section.name] = sub_section

        return all_sub_sections
1126

1127
1128
1129
    @cached_property
    def all_sub_sections_by_section(self) -> Dict['Section', 'SubSection']:
        """ All sub section definitions for this section definition by their section definition. """
1130
1131
1132
1133
1134
1135
1136

        all_sub_sections: Dict[Section, SubSection] = {}
        for section in itertools.chain(self.all_base_sections, [self]):
            for sub_section in section.m_get_sub_sections(Section.sub_sections):
                all_sub_sections[sub_section.sub_section] = sub_section

        return all_sub_sections
1137

1138

1139
class Package(Definition):
1140

1141
1142
    section_definitions: 'SubSection' = None
    category_definitions: 'SubSection' = None
1143

1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
    @staticmethod
    def from_module(module_name: str):
        module = sys.modules[module_name]

        pkg: 'Package' = getattr(module, 'm_package', None)
        if pkg is None:
            pkg = Package()
            setattr(module, 'm_package', pkg)

        pkg.name = module_name
        if pkg.description is None and module.__doc__ is not None:
1155
            pkg.description = inspect.cleandoc(module.__doc__).strip()
1156
1157

        return pkg
1158
1159


1160
1161
1162
1163
1164
class Category(Definition):
    """Can be used to define categories for definitions.

    Each definition, including categories themselves, can belong to a set of categories.
    Categories therefore form a hierarchy of concepts that definitions can belong to, i.e.
1165
    they form a `is a` relationship.
1166

1167
1168
    In the old meta-info this was known as `abstract types`.
    """
1169
1170
1171
1172
1173
1174

    @cached_property
    def definitions(self) -> Iterable[Definition]:
        """ All definitions that are directly or indirectly in this category. """
        return list([
            definition for definition in Definition.all_definitions()
1175
            if self in definition.all_categories])
1176
1177


Markus Scheidgen's avatar
Markus Scheidgen committed