metainfo.py 91.5 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
import flask_restplus.inputs
33

34
35
36

m_package: 'Package' = None

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

41
42
43
44
45
46
47
48
# Make pylint believe all bootstrap quantities are actual properties even though
# we have to initialize them to None due to bootstrapping
_placeholder_quantity: 'Quantity' = property()  # type: ignore
if True:
    _placeholder_quantity: 'Quantity' = None  # type: ignore

_primitive_types = {str: str, int: int, float: float, bool: bool}

49

Markus Scheidgen's avatar
Markus Scheidgen committed
50
51
# Metainfo errors

52
class MetainfoError(Exception):
53
    ''' Metainfo related errors. '''
54
55
56
    pass


57
class DeriveError(MetainfoError):
58
    ''' An error occurred while computing a derived value. '''
59
60
61
    pass


62
class MetainfoReferenceError(MetainfoError):
63
    ''' An error indicating that a reference could not be resolved. '''
64
    pass
65
66


Markus Scheidgen's avatar
Markus Scheidgen committed
67
# Metainfo quantity data types
68

69
class MEnum():
70
    '''Allows to define str types with values limited to a pre-set list of possible values.'''
71
72
    def __init__(self, *args, **kwargs):
        # Supports one big list in place of args
73
        if len(args) == 1 and isinstance(args[0], list):
74
            args = args[0]
75

76
77
78
79
80
81
82
83
84
85
86
87
88
        # 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]
89
90


91
class MProxy():
92
    ''' A placeholder object that acts as reference to a value that is not yet resolved.
93
94
95

    Attributes:
        url: The reference represented as an URL string.
96
    '''
97

98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
    def __init__(self, m_proxy_url: str, m_proxy_section: 'MSection', m_proxy_quantity: 'Quantity'):
        self.m_proxy_url = m_proxy_url
        self.m_proxy_section = m_proxy_section
        self.m_proxy_resolved = None
        self.m_reference_type = m_proxy_quantity.type

    def m_proxy_resolve(self):
        if self.m_proxy_section and not self.m_proxy_resolved:
            self.m_proxy_resolved = self.m_reference_type.resolve(self)

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

        return self.m_proxy_resolved

    def __getattr__(self, key):
        if self.m_proxy_resolve():
            return getattr(self.m_proxy_resolved, key)

        raise ReferenceError('could not resolve %s' % self.m_proxy_url)
119
120


121
class DataType:
122
    '''
123
124
    Allows to define custom data types that can be used in the meta-info.

125
    The metainfo supports the most types out of the box. These includes the python build-in
126
127
    primitive types (int, bool, str, float, ...), references to sections, and enums.
    However, in some occasions you need to add custom data types.
128
129
130
131
132

    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.
133
    '''
134
    def set_normalize(self, section: 'MSection', quantity_def: 'Quantity', value: Any) -> Any:
135
        ''' Transforms the given value before it is set and checks its type. '''
136
137
138
        return value

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

142
    def serialize(self, section: 'MSection', quantity_def: 'Quantity', value: Any) -> Any:
143
        ''' Transforms the given value when making the section serializeable. '''
144
145
        return value

146
    def deserialize(self, section: 'MSection', quantity_def: 'Quantity', value: Any) -> Any:
147
        ''' Transforms the given value from its serializeable form. '''
148
149
150
        return value


151
152
153
154
155
range_re = re.compile(r'(\d)\.\.(\d|\*)')


class _Dimension(DataType):

156
    def set_normalize(self, section, quantity_def: 'Quantity', value):
157
        if isinstance(value, int):
Markus Scheidgen's avatar
Markus Scheidgen committed
158
            return value
159
160
161

        if isinstance(value, str):
            if value.isidentifier():
Markus Scheidgen's avatar
Markus Scheidgen committed
162
                return value
163
            if re.match(range_re, value):
Markus Scheidgen's avatar
Markus Scheidgen committed
164
                return value
165
166

        if isinstance(value, Section):
