metainfo.py 77.9 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
27
import pint
import pint.unit
import pint.quantity
28
29
30
import aniso8601
from datetime import datetime
import pytz
31
import docstring_parser
32

33
34
35

m_package: 'Package' = None

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

40

Markus Scheidgen's avatar
Markus Scheidgen committed
41
42
# Metainfo errors

43
class MetainfoError(Exception):
44
    """ Metainfo related errors. """
45
46
47
    pass


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


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


Markus Scheidgen's avatar
Markus Scheidgen committed
58
# Metainfo quantity data types
59

60
61
62
63
class MEnum():
    """Allows to define str types with values limited to a pre-set list of possible values."""
    def __init__(self, *args, **kwargs):
        # Supports one big list in place of args
64
        if len(args) == 1 and isinstance(args[0], list):
65
            args = args[0]
66

67
68
69
70
71
72
73
74
75
76
77
78
79
        # 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

        self._values = set(kwargs.values())  # For allowing constant time member check
        self._map = kwargs

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


82
class MProxy():
83
84
85
86
87
    """ A placeholder object that acts as reference to a value that is not yet resolved.

    Attributes:
        url: The reference represented as an URL string.
    """
88
89
90
91
92

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


93
94
95
96
class DataType:
    """
    Allows to define custom data types that can be used in the meta-info.

97
    The metainfo supports the most types out of the box. These includes the python build-in
98
99
    primitive types (int, bool, str, float, ...), references to sections, and enums.
    However, in some occasions you need to add custom data types.
100
101
102
103
104

    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.
105
    """
106
107
108
109
110
111
    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. """
112
113
        return value

114
115
    def serialize(self, section: 'MSection', quantity_def: 'Quantity', value: Any) -> Any:
        """ Transforms the given value when making the section serializeable. """
116
117
        return value

118
119
    def deserialize(self, section: 'MSection', quantity_def: 'Quantity', value: Any) -> Any:
        """ Transforms the given value from its serializeable form. """
120
121
122
        return value


123
124
125
126
127
range_re = re.compile(r'(\d)\.\.(\d|\*)')


class _Dimension(DataType):

128
    def set_normalize(self, section, quantity_def: 'Quantity', value):
129
        if isinstance(value, int):
Markus Scheidgen's avatar
Markus Scheidgen committed
130
            return value
131
132
133

        if isinstance(value, str):
            if value.isidentifier():
Markus Scheidgen's avatar
Markus Scheidgen committed
134
                return value
135
            if re.match(range_re, value):
Markus Scheidgen's avatar
Markus Scheidgen committed
136
                return value
137
138

        if isinstance(value, Section):
Markus Scheidgen's avatar
Markus Scheidgen committed
139
            return value
140

141
        if isinstance(value, type) and hasattr(value, 'm_def'):
Markus Scheidgen's avatar
Markus Scheidgen committed
142
            return value
143
144
145

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

146
147
148
149
150
151
152
    @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)
153

154
155
156
157
158
159
160
            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):
161
    def set_normalize(self, section, quantity_def: 'Quantity', value):
162
163
164
        if isinstance(value, str):
            value = units.parse_units(value)

165
        elif not isinstance(value, pint.unit._Unit):
166
167
168
169
            raise TypeError('Units must be given as str or pint Unit instances.')

        return value

170
    def serialize(self, section, quantity_def: 'Quantity', value):
171
172
        return value.__str__()

173
    def deserialize(self, section, quantity_def: 'Quantity', value):
174
175
        return units.parse_units(value)

176

177
units = pint.UnitRegistry()
Markus Scheidgen's avatar
Markus Scheidgen committed
178
179
180
""" The default pint unit registry that should be used to give units to quantity definitions. """


181
class _Callable(DataType):
182
183
184
185
186
187
188
    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')


189
class _QuantityType(DataType):
190
191
192
193
194
195
196
    """ 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
197
    - an MEnum instance to use it's values as possible str values
198
199
200
201
202
203
204
205
    - 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

206
207
        if isinstance(value, MEnum):
            for enum_value in value._values:
208
                if not isinstance(enum_value, str):
