metainfo.py 69.6 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
from typing import Type, TypeVar, Union, Tuple, Iterable, List, Any, Dict, Set, \
    Callable as TypingCallable, cast
17
from collections.abc import Iterable as IterableABC
18
import sys
19
import inspect
20
import re
21
import json
22
import itertools
23

24
import numpy as np
25
26
from pint.unit import _Unit
from pint import UnitRegistry
27
28
29
import aniso8601
from datetime import datetime
import pytz
30

31
32
33

m_package: 'Package' = None

Markus Scheidgen's avatar
Markus Scheidgen committed
34
35
is_bootstrapping = True
MSectionBound = TypeVar('MSectionBound', bound='MSection')
36
T = TypeVar('T')
37

38

Markus Scheidgen's avatar
Markus Scheidgen committed
39
40
# Metainfo errors

41
class MetainfoError(Exception):
42
    """ Metainfo related errors. """
43
44
45
    pass


46
47
48
49
50
class DeriveError(MetainfoError):
    """ An error occurred while computing a derived value. """
    pass


51
52
class MetainfoReferenceError(MetainfoError):
    """ An error indicating that a reference could not be resolved. """
53
    pass
54
55


Markus Scheidgen's avatar
Markus Scheidgen committed
56
# Metainfo quantity data types
57

58
class Enum(list):
59
    """ Allows to define str types with values limited to a pre-set list of possible values. """
60
61
62
63
64
65
    def __init__(self, *args):
        if len(args) == 1 and isinstance(args[0], list):
            super().__init__(args[0])

        else:
            super().__init__(args)
66
67


68
class MProxy():
69
70
71
72
73
    """ A placeholder object that acts as reference to a value that is not yet resolved.

    Attributes:
        url: The reference represented as an URL string.
    """
74
75
76
77
78

    def __init__(self, url: str):
        self.url = url


79
80
81
82
class DataType:
    """
    Allows to define custom data types that can be used in the meta-info.

83
    The metainfo supports the most types out of the box. These includes the python build-in
84
85
    primitive types (int, bool, str, float, ...), references to sections, and enums.
    However, in some occasions you need to add custom data types.
86
87
88
89
90

    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.
91
    """
92
93
94
95
96
97
    def set_normalize(self, section: 'MSection', quantity_def: 'Quantity', value: Any) -> Any:
        """ Transforms the given value before it is set and checks its type. """
        return value

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

100
101
    def serialize(self, section: 'MSection', quantity_def: 'Quantity', value: Any) -> Any:
        """ Transforms the given value when making the section serializeable. """
102
103
        return value

104
105
    def deserialize(self, section: 'MSection', quantity_def: 'Quantity', value: Any) -> Any:
        """ Transforms the given value from its serializeable form. """
106
107
108
        return value


109
110
class __Dimension(DataType):
    def set_normalize(self, section, quantity_def: 'Quantity', value):
111
        if isinstance(value, int):
Markus Scheidgen's avatar
Markus Scheidgen committed
112
            return value
113
114
115

        if isinstance(value, str):
            if value.isidentifier():
Markus Scheidgen's avatar
Markus Scheidgen committed
116
                return value
117
            if re.match(r'(\d)\.\.(\d|\*)', value):
Markus Scheidgen's avatar
Markus Scheidgen committed
118
                return value
119
120

        if isinstance(value, Section):
Markus Scheidgen's avatar
Markus Scheidgen committed
121
            return value
122

123
        if isinstance(value, type) and hasattr(value, 'm_def'):
Markus Scheidgen's avatar
Markus Scheidgen committed
124
            return value
125
126
127
128

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


129
130
class __Unit(DataType):
    def set_normalize(self, section, quantity_def: 'Quantity', value):
131
132
133
134
135
136
137
138
        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

139
    def serialize(self, section, quantity_def: 'Quantity', value):
140
141
        return value.__str__()

142
    def deserialize(self, section, quantity_def: 'Quantity', value):
143
144
        return units.parse_units(value)

145

Markus Scheidgen's avatar
Markus Scheidgen committed
146
147
148
149
units = UnitRegistry()
""" The default pint unit registry that should be used to give units to quantity definitions. """


150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
class __Callable(DataType):
    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')