Markus Scheidgen's avatar
Markus Scheidgen committed
167
            return value
168

169
        if isinstance(value, type) and hasattr(value, 'm_def'):
Markus Scheidgen's avatar
Markus Scheidgen committed
170
            return value
171

172
173
174
175
        if isinstance(value, str):
            # TODO error/warning?
            return '0..*'

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

178
179
180
181
182
183
184
    @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)
185

186
187
188
189
190
191
192
            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):
193
    def set_normalize(self, section, quantity_def: 'Quantity', value):
194
195
196
        if isinstance(value, str):
            value = units.parse_units(value)

197
        elif not isinstance(value, pint.unit._Unit):
198
199
200
201
            raise TypeError('Units must be given as str or pint Unit instances.')

        return value

202
    def serialize(self, section, quantity_def: 'Quantity', value):
203
204
        return value.__str__()

205
    def deserialize(self, section, quantity_def: 'Quantity', value):
206
207
        return units.parse_units(value)

208

209
units = pint.UnitRegistry()
210
''' The default pint unit registry that should be used to give units to quantity definitions. '''
Markus Scheidgen's avatar
Markus Scheidgen committed
211
212


213
class _Callable(DataType):
214
215
216
217
218
219
220
    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')


221
class _QuantityType(DataType):
222
    ''' Data type for defining the type of a metainfo quantity.
223
224
225
226
227
228

    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
229
    - an MEnum instance to use it's values as possible str values
230
231
    - a custom datatype, i.e. instance of :class:`DataType`
    - Any
232
    '''
233
234
235
236
237

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

238
239
        if isinstance(value, MEnum):
            for enum_value in value._values:
240
                if not isinstance(enum_value, str):
241
                    raise TypeError('MEnum value %s is not a string.' % enum_value)
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
            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)

261
262
263
        if isinstance(value, MProxy):
            return value

264
265
266
267
268
        raise MetainfoError(
            'Type %s of %s is not a valid metainfo quantity type' %
            (value, quantity_def))

    def serialize(self, section, quantity_def, value):
269
        if value is str or value is int or value is float or value is bool:
270
271
            return dict(type_kind='python', type_data=value.__name__)

272
        if isinstance(value, MEnum):
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
            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):
299
    ''' Datatype used for reference quantities. '''
300
301
302
303
304
305

    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

306
307
308
309
310
311
312
    def resolve(self, proxy) -> 'MSection':
        '''
        Resolve the given proxy. The proxy is gurantied to have a context and
        will to be not yet resolved.
        '''
        return proxy.m_proxy_section.m_resolve(proxy.m_proxy_url)

313
314
315
316
317
318
319
320
321
322
    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

323
324
325
        if isinstance(value, str):
            return MProxy(value, m_proxy_section=section, m_proxy_quantity=quantity_def)

326
        if isinstance(value, MProxy):
327
            value.m_proxy_section = section
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
            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 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:
345
        return MProxy(value, m_proxy_section=section, m_proxy_quantity=quantity_def)
346
347


348
class _Datetime(DataType):
349

350
    def _parse(self, datetime_str: str) -> datetime:
351
        try:
352
353
354
            return aniso8601.parse_datetime(datetime_str)
        except ValueError:
            pass
355

356
357
358
359
360
361
362
363
364
365
366
367
368
369
        try:
            return aniso8601.parse_date(datetime_str)
        except ValueError:
            pass

        try:
            # TODO necessary?
            return flask_restplus.inputs.datetime_from_rfc822(datetime_str)
        except ValueError:
            pass

        raise TypeError('Invalid date literal "{0}"'.format(datetime_str))

    def _convert(self, value):
370
371
372
        if value is None:
            return None

373
        if isinstance(value, str):
374
375
376
377
            value = self._parse(value)

        elif isinstance(value, (int, float)):
            value = datetime.fromtimestamp(value)
378
379
380
381
382
383

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

        return value