209
                    raise TypeError('MEnum value %s is not a string.' % enum_value)
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
            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):
234
        if value is str or value is int or value is float or value is bool:
235
236
            return dict(type_kind='python', type_data=value.__name__)

237
        if isinstance(value, MEnum):
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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
            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)


312
class _Datetime(DataType):
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340

    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)


341
342
343
344
345
Dimension = _Dimension()
Unit = _Unit()
QuantityType = _QuantityType()
Callable = _Callable()
Datetime = _Datetime()
346
347


Markus Scheidgen's avatar
Markus Scheidgen committed
348
349
# Metainfo data storage and reflection interface

350
class MObjectMeta(type):
351

352
    def __new__(self, cls_name, bases, dct):
353
354
355
356
357
358
        do_init = dct.get('do_init', None)
        if do_init is not None:
            del(dct['do_init'])
        else:
            do_init = True

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

Markus Scheidgen's avatar
Markus Scheidgen committed
361
        init = getattr(cls, '__init_cls__')
362
        if init is not None and do_init and not is_bootstrapping:
363
364
            init()
        return cls
365
366


367
368
369
370
371
372
373
374
375
376
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
"""
377
378


379
380
381
382
383
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.
384
    Different implementations of this interface, can realize different storage backends.
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437

    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):
438
    """ A simple dict backed implementaton of :class:`MData`. It is used by default. """
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511

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


512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
class MResource():
    """Represents a collection of related metainfo data, i.e. a set of :class:`MSection` instances.

    MResource allows to keep related objects together and resolve sections of certain
    section definitions.
    """
    def __init__(self):
        self.__data: Dict['Section', List['MSection']] = dict()
        self.contents: List['MSection'] = []

    def create(self, section_cls: Type[MSectionBound], *args, **kwargs) -> MSectionBound:
        """ Create an instance of the given section class and adds it to this resource. """
        result = section_cls(*args, **kwargs)
        self.add(result)
        return cast(MSectionBound, result)

    def add(self, section):
        section.m_resource = self
        self.__data.setdefault(section.m_def, []).append(section)
        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)
        if section.m_parent is not None:
            self.contents.remove(section)

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

    def unload(self):
        """ Breaks all references among the contain metainfo sections to allow GC. """
        for collections in self.__data.values():
            for section in collections:
                section.m_parent = None
            collections.clear()

        # TODO break actual references via quantities


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

558
559
560
561
562
    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`.
563
564
565
566

    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.

567
568
569
    Attributes:
        m_def: The `section definition` that this `section instance` follows as a
            :class:`Section` object.
570

571
572
        m_parent:
            If this section is a sub-section, this references the parent section instance.
573

574
575
576
        m_parent_sub_section:
            If this section is a sub-section, this is the :class:`SubSection` that defines
            this relationship.
577

578
579
580
581
582
583
584
        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).
585

586
587
        m_resource: The :class:`MResource` that contains and manages this section.

588
589
    """

590
    m_def: 'Section' = None
591

592
593
594
    def __init__(
            self, m_def: 'Section' = None, m_data: MData = None,
            m_resource: MResource = None, **kwargs):
595

596
        self.m_def: 'Section' = m_def
597
598
        self.m_parent: 'MSection' = None
        self.m_parent_sub_section: 'SubSection' = None
599
        self.m_parent_index = -1
600
        self.m_resource = m_resource
601

602
        # get missing m_def from class
603
        cls = self.__class__
604
605
        if self.m_def is None:
            self.m_def = cls.m_def
606

607
        # check m_def
608
        if cls.m_def is not None:
609
610
611
612
613
614
615
616
617
            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.')
618

619
        # get annotations from kwargs
620
        self.m_annotations: Dict[str, Any] = {}
Markus Scheidgen's avatar
Markus Scheidgen committed
621
        rest = {}
622
623
624
625
        for key, value in kwargs.items():
            if key.startswith('a_'):
                self.m_annotations[key[2:]] = value
            else:
Markus Scheidgen's avatar
Markus Scheidgen committed
626
627
                rest[key] = value