class __QuantityType(DataType):
    """ Data type for defining the type of a metainfo quantity.

    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
    - an Enum instance to use it's values as possible str values
    - a custom datatype, i.e. instance of :class:`DataType`
    - Any
    """

    def set_normalize(self, section, quantity_def, value):
        if value in [str, int, float, bool]:
            return value

        if isinstance(value, Enum):
            for enum_value in value:
                if not isinstance(enum_value, str):
                    raise TypeError('Enum value %s is not a string.' % enum_value)
            return value

        if type(value) == np.dtype:
            return value

        if isinstance(value, Section):
            return value

        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)

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

    def serialize(self, section, quantity_def, value):
        if value in [str, int, float, bool]:
            return dict(type_kind='python', type_data=value.__name__)

        if isinstance(value, Enum):
            return dict(type_kind='Enum', type_data=list(value))

        if type(value) == np.dtype:
            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):
    """ Datatype used for reference quantities. """

    def __init__(self, section_def: 'Section'):
        if not isinstance(section_def, Section):
            raise MetainfoError('%s is not a section definition.' % section_def)
        self.target_section_def = section_def

    def set_normalize(self, section: 'MSection', quantity_def: 'Quantity', value: Any) -> Any:
        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

        if isinstance(value, MProxy):
            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)

        if not value.m_follows(self.target_section_def):
            raise TypeError(
                '%s is not a %s and therefore an invalid value of %s.' %
                (value, self.target_section_def, quantity_def))

        return value

    def get_normalize(self, section: 'MSection', quantity_def: 'Quantity', value: Any) -> Any:
        if isinstance(value, MProxy):
            resolved: 'MSection' = section.m_resolve(value.url)
            if resolved is None:
                raise ReferenceError('Could not resolve %s from %s.' % (value, section))
            section.m_set(quantity_def, value)
            return resolved

        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:
        return MProxy(value)


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
class __Datetime(DataType):

    def __parse(self, datetime_str: str) -> datetime:
        try:
            try:
                return aniso8601.parse_datetime(datetime_str)
            except ValueError:
                date = aniso8601.parse_date(datetime_str)
                return datetime(date.year, date.month, date.day)
        except Exception:
            raise TypeError('Invalid date literal "{0}"'.format(datetime_str))

    def set_normalize(self, section: 'MSection', quantity_def: 'Quantity', value: Any) -> Any:
        if isinstance(value, str):
            value = self.__parse(value)

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

        return value

    def serialize(self, section: 'MSection', quantity_def: 'Quantity', value: Any) -> Any:
        value.replace(tzinfo=pytz.utc)
        return value.isoformat()

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


310
311
312
313
Dimension = __Dimension()
Unit = __Unit()
QuantityType = __QuantityType()
Callable = __Callable()
314
Datetime = __Datetime()
315
316


Markus Scheidgen's avatar
Markus Scheidgen committed
317
318
# Metainfo data storage and reflection interface

319
class MObjectMeta(type):
320

321
322
    def __new__(self, cls_name, bases, dct):
        cls = super().__new__(self, cls_name, bases, dct)
Markus Scheidgen's avatar
Markus Scheidgen committed
323

Markus Scheidgen's avatar
Markus Scheidgen committed
324
325
        init = getattr(cls, '__init_cls__')
        if init is not None and not is_bootstrapping:
326
327
            init()
        return cls
328
329


330
Content = Tuple['MSection', int, 'SubSection', 'MSection']
331
332
333
334
335
336
337
338
339
340
341

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
"""
342
343


344
345
346
347
348
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.
349
    Different implementations of this interface, can realize different storage backends.
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

    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 MDataDict(MData):
403
    """ A simple dict backed implementaton of :class:`MData`. It is used by default. """
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

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


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

480
481
482
483
484
    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`.
485
486
487
488

    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.

489
490
491
    Attributes:
        m_def: The `section definition` that this `section instance` follows as a
            :class:`Section` object.
492

493
494
        m_parent:
            If this section is a sub-section, this references the parent section instance.
495

496
497
498
        m_parent_sub_section:
            If this section is a sub-section, this is the :class:`SubSection` that defines
            this relationship.
499

500
501
502
503
504
505
506
        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.

        m_data: The :class:`MData` implementations that stores the section data. It keeps
            the quantity values and sub-section. It should only be read directly
            (and never manipulated).
507
508
509

    """