384
385
386
    def set_normalize(self, section: 'MSection', quantity_def: 'Quantity', value: Any) -> Any:
        return self._convert(value)

387
    def serialize(self, section: 'MSection', quantity_def: 'Quantity', value: Any) -> Any:
388
389
390
        if value is None:
            return None

391
392
393
394
        value.replace(tzinfo=pytz.utc)
        return value.isoformat()

    def deserialize(self, section: 'MSection', quantity_def: 'Quantity', value: Any) -> Any:
395
        return self._convert(value)
396
397


398
399
400
401
402
Dimension = _Dimension()
Unit = _Unit()
QuantityType = _QuantityType()
Callable = _Callable()
Datetime = _Datetime()
403
404


Markus Scheidgen's avatar
Markus Scheidgen committed
405
406
# Metainfo data storage and reflection interface

407
class MObjectMeta(type):
408

409
    def __new__(self, cls_name, bases, dct):
410
411
412
413
414
415
        do_init = dct.get('do_init', None)
        if do_init is not None:
            del(dct['do_init'])
        else:
            do_init = True

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

Markus Scheidgen's avatar
Markus Scheidgen committed
418
        init = getattr(cls, '__init_cls__')
419
        if init is not None and do_init and not is_bootstrapping:
420
421
            init()
        return cls
422
423


424
SectionDef = Union[str, 'Section', 'SubSection', Type[MSectionBound]]
425
''' Type for section definition references.
426
427
428
429
430
431
432

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
433
'''
434
435


436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
def constraint(warning):
    ''' A decorator for methods implementing constraints. '''
    f = None
    if not isinstance(warning, bool):
        f = warning
        warning = False

    def decorator(f):
        setattr(f, 'm_constraint', True)
        setattr(f, 'm_warning', warning)
        return f

    if f is None:
        return decorator
    else:
        return decorator(f)


454
class MResource():
455
    '''Represents a collection of related metainfo data, i.e. a set of :class:`MSection` instances.
456
457
458

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

    def create(self, section_cls: Type[MSectionBound], *args, **kwargs) -> MSectionBound:
465
        ''' Create an instance of the given section class and adds it to this resource. '''
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
        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]:
484
        ''' Returns all instances of the given section class in this resource. '''
485
486
487
        return cast(List[MSectionBound], self.__data.get(section_cls.m_def, []))

    def unload(self):
488
        ''' Breaks all references among the contain metainfo sections to allow GC. '''
489
490
491
492
493
494
495
496
        for collections in self.__data.values():
            for section in collections:
                section.m_parent = None
            collections.clear()

        # TODO break actual references via quantities


497
498
class MSection(metaclass=MObjectMeta):  # TODO find a way to make this a subclass of collections.abs.Mapping
    '''Base class for all section instances on all meta-info levels.
499

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

    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.

509
510
511
    Attributes:
        m_def: The `section definition` that this `section instance` follows as a
            :class:`Section` object.
512

513
514
        m_parent:
            If this section is a sub-section, this references the parent section instance.
515

516
517
518
        m_parent_sub_section:
            If this section is a sub-section, this is the :class:`SubSection` that defines
            this relationship.
519

520
521
522
523
        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.

524
525
        m_resource: The :class:`MResource` that contains and manages this section.

