metainfo.py 114 KB
Newer Older
Markus Scheidgen's avatar
Markus Scheidgen committed
1
2
3
4
#
# Copyright The NOMAD Authors.
#
# This file is part of NOMAD. See https://nomad-lab.eu for further info.
5
6
7
8
9
#
# 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
#
Markus Scheidgen's avatar
Markus Scheidgen committed
10
#     http://www.apache.org/licenses/LICENSE-2.0
11
12
#
# Unless required by applicable law or agreed to in writing, software
Markus Scheidgen's avatar
Markus Scheidgen committed
13
# distributed under the License is distributed on an "AS IS" BASIS,
14
15
16
# 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.
Markus Scheidgen's avatar
Markus Scheidgen committed
17
#
18

19
20
from typing import Type, TypeVar, Union, Tuple, Iterable, List, Any, Dict, Set, \
    Callable as TypingCallable, cast
21
from collections.abc import Iterable as IterableABC, Sequence
22
import sys
23
import inspect
24
import re
25
import json
26
import itertools
27

28
import numpy as np
29
30
31
import pint
import pint.unit
import pint.quantity
32
33
34
import aniso8601
from datetime import datetime
import pytz
35
import docstring_parser
36
import jmespath
37

38
from nomad.units import ureg as units
39

40
41
42

m_package: 'Package' = None

Markus Scheidgen's avatar
Markus Scheidgen committed
43
44
is_bootstrapping = True
MSectionBound = TypeVar('MSectionBound', bound='MSection')
45
T = TypeVar('T')
46

47
48
49
50
51
52
# Make pylint believe all bootstrap quantities are actual properties even though
# we have to initialize them to None due to bootstrapping
_placeholder_quantity: 'Quantity' = property()  # type: ignore
if True:
    _placeholder_quantity: 'Quantity' = None  # type: ignore

53
_primitive_types = {str: str, int: int, float: float, bool: bool, np.bool_: bool}
54

55

Markus Scheidgen's avatar
Markus Scheidgen committed
56
57
# Metainfo errors

58
class MetainfoError(Exception):
59
    ''' Metainfo related errors. '''
60
61
62
    pass


63
class DeriveError(MetainfoError):
64
    ''' An error occurred while computing a derived value. '''
65
66
67
    pass


68
class MetainfoReferenceError(MetainfoError):
69
    ''' An error indicating that a reference could not be resolved. '''
70
    pass
71
72


Markus Scheidgen's avatar
Markus Scheidgen committed
73
# Metainfo quantity data types
74

75
class MEnum(Sequence):
76
    '''Allows to define str types with values limited to a pre-set list of possible values.'''
77
78
    def __init__(self, *args, **kwargs):
        # Supports one big list in place of args
79
        if len(args) == 1 and isinstance(args[0], list):
80
            args = args[0]
81

82
83
84
85
86
87
88
89
        # If non-named arguments are given, the default is to have them placed
        # into a dictionary with their string value as both the enum name and
        # the value.
        for arg in args:
            if arg in kwargs:
                raise ValueError("Duplicate value '{}' provided for enum".format(arg))
            kwargs[arg] = arg

90
        self._list = list(kwargs.values())
91
92
93
94
95
        self._values = set(kwargs.values())  # For allowing constant time member check
        self._map = kwargs

    def __getattr__(self, attr):
        return self._map[attr]
96

97
98
99
100
101
102
    def __getitem__(self, index):
        return self._list[index]

    def __len__(self):
        return len(self._list)

103

104
class MProxy():
105
    ''' A placeholder object that acts as reference to a value that is not yet resolved.
106
107
108

    Attributes:
        url: The reference represented as an URL string.
109
    '''
110

111
    def __init__(
112
            self, m_proxy_value: Union[str, int, dict], m_proxy_section: 'MSection' = None,
113
            m_proxy_quantity: 'Quantity' = None):
114
        self.m_proxy_value = m_proxy_value
115
116
        self.m_proxy_section = m_proxy_section
        self.m_proxy_resolved = None
117
        self.m_proxy_quantity = m_proxy_quantity
118
119

    def m_proxy_resolve(self):
120
121
        if self.m_proxy_section and self.m_proxy_quantity and not self.m_proxy_resolved:
            self.m_proxy_resolved = self.m_proxy_quantity.type.resolve(self)
122
123
124
125
126
127
128
129

        if self.m_proxy_resolved is not None and isinstance(self, MProxy):
            setattr(self, '__class__', self.m_proxy_resolved.__class__)
            self.__dict__.update(**self.m_proxy_resolved.__dict__)

        return self.m_proxy_resolved

    def __getattr__(self, key):