510
    m_def: 'Section' = None
511

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

514
        self.m_def: 'Section' = m_def
515
516
        self.m_parent: 'MSection' = None
        self.m_parent_sub_section: 'SubSection' = None
517
        self.m_parent_index = -1
518

519
        # get missing m_def from class
520
        cls = self.__class__
521
522
        if self.m_def is None:
            self.m_def = cls.m_def
523

524
        # check m_def
525
        if cls.m_def is not None:
526
527
528
529
530
531
532
533
534
            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.')
535

536
        # get annotations from kwargs
537
        self.m_annotations: Dict[str, Any] = {}
Markus Scheidgen's avatar
Markus Scheidgen committed
538
        rest = {}
539
540
541
542
        for key, value in kwargs.items():
            if key.startswith('a_'):
                self.m_annotations[key[2:]] = value
            else:
Markus Scheidgen's avatar
Markus Scheidgen committed
543
544
                rest[key] = value

545
546
547
        # initialize data
        self.m_data = m_data
        if self.m_data is None:
548
            self.m_data = MDataDict()
549

550
551
        # set remaining kwargs
        if is_bootstrapping:
552
            self.m_data.dct.update(**rest)  # type: ignore
Markus Scheidgen's avatar
Markus Scheidgen committed
553
        else:
554
            self.m_update(**rest)
555

556
    @classmethod
Markus Scheidgen's avatar
Markus Scheidgen committed
557
    def __init_cls__(cls):
558
559
        # ensure that the m_def is defined
        m_def = cls.m_def
Markus Scheidgen's avatar
Markus Scheidgen committed
560
        if m_def is None:
561
562
            m_def = Section()
            setattr(cls, 'm_def', m_def)
563

564
565
        # transfer name and description to m_def
        m_def.name = cls.__name__
566
        if cls.__doc__ is not None:
567
            m_def.description = inspect.cleandoc(cls.__doc__).strip()
568
        m_def.section_cls = cls
569

570
571
572
573
574
575
576
        # add base sections
        if m_def.extends_base_section:
            base_sections_count = len(cls.__bases__)
            if base_sections_count == 0:
                raise MetainfoError(
                    'Section %s extend the base section, but has no base section.' % m_def)

Markus Scheidgen's avatar
Markus Scheidgen committed
577
            if base_sections_count > 1:
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
                raise MetainfoError(
                    'Section %s extend the base section, but has more than one base section' % m_def)

            base_section_cls = cls.__bases__[0]
            base_section = getattr(base_section_cls, 'm_def', None)
            if base_section is None:
                raise MetainfoError(
                    'The base section of %s is not a section class.' % m_def)

            for name, attr in cls.__dict__.items():
                if isinstance(attr, Property):
                    setattr(base_section_cls, name, attr)

            section_to_add_properties_to = base_section
        else:
            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 = list(m_def.m_get(Section.base_sections))
                    base_sections.append(base_section)
                    m_def.m_set(Section.base_sections, base_sections)

            section_to_add_properties_to = m_def

607
608
        constraints: Set[str] = set()
        event_handlers: Set[Callable] = set(m_def.event_handlers)
609
        for name, attr in cls.__dict__.items():
610
611
            # transfer names and descriptions for properties
            if isinstance(attr, Property):
612
                attr.name = name
613
                if attr.description is not None:
614
                    attr.description = inspect.cleandoc(attr.description).strip()
615
                    attr.__doc__ = attr.description
616

617
                if isinstance(attr, Quantity):
618
                    section_to_add_properties_to.m_add_sub_section(Section.quantities, attr)
619
                elif isinstance(attr, SubSection):
620
                    section_to_add_properties_to.m_add_sub_section(Section.sub_sections, attr)
621
622
                else:
                    raise NotImplementedError('Unknown property kind.')
623

624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
            if inspect.isfunction(attr):
                method_name = attr.__name__

                # transfer constraints
                if method_name.startswith('c_'):
                    constraint = method_name[2:]
                    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
643