526
    '''
527

528
    m_def: 'Section' = None
529

530
    def __init__(
531
            self, m_def: 'Section' = None, m_resource: MResource = None, **kwargs):
532

533
        self.m_def: 'Section' = m_def
534
535
        self.m_parent: 'MSection' = None
        self.m_parent_sub_section: 'SubSection' = None
536
        self.m_parent_index = -1
537
        self.m_resource = m_resource
538
        self.m_mod_count = 0
539

540
        # get missing m_def from class
541
        cls = self.__class__
542
543
        if self.m_def is None:
            self.m_def = cls.m_def
544

545
        # check m_def
546
        if cls.m_def is not None:
547
548
549
550
551
552
553
554
555
            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.')
556

557
        # get annotations from kwargs
558
559
        self.m_annotations: Dict[str, Any] = {}
        other_kwargs = {}
560
561
562
563
        for key, value in kwargs.items():
            if key.startswith('a_'):
                self.m_annotations[key[2:]] = value
            else:
564
565
566
567
                other_kwargs[key] = value

        # get additional annotations from the section definition
        if not is_bootstrapping:
568
            for section_annotation in self.m_def.m_get_annotations(SectionAnnotation, as_list=True):
569
570
571
572
573
574
                for name, annotation in section_annotation.new(self).items():
                    self.m_annotations[name] = annotation

        # add annotation attributes for names annotations
        for annotation_name, annotation in self.m_annotations.items():
            setattr(self, 'a_%s' % annotation_name, annotation)
Markus Scheidgen's avatar
Markus Scheidgen committed
575

576
577
        # set remaining kwargs
        if is_bootstrapping:
578
            self.__dict__.update(**other_kwargs)  # type: ignore
Markus Scheidgen's avatar
Markus Scheidgen committed
579
        else:
580
            self.m_update(**other_kwargs)
581

582
    @classmethod
Markus Scheidgen's avatar
Markus Scheidgen committed
583
    def __init_cls__(cls):
584
        # ensure that the m_def is defined
585
        m_def = cls.__dict__.get('m_def')  # do not accedentally get the m_def from a potential base section
Markus Scheidgen's avatar
Markus Scheidgen committed
586
        if m_def is None:
587
588
            m_def = Section()
            setattr(cls, 'm_def', m_def)
589

590
        # transfer name m_def
591
        m_def.name = cls.__name__
592
        m_def._section_cls = cls
593

594
        # add base sections
595
596
597
598
599
600
601
602
603
        base_sections: List[Section] = []
        for base_cls in cls.__bases__:
            if base_cls != MSection:
                base_section = getattr(base_cls, 'm_def')
                if base_section is None:
                    raise TypeError(
                        'Section defining classes must have MSection or a decendant as '
                        'base classes.')
                base_sections.append(base_section)
604

605
606
607
        m_def.m_set(Section.base_sections, base_sections)

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

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

625
626
627
628
            if inspect.isfunction(attr):
                method_name = attr.__name__

                # transfer constraints
629
630
                if getattr(attr, 'm_constraint', False):
                    constraint = method_name
631
632
633
634
635
636
637
638
639
640
641
642
643
                    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
644

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

648
649
650
        # add section cls' section to the module's package
        module_name = cls.__module__
        pkg = Package.from_module(module_name)
651
        pkg.m_add_sub_section(Package.section_definitions, cls.m_def)
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
        # 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

684
685
        for content in m_def.m_all_contents(depth_first=True, include_self=True):
            cast(Definition, content).__init_metainfo__()
686

687
688
689
690
    def __getattr__(self, name):
        # This will make mypy and pylint ignore 'missing' dynamic attributes and functions
        # and wrong types of those.
        # Ideally we have a plugin for both that add the corrent type info
691
        raise AttributeError(name)
692

693
694
695
696
697
698
699
    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))

700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
        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))

721
722
        elif isinstance(quantity_def.type, MEnum):
            if value not in quantity_def.type._values:
723
724
725
726
727
728
729
                raise TypeError(
                    'The value %s is not an enum value for quantity %s.' %
                    (value, quantity_def))

        elif quantity_def.type == Any:
            pass

730
731
732
733
734
735
        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)

736
        else:
737
            if value is not None and type(value) != quantity_def.type:
738
739
740
741
742
743
                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

744
745
746
747
    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
748

749
750
751
752
753
754
755
756
    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

757
        if len(quantity_def.shape) > 0 and type(value) != np.ndarray:
758
759
760
761
762
763
            try:
                value = np.asarray(value)
            except TypeError:
                raise TypeError(
                    'Could not convert value %s of %s to a numpy array' %
                    (value, quantity_def))
764
765
766
767
768
769
770
        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))
771
772
773

        return self.__check_np(quantity_def, value)

774
    def m_set(self, quantity_def: 'Quantity', value: Any) -> None:
775
        ''' Set the given value for the given quantity. '''
776
        self.m_mod_count += 1
777
        quantity_def = self.__resolve_synonym(quantity_def)
778

779
780
        if quantity_def.derived is not None:
            raise MetainfoError('The quantity %s is derived and cannot be set.' % quantity_def)
781
782

        if type(quantity_def.type) == np.dtype:
783
            value = self.__to_np(quantity_def, value)
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800

        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 '
801
                    'quantities: %s' % quantity_def)
802

803
        self.__dict__[quantity_def.name] = value
804

805
806
807
808
        for handler in self.m_def.event_handlers:
            if handler.__name__.startswith('on_set'):
                handler(self, quantity_def, value)

809
    def m_get(self, quantity_def: 'Quantity') -> Any:
810
        ''' Retrieve the given value for the given quantity. '''
811
        return quantity_def.__get__(self, Quantity)
812

813
    def m_is_set(self, quantity_def: 'Quantity') -> bool:
814
        ''' True if the given quantity is set. '''
815
        quantity_def = self.__resolve_synonym(quantity_def)
816
817
818
        if quantity_def.derived is not None:
            return True

819
        return quantity_def.name in self.__dict__
Markus Scheidgen's avatar
Markus Scheidgen committed
820

821
    def m_add_values(self, quantity_def: 'Quantity', values: Any, offset: int) -> None:
822
        ''' Add (partial) values for the given quantity of higher dimensionality. '''
823
824
        # TODO
        raise NotImplementedError()
825

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

829
        self.m_mod_count += 1
830
        parent_index = -1
831
        if sub_section_def.repeats:
832
            parent_index = self.m_sub_section_count(sub_section_def)
833
834

        else:
835
            old_sub_section = self.__dict__.get(sub_section_def.name)
836
837
838
839
840
841
842
            if old_sub_section is not None:
                old_sub_section.m_parent = None
                old_sub_section.m_parent_sub_section = None
                old_sub_section.m_parent_index = -1
                if self.m_resource is not None:
                    self.m_resource.remove(sub_section)

843
844
845
        sub_section.m_parent = self
        sub_section.m_parent_sub_section = sub_section_def
        sub_section.m_parent_index = parent_index
846
847
848
849
        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)
850

851
852
853
854
855
856
857
858
859
860
        sub_section_name = sub_section_def.name
        if sub_section_def.repeats:
            sub_section_lst = self.__dict__.get(sub_section_name)
            if sub_section_lst is None:
                sub_section_lst = self.__dict__.setdefault(sub_section_name, [])

            sub_section_lst.append(sub_section)

        else:
            self.__dict__[sub_section_name] = sub_section
861

862
863
864
865
        for handler in self.m_def.event_handlers:
            if handler.__name__.startswith('on_add_sub_section'):
                handler(self, sub_section_def, sub_section)

866
867
    def m_remove_sub_section(self, sub_section_def: 'SubSection', index: int) -> None:
        ''' Removes the exiting section for a non repeatable sub section '''
868
        self.m_mod_count += 1
869
870
871
872
873
        if sub_section_def.repeats:
            del(self.__dict__[sub_section_def.name][index])

        elif sub_section_def.name in self.__dict__:
            del(self.__dict__[sub_section_def.name])
874

875
    def m_get_sub_section(self, sub_section_def: 'SubSection', index: int) -> 'MSection':
876
        ''' Retrieves a single sub section of the given sub section definition. '''
877
878
879
880
881
        if sub_section_def.repeats:
            return self.__dict__[sub_section_def.name][index]

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

883
    def m_get_sub_sections(self, sub_section_def: 'SubSection') -> Iterable['MSection']:
884
        ''' Retrieves  all sub sections of the given sub section definition. '''
885
        try:
886
887
888
889
            if sub_section_def.repeats:
                return self.__dict__[sub_section_def.name]
            else:
                return [self.__dict__[sub_section_def.name]]
890
891
        except KeyError:
            return []
892

893
    def m_sub_section_count(self, sub_section_def: 'SubSection') -> int:
894
        ''' Returns the number of sub sections for the given sub section definition. '''
895
896
897
898
899
900
901
902
        try:
            value = self.__dict__[sub_section_def.name]
            if sub_section_def.repeats:
                return len(value)
            else:
                return 1
        except KeyError:
            return 0
903

904
905
906
    def m_create(
            self, section_cls: Type[MSectionBound], sub_section_def: 'SubSection' = None,
            **kwargs) -> MSectionBound:
907
        ''' Creates a section instance and adds it to this section provided there is a