130
        if self.m_proxy_resolve() is not None:
131
132
            return getattr(self.m_proxy_resolved, key)

133
        raise ReferenceError('could not resolve %s' % self.m_proxy_value)
134
135


136
137
138
139
class SectionProxy(MProxy):
    def m_proxy_resolve(self):
        if self.m_proxy_section and not self.m_proxy_resolved:
            root = self.m_proxy_section
140
            while root.m_parent is not None and not isinstance(root, Package):
141
142
143
                root = root.m_parent

            if isinstance(root, Package):
144
                self.m_proxy_resolved = root.all_definitions.get(self.m_proxy_value)
145
146

            if self.m_proxy_resolved is None:
147
                raise ReferenceError('could not resolve %s' % self.m_proxy_value)
148

149
        return self.m_proxy_resolved
150
151


152
class DataType:
153
    '''
154
155
    Allows to define custom data types that can be used in the meta-info.

156
    The metainfo supports the most types out of the box. These includes the python build-in
157
158
    primitive types (int, bool, str, float, ...), references to sections, and enums.
    However, in some occasions you need to add custom data types.
159
160
161
162
163

    This base class lets you customize various aspects of value treatment. This includes
    type checks and various value transformations. This allows to store values in the
    section differently from how the usermight set/get them, and it allows to have non
    serializeable values that are transformed on de-/serialization.
164
    '''
165
    def set_normalize(self, section: 'MSection', quantity_def: 'Quantity', value: Any) -> Any:
166
        ''' Transforms the given value before it is set and checks its type. '''
167
168
169
        return value

    def get_normalize(self, section: 'MSection', quantity_def: 'Quantity', value: Any) -> Any:
170
        ''' Transforms the given value when it is get. '''
171
172
        return value

173
    def serialize(self, section: 'MSection', quantity_def: 'Quantity', value: Any) -> Any:
174
        ''' Transforms the given value when making the section serializeable. '''
175
176
        return value

177
    def deserialize(self, section: 'MSection', quantity_def: 'Quantity', value: Any) -> Any:
178
        ''' Transforms the given value from its serializeable form. '''
179
180
181
        return value


182
183
184
185
186
range_re = re.compile(r'(\d)\.\.(\d|\*)')


class _Dimension(DataType):

187
    def set_normalize(self, section, quantity_def: 'Quantity', value):
188
        if isinstance(value, int):
Markus Scheidgen's avatar
Markus Scheidgen committed
189
            return value
190
191
192

        if isinstance(value, str):
            if value.isidentifier():
Markus Scheidgen's avatar
Markus Scheidgen committed
193
                return value
194
            if re.match(range_re, value):
Markus Scheidgen's avatar
Markus Scheidgen committed
195
                return value
196
197

        if isinstance(value, Section):
Markus Scheidgen's avatar
Markus Scheidgen committed
198
            return value
199

200
        if isinstance(value, type) and hasattr(value, 'm_def'):
Markus Scheidgen's avatar
Markus Scheidgen committed
201
            return value
202

203
        if isinstance(value, str):
204
205
206
207
            # TODO raise a warning or allow this?
            # In the old metainfo there are cases where an expression is used
            # that is later evaluated in the parser
            return value
208

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

211
212
213
214
215
216
217
    @staticmethod
    def check_dimension(section, dimension, length):
        if isinstance(dimension, int):
            return dimension == length
        if isinstance(dimension, str):
            if dimension.isidentifier():
                return dimension == getattr(section, dimension)
218

219
220
221
222
223
224
225
            m = re.match(range_re, dimension)
            start = int(m.group(1))
            end = -1 if m.group(2) == '*' else int(m.group(2))
            return start <= length and (end == -1 or length <= end)


class _Unit(DataType):
226
    def set_normalize(self, section, quantity_def: 'Quantity', value):
227
        if isinstance(value, str):
228
            value = units.parse_units(value)
229

230
        elif not isinstance(value, pint.unit._Unit):
231
232
233
234
            raise TypeError('Units must be given as str or pint Unit instances.')

        return value

235
    def serialize(self, section, quantity_def: 'Quantity', value):
236
237
        return value.__str__()

238
    def deserialize(self, section, quantity_def: 'Quantity', value):
239
        return units.parse_units(value)
Markus Scheidgen's avatar
Markus Scheidgen committed
240
241


242
class _Callable(DataType):
243
244
245
246
247
248
249
    def serialize(self, section, quantity_def: 'Quantity', value):
        raise MetainfoError('Callables cannot be serialized')

    def deserialize(self, section, quantity_def: 'Quantity', value):
        raise MetainfoError('Callables cannot be serialized')