644
645
        m_def.constraints = list(constraints)
        m_def.event_handlers = list(event_handlers)
Markus Scheidgen's avatar
Markus Scheidgen committed
646

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

652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
    def __check_np(self, quantity_ref: 'Quantity', value: np.ndarray) -> np.ndarray:
        # TODO
        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))

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

692
693
694
695
    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
696

697
698
699
    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)
700

701
702
        if quantity_def.derived is not None:
            raise MetainfoError('The quantity %s is derived and cannot be set.' % quantity_def)
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732

        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.__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 '
                    'quantities.')

733
        self.m_data.m_set(self, quantity_def, value)
734

735
736
737
738
        for handler in self.m_def.event_handlers:
            if handler.__name__.startswith('on_set'):
                handler(self, quantity_def, value)

739
740
741
    def m_get(self, quantity_def: 'Quantity') -> Any:
        """ Retrieve the given value for the given quantity. """
        quantity_def = self.__resolve_synonym(quantity_def)
742
743
744
745
746
747
        if quantity_def.derived is not None:
            try:
                return quantity_def.derived(self)
            except Exception as e:
                raise DeriveError('Could not derive value for %s: %s' % (quantity_def, str(e)))

748
749
        value = self.m_data.m_get(self, quantity_def)

750
751
752
753
754
755
756
757
758
759
760
761
762
763
        if isinstance(quantity_def.type, DataType) and quantity_def.type.get_normalize != DataType.get_normalize:
            dimensions = len(quantity_def.shape)
            if dimensions == 0:
                value = quantity_def.type.get_normalize(self, quantity_def, value)

            elif dimensions == 1:
                value = list(
                    quantity_def.type.get_normalize(self, quantity_def, item)
                    for item in value)

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

        return value
766

767
    def m_is_set(self, quantity_def: 'Quantity') -> bool:
768
        """ True if the given quantity is set. """
769
        quantity_def = self.__resolve_synonym(quantity_def)
770
771
772
        if quantity_def.derived is not None:
            return True

773
        return self.m_data.m_is_set(self, quantity_def)
Markus Scheidgen's avatar
Markus Scheidgen committed
774

775
776
777
    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)
778

779
780
    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
781

782
        parent_index = -1
783
        if sub_section_def.repeats:
784
785
786
787
            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
788

789
        self.m_data.m_add_sub_section(self, sub_section_def, sub_section)
790

791
792
793
794
        for handler in self.m_def.event_handlers:
            if handler.__name__.startswith('on_add_sub_section'):
                handler(self, sub_section_def, sub_section)

795
796
797
    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)
798

799
800
801
    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)
802

803
804
805
    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)
806

807
808
809
    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.
810
        """
811

812
813
814
        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:
815
            raise TypeError('There is no sub section to hold a %s in %s.' % (section_def, self.m_def))
816

817
818
        sub_section = section_cls(**kwargs)
        self.m_add_sub_section(sub_section_def, sub_section)
819

820
        return cast(MSectionBound, sub_section)
821

822
    def m_update(self, safe: bool = True, **kwargs):
823
        """ Updates all quantities and sub-sections with the given arguments. """
824
825
826
827
828
829
830
831
832
833
834
835
836
        if safe:
            for name, value in kwargs.items():
                prop = self.m_def.all_properties.get(name, None)
                if prop is None:
                    raise KeyError('%s is not an attribute of this section %s' % (name, self))

                if isinstance(prop, SubSection):
                    if prop.repeats:
                        if isinstance(value, List):
                            for item in value:
                                self.m_add_sub_section(prop, item)
                        else:
                            raise TypeError('Sub section %s repeats, but no list was given' % prop.name)
837
                    else:
838
839
                        self.m_add_sub_section(prop, item)

840
                else:
841
                    self.m_set(prop, value)
842

843
844
        else:
            self.m_data.m_data.dct.update(**kwargs)  # type: ignore
845

846
847
848
849
    def m_as(self, section_cls: Type[MSectionBound]) -> MSectionBound:
        """ 'Casts' this section to the given extending sections. """
        return cast(MSectionBound, self)

850
    def m_follows(self, definition: 'Section') -> bool:
851
        """ Determines if this section's definition is or is derived from the given definition. """