908
        corresponding sub section.
909
910
911
912
913

        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.
914
        '''
915

916
        section_def = section_cls.m_def
917
918
919
        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:
920
            raise TypeError('There is no sub section to hold a %s in %s.' % (section_def, self.m_def))
921

922
923
924
925
926
927
928
929
930
931
932
933
934
        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]

935
936
        sub_section = section_cls(**kwargs)
        self.m_add_sub_section(sub_section_def, sub_section)
937

938
        return cast(MSectionBound, sub_section)
939

940
    def m_update(self, safe: bool = True, **kwargs):
941
        ''' Updates all quantities and sub-sections with the given arguments. '''
942
        self.m_mod_count += 1
943
944
945
946
947
948
949
950
951
952
953
954
955
        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)
956
                    else:
957
958
                        self.m_add_sub_section(prop, item)

959
                else:
960
                    self.m_set(prop, value)
961

962
        else:
963
            self.__dict__.update(**kwargs)
964

965
    def m_as(self, section_cls: Type[MSectionBound]) -> MSectionBound:
966
        ''' 'Casts' this section to the given extending sections. '''
967
968
        return cast(MSectionBound, self)

969
    def m_follows(self, definition: 'Section') -> bool:
970
        ''' Determines if this section's definition is or is derived from the given definition. '''
