-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathsemantics_models.py
1914 lines (1563 loc) · 58.1 KB
/
semantics_models.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
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
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
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
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Module containing the models describing a semantic state"""
import uuid
import pydantic as pyd
import requests
from aenum import Enum
from typing import (
List,
Tuple,
Dict,
Type,
TYPE_CHECKING,
Optional,
Union,
Set,
Iterator,
Any,
)
import filip.models.ngsi_v2.iot as iot
# from filip.models.ngsi_v2.iot import ExpressionLanguage, TransportProtocol
from filip.models.base import DataType, NgsiVersion
from filip.utils.validators import FiwareRegex
from filip.models.ngsi_v2.context import (
ContextEntity,
NamedContextAttribute,
NamedCommand,
)
from filip.models import FiwareHeader
from pydantic import ConfigDict, BaseModel, Field
from filip.config import settings
from filip.semantics.vocabulary.entities import DatatypeFields, DatatypeType
from filip.semantics.vocabulary_configurator import (
label_blacklist,
label_char_whitelist,
)
if TYPE_CHECKING:
from filip.semantics.semantics_manager import SemanticsManager
class InstanceHeader(FiwareHeader):
"""
Header of a SemanticClass instance, describes the Fiware Location were
the instance will be / is saved.
The header is not bound to one Fiware Setup, but can describe the
exact location in the web
"""
model_config = ConfigDict(frozen=True, use_enum_values=True)
cb_url: str = Field(
default=settings.CB_URL,
description="Url of the ContextBroker from the Fiware " "setup",
)
iota_url: str = Field(
default=settings.IOTA_URL,
description="Url of the IoTABroker from the Fiware " "setup",
)
ngsi_version: NgsiVersion = Field(
default=NgsiVersion.v2, description="Used Version in the " "Fiware setup"
)
def get_fiware_header(self) -> FiwareHeader:
"""
Get a Filip FiwareHeader from the InstanceHeader
"""
return FiwareHeader(service=self.service, service_path=self.service_path)
class InstanceIdentifier(BaseModel):
"""
Each Instance of a SemanticClass posses a unique identifier that is
directly linked to one Fiware entry
"""
model_config = ConfigDict(frozen=True)
id: str = Field(description="Id of the entry in Fiware")
type: str = Field(description="Type of the entry in Fiware, equal to " "class_name")
header: InstanceHeader = Field(
description="describes the Fiware "
"Location were the instance "
"will be / is saved."
)
class Datatype(DatatypeFields):
"""
Model of a vocabulary/ontology Datatype used to validate assignments in
DataFields
"""
def value_is_valid(self, value: str) -> bool:
"""
Test if value is valid for this datatype.
Numbers are also given as strings
Args:
value (str): value to be tested
Returns:
bool
"""
if self.type == "string":
if len(self.allowed_chars) > 0:
for char in value:
if char not in self.allowed_chars:
return False
for char in self.forbidden_chars:
if char in value:
return False
return True
if self.type == "number":
if self.number_decimal_allowed:
try:
number = float(value)
except ValueError:
return False
else:
try:
number = int(value)
except ValueError:
return False
if not self.number_range_min == "/":
if number < self.number_range_min:
return False
if not self.number_range_max == "/":
if number > self.number_range_max:
return False
return True
if self.type == "enum":
return value in self.enum_values
if self.type == "date":
try:
from dateutil.parser import parse
parse(value, fuzzy=False)
return True
except ValueError:
return False
return True
class DevicePropertyInstanceLink(BaseModel):
"""
SubProperties of a DeviceProperty, containing the information to which
instance the DeviceProperty belongs.
Modeled as a standalone model, to bypass the read-only logic of
DeviceProperty
"""
instance_identifier: Optional[InstanceIdentifier] = Field(
default=None, description="Identifier of the instance holding this Property"
)
semantic_manager: Optional["SemanticsManager"] = Field(
default=None, description="Link to the governing semantic_manager"
)
field_name: Optional[str] = Field(
default=None,
description="Name of the field to which this property was added "
"in the instance",
)
class DeviceProperty(BaseModel):
"""
Model describing one specific property of an IoT device.
It is either a command that can be executed or an attribute that can be read
A property can only belong to one field of one instance. Assigning it to
multiple fields will result in an error.
"""
model_config = ConfigDict()
name: str = Field("Internally used name in the IoT Device")
_instance_link: DevicePropertyInstanceLink = DevicePropertyInstanceLink()
"""Additional properties describing the instance and field where this \
property was added"""
def _get_instance(self) -> "SemanticClass":
"""Get the instance object to which this property was added"""
return self._instance_link.semantic_manager.get_instance(
self._instance_link.instance_identifier
)
def _get_field_from_fiware(
self, field_name: str, required_type: str
) -> NamedContextAttribute:
"""
Retrieves live information about a field from the assigned instance
from Fiware
Args:
field_name (str): Name of the to retrieving field
required_type (str): Type that the retrieved field is required to
have
Raises:
Exception; if the instance or the field is not present in Fiware
(the instance state was not yet saved)
Exception; The field_type does not match
"""
if self._instance_link.field_name is None:
raise Exception(
"This DeviceProperty needs to be added to a "
"device field of an SemanticDeviceClass instance "
"and the state saved before this methode can be "
"executed"
)
try:
entity = self._instance_link.semantic_manager.get_entity_from_fiware(
instance_identifier=self._instance_link.instance_identifier
)
except requests.RequestException:
raise Exception(
"The instance to which this property belongs is "
"not yet present in Fiware, you need to save the "
"state first"
)
try:
attr = entity.get_attribute(field_name)
except requests.RequestException:
raise Exception(
"This property was not yet saved in Fiware. "
"You need to save the state first before this "
"methode can be executed"
)
if not attr.type == required_type:
raise Exception(
"The field in Fiware has a wrong type, "
"an uncaught naming conflict happened"
)
return attr
def get_all_field_names(self, field_name: Optional[str] = None) -> List[str]:
"""
Get all field names which this property creates in the fiware
instance
Args:
field_name (Optional[str]): Name of the field to which the attribute
is/will be added. If none is provided, the linked field name
is used
"""
pass
class Command(DeviceProperty):
"""
Model describing a command property of an IoT device.
The command will add three fields to the fiware instance:
- name - Used to execute the command, function: send()
- name_info - Used to retrieve the command result: get_info()
- name_status - Used to see the current status: get_status()
A command can only belong to one field of one instance. Assigning it to
multiple fields will result in an error.
"""
model_config = ConfigDict(frozen=True)
def send(self):
"""
Execute the command on the IoT device
Raises:
Exception: If the command was not yet saved to Fiware
"""
client = self._instance_link.semantic_manager.get_client(
self._instance_link.instance_identifier.header
)
context_command = NamedCommand(name=self.name, value="")
identifier = self._instance_link.instance_identifier
client.post_command(
entity_id=identifier.id,
entity_type=identifier.type,
command=context_command,
)
client.close()
def get_info(self) -> str:
"""
Retrieve the executed command result from the IoT-Device
Raises:
Exception: If the command was not yet saved to Fiware
"""
return self._get_field_from_fiware(
field_name=f"{self.name}_info", required_type="commandResult"
).value
def get_status(self):
"""
Retrieve the executed command status from the IoT-Device
Raises:
Exception: If the command was not yet saved to Fiware
"""
return self._get_field_from_fiware(
field_name=f"{self.name}_status", required_type="commandStatus"
).value
def get_all_field_names(self, field_name: Optional[str] = None) -> List[str]:
"""
Get all the field names that this command will add to Fiware
Args:
field_name (Optional[str]): Not used, but needed in the signature
"""
return [self.name, f"{self.name}_info", f"{self.name}_result"]
class DeviceAttributeType(str, Enum):
"""
Retrieval type of the DeviceAttribute value from the IoT Device into Fiware
"""
_init_ = "value __doc__"
lazy = "lazy", "The value is only read out if it is requested"
active = "active", "The value is kept up-to-date"
class DeviceAttribute(DeviceProperty):
"""
Model describing an attribute property of an IoT device.
The attribute will add one field to the fiware instance:
- {NameOfInstanceField}_{Name}, holds the value of the Iot device
attribute: get_value()
A DeviceAttribute can only belong to one field of one instance. Assigning
it to multiple fields will result in an error.
"""
model_config = ConfigDict(frozen=True, use_enum_values=True)
attribute_type: DeviceAttributeType = Field(
description="States if the attribute is read actively or lazy from "
"the IoT Device into Fiware"
)
def get_value(self):
"""
Retrieve the current value from the Iot Device
Raises:
Exception: If the DeviceAttribute was not yet saved to Fiware
"""
return self._get_field_from_fiware(
field_name=f"{self._instance_link.field_name}_{self.name}",
required_type="StructuredValue",
).value
def get_all_field_names(self, field_name: Optional[str] = None) -> List[str]:
"""
Get all field names which this property creates in the fiware
instance
Args:
field_name (str): Name of the field to which the attribute
is/will be added. If none is provided, the linked field name
is used
"""
if field_name is None:
field_name = self._instance_link.field_name
return [f"{field_name}_{self.name}"]
class Field(BaseModel):
"""
A Field corresponds to a CombinedRelation for a class from the vocabulary.
It itself is a _set, that is enhanced with methods to provide validation
of the values according to the rules stated in the vocabulary.
The values of a field are unique and without order
The fields of a class are predefined. A field can contain standard values
on init
"""
model_config = ConfigDict()
name: str = Field(
default="",
description="Name of the Field, corresponds to the property name that "
"it has in the SemanticClass",
)
_semantic_manager: "SemanticsManager"
"Reference to the global SemanticsManager"
_instance_identifier: InstanceIdentifier
"Identifier of instance, that has this field as property"
_set: Set = Field(
default=set(),
description="Internal set of the field, to which values are saved",
)
def __init__(self, name, semantic_manager):
self._semantic_manager = semantic_manager
super().__init__()
self.name = name
self._set = set()
def is_valid(self) -> bool:
"""
Check if the current state is valid -> Can be saved to Fiware
"""
pass
def build_context_attribute(self) -> NamedContextAttribute:
"""
Convert the field to a NamedContextAttribute that can eb added to a
ContextEntity
Returns:
NamedContextAttribute
"""
pass
def build_device_attributes(
self,
) -> List[
Union[
iot.DeviceAttribute,
iot.LazyDeviceAttribute,
iot.StaticDeviceAttribute,
iot.DeviceCommand,
]
]:
"""
Convert the field to a DeviceAttribute that can eb added to a
DeviceEntity
Returns:
List[Union[iot.DeviceAttribute,
iot.LazyDeviceAttribute,
iot.StaticDeviceAttribute,
iot.DeviceCommand]]
"""
values = []
for v in self.get_all_raw():
if isinstance(v, BaseModel):
values.append(v.model_dump())
else:
values.append(v)
x = [
iot.StaticDeviceAttribute(
name=self.name,
type=DataType.STRUCTUREDVALUE,
value=values,
entity_name=None,
entity_type=None,
)
]
return x
def __len__(self) -> int:
"""Get the number of values
Returns:
int
"""
return len(self._set)
def size(self) -> int:
"""Get the number of values
Returns:
int
"""
return self.__len__()
def remove(self, v):
"""
Remove the given value from the field.
Args:
v, value that is in the field
Raises:
KeyError: if value not in field
"""
self._set.remove(v)
def add(self, v):
"""
Add the value v to the field, duplicates are ignored (Set logic)
Args:
v (Any) Value to be added, of fitting type
Raises:
ValueError: if v is of invalid type
"""
self._set.add(v)
def update(self, values: Union[List, Set]):
"""
Add all the values to the field, duplicates are ignored (Set logic)
Args:
values (Union[List, Set]): Values to be added, each of fitting type
Raises:
ValueError: if one value is of invalid type
"""
for v in values:
self.add(v)
def set(self, values: List):
"""
Set the values of the field equal to the given list
Args:
values: List of values fitting for the field
Returns:
None
"""
self.clear()
for v in values:
self.add(v)
def clear(self):
"""
Remove all values of the field
Returns:
None
"""
for v in self.get_all():
self.remove(v)
def __str__(self):
"""
Get Field in a nice readable way
Returns:
str
"""
result = f"Field: {self.name},\n\tvalues: ["
values = self.get_all_raw()
for value in values:
result += f"{value}, "
if len(values) > 0:
result = result[:-2]
return result
def get_all_raw(self) -> Set:
"""
Get all values of the field exactly as they are hold inside the
internal list
"""
return self._set
def get_all(self) -> List:
"""
Get all values of the field in usable form.
Returns the set in List for as some values are not hashable in
converted form.
But the order is random
Returns:
List, unsorted
"""
return [self._convert_value(v) for v in self._set]
def _convert_value(self, v):
"""
Converts the internal saved value v, to the type that should be returned
"""
return v
def _get_instance(self) -> "SemanticClass":
"""
Get the instance object to which this field belongs
"""
return self._semantic_manager.get_instance(self._instance_identifier)
def get_field_names(self) -> List[str]:
"""
Get the names of all fields this field will create in the Fiware entity.
(DeviceProperties can create additional fields)
Returns:
List[str]
"""
return [self.name]
def values_to_json(self) -> List[str]:
"""
Convert each value of the field to a json string
Returns:
List[str]
"""
res = []
for v in self.get_all_raw():
if isinstance(v, BaseModel):
res.append(v.model_dump_json())
else:
res.append(v)
return res
def __contains__(self, item) -> bool:
"""
Overrides the magic "in" to test if a value/item is inside the field.
Returns:
bool
"""
return item in self.get_all()
def __iter__(self) -> Iterator[Any]:
"""
Overrides the magic "in" to loop over the field values
"""
return self.get_all().__iter__()
class DeviceField(Field):
"""
A Field that represents a logical part of a device.
Abstract Superclass
"""
_internal_type: type = DeviceProperty
"""
Type which is allowed to be stored in the field.
Set in the subclasses, but has to be a subclass of DeviceProperty
"""
def is_valid(self) -> bool:
"""
Check if the current state is valid -> Can be saved to Fiware
Returns:
True, if all values are of type _internal_type
"""
for value in self.get_all_raw():
if not isinstance(value, self._internal_type):
return False
return True
def name_check(self, v: _internal_type):
"""
Executes name checks before value v is assigned to field values
Each field name that v will add to the Fiware instance needs to be
available
Args:
v (_internal_type): Value to be added to the field
Raises:
NameError: if a field name of v is not available
if a field name of v is blacklisted
if the name of v contains a forbidden character
"""
taken_fields = self._get_instance().get_all_field_names()
for name in v.get_all_field_names(field_name=self.name):
if name in taken_fields:
raise NameError(
f"The property can not be added to the field "
f"{self.name}, because the instance already"
f" posses a field with the name {name}"
)
if name in label_blacklist:
raise NameError(
f"The property can not be added to the field "
f"{self.name}, because the name {name} is "
f"forbidden"
)
for c in name:
if c not in label_char_whitelist:
raise NameError(
f"The property can not be added to the field "
f"{self.name}, because the name {name} "
f"contains the forbidden character {c}"
)
def remove(self, v):
"""List function: Remove a values
Makes the value available again to be added to other fields/instances
"""
v._instance_link.instance_identifier = None
v._instance_link.semantic_manager = None
v._instance_link.field_name = None
super(DeviceField, self).remove(v)
def add(self, v):
"""List function: If checks pass , add value
Args:
v, value to add
Raises:
AssertionError, if v is of wrong type
AssertionError, if v already belongs to a field
NameError, if v has an invalid name
Returns:
None
"""
# assert that the given value fulfills certain conditions
assert isinstance(v, self._internal_type)
assert isinstance(v, DeviceProperty)
assert (
v._instance_link.instance_identifier is None
), "DeviceProperty can only belong to one device instance"
# test if name of v is valid, if not an error is raised
self.name_check(v)
# link attribute to field and instance
v._instance_link.instance_identifier = self._instance_identifier
v._instance_link.semantic_manager = self._semantic_manager
v._instance_link.field_name = self.name
super(DeviceField, self).add(v)
def get_field_names(self) -> List[str]:
"""
Get all names of fields that would be/are generated by this field in
the fiware device_entity and its current values
Returns:
List[str]
"""
names = super().get_field_names()
for v in self.get_all_raw():
names.extend(v.get_all_field_names())
return names
def build_context_attribute(self) -> NamedContextAttribute:
"""Export Field as NamedContextAttribute
only needed when saving local state as json
Returns:
NamedContextAttribute
"""
values = []
for v in self.get_all_raw():
if isinstance(v, BaseModel):
values.append(v.model_dump())
else:
values.append(v)
return NamedContextAttribute(name=self.name, value=values)
class CommandField(DeviceField):
"""
A Field that holds commands that can be send to the device
"""
_internal_type = Command
def get_all_raw(self) -> Set[Command]:
return super().get_all_raw()
def get_all(self) -> List[Command]:
return super().get_all()
def __iter__(self) -> Iterator[Command]:
return super().__iter__()
def build_device_attributes(
self,
) -> List[
Union[
iot.DeviceAttribute,
iot.LazyDeviceAttribute,
iot.StaticDeviceAttribute,
iot.DeviceCommand,
]
]:
attrs = super().build_device_attributes()
for command in self.get_all_raw():
attrs.append(
iot.DeviceCommand(
name=command.name,
)
)
return attrs
class DeviceAttributeField(DeviceField):
"""
A Field that holds attributes of the device that can be referenced for
live reading of the device
"""
_internal_type = DeviceAttribute
def get_all_raw(self) -> Set[DeviceAttribute]:
return super().get_all_raw()
def get_all(self) -> List[DeviceAttribute]:
return super().get_all()
def __iter__(self) -> Iterator[DeviceAttribute]:
return super().__iter__()
def build_device_attributes(
self,
) -> List[
Union[
iot.DeviceAttribute,
iot.LazyDeviceAttribute,
iot.StaticDeviceAttribute,
iot.DeviceCommand,
]
]:
attrs = super().build_device_attributes()
for attribute in self.get_all_raw():
if attribute.attribute_type == DeviceAttributeType.active:
attrs.append(
iot.DeviceAttribute(
object_id=attribute.name,
name=f"{self.name}_{attribute.name}",
type=DataType.STRUCTUREDVALUE,
entity_name=None,
entity_type=None,
)
)
else:
attrs.append(
iot.LazyDeviceAttribute(
object_id=attribute.name,
name=f"{self.name}_{attribute.name}",
type=DataType.STRUCTUREDVALUE,
entity_name=None,
entity_type=None,
)
)
return attrs
class RuleField(Field):
"""
A RuleField corresponds to a CombinedRelation for a class from the
vocabulary.
It itself is a list, that is enhanced with methods to provide validation
of the values according to the rules stated in the vocabulary
The fields of a class are predefined. A field can contain standard values
on init
"""
_rules: List[Tuple[str, List[List[str]]]]
"""rule formatted for machine readability """
rule: str = pyd.Field(
default="", description="rule formatted for human readability"
)
def __init__(self, rule, name, semantic_manager):
self._semantic_manager = semantic_manager
super().__init__(name, semantic_manager)
self.rule = rule
def is_valid(self) -> bool:
"""
Check if the values present in this relationship fulfills the semantic
rule.
returns:
bool
"""
# true if all rules are fulfilled
for [rule, fulfilled] in self.are_rules_fulfilled():
if not fulfilled:
return False
return True
def are_rules_fulfilled(self) -> List[Tuple[str, bool]]:
"""
Check if the values present in this relationship fulfill the
individual semantic rules.
Returns:
List[Tuple[str, bool]], [[readable_rule, fulfilled]]
"""
# rule has form: (STATEMENT, [[a,b],[c],[a,..],..])
# A value fulfills the rule if it is an instance of all the classes,
# datatype_catalogue listed in at least one innerlist
# A field is fulfilled if a number of values fulfill the rule,
# the number is depending on the statement
# The STATEMENTs and their according numbers are (STATEMENT|min|max):
# - only | len(values) | len(values)
# - some | 1 | len(values)
# - min n | n | len(values)
# - max n | 0 | n
# - range n,m | n | m
res = []
values = self.get_all()
readable_rules = self.rule.split(",")
rule_counter = 0
# loop over all rules, if a rule is not fulfilled return False
for rule in self._rules:
# rule has form: (STATEMENT, [[a,b],[c],[a,..],..])
statement: str = rule[0]
outer_list: List[List] = rule[1]
readable_rule = readable_rules[rule_counter].strip()
rule_counter = rule_counter + 1
# count how many values fulfill this rule
fulfilling_values = 0
for v in values:
# A value fulfills the rule if there exists an innerlist of
# which the value is an instance of each value
fulfilled = False
for inner_list in outer_list:
counter = 0
for rule_value in inner_list:
if self._value_is_valid(v, rule_value):
counter += 1
if len(inner_list) == counter:
fulfilled = True
if fulfilled:
fulfilling_values += 1
# test if rule failed by evaluating the statement and the
# number of fulfilling values
if "min" in statement:
number = int(statement.split("|")[1])
if not fulfilling_values >= number:
res.append([readable_rule, False])
elif "max" in statement:
number = int(statement.split("|")[1])
if not fulfilling_values <= number:
res.append([readable_rule, False])
elif "exactly" in statement:
number = int(statement.split("|")[1])
if not fulfilling_values == number:
res.append([readable_rule, False])
elif "some" in statement:
if not fulfilling_values >= 1:
res.append([readable_rule, False])
elif "only" in statement:
if not fulfilling_values == len(values):
res.append([readable_rule, False])
elif "value" in statement:
if not fulfilling_values >= 1:
res.append([readable_rule, False])
if len(res) == 0 or not (res[-1][0] == readable_rule):
res.append([readable_rule, True])
return res
def _value_is_valid(self, value, rule_value) -> bool:
"""
Test if a value of the field, fulfills a part of a rule
Args:
value: Value in field
rule_value: Value from inner List of rules_
Returns:
bool, True if valid
"""
pass
def __str__(self):
"""
Get Field in a nice readable way
Returns:
str
"""