250
class _QuantityType(DataType):
251
    ''' Data type for defining the type of a metainfo quantity.
252
253
254
255
256
257

    A metainfo quantity type can be one of

    - python build-in primitives: int, float, bool, str
    - numpy dtypes, e.g. f, int32
    - a section definition to define references
258
    - an MEnum instance to use it's values as possible str values
259
260
    - a custom datatype, i.e. instance of :class:`DataType`
    - Any
261
    '''
262
263

    def set_normalize(self, section, quantity_def, value):
264
        if value in _primitive_types:
265
266
            return value

267
268
        if isinstance(value, MEnum):
            for enum_value in value._values:
269
                if not isinstance(enum_value, str):
270
                    raise TypeError('MEnum value %s is not a string.' % enum_value)
271
272
            return value

273
        if isinstance(value, np.dtype):
274
275
276
277
278
            return value

        if isinstance(value, Section):
            return value

279
280
281
282
283
284
        if isinstance(value, Reference) and isinstance(value.target_section_def, MProxy):
            proxy = value.target_section_def
            proxy.m_proxy_section = section
            proxy.m_proxy_quantity = quantity_def
            return value

285
286
287
288
289
290
291
292
293
294
295
        if isinstance(value, DataType):
            return value

        if value == Any:
            return value

        if isinstance(value, type):
            section = getattr(value, 'm_def', None)
            if section is not None:
                return Reference(section)

296
297
298
        if isinstance(value, Quantity):
            return QuantityReference(value)

299
        if isinstance(value, MProxy):
300
301
            value.m_proxy_section = section
            value.m_proxy_quantity = quantity_def
302
303
            return value

304
305
306
307
308
        raise MetainfoError(
            'Type %s of %s is not a valid metainfo quantity type' %
            (value, quantity_def))

    def serialize(self, section, quantity_def, value):
309
        if value in _primitive_types:
310
311
            return dict(type_kind='python', type_data=value.__name__)

312
        if isinstance(value, MEnum):
313
314
            return dict(type_kind='Enum', type_data=list(value))

315
        if isinstance(value, np.dtype):
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
            return dict(type_kind='numpy', type_data=str(value))

        if isinstance(value, Reference):
            return dict(type_kind='reference', type_data=value.target_section_def.m_path())

        if isinstance(value, DataType):
            module = value.__class__.__module__
            if module is None or module == str.__class__.__module__:
                type_data = value.__class__.__name__
            else:
                type_data = '%s.%s' % (module, value.__class__.__name__)

            return dict(type_kind='custom', type_data=type_data)

        if value == Any:
            return dict(type_kind='Any')

        raise MetainfoError(
            'Type %s of %s is not a valid metainfo quantity type' %
            (value, quantity_def))


class Reference(DataType):
339
    ''' Datatype used for reference quantities. '''
340

341
    def __init__(self, section_def: Union['Section', 'SectionProxy']):
342
343
        self.target_section_def = section_def

344
345
    def resolve(self, proxy) -> 'MSection':
        '''
346
        Resolve the given proxy. The proxy is guaranteed to have a context and
347
348
        will to be not yet resolved.
        '''
349
        return proxy.m_proxy_section.m_resolve(proxy.m_proxy_value)
350

351
    def set_normalize(self, section: 'MSection', quantity_def: 'Quantity', value: Any) -> Any:
352
353
        if isinstance(self.target_section_def, MProxy):
            proxy = self.target_section_def
354
            proxy.m_proxy_section = section.m_def
355
356
357
            proxy.m_proxy_quantity = quantity_def
            self.target_section_def = proxy.m_proxy_resolve()

358
359
360
361
362
363
364
365
366
        if self.target_section_def.m_follows(Definition.m_def):
            # special case used in metainfo definitions, where we reference metainfo definitions
            # using their Python class. E.g. referencing a section definition using its
            # class instead of the object: Run vs. Run.m_def
            if isinstance(value, type):
                definition = getattr(value, 'm_def', None)
                if definition is not None and definition.m_follows(self.target_section_def):
                    return definition

367
        if isinstance(value, (str, int, dict)):
368
369
            return MProxy(value, m_proxy_section=section, m_proxy_quantity=quantity_def)

370
        if isinstance(value, MProxy):
371
            value.m_proxy_section = section
372
            value.m_proxy_quantity = quantity_def
373
374
375
376
377
378
            return value

        if not isinstance(value, MSection):
            raise TypeError(
                'The value %s is not a section and can not be used as a reference.' % value)

379
        if not value.m_follows(self.target_section_def):  # type: ignore