852
        return self.m_def == definition or definition in self.m_def.all_base_sections
853

854
    def m_to_dict(self, with_meta: bool = False) -> Dict[str, Any]:
855
        """Returns the data of this section as a json serializeable dictionary. """
856
857

        def items() -> Iterable[Tuple[str, Any]]:
858
859
860
861
862
863
864
865
866
            # metadata
            if with_meta:
                yield 'm_def', self.m_def.name
                if self.m_parent_index != -1:
                    yield 'm_parent_index', self.m_parent_index
                if self.m_parent_sub_section is not None:
                    yield 'm_parent_sub_section', self.m_parent_sub_section.name

            # quantities
867
            for name, quantity in self.m_def.all_quantities.items():
868
869
870
                if quantity.virtual:
                    continue

871
                if self.m_is_set(quantity) and quantity.derived is None:
872
                    serialize: TypingCallable[[Any], Any] = str
873
                    if isinstance(quantity.type, DataType):
874
875

                        def data_type_serialize(value):
Markus Scheidgen's avatar
Markus Scheidgen committed
876
                            return quantity.type.serialize(self, quantity, value)
877
878

                        serialize = data_type_serialize
879

880
                    elif quantity.type in [str, int, float, bool]:
881
                        serialize = quantity.type
882

883
                    elif type(quantity.type) == np.dtype:
884
885
                        pass

886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
                    elif isinstance(quantity.type, Enum):
                        pass

                    elif quantity.type == Any:
                        def _serialize(value: Any):
                            if type(value) not in [str, int, float, bool, list, type(None)]:
                                raise MetainfoError(
                                    'Only python primitives are allowed for Any typed non '
                                    'virtual quantities: %s of quantity %s in section %s' %
                                    (value, quantity, self))

                            return value

                        serialize = _serialize

                    else:
                        raise MetainfoError(
                            'Do not know how to serialize data with type %s for quantity %s' %
                            (quantity.type, quantity))

906
                    value = getattr(self, name)
907

908
                    if type(quantity.type) == np.dtype:
909
910
911
912
                        serializable_value = value.tolist()

                    else:
                        if len(quantity.shape) == 0:
913
                            serializable_value = serialize(value)
914
                        elif len(quantity.shape) == 1:
915
                            serializable_value = [serialize(i) for i in value]
916
917
918
919
                        else:
                            raise NotImplementedError('Higher shapes (%s) not supported: %s' % (quantity.shape, quantity))

                    yield name, serializable_value
920

921
922
923
924
925
926
927
928
929
930
931
932
            # sub sections
            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)]
                else:
                    sub_section = self.m_get_sub_section(sub_section_def, -1)
                    if sub_section is not None:
                        yield name, sub_section.m_to_dict()

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

935
    @classmethod
Markus Scheidgen's avatar
Markus Scheidgen committed
936
    def m_from_dict(cls: Type[MSectionBound], dct: Dict[str, Any]) -> MSectionBound:
937
        """ Creates a section from the given serializable data dictionary.
938

939
        This is the 'opposite' of :func:`m_to_dict`. It takes a deserialised dict, e.g
940
941
942
943
        loaded from JSON, and turns it into a proper section, i.e. instance of the given
        section class.
        """

944
        section_def = cls.m_def
945

946
947
948
949
950
        # remove m_def, m_parent_index, m_parent_sub_section metadata,
        # they set themselves automatically
        dct.pop('m_def', None)
        dct.pop('m_parent_index', None)
        dct.pop('m_parent_sub_section', None)
951

952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
        section = cls()

        for name, sub_section_def in section_def.all_sub_sections.items():
            if name in dct:
                sub_section_value = dct.pop(name)
                if sub_section_def.repeats:
                    for sub_section_dct in sub_section_value:
                        sub_section = sub_section_def.sub_section.section_cls.m_from_dict(sub_section_dct)
                        section.m_add_sub_section(sub_section_def, sub_section)

                else:
                    sub_section = sub_section_def.sub_section.section_cls.m_from_dict(sub_section_value)
                    section.m_add_sub_section(sub_section_def, sub_section)

        for name, quantity_def in section_def.all_quantities.items():
            if name in dct:
                quantity_value = dct[name]

                if type(quantity_def.type) == np.dtype:
                    quantity_value = np.asarray(quantity_value)

                if isinstance(quantity_def.type, DataType):
                    dimensions = len(quantity_def.shape)
                    if dimensions == 0:
                        quantity_value = quantity_def.type.deserialize(
                            section, quantity_def, quantity_value)
                    elif dimensions == 1:
                        quantity_value = list(
                            quantity_def.type.deserialize(section, quantity_def, item)
                            for item in quantity_value)