628
629
630
        # initialize data
        self.m_data = m_data
        if self.m_data is None:
631
            self.m_data = MDataDict()
632

633
634
        # set remaining kwargs
        if is_bootstrapping:
635
            self.m_data.dct.update(**rest)  # type: ignore
Markus Scheidgen's avatar
Markus Scheidgen committed
636
        else:
637
            self.m_update(**rest)
638

639
    @classmethod
Markus Scheidgen's avatar
Markus Scheidgen committed
640
    def __init_cls__(cls):
641
642
        # ensure that the m_def is defined
        m_def = cls.m_def
Markus Scheidgen's avatar
Markus Scheidgen committed
643
        if m_def is None:
644
645
            m_def = Section()
            setattr(cls, 'm_def', m_def)
646

647
648
649
        # Use class name if name is not explicitly defined
        if m_def.name is None:
            m_def.name = cls.__name__
650
        m_def.section_cls = cls
651

652
        # add base sections
653
        extended_base_section = None
654
655
656
657
658
659
        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
660
            if base_sections_count > 1:
661
662
663
664
                raise MetainfoError(
                    'Section %s extend the base section, but has more than one base section' % m_def)

            base_section_cls = cls.__bases__[0]
665
            extended_base_section = base_section = getattr(base_section_cls, 'm_def', None)
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
            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

690
691
        constraints: Set[str] = set()
        event_handlers: Set[Callable] = set(m_def.event_handlers)
692
        for name, attr in cls.__dict__.items():
693
694
            # transfer names and descriptions for properties
            if isinstance(attr, Property):
695
                attr.name = name
696
                if attr.description is not None:
697
                    attr.description = inspect.cleandoc(attr.description).strip()
698
                    attr.__doc__ = attr.description
699

700
                if isinstance(attr, Quantity):
701
                    section_to_add_properties_to.m_add_sub_section(Section.quantities, attr)
702
                elif isinstance(attr, SubSection):
703
                    section_to_add_properties_to.m_add_sub_section(Section.sub_sections, attr)
704
705
                else:
                    raise NotImplementedError('Unknown property kind.')
706

707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
            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
726

727
728
        m_def.constraints = list(constraints)
        m_def.event_handlers = list(event_handlers)
Markus Scheidgen's avatar
Markus Scheidgen committed
729

730
731
732
        # add section cls' section to the module's package
        module_name = cls.__module__
        pkg = Package.from_module(module_name)
733
        pkg.m_add_sub_section(Package.section_definitions, cls.m_def)
734

735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
        # 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

766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
        # validate
        def validate(definition):
            errors = definition.m_all_validate()
            if len(errors) > 0:
                raise MetainfoError(
                    '%s. The section definition %s violates %d more constraints' %
                    (str(errors[0]).strip('.'), definition, len(errors) - 1))

        if extended_base_section is not None:
            validate(extended_base_section)
        validate(m_def)

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

785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
        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))

806
807
        elif isinstance(quantity_def.type, MEnum):
            if value not in quantity_def.type._values:
808
809
810
811
812
813
814
                raise TypeError(
                    'The value %s is not an enum value for quantity %s.' %
                    (value, quantity_def))

        elif quantity_def.type == Any:
            pass

815
816
817
818
819
820
        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)

821
        else:
822
            if value is not None and type(value) != quantity_def.type:
823
824
825
826
827
828
                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

829
830
831
832
    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
833

834
835
836
837
838
839
840
841
    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))
            value = value.to(quantity_def.unit).magnitude

842
        if len(quantity_def.shape) > 0 and type(value) != np.ndarray:
843
844
845
846
847
848
            try:
                value = np.asarray(value)
            except TypeError:
                raise TypeError(
                    'Could not convert value %s of %s to a numpy array' %
                    (value, quantity_def))
849
850
851
852
853
854
855
        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))
856
857
858

        return self.__check_np(quantity_def, value)

859
860
861
    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)
862

863
864
        if quantity_def.derived is not None:
            raise MetainfoError('The quantity %s is derived and cannot be set.' % quantity_def)
865
866

        if type(quantity_def.type) == np.dtype:
867
            value = self.__to_np(quantity_def, value)
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886

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

887
        self.m_data.m_set(self, quantity_def, value)
888

889
890
891
892
        for handler in self.m_def.event_handlers:
            if handler.__name__.startswith('on_set'):
                handler(self, quantity_def, value)

893
894
895
    def m_get(self, quantity_def: 'Quantity') -> Any:
        """ Retrieve the given value for the given quantity. """
        quantity_def = self.__resolve_synonym(quantity_def)
896
897
898
899
900
901
        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)))

902
903
        value = self.m_data.m_get(self, quantity_def)

904
905
906
        if value is None:
            return value

907
908
909
910
911
912
913
914
915
916
917
918
919
920
        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.')
921

922
923
924
925
        elif type(quantity_def.type) == np.dtype:
            if quantity_def.unit is not None:
                value = value * quantity_def.unit

926
        return value
927

928
    def m_is_set(self, quantity_def: 'Quantity') -> bool:
929
        """ True if the given quantity is set. """
930
        quantity_def = self.__resolve_synonym(quantity_def)
931
932
933
        if quantity_def.derived is not None:
            return True

934
        return self.m_data.m_is_set(self, quantity_def)
Markus Scheidgen's avatar
Markus Scheidgen committed
935

936
937
938
    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)
939

940
941
    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
942

943
        parent_index = -1
944
        if sub_section_def.repeats:
945
946
947
948
            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
949
950
951
952
        if sub_section.m_resource is not None:
            sub_section.m_resource.remove(sub_section)
        if self.m_resource is not None:
            self.m_resource.add(sub_section)
953

954
        self.m_data.m_add_sub_section(self, sub_section_def, sub_section)
955

956
957
958
959
        for handler in self.m_def.event_handlers:
            if handler.__name__.startswith('on_add_sub_section'):
                handler(self, sub_section_def, sub_section)

960
961
962
    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)
963

964
965
966
    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)
967

968
969
970
    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)
971

972
973
974
    def m_create(
            self, section_cls: Type[MSectionBound], sub_section_def: 'SubSection' = None,
            **kwargs) -> MSectionBound:
975
976
        """ Creates a section instance and adds it to this section provided there is a
        corresponding sub section.
977
978
979
980
981

        Args:
            section_cls: The section class for the sub-secton to create
            sub_section_def: If there are multiple sub-sections for the given class,
                this must be used to explicitely state the sub-section definition.
982
        """
983

984
        section_def = section_cls.m_def
985
986
987
        sub_section_defs = self.m_def.all_sub_sections_by_section.get(section_def, [])
        n_sub_section_defs = len(sub_section_defs)
        if n_sub_section_defs == 0:
988
            raise TypeError('There is no sub section to hold a %s in %s.' % (section_def, self.m_def))
989

990
991
992
993
994
995
996
997
998
999
1000
1001
1002
        if n_sub_section_defs > 1 and sub_section_def is None:
            raise MetainfoError(
                'There are multiple sub section to hold a %s in %s, '
                'but no sub-section was explicitely given.' % (section_def, self.m_def))

        if sub_section_def is not None and sub_section_def not in sub_section_defs:
            raise MetainfoError(
                'The given sub-section class %s does not match the given sub-section '
                'definition %s.' % (section_cls, sub_section_def))

        if sub_section_def is None:
            sub_section_def = sub_section_defs[0]

1003
1004
        sub_section = section_cls(**kwargs)
        self.m_add_sub_section(sub_section_def, sub_section)
1005

1006
        return cast(MSectionBound, sub_section)
1007

1008
    def m_update(self, safe: bool = True, **kwargs):
1009
        """ Updates all quantities and sub-sections with the given arguments. """
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
        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)
1023
                    else:
1024
1025
                        self.m_add_sub_section(prop, item)

1026
                else:
1027
                    self.m_set(prop, value)
1028

1029
1030
        else:
            self.m_data.m_data.dct.update(**kwargs)  # type: ignore
1031

1032
1033
1034
1035
    def m_as(self, section_cls: Type[MSectionBound]) -> MSectionBound:
        """ 'Casts' this section to the given extending sections. """
        return cast(MSectionBound, self)