380
381
382
383
384
385
386
387
388
389
            raise TypeError(
                '%s is not a %s and therefore an invalid value of %s.' %
                (value, self.target_section_def, quantity_def))

        return value

    def serialize(self, section: 'MSection', quantity_def: 'Quantity', value: Any) -> Any:
        return value.m_path()

    def deserialize(self, section: 'MSection', quantity_def: 'Quantity', value: Any) -> Any:
390
        return MProxy(value, m_proxy_section=section, m_proxy_quantity=quantity_def)
391
392


393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
class QuantityReference(Reference):
    ''' Datatype used for reference quantities that reference other quantities. '''

    def __init__(self, quantity_def: Union['Quantity']):
        super().__init__(cast(Section, quantity_def.m_parent))
        self.target_quantity_def = quantity_def

    def get_normalize(self, section: 'MSection', quantity_def: 'Quantity', value: Any) -> Any:
        section = super().get_normalize(section, quantity_def, value)
        return getattr(section, self.target_quantity_def.name)

    def serialize(self, section: 'MSection', quantity_def: 'Quantity', value: Any) -> Any:
        section_path = super().serialize(section, quantity_def, value)
        return f'{section_path}/{self.target_quantity_def.name}'

    def deserialize(self, section: 'MSection', quantity_def: 'Quantity', value: Any) -> Any:
        section_path = value.rsplit('/', 1)[0]
        return MProxy(section_path, m_proxy_section=section, m_proxy_quantity=quantity_def)


413
class _Datetime(DataType):
414

415
    def _parse(self, datetime_str: str) -> datetime:
416
        try:
417
418
419
            return aniso8601.parse_datetime(datetime_str)
        except ValueError:
            pass
420

421
        try:
422
423
424
425
            date = aniso8601.parse_date(datetime_str)
            if isinstance(date, datetime):
                return date
        except ValueError as e:
426
427
428
429
            pass

        try:
            # TODO necessary?
430
            import flask_restplus.inputs
431
432
433
434
            return flask_restplus.inputs.datetime_from_rfc822(datetime_str)
        except ValueError:
            pass

435
436
437
438
439
440
441
442
443
444
        try:
            return datetime.strptime(datetime_str, '%Y-%m-%d %H:%M:%S.%f')
        except ValueError:
            pass

        try:
            return datetime.strptime(datetime_str, '%Y-%m-%d %H:%M:%S')
        except ValueError:
            pass

445
446
447
448
449
        try:
            return datetime.strptime(datetime_str, '%Y-%m-%d')
        except ValueError:
            pass

450
        raise TypeError('Invalid date literal %s' % datetime_str)
451
452

    def _convert(self, value):
453
454
        if value is None:
            return None
455
456

        if isinstance(value, str):
457
458
459
460
            value = self._parse(value)

        elif isinstance(value, (int, float)):
            value = datetime.fromtimestamp(value)
461

462
463
        elif isinstance(value, pint.Quantity):
            value = datetime.fromtimestamp(value.magnitude)
464
465
466
467
468
469

        if not isinstance(value, datetime):
            raise TypeError('%s is not a datetime.' % value)

        return value

470
471
472
    def set_normalize(self, section: 'MSection', quantity_def: 'Quantity', value: Any) -> Any:
        return self._convert(value)

473
    def serialize(self, section: 'MSection', quantity_def: 'Quantity', value: Any) -> Any:
474
475
476
        if value is None:
            return None

477
478
479
480
        value.replace(tzinfo=pytz.utc)
        return value.isoformat()

    def deserialize(self, section: 'MSection', quantity_def: 'Quantity', value: Any) -> Any:
481
        return self._convert(value)
482
483


484
485
486
487
class _JSON(DataType):
    pass


488
489
490
491
492
493
494
495
class _Capitalized(DataType):
    def set_normalize(self, section: 'MSection', quantity_def: 'Quantity', value: Any) -> Any:
        if value is not None and len(value) >= 1:
            return value[0].capitalize() + value[1:]

        return value


496
497
498
499
500
Dimension = _Dimension()
Unit = _Unit()
QuantityType = _QuantityType()
Callable = _Callable()
Datetime = _Datetime()
501
JSON = _JSON()
502
Capitalized = _Capitalized()
503
504


Markus Scheidgen's avatar
Markus Scheidgen committed
505
506
# Metainfo data storage and reflection interface

507
class MObjectMeta(type):
508

509
    def __new__(self, cls_name, bases, dct):
510
511
512
513
514
515
        do_init = dct.get('do_init', None)
        if do_init is not None:
            del(dct['do_init'])
        else:
            do_init = True