982
                    else:
983
984
                        raise MetainfoError(
                            'Only numpy quantities can have more than 1 dimension.')
985

986
                section.m_data.dct[name] = quantity_value  # type: ignore
987

988
        return section
989

990
    def m_to_json(self, **kwargs):
991
        """ Returns the data of this section as a json string. """
992
        return json.dumps(self.m_to_dict(), **kwargs)
993

994
    def m_all_contents(self) -> Iterable[Content]:
Markus Scheidgen's avatar
Markus Scheidgen committed
995
        """ Returns an iterable over all sub and sub subs sections. """
996
997
998
        for content in self.m_contents():
            for sub_content in content[0].m_all_contents():
                yield sub_content
999

1000
            yield content
1001

1002
    def m_contents(self) -> Iterable[Content]:
1003
        """ Returns an iterable over all direct subs sections. """
1004
1005
1006
1007
1008
1009
        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
1010

1011
1012
1013
            else:
                sub_section = self.m_get_sub_section(sub_section_def, -1)
                yield sub_section, -1, sub_section_def, self
1014

1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
    def m_path(self, quantity_def: 'Quantity' = None) -> str:
        """ Returns the path of this section or the given quantity within the section hierarchy. """
        if self.m_parent is None:
            return '/'

        if self.m_parent_index == -1:
            segment = self.m_parent_sub_section.name
        else:
            segment = '%s/%d' % (self.m_parent_sub_section.name, self.m_parent_index)

        if quantity_def is not None:
            segment = '%s/%s' % (segment, quantity_def.name)

        return '%s/%s' % (self.m_parent.m_path().rstrip('/'), segment)

    def m_root(self, cls: Type[MSectionBound] = None) -> MSectionBound:
1031
        """ Returns the first parent of the parent section that has no parent; the root. """
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
        if self.m_parent is None:
            return cast(MSectionBound, self)
        else:
            return self.m_parent.m_root(cls)

    def m_resolve(self, path: str, cls: Type[MSectionBound] = None) -> MSectionBound:
        """ Resolves the given path using this section as context. """

        if path.startswith('/'):
            context: 'MSection' = self.m_root()
        else:
            context = self

        path_stack = path.strip('/').split('/')
        path_stack.reverse()
        while len(path_stack) > 1:
            prop_name = path_stack.pop()
            prop_def = context.m_def.all_properties.get(prop_name, None)

            if prop_def is None:
                raise ReferenceError(
                    'Could not resolve %s, property %s does not exist in %s' %
                    (path, prop_name, context.m_def))

            if isinstance(prop_def, SubSection):
                if prop_def.repeats:
                    try:
                        index = int(path_stack.pop())
                    except ValueError:
                        raise ReferenceError(
                            'Could not resolve %s, %s repeats but there is no index in the path' %
                            (path, prop_name))

                    try:
                        context = context.m_get_sub_section(prop_def, index)
                    except Exception:
                        raise ReferenceError(
                            'Could not resolve %s, there is no sub section for %s at %d' %
                            (path, prop_name, index))

                else:
                    context = context.m_get_sub_section(prop_def, -1)
                    if context is None:
                        raise ReferenceError(
                            'Could not resolve %s, there is no sub section for %s' %
                            (path, prop_name))

            elif isinstance(prop_def, Quantity):
                if len(path_stack) > 0:
                    raise ReferenceError(
                        'Could not resolve %s, %s is not a sub section' % (path, prop_name))

                return context.m_get(prop_def)

        return cast(MSectionBound, context)