1036
    def m_follows(self, definition: 'Section') -> bool:
1037
        """ Determines if this section's definition is or is derived from the given definition. """
1038
        return self.m_def == definition or definition in self.m_def.all_base_sections
1039

1040
    def m_to_dict(self, with_meta: bool = False) -> Dict[str, Any]:
1041
        """Returns the data of this section as a json serializeable dictionary. """
1042
1043

        def items() -> Iterable[Tuple[str, Any]]:
1044
1045
1046
1047
1048
1049
1050
1051
1052
            # 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
1053
            for name, quantity in self.m_def.all_quantities.items():
1054
                if quantity.virtual or not self.m_is_set(quantity):
1055
1056
                    continue

1057
                if self.m_is_set(quantity) and quantity.derived is None:
1058
                    serialize: TypingCallable[[Any], Any] = str
1059
                    if isinstance(quantity.type, DataType):
1060
1061

                        def data_type_serialize(value):
Markus Scheidgen's avatar
Markus Scheidgen committed
1062
                            return quantity.type.serialize(self, quantity, value)
1063
1064

                        serialize = data_type_serialize
1065

1066
                    elif quantity.type in [str, int, float, bool]:
1067
                        serialize = quantity.type
1068

1069
                    elif type(quantity.type) == np.dtype:
1070
1071
                        pass

1072
                    elif isinstance(quantity.type, MEnum):
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
                        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))

1092
                    value = cast(MDataDict, self.m_data).dct[name]
1093

1094
                    if type(quantity.type) == np.dtype:
1095
1096
1097
1098
                        serializable_value = value.tolist()

                    else:
                        if len(quantity.shape) == 0:
1099
                            serializable_value = serialize(value)
1100
                        elif len(quantity.shape) == 1:
1101
                            serializable_value = [serialize(i) for i in value]
1102
1103
1104
1105
                        else:
                            raise NotImplementedError('Higher shapes (%s) not supported: %s' % (quantity.shape, quantity))

                    yield name, serializable_value
1106

1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
            # 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()

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

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

1125
        This is the 'opposite' of :func:`m_to_dict`. It takes a deserialised dict, e.g
1126
1127
1128
1129
        loaded from JSON, and turns it into a proper section, i.e. instance of the given
        section class.
        """

1130
        section_def = cls.m_def
1131

1132
1133
1134
1135
1136
        # 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)
1137

1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
        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)
1168
                    else:
1169
1170
                        raise MetainfoError(
                            'Only numpy quantities can have more than 1 dimension.')
1171

1172
                section.m_data.dct[name] = quantity_value  # type: ignore
1173

1174
        return section
1175

1176
    def m_to_json(self, **kwargs):
1177
        """ Returns the data of this section as a json string. """
1178
        return json.dumps(self.m_to_dict(), **kwargs)
1179

1180
    def m_all_contents(self) -> Iterable['MSection']:
Markus Scheidgen's avatar
Markus Scheidgen committed
1181
        """ Returns an iterable over all sub and sub subs sections. """
1182
        for content in self.m_contents():
1183
            for sub_content in content.m_all_contents():
1184
                yield sub_content
1185

1186
            yield content
1187

1188
    def m_contents(self) -> Iterable['MSection']:
1189
        """ Returns an iterable over all direct subs sections. """
1190
1191
1192
1193
        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):
1194
                    yield sub_section
1195
                    index += 1
1196

1197
1198
            else:
                sub_section = self.m_get_sub_section(sub_section_def, -1)
1199
                yield sub_section
1200

1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
    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:
1217
        """ Returns the first parent of the parent section that has no parent; the root. """
1218
1219
1220
1221
1222
        if self.m_parent is None:
            return cast(MSectionBound, self)
        else:
            return self.m_parent.m_root(cls)

1223
1224
1225
1226
    def m_parent_as(self, cls: Type[MSectionBound] = None) -> MSectionBound:
        """ Returns the parent section with the given section class type. """
        return cast(MSectionBound, self.m_parent)