516
        cls = super().__new__(self, cls_name, bases, dct)
Markus Scheidgen's avatar
Markus Scheidgen committed
517

Markus Scheidgen's avatar
Markus Scheidgen committed
518
        init = getattr(cls, '__init_cls__')
519
        if init is not None and do_init and not is_bootstrapping:
520
521
            init()
        return cls
522
523


524
SectionDef = Union[str, 'Section', 'SubSection', Type[MSectionBound]]
525
''' Type for section definition references.
526
527
528
529
530
531
532

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
533
'''
534
535


536
537
538
539
540
541
def constraint(warning):
    ''' A decorator for methods implementing constraints. '''
    f = None
    if not isinstance(warning, bool):
        f = warning
        warning = False
542

543
544
545
546
    def decorator(f):
        setattr(f, 'm_constraint', True)
        setattr(f, 'm_warning', warning)
        return f
547

548
549
550
551
    if f is None:
        return decorator
    else:
        return decorator(f)
552
553


554
class MResource():
555
    '''
556
557
    Represents a collection of related metainfo data, i.e. a set of :class:`MSection` instances.
    '''
558

559
    def __init__(self, logger=None):
560
561
        self.__data: Dict['Section', List['MSection']] = dict()
        self.contents: List['MSection'] = []
562
        self.logger = logger
563
564

    def create(self, section_cls: Type[MSectionBound], *args, **kwargs) -> MSectionBound:
565
566
567
568
569
570
571
572
573
574
        '''
        Create an instance of the given section class and adds it to this resource as
        a root section. The m_parent_index will be set sequentially among root sections of
        the same section definition starting with 0.
        '''
        index = 0
        for content in self.contents:
            if content.m_follows(section_cls.m_def):
                index = max(index, content.m_parent_index + 1)

575
        result = section_cls(*args, **kwargs)
576
577
        result.m_parent_index = index

578
579
580
581
        self.add(result)
        return cast(MSectionBound, result)

    def add(self, section):
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
        '''
        Add the given section to this resource. Will also add all its contents to the
        resource and make all contest available for :func:`all`. Will also remove
        all contents from possible other resources. A section can only be contained in
        one resource at a time.

        This is potentially expensive. Do not add a section that already has a deep tree
        of sub-sections. Ideally, add the root section first. If you create sub sections
        afterwards, they will be automatically added to this resource.
        '''
        if section.m_resource is not None:
            section.m_resource.remove(section)

        for content in section.m_all_contents(include_self=True):
            content.m_resource = self
            self.__data.setdefault(content.m_def, []).append(content)

599
600
601
602
603
604
605
        if section.m_parent is None:
            self.contents.append(section)

    def remove(self, section):
        assert section.m_resource == self, 'Can only remove section from the resource that contains it.'
        section.m_resource = None
        self.__data.get(section.m_def).remove(section)
606
        if section.m_parent is None:
607
608
609
            self.contents.remove(section)

    def all(self, section_cls: Type[MSectionBound]) -> List[MSectionBound]:
610
        ''' Returns all instances of the given section class in this resource. '''
611
612
613
        return cast(List[MSectionBound], self.__data.get(section_cls.m_def, []))

    def unload(self):
614
        ''' Breaks all references among the contain metainfo sections to allow GC. '''
615
616
617
        for collections in self.__data.values():
            for section in collections:
                section.m_parent = None
618
                section.__dict__.clear()
619
620
            collections.clear()

621
622
623
624
    def m_to_dict(self, filter: TypingCallable[['MSection'], bool] = None):
        if filter is None:
            def filter(_):  # pylint: disable=function-redefined
                return True
625

626
627
628
629
        return {
            section.m_def.name: section.m_to_dict()
            for section in self.contents
            if filter(section)}
630

631
632
633
634
    def warning(self, *args, **kwargs):
        if self.logger is not None:
            self.logger.warn(*args, **kwargs)

635