Markus Scheidgen's avatar
Markus Scheidgen committed
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
    def m_validate(self):
        """ Evaluates all constraints of this section and returns a list of errors. """
        errors: List[str] = []
        for constraint_name in self.m_def.constraints:
            constraint = getattr(self, 'c_%s' % constraint_name, None)
            if constraint is None:
                raise MetainfoError(
                    'Could not find implementation for contraint %s of section %s.' %
                    (constraint_name, self.m_def))

            try:
                constraint()
            except AssertionError as e:
                error_str = str(e).strip()
                if error_str == '':
                    error_str = 'Constraint %s violated.' % constraint_name
                errors.append(error_str)

        return errors

    def m_all_validate(self):
1109
        """ Evaluates all constraints in the whole section hierarchy, incl. this section. """
Markus Scheidgen's avatar
Markus Scheidgen committed
1110
1111
1112
1113
1114
1115
1116
        errors: List[str] = []
        for section, _, _, _ in itertools.chain([(self, None, None, None)], self.m_all_contents()):
            for error in section.m_validate():
                errors.append(error)

        return errors

1117
    def __repr__(self):
1118
        m_section_name = self.m_def.name
1119
1120
1121
1122
        # 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:
1123
            name = self.m_data['name']
1124
1125
        except KeyError:
            name = '<noname>'
1126
1127

        return '%s:%s' % (name, m_section_name)
1128
1129


Markus Scheidgen's avatar
Markus Scheidgen committed
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
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:
1145
            m_def.description = inspect.cleandoc(cls.__doc__).strip()
Markus Scheidgen's avatar
Markus Scheidgen committed
1146
1147
1148
1149

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


Markus Scheidgen's avatar
Markus Scheidgen committed
1153
1154
# Metainfo M3 (i.e. definitions of definitions)

Markus Scheidgen's avatar
Markus Scheidgen committed
1155
class Definition(MSection):
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
    """ A common base for all metainfo definitions.

    All metainfo `definitions` (sections, quantities, sub-sections, packages, ...) share
    some common attributes. These are defined in a common base: all
    metainfo items extend this common base and inherit from ``Definition``.

    Attributes:
        name: Each `definition` has a name. Names have to be valid Python identifier.
            They can contain letters, numbers and _, but must not start with a number.
            This also qualifies them as identifier in most storage formats, databases,
            makes them URL safe, etc.

            Names must be unique within the :class:`Package` or :class:`Section` that
            this definition is part of.

        description: The description can be an arbitrary human readable text that explains
            what this definition is about.

        links: Each definition can be accompanied by a list of URLs. These should point
            to resources that further explain the definition.

        categories: All metainfo definitions can be put into one or more `categories`.
            Categories allow to organize the definitions themselves. It is different from
            sections, which organize the data (e.g. quantity values) and not the definitions
            of data (e.g. quantities definitions). See :ref:`metainfo-categories` for more details.

    Additional helper functions for `definitions`:

    .. automethod:: all_definitions
    """
1186

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

1189
1190
1191
    name: 'Quantity' = None
    description: 'Quantity' = None
    links: 'Quantity' = None
1192
    categories: 'Quantity' = None
1193

1194
    def __init__(self, *args, **kwargs):
1195
1196
        self.all_categories: Set[Category] = set()

1197
1198
        super().__init__(*args, **kwargs)

1199
1200
1201
1202
1203
        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
1204
    def all_definitions(cls: Type[MSectionBound]) -> Iterable[MSectionBound]:
1205
1206
1207
1208
1209
        """ Class method that returns all definitions of this class.

        This can be used to get a list of all globally available `defintions` or a certain
        kind. E.g. to get all `quantities`: ``Quantity.all_definitions()``.
        """
Markus Scheidgen's avatar
Markus Scheidgen committed
1210
        return cast(Iterable[MSectionBound], Definition.__all_definitions.get(cls, []))
1211

1212
1213
1214
1215
1216
1217
1218
    def on_set(self, quantity_def, value):
        if quantity_def == Definition.categories:
            for category in value:
                category.definitions.add(self)
                self.all_categories.add(category)
                for base_category in category.all_categories:
                    self.all_categories.add(base_category)
1219

1220

1221
1222
1223
1224
1225
class Property(Definition):
    pass