971
        return self.m_def == definition or definition in self.m_def.all_base_sections
972

973
974
975
976
977
978
979
980
981
    def m_to_dict(self, with_meta: bool = False, include_defaults: bool = False) -> Dict[str, Any]:
        '''
        Returns the data of this section as a json serializeable dictionary.

        Arguments:
            with_meta: Include information about the section definition and the sections
                position in its parent.
            include_defaults: Include default values of unset quantities.
        '''
982
983

        def items() -> Iterable[Tuple[str, Any]]:
984
985
986
987
988
989
990
991
992
            # 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
993
            for name, quantity in self.m_def.all_quantities.items():
994
                if quantity.virtual:
995
996
                    continue

997
998
999
1000
                is_set = self.m_is_set(quantity)
                if not is_set:
                    if not include_defaults or not quantity.m_is_set(Quantity.default):
                        continue
1001

1002
                quantity_type = quantity.type
1003

1004
1005
                serialize: TypingCallable[[Any], Any] = str
                if isinstance(quantity_type, Reference):
1006

1007
1008
                    def reference_serialize(value):
                        if isinstance(value, MProxy):
1009
                            return value.m_proxy_url
1010
1011
1012
                        else:
                            return quantity_type.serialize(self, quantity, value)
                    serialize = reference_serialize
1013

1014
                elif isinstance(quantity_type, DataType):
1015

1016
1017
                    def data_type_serialize(value):
                        return quantity_type.serialize(self, quantity, value)
1018

1019
                    serialize = data_type_serialize
1020

1021
1022
                elif quantity_type in _primitive_types:
                    serialize = _primitive_types[quantity_type]
1023

1024
                elif type(quantity_type) == np.dtype:
1025
1026
1027
1028
                    def serialize_dtype(x):
                        return x.item()

                    serialize = serialize_dtype
1029
1030

                elif isinstance(quantity_type, MEnum):
1031
                    serialize = str
1032
1033
1034

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