636
class MSection(metaclass=MObjectMeta):  # TODO find a way to make this a subclass of collections.abs.Mapping
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
    '''
    The base-class for all *section defining classes* and respectively the base-class
    for all section objects.

    While we use *section classes* to *define sections*, it is important to note that
    the *section class* is a different Python object than the actual *section definition*.
    For each *section class* (a Python class), we automatically generate a *section definition*
    Python object that instantiates :class:`Section`. :class:`MSection` and :class:`Section`
    are completely different classes. :class:`MSection` is used as a base-class for all
    *section defining* classes and :class:`Section` is a *section class* that defines the
    section `Section`.

    Attributes:
        m_def: Each *section class* (and also *section instance*) has a build-in
            property ``m_def`` that refers to the actual *section definition*. While this defined
            automatically, you can do it manually to provide additional characteristics that cannot
            be covered in a Python class definition.
654

655
656
657
658
659
    All `section instances` indirectly instantiate the :class:`MSection` and therefore all
    members of :class:`MSection` are available on all `section instances`. :class:`MSection`
    provides many special attributes and functions (they all start with ``m_``) that allow
    to reflect on a `section's definition` and allow to manipulate the `section instance`
    without a priori knowledge of the `section defintion`.
660

661
662
663
664
665
666
667
    .. automethod:: m_set
    .. automethod:: m_get
    .. automethod:: m_add_values
    .. automethod:: m_get_sub_section
    .. automethod:: m_get_sub_sections
    .. automethod:: m_create
    .. automethod:: m_add_sub_section
668
    .. automethod:: m_remove_sub_section
669
670
671
672
673
674

    There are some specific attributes for section instances that are sub-sections of
    another section. While sub-sections are directly accessible from the containing
    section by using the Python property that represents the sub-section (e.g.
    `run.section_system`), there is also a way to navigate from the sub-section to
    the containing section (`parent section`) using these Python properties:
675

676
677
678
    Attributes:
        m_parent:
            If this section is a sub-section, this references the parent section instance.
679

680
681
682
        m_parent_sub_section:
            If this section is a sub-section, this is the :class:`SubSection` that defines
            this relationship.
683

684
685
686
687
        m_parent_index:
            For repeatable sections, parent keep a list of sub-sections. This is the index
            of this section in the respective parent sub-section list.

688
689
        m_resource: The :class:`MResource` that contains and manages this section.

690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
    Often some general tasks have to be performed on a whole tree of sections without
    knowing about the definitions in advance. The following methods allow to access
    sub-sections reflectively.

    .. automethod:: m_traverse
    .. automethod:: m_all_contents
    .. automethod:: m_contents
    .. automethod:: m_xpath

    Each section and all its quantities and contents can be transformed into a general
    JSON-serializable Python dictionary. Similarely, a section can be instantiated from
    such a Python dictionary. This allows to save and load sections to JSON-files or
    by other compatible means (e.g. document databases, binary JSON flavours).

    .. automethod:: m_to_dict
    .. automethod:: m_from_dict
    .. automethod:: m_update_from_dict
    .. automethod:: m_to_json
708
    '''
709

710
    m_def: 'Section' = None
711

712
    def __init__(
713
            self, m_def: 'Section' = None, m_resource: MResource = None, **kwargs):
714

715
        self.m_def: 'Section' = m_def
716
717
        self.m_parent: 'MSection' = None
        self.m_parent_sub_section: 'SubSection' = None
718
        self.m_parent_index = -1
719
        self.m_resource = m_resource
720
        self.m_mod_count = 0
721
        self.m_cache: dict = {}  # Dictionary for caching temporary values that are not persisted to the Archive
722

723
        # get missing m_def from class
724
        cls = self.__class__
725
726
        if self.m_def is None:
            self.m_def = cls.m_def
727

728
        # check m_def
729
        if cls.m_def is not None:
730
731
732
733
734
735
736
737
738
            if self.m_def != cls.m_def:
                MetainfoError('Section class and section definition must match.')

            if self.m_def.extends_base_section:
                MetainfoError('Section extends another section and cannot be instantiated.')

        else:
            if not is_bootstrapping:
                MetainfoError('Section has not m_def.')
739

740
        # get annotations from kwargs
741
        self.m_annotations: Dict[str, Any] = {}
742
        other_kwargs = {}
743
744
745
746
        for key, value in kwargs.items():
            if key.startswith('a_'):
                self.m_annotations[key[2:]] = value
            else:
747
                other_kwargs[key] = value
Markus Scheidgen's avatar
Markus Scheidgen committed
748

749
750
        # get additional annotations from the section definition
        if not is_bootstrapping:
751
            for section_annotation in self.m_def.m_get_annotations(SectionAnnotation, as_list=True):
752
753
754
755
756
757
                for name, annotation in section_annotation.new(self).items():
                    self.m_annotations[name] = annotation

        # add annotation attributes for names annotations
        for annotation_name, annotation in self.m_annotations.items():
            setattr(self, 'a_%s' % annotation_name, annotation)
758

759
760
        # set remaining kwargs
        if is_bootstrapping:
761
            self.__dict__.update(**other_kwargs)  # type: ignore
Markus Scheidgen's avatar
Markus Scheidgen committed
762
        else:
763
            self.m_update(**other_kwargs)