class Quantity(Property):
1226
    """ Definition of an atomic piece of data.
1227

1228
1229
    Quantity definitions are the main building block of meta-info schemas. Each quantity
    represents a single piece of data.
1230

1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
    To define quantities, use objects of this class as classattribute values in
    `section classes`. The name of a quantity is automatically taken from its `section class`
    attribute. You can provide all other attributes to the constructor with keyword arguments

    See :ref:`metainfo-sections` to learn about `section classes`.
    In Python terms, ``Quantity`` is a descriptor. Descriptors define how to get and
    set attributes in a Python object. This allows us to use sections like regular
    Python objects and quantity like regular Python attributes.

    Beyond basic :class:`Definition` attributes, Quantities are defined with the following
    attributes.

    Attributes:
        type:
            Defines the datatype of quantity values. This is the type of individual elements
            in a potentially complex shape. If you define a list of integers for example,
            the `shape` would be list and the `type` integer:
            ``Quantity(type=int, shape=['0..*'])``.

            The `type` can be one of:

            - a build-in primitive Python type: ``int``, ``str``, ``bool``, ``float``
            - an instance of :class:`Enum`, e.g. ``Enum('one', 'two', 'three')``
            - a section to define references to other sections as quantity values
            - a custom meta-info :class:`DataType`, see :ref:`metainfo-custom-types`
            - a numpy `dtype`, e.g. ``np.dtype('float32')``
            - ``typing.Any`` to support any value

            If set to `dtype`, this quantity will use a numpy array to store values internally.
            If a regular (nested) Python list is given, it will be automatically converted.
            The given `dtype` will be used in the numpy array.

            To define a reference, either a `section class` or instance of :class:`Section`
            can be given. See :ref:`metainfo-sections` for details. Instances of the given section
            constitute valid values for this type. Upon serialization, references section
            instance will represented with metainfo URLs. See :ref:`metainfo-urls`.

            For quantities with more than one dimension, only numpy arrays and `dtypes`
            are allowed.

        shape:
            The shape of the quantity. It defines its dimensionality.

            A shape is a list, where each item defines one dimension.
            Each dimension can be:

            - an integer that defines the exact size of the dimension, e.g. ``[3]`` is the
              shape of a 3D spacial vector
            - a string that specifies a possible range, e.g. ``0..*``, ``1..*``, ``3..6``
            - the name of an int typed and shapeless quantity in the same section which
              values define the length of this dimension, e.g. ``number_of_atoms`` defines
              the length of ``atom_positions``

            Range specifications define lower and upper bounds for the possible dimension
            length. The ``*`` can be used to denote an arbitrarily high upper bound.

            Quantities with dimensionality (length of the shape) higher than 1, must be
            numpy arrays. Theire type must be a `dtype`.

        unit:
            The physics unit for this quantity. It is optional.

            Units are represented with the pint_ Python package. Pint defines units and
            their algebra. You can either use `pint` units directly, e.g. ``units.m / units.s``.
            The metainfo provides a preconfigured `pint` unit registry :py:data:`units`.
            You can also provide the unit as `pint` parsable string, e.g. ``'meter / seconds'`` or
            ``'m/s'``.

        default:
            The default value for this quantity. The value must match type and shape.

            Be careful with a default value like ``[]`` as it will be the default value for
            all occurences of this quantity.

        synonym_for:
            The name of a quantity defined in the same section as string. This will make
            this quantity a synonym for the other quantity. All other properties (type,
            shape, unit, etc.) are ignored. Getting or setting from/to this quantity will
            be delegated to the other quantity. Synonyms are always virtual.

        derived:
            A Python callable that takes the containing section as input and outputs the
            value for this quantity. This quantity cannot be set directly, its value
            is only derived by the given callable. The callable is executed when this
            quantity is get. Derived quantities are always virtual.

        virtual:
            A boolean that determines if this quantity is virtual. Virtual quantities can
            be get/set like regular quantities, but their values are not (de-)serialized,
            hence never permanently stored.
        """
1322

1323
1324
    type: 'Quantity' = None
    shape: 'Quantity' = None
1325
1326
    unit: 'Quantity' = None
    default: 'Quantity' = None
Markus Scheidgen's avatar
Markus Scheidgen committed
1327
    synonym_for: 'Quantity' = None
1328
    derived: 'Quantity' = None
1329
    virtual: 'Quantity' = None