764

765
    @classmethod
Markus Scheidgen's avatar
Markus Scheidgen committed
766
    def __init_cls__(cls):
767
        # ensure that the m_def is defined
768
        m_def = cls.__dict__.get('m_def')  # do not accedentally get the m_def from a potential base section
Markus Scheidgen's avatar
Markus Scheidgen committed
769
        if m_def is None:
770
771
            m_def = Section()
            setattr(cls, 'm_def', m_def)
772

773
774
775
        # Use class name if name is not explicitly defined
        if m_def.name is None:
            m_def.name = cls.__name__
776
        m_def._section_cls = cls
777

778
        # add base sections
779
780
781
782
783
784
785
786
787
        base_sections: List[Section] = []
        for base_cls in cls.__bases__:
            if base_cls != MSection:
                base_section = getattr(base_cls, 'm_def')
                if base_section is None:
                    raise TypeError(
                        'Section defining classes must have MSection or a decendant as '
                        'base classes.')
                base_sections.append(base_section)
788

789
        m_def.m_set(Section.base_sections, base_sections)
790

791
        # transfer names, descriptions, constraints, event_handlers
792
793
        constraints: Set[str] = set()
        event_handlers: Set[Callable] = set(m_def.event_handlers)
794
        for name, attr in cls.__dict__.items():
795
            # transfer names and descriptions for properties, init properties
796
            if isinstance(attr, Property):
797
                attr.name = name
798
                if attr.description is not None:
799
800
801
802
803
804
805
                    description = inspect.cleandoc(attr.description)
                    description = description.strip()
                    description = re.sub(
                        r'\(https?://[^\)]*\)',
                        lambda m: re.sub(r'\n', '', m.group(0)),
                        description)
                    attr.description = description
806
                    attr.__doc__ = attr.description
807

808
                if isinstance(attr, Quantity):
809
                    m_def.m_add_sub_section(Section.quantities, attr)
810
                elif isinstance(attr, SubSection):
811
                    m_def.m_add_sub_section(Section.sub_sections, attr)
812
813
                else:
                    raise NotImplementedError('Unknown property kind.')
814

815
816
817
818
            if inspect.isfunction(attr):
                method_name = attr.__name__

                # transfer constraints
819
820
                if getattr(attr, 'm_constraint', False):
                    constraint = method_name
821
822
823
824
825
826
827
828
829
830
831
832
833
                    constraints.add(constraint)

                # register event_handlers from event_handler methods
                if method_name.startswith('on_set') or method_name.startswith('on_add_sub_section'):
                    if attr not in event_handlers:
                        event_handlers.add(attr)

        # add handler and constraints from base sections
        for base_section in m_def.all_base_sections:
            for constraint in base_section.constraints:
                constraints.add(constraint)
            for event_handler in base_section.event_handlers:
                event_handlers.add(event_handler)
Markus Scheidgen's avatar
Markus Scheidgen committed
834

835
836
        m_def.constraints = list(constraints)
        m_def.event_handlers = list(event_handlers)
Markus Scheidgen's avatar
Markus Scheidgen committed
837

838
839
840
        # add section cls' section to the module's package
        module_name = cls.__module__
        pkg = Package.from_module(module_name)
841
        pkg.m_add_sub_section(Package.section_definitions, cls.m_def)
842

843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
        # apply_google_docstrings
        # Parses the google doc string of the given class and properly updates the
        # definition descriptions.

        # This allows to document quantities and sub-sections with 'Args:' in the section
        # class. It will remove the 'Args' section from the section definition and will
        # set the respective pieces to the quantity and sub-section descriptions.
        docstring = cls.__doc__
        if docstring is not None:
            parsed_docstring = docstring_parser.parse(docstring)
            short = parsed_docstring.short_description
            dsc = parsed_docstring.long_description

            if short and dsc:
                description = '%s %s' % (short.strip(), dsc.strip())
            elif short:
                description = short.strip()
            elif dsc:
                description = dsc.strip()
            else:
                description = None

            if m_def.description is None:
                m_def.description = description

            for param in parsed_docstring.params:
                prop = m_def.all_properties.get(param.arg_name)
                if prop is not None:
                    if prop.description is None:
                        prop.description = param.description

874
875
        for content in m_def.m_all_contents(depth_first=True, include_self=True):
            cast(Definition, content).__init_metainfo__()
876

877
878
879
880
881
882
883
884
885
886
    def __setattr__(self, name, value):
        all_aliases = None
        if self.m_def is not None:
            all_aliases = self.m_def.all_aliases

        if all_aliases is not None and name in self.m_def.all_aliases:
            name = self.m_def.all_aliases[name].name

        return super().__setattr__(name, value)

887
    def __getattr__(self, name):
888
889
        # The existence of __getattr__ will make mypy and pylint ignore 'missing' dynamic
        # attributes and functions and wrong types of those.
890
        # Ideally we have a plugin for both that add the corrent type info
891
892
893
894

        if name in self.m_def.all_aliases:
            return getattr(self, self.m_def.all_aliases[name].name)

895
        raise AttributeError(name)
896
897
898
899
900
901
902
903

    def __check_np(self, quantity_def: 'Quantity', value: np.ndarray) -> np.ndarray:
        # TODO this feels expensive, first check, then possible convert very often?
        # if quantity_ref.type != value.dtype:
        #     raise MetainfoError(
        #         'Quantity dtype %s and value dtype %s do not match.' %
        #         (quantity_ref.type, value.dtype))

904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
        return value

    def __set_normalize(self, quantity_def: 'Quantity', value: Any) -> Any:

        if isinstance(quantity_def.type, DataType):
            return quantity_def.type.set_normalize(self, quantity_def, value)

        elif isinstance(quantity_def.type, Section):
            if isinstance(value, MProxy):
                return value

            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))

925
926
        elif isinstance(quantity_def.type, MEnum):
            if value not in quantity_def.type._values:
927
928
929
930
931
932
933
                raise TypeError(
                    'The value %s is not an enum value for quantity %s.' %
                    (value, quantity_def))

        elif quantity_def.type == Any:
            pass

934
935
936
937
938
939
        elif quantity_def.type == str and type(value) == np.str_:
            return str(value)

        elif quantity_def.type == bool and type(value) == np.bool_:
            return bool(value)

940
        else:
941
            if value is not None and type(value) != quantity_def.type:
942
943
944
945
946
947
                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

948
949
950
951
952
953
    def __to_np(self, quantity_def: 'Quantity', value):
        if isinstance(value, pint.quantity._Quantity):
            if quantity_def.unit is None:
                raise MetainfoError(
                    'The quantity %s has not a unit, but value %s has.' %
                    (quantity_def, value))
954
955
956
957

            if type(value.magnitude) == np.ndarray and quantity_def.type != value.dtype:
                value = value.astype(quantity_def.type)

958
959
            value = value.to(quantity_def.unit).magnitude

960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
        if type(value) != np.ndarray:
            if len(quantity_def.shape) > 0:
                try:
                    value = np.asarray(value)
                except TypeError:
                    raise TypeError(
                        'Could not convert value %s of %s to a numpy array' %
                        (value, quantity_def))
            elif type(value) != quantity_def.type.type:
                try:
                    value = quantity_def.type.type(value)
                except TypeError:
                    raise TypeError(
                        'Could not convert value %s of %s to a numpy scalar' %
                        (value, quantity_def))
975
976
977

        return self.__check_np(quantity_def, value)

978
    def m_set(self, quantity_def: 'Quantity', value: Any) -> None:
979
        ''' Set the given value for the given quantity. '''
980
        self.m_mod_count += 1
981

982
983
        if quantity_def.derived is not None:
            raise MetainfoError('The quantity %s is derived and cannot be set.' % quantity_def)
984

985
986
987
988
989
990
        if value is None:
            # This implements the implicit "unset" semantics of assigned None as a
            # value
            self.__dict__.pop(quantity_def.name, None)
            return

991
        if isinstance(quantity_def.type, np.dtype):
992
            value = self.__to_np(quantity_def, value)
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009

        else:
            dimensions = len(quantity_def.shape)
            if dimensions == 0:
                value = self.__set_normalize(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.__set_normalize(quantity_def, item) for item in value)

            else:
                raise MetainfoError(
                    'Only numpy arrays and dtypes can be used for higher dimensional '
1010
                    'quantities: %s' % quantity_def)
1011

1012
        self.__dict__[quantity_def.name] = value
1013

1014
1015
1016
1017
        for handler in self.m_def.event_handlers:
            if handler.__name__.startswith('on_set'):
                handler(self, quantity_def, value)

1018
    def m_get(self, quantity_def: 'Quantity') -> Any:
1019
        ''' Retrieve the given value for the given quantity. '''
1020
        return quantity_def.__get__(self, Quantity)
1021

1022
    def m_is_set(self, quantity_def: 'Quantity') -> bool:
1023
        ''' True if the given quantity is set. '''
1024
1025
1026
        if quantity_def.derived is not None:
            return True

1027
        return quantity_def.name in self.__dict__
Markus Scheidgen's avatar
Markus Scheidgen committed
1028