Repository navigation
Expand file tree
/
Copy pathids.py
More file actions
1211 lines (1031 loc) · 45.8 KB
/
Copy pathids.py
File metadata and controls
1211 lines (1031 loc) · 45.8 KB
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
# IDS - Information Delivery Specification.
# Copyright (C) 2021 Artur Tomczak <artomczak@gmail.com>, Thomas Krijnen <mail@thomaskrijnen.com>
#
# This file is part of IfcOpenShell.
#
# IfcOpenShell is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# IfcOpenShell is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with IfcOpenShell. If not, see <http://www.gnu.org/licenses/>.
import re
import logging
import operator
import os
import csv
import numpy as np
from datetime import date
import ifcopenshell.util.element
import ifcopenshell.util.placement
from bcf.v2.bcfxml import BcfXml
from bcf.v2 import data as bcf
from bcf import bcfxml
from xmlschema import XMLSchema
from xmlschema import XMLSchemaConverter
from xmlschema import etree_tostring
from lxml import etree as ElementTree
from xmlschema.validators import facets
from xmlschema.validators import identities
cwd = os.path.dirname(os.path.realpath(__file__))
ids_schema = XMLSchema(os.path.join(cwd, "ids.xsd")) # source: "http://standards.buildingsmart.org/IDS/ids_04.xsd"
def error(msg):
raise Exception(msg)
class ids:
"""Represents the XML root <ids> node and its <specification> childNodes."""
def __init__(
self,
ifcversion=None,
description=None,
author=None,
copyright=None,
version=None,
creation_date=None,
purpose=None,
milestone=None,
):
"""Create an IDS object.
:param ifcversion: IFC schema version. If None, then schema independent. Options: '2.3.0.1'|'4.0.2.1'|'4.3.0.0'|None, defaults to None
:type ifcversion: str, optional
:param description:, defaults to None
:type description: str, optional
:param author: Email of the IDS author, defaults to None
:type author: str, optional
:param copyright:, defaults to None
:type copyright: str, optional
:param version: IDS file version, defaults to None
:type version: float, optional
:param creation_date: Date in 'yyyy-mm-dd' format, defaults to current date
:type creation_date: str, optional
:param purpose:, defaults to None
:type purpose: str, optional
:param milestone:, defaults to None
:type milestone: str, optional
"""
self.specifications = []
self.info = {}
if ifcversion:
if ifcversion in ["2.3.0.1", "4.0.2.1", "4.3.0.0"]:
self.info["ifcversion"] = ifcversion
if author:
if "@" in author:
self.info["author"] = author
if description:
self.info["description"] = description
if copyright:
self.info["copyright"] = copyright
if version:
self.info["version"] = version
if creation_date:
if re.match(r"\d\d\d\d-\d\d-\d\d", creation_date):
self.info["date"] = creation_date # date.fromisoformat(creation_date).isoformat()
if "date" not in self.info:
self.info["date"] = date.today().isoformat()
if purpose:
self.info["purpose"] = purpose
if milestone:
self.info["milestone"] = milestone
def asdict(self):
"""Converts object to a dictionary, adding required attributes.
:return: Xmlschema compliant dictionary.
:rtype: dict
"""
ids_dict = {
"@xmlns": "http://standards.buildingsmart.org/IDS",
"@xmlns:xs": "http://www.w3.org/2001/XMLSchema",
"@xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance",
"@xsi:schemaLocation": "http://standards.buildingsmart.org/IDS/ids_04.xsd",
"specification": [],
"info": self.info,
}
for spec in self.specifications:
ids_dict["specification"].append(spec.asdict())
return ids_dict
def to_xml(self, filepath="./", ids_schema=ids_schema):
"""Save IDS object as .xml file.
:param filepath: Path for the new file, defaults to "./"
:type filepath: str, optional
:param ids_schema: XML Schema for an IDS file, defaults to ids_schema object from buildingSMART
:type ids_schema: XMLschema, optional
:return: Result of the newly created file validation against the schema.
:rtype: bool
"""
if filepath.endswith("/"):
filepath = filepath + "IDS"
if not filepath.endswith(".xml"):
filepath = filepath + ".xml"
ids_dict = self.asdict()
ids_xml = ids_schema.encode(
ids_dict,
namespaces={
"": "http://standards.buildingsmart.org/IDS",
"xs": "http://www.w3.org/2001/XMLSchema",
"xsi": "http://www.w3.org/2001/XMLSchema-instance",
"xsi:schemaLocation": "http://standards.buildingsmart.org/IDS/ids_04.xsd",
},
) # validation='skip',
ids_str = etree_tostring(
ids_xml,
namespaces={
"": "http://standards.buildingsmart.org/IDS",
# 'xs': 'http://www.w3.org/2001/XMLSchema',
# 'xsi': 'http://www.w3.org/2001/XMLSchema-instance',
# 'xsi:schemaLocation': "http://standards.buildingsmart.org/IDS/ids_04.xsd"
},
)
with open(filepath, "w") as f:
f.write('<?xml version="1.0" encoding="UTF-8"?>\n')
f.write("<!-- IDS (INFORMATION DELIVERY SPECIFICATION) CREATED USING IFCOPENSHELL -->\n")
f.write(ids_str)
f.close()
# ids_schema.validate(filepath)
return ids_schema.is_valid(filepath)
@staticmethod
def open(filepath, ids_schema=ids_schema):
"""Use to open ids.xml files
:param filepath: ids file path
:type filepath: str
:param ids_schema: XML Schema for an IDS file, defaults to ids_schema object from buildingSMART
:type ids_schema: XMLschema, optional
:return: IDS file as a python object
:rtype: ids object
"""
ids_schema.validate(filepath)
ids_content = ids_schema.decode(
filepath, strip_namespaces=True, namespaces={"": "http://standards.buildingsmart.org/IDS"}
)
ids_file = ids()
ids_file.specifications = [specification.parse(s) for s in ids_content["specification"]]
return ids_file
def validate(self, ifc_file, logger=None):
"""Use to validate IFC model against IDS specifications.
:param ifc_file: path to ifc file
:type ifc_file: str
:param logger: Logging object with handlers, defaults to None
:type logger: logging, optional
"""
if not isinstance(logger, logging.Logger):
logger = logging.getLogger("IDS_Logger")
logging.basicConfig(level=logging.INFO, format="%(message)s")
logger.setLevel(logging.INFO)
if "ifcversion" in self.info.keys():
if self.info["ifcversion"] in ["2.3.0.1", "4.0.2.1", "4.3.0.0"]:
if self.info["ifcversion"][0:3] == "2.3":
if not ifc_file.schema.startswith("IFC2x3"):
logger.error("IFC file is of %s not of %s schema." % (ifc_file.schema, self.info["ifcversion"]))
elif self.info["ifcversion"][0:3] == "4.0":
if not ifc_file.schema == "IFC4":
logger.error("IFC file is of %s not of %s schema." % (ifc_file.schema, self.info["ifcversion"]))
elif self.info["ifcversion"][0:3] == "4.3":
if not ifc_file.schema.startswith("IFC4x3"):
logger.error("IFC file is of %s not of %s schema." % (ifc_file.schema, self.info["ifcversion"]))
else:
logger.error("IFC version not recognized")
# Consider other way around: for elem, for spec so we can see if an element pass all IDSes?
for spec in self.specifications:
self.ifc_applicable = 0
self.ifc_passed = 0
for elem in ifc_file.by_type("IfcObject"):
apply, comply = spec(elem, logger)
if apply:
self.ifc_applicable += 1
if comply:
self.ifc_passed += 1
if self.ifc_applicable == 0:
if spec.necessity == "required":
logger.error("No applicable elements found. Minimum 1 applicable element required.")
else:
logger.debug("No applicable elements found. None required.")
logger.debug(
"Out of %s IFC elements, %s were applicable and %s of them passed (%s)."
% (
len(ifc_file.by_type("IfcProduct")),
self.ifc_applicable,
self.ifc_passed,
str(self.ifc_passed / self.ifc_applicable * 100) + "%",
)
)
for h in logger.handlers:
h.flush()
class specification:
"""Represents the XML <specification> node and its two children <applicability> and <requirements>"""
def __init__(self, name="Specification", necessity="required"):
"""Create a specification to be added in ids.
:param name:, defaults to "Specification"
:type name: str, optional
:param necessity: 'required'|'optional', defaults to "required"
:type necessity: str, optional
"""
self.name = name
self.applicability = None
self.requirements = None
self.necessity = necessity
def asdict(self):
"""Converts object to a dictionary, adding required attributes.
:return: Xmlschema compliant dictionary.
:rtype: dict
"""
# if older python collections.OrderedDict()
spec_dict = {
"@name": self.name,
"@necessity": self.necessity,
"applicability": {},
"requirements": {},
}
for x in ["applicability", "requirements"]:
for fac in (getattr(self, x)).terms:
fclass = type(fac).__name__
if fclass in spec_dict[x]:
spec_dict[x][fclass].append(fac.asdict())
else:
spec_dict[x][fclass] = [fac.asdict()]
return spec_dict
@staticmethod
def parse(ids_dict):
"""Parse xml specification to python object.
:param ids_dict:
:type ids_dict: dict
"""
def parse_rules(dict):
facet_names = list(dict.keys())
facet_properties = [v[0] if isinstance(v, list) else v for v in list(dict.values())]
classes = [meta_facet.facets.__getitem__(f) for f in facet_names]
facets = [cls(n) for cls, n in zip(classes, facet_properties)]
return facets
spec = specification()
spec.name = ids_dict["@name"]
spec.necessity = ids_dict["@necessity"]
spec.applicability = boolean_and(parse_rules(ids_dict["applicability"]))
spec.requirements = boolean_and(parse_rules(ids_dict["requirements"]))
return spec
def add_applicability(self, facet):
"""Applicability specifies what conditions must be meet for an IFC object to be used for validation. Note, that at least one entity facet is required.
:param facet: any of entity|classification|property|material
:type facet: facet
Example::
i = ids.ids()
i.specifications.append(ids.specification(name="Test_Specification"))
e = ids.entity.create(name="Test_Name", predefinedtype="Test_PredefinedType")
i.specifications[0].add_applicability(e)
"""
if self.applicability:
self.applicability = boolean_and(self.applicability.terms + [facet])
else:
self.applicability = boolean_and([facet])
def add_requirement(self, facet):
"""Requirement is validated on all applicable IFC elements. Note, that at least one facet of any type is required.
:param facet: any of entity|classification|property|material
:type facet: facet
"""
if self.requirements:
self.requirements = boolean_and(self.requirements.terms + [facet])
else:
self.requirements = boolean_and([facet])
def __call__(self, inst, logger):
"""When specification is called on an ifc instance, it validates against applicability and requirements.
:param inst: IFC entity element
:type inst: IFC entity
:param logger: Logging object
:type logger: logging
:return: results of validation on applicability and requirements
:rtype: [bool,bool]
"""
if self.applicability(inst, logger):
valid = self.requirements(inst, logger)
if valid:
logger.info(
{
"guid": inst.GlobalId,
"result": valid.success,
"sentence": str(self)
+ ".\n"
+ inst.is_a()
+ " '"
+ str(inst.Name)
+ "' (#"
+ str(inst.id())
+ ") has "
+ str(valid)
+ " so is compliant",
"ifc_element": inst,
}
)
return True, True
else:
# BUG "has does not have"
logger.error(
{
"guid": inst.GlobalId,
"result": valid.success,
"sentence": str(self)
+ ".\n"
+ inst.is_a()
+ " '"
+ str(inst.Name)
+ "' (#"
+ str(inst.id())
+ ") has "
+ str(valid)
+ " so is not compliant",
"ifc_element": inst,
}
)
return True, False
else:
return False, False
def __str__(self):
"""Represent the specification in human readible sentence.
:return: sentence
:rtype: str
"""
return "Given an instance with %(applicability)s\nWe expect %(requirements)s" % self.__dict__
class facet_evaluation:
"""The evaluation of a facet with data from IFC. Converts to bool and has a human readable string format."""
def __init__(self, success, str):
self.success = success
self.str = str
def __bool__(self):
return self.success
def __str__(self):
return self.str
class meta_facet(type):
"""A metaclass for automatically registering facets in a map to be instantiated based on XML tagnames."""
facets = {}
def __new__(cls, clsname, bases, attrs):
newclass = super(meta_facet, cls).__new__(cls, clsname, bases, attrs)
meta_facet.facets[clsname] = newclass
return newclass
class facet(metaclass=meta_facet):
"""
The base class for IDS facets. IDS facets are functors constructed from
XML nodes that return True or False. A getattr method is provided for
conveniently extracting XML child node text content.
Use child classes instead: entity, classification, property and material.
"""
def __init__(self, node=None, location=None):
if node:
self.node = node
if "@location" in self:
self.location = self.node["@location"]
else:
self.location = "any"
if location:
self.location = location
else:
self.location = "any"
def __getattr__(self, k):
if k in self.node:
v = self.node[k]
# BUG list of dictionaries should not happen
if isinstance(v, list):
v = v[0]
if "simpleValue" in list(v):
return v["simpleValue"]
elif "restriction" in list(v):
return restriction.parse(v["restriction"][0])
# TODO handle more than one restriction: return [restriction(r) for r in v["restriction"]]
else:
raise Exception("Unknown value declaration.")
else:
return None
def __iter__(self):
for k in self.parameters:
yield k, getattr(self, k)
def __str__(self):
di = dict(list(self))
for k, v in di.items():
if isinstance(v, str) and not len(v):
di[k] = "not specified"
return self.message % di
class entity(facet):
"""The IDS entity facet currently *with* inheritance"""
parameters = ["name", "predefinedtype"]
@staticmethod
def create(name=None, predefinedtype=None):
"""Create an entity facet that can be added to applicability or requirements of IDS specification.
:param name: IFC entity name that is required. e.g. IfcWall, defaults to None
:type name: str, optional
:param predefinedtype: name of the predefined type, defaults to None
:type predefinedtype: str, optional
:return: entity object
:rtype: entity
"""
inst = entity()
inst.name = name
inst.predefinedtype = predefinedtype
return inst
def asdict(self):
"""Converts object to a dictionary, adding required attributes.
:return: Xmlschema compliant dictionary.
:rtype: dict
"""
fac_dict = {"name": parameter_asdict(self.name)}
try:
fac_dict["predefinedtype"] = parameter_asdict(self.predefinedtype)
except (RecursionError, UnboundLocalError) as e:
print(e)
return fac_dict
def __call__(self, inst, logger):
"""Validate an ifc instance against that entity facet.
:param inst: IFC entity element
:type inst: IFC entity
:param logger: Logging object
:type logger: logging
:return: result of the validation as bool and message
:rtype: facet_evaluation(bool, str)
"""
# @nb with inheritance
if self.predefinedtype and hasattr(inst, "PredefinedType"):
self.message = "an entity name '%(name)s' of predefined type '%(predefinedtype)s'"
return facet_evaluation(
inst.is_a(self.name) and inst.PredefinedType == self.predefinedtype,
self.message % {"name": inst.is_a(), "predefinedtype": inst.PredefinedType},
)
else:
self.message = "an entity name '%(name)s'"
return facet_evaluation(inst.is_a(self.name), self.message % {"name": inst.is_a()})
class classification(facet):
"""
The IDS classification facet by traversing the HasAssociations inverse attribute
"""
parameters = ["system", "value", "location"]
message = "%(location)sclassification reference %(value)s from '%(system)s'"
@staticmethod
def create(location="any", value=None, system=None):
"""Create a classification facet that can be added to applicability or requirements of IDS specification.
:param location: Define where to check for the parameter. One of "any"|"instance"|"type", defaults to "any"
:type location: str, optional
:param value: Value that is required. Could be alphanumeric or restriction object, defaults to None
:type value: restriction|alphanumeric, optional
:param system: System that is required. Could be alphanumeric or restriction object, defaults to None
:type system: restriction|alphanumeric, optional
:return: classification object
:rtype: classification
"""
inst = classification()
inst.location = location
inst.value = value
inst.system = system
return inst
def asdict(self):
"""Converts object to a dictionary, adding required attributes.
:return: Xmlschema compliant dictionary.
:rtype: dict
"""
fac_dict = {
"value": parameter_asdict(self.value),
"system": parameter_asdict(self.system),
"@location": self.location,
# "instructions": "SAMPLE_INSTRUCTIONS",
}
return fac_dict
def __call__(self, inst, logger):
"""Validate an ifc instance against that classification facet.
:param inst: IFC entity element
:type inst: IFC entity
:param logger: Logging object
:type logger: logging
:return: result of the validation as bool and message
:rtype: facet_evaluation(bool, str)
"""
instance_classiciations = inst.HasAssociations
if ifcopenshell.util.element.get_type(inst):
type_classifications = ifcopenshell.util.element.get_type(inst).HasAssociations
else:
type_classifications = ()
if self.location == "instance" and instance_classiciations:
associations = instance_classiciations
elif self.location == "type" and type_classifications:
associations = type_classifications
elif self.location == "any" and (instance_classiciations or type_classifications):
associations = instance_classiciations + type_classifications
else:
associations = ()
refs = []
for association in associations:
if association.is_a("IfcRelAssociatesClassification"):
cref = association.RelatingClassification
if hasattr(cref, "ItemReference"): # IFC2x3
refs.append((cref.ReferencedSource.Name, cref.ItemReference))
elif hasattr(cref, "Identification"): # IFC4
refs.append((cref.ReferencedSource.Name, cref.Identification))
self.location_msg = location[self.location]
if refs:
return facet_evaluation(
(self.system, self.value) in refs,
self.message
% {
"system": refs[0][0],
"value": "'" + refs[0][1] + "'",
"location": self.location_msg,
}, # what if not first item of refs?
)
else:
return facet_evaluation(False, "does not have %sclassification reference" % self.location_msg)
class property(facet):
"""
The IDS property facet implemented using `ifcopenshell.util.element`
"""
parameters = ["name", "propertyset", "value", "location"]
message = "%(location)sproperty '%(name)s' in '%(propertyset)s' with a value %(value)s"
@staticmethod
def create(location="any", propertyset=None, name=None, value=None):
"""Create a property facet that can be added to applicability or requirements of IDS specification.
:param location: Define where to check for the parameter. One of "any"|"instance"|"type", defaults to "any"
:type location: str, optional
:param propertyset: Propertyset that is required. Could be alphanumeric or restriction object, defaults to None
:type propertyset: restriction|alphanumeric, optional
:param name: Name that is required. Could be alphanumeric or restriction object, defaults to None
:type name: restriction|alphanumeric, optional
:param value: Value that is required. Could be alphanumeric or restriction object, defaults to None
:type value: restriction|alphanumeric, optional
:return: property object
:rtype: property
"""
inst = property()
inst.location = location
inst.propertyset = propertyset
inst.name = name
inst.value = value
# cls.attributes = {'@location': location} # 'type', 'instance', 'any'
# BUG '@href': 'http://identifier.buildingsmart.org/uri/buildingsmart/ifc-4.3/prop/FireRating', #https://identifier.buildingsmart.org/uri/something
# BUG 'instructions': 'Please add the desired rating.',
return inst
def asdict(self):
"""Converts object to a dictionary, adding required attributes.
:return: Xmlschema compliant dictionary.
:rtype: dict
"""
fac_dict = {
"@location": self.location,
"propertyset": parameter_asdict(self.propertyset),
"name": parameter_asdict(self.name),
"value": parameter_asdict(self.value),
# "instructions": "SAMPLE_INSTRUCTIONS",
# TODO '@href': 'http://identifier.buildingsmart.org/uri/buildingsmart/ifc-4.3/prop/FireRating', #https://identifier.buildingsmart.org/uri/something
}
return fac_dict
def __call__(self, inst, logger):
"""Validate an ifc instance against that property facet.
:param inst: IFC entity element
:type inst: IFC entity
:param logger: Logging object
:type logger: logging
:return: result of the validation as bool and message
:rtype: facet_evaluation(bool, str)
"""
self.location = self.node["@location"]
# TODO sometimes AttributeError: 'str' object has no attribute 'wrappedValue'
instance_props = ifcopenshell.util.element.get_psets(inst)
if ifcopenshell.util.element.get_type(inst):
type_props = ifcopenshell.util.element.get_psets(ifcopenshell.util.element.get_type(inst))
else:
type_props = {}
if self.location == "instance":
props = instance_props
elif self.location == "type" and type_props:
props = type_props
elif self.location == "any" and (instance_props or type_props):
props = {**instance_props, **type_props}
else:
props = {}
pset = props.get(self.propertyset)
val = pset.get(self.name) if pset else None
self.location_msg = location[self.location]
di = {"name": self.name, "propertyset": self.propertyset, "value": "'%s'" % val, "location": self.location_msg}
if val is not None:
msg = self.message % di
else:
if pset:
msg = "does not have %(location)sproperty '%(name)s' in a set '%(propertyset)s'" % di
else:
msg = "does not have %(location)sset '%(propertyset)s'" % di
# TODO implement data type comparison
# xs:string
# xs:decimal
# xs:integer
# xs:boolean
# xs:anyURI
# xs:date YYYY-MM-DD
# xs:time hh:mm:ss
# xs:dateTime YYYY-MM-DDThh:mm:ss
# xs:duration PnYnMnDTnHnMnS
return facet_evaluation(val == self.value, msg)
class material(facet):
"""The IDS material facet used to traverse the HasAssociations inverse attribute."""
parameters = ["value", "location"]
message = "%(location)smaterial '%(value)s'"
@staticmethod
def create(location="any", value=None):
"""Create a material facet that can be added to applicability or requirements of IDS specification.
:param location: Define where to check for the parameter. One of "any"|"instance"|"type", defaults to "any"
:type location: str, optional
:param value: Value that is required. Could be alphanumeric or restriction object, defaults to None
:type value: restriction|alphanumeric, optional
:return: material object
:rtype: material
"""
inst = material()
inst.location = location
inst.value = value
# TODO '@use': 'optional'
# TODO '@href': 'https://identifier.buildingsmart.org/uri/something',
# TODO 'instructions': 'Please add the desired...',
return inst
def asdict(self):
"""Converts object to a dictionary, adding required attributes.
:return: Xmlschema compliant dictionary.
:rtype: dict
"""
fac_dict = {
"value": parameter_asdict(self.value),
"@location": self.location,
# TODO "instructions": "SAMPLE_INSTRUCTIONS",
# TODO '@href': 'http://identifier.buildingsmart.org/uri/buildingsmart/ifc-4.3/prop/FireRating', #https://identifier.buildingsmart.org/uri/something
# TODO '@use': 'optional'
}
return fac_dict
def __call__(self, inst, logger):
"""Validate an ifc instance against that material facet.
:param inst: IFC entity element
:type inst: IFC entity
:param logger: Logging object
:type logger: logging
:return: result of the validation as bool and message
:rtype: facet_evaluation(bool, str)
"""
self.location = self.node["@location"]
instance_material_rel = [rel for rel in inst.HasAssociations if rel.is_a("IfcRelAssociatesMaterial")]
if ifcopenshell.util.element.get_type(inst):
type_material_rel = [
rel
for rel in ifcopenshell.util.element.get_type(inst).HasAssociations
if rel.is_a("IfcRelAssociatesMaterial")
]
else:
type_material_rel = []
if self.location == "instance":
material_relations = list(instance_material_rel)
elif self.location == "type" and type_material_rel:
material_relations = list(type_material_rel)
elif self.location == "any" and (instance_material_rel or type_material_rel):
material_relations = instance_material_rel + type_material_rel
else:
material_relations = []
materials = []
for rel in material_relations:
if rel.RelatingMaterial.is_a() == "IfcMaterial":
materials.append(rel.RelatingMaterial.Name)
elif rel.RelatingMaterial.is_a() == "IfcMaterialMaterialList": # DEPRECATED in IFC4
[materials.append(mat.Name) for mat in rel.RelatingMaterial]
elif rel.RelatingMaterial.is_a() == "IfcMaterialConstituentSet":
[materials.append(mat.Material.Name) for mat in rel.RelatingMaterial.MaterialConstituents]
elif rel.RelatingMaterial.is_a() == "IfcMaterialLayerSet":
[materials.append(mat.Name) for mat in rel.RelatingMaterial.MaterialLayers]
elif rel.RelatingMaterial.is_a() == "IfcMaterialLayerSetUsage":
layers = rel.RelatingMaterial.ForLayerSet.MaterialLayers
[materials.append(layer.Material.Name) for layer in layers]
elif rel.RelatingMaterial.is_a() == "IfcMaterialProfileSet":
[materials.append(mat.Material.Name) for mat in rel.RelatingMaterial.MaterialProfiles]
elif rel.RelatingMaterial.is_a() == "IfcMaterialProfileSetUsage":
profileSets = rel.RelatingMaterial.ForProfileSet.MaterialProfiles
[materials.append(pset.Material.Name) for pset in profileSets]
else:
raise Exception("IfcRelAssociatesMaterial not implemented")
if not materials:
materials.append("UNDEFINED")
self.location_msg = location[self.location]
return facet_evaluation(
self.value in materials,
self.message % {"value": "'/'".join(materials), "location": self.location_msg},
)
def parameter_asdict(parameter):
"""Converts parameter to an IDS compliant dictionary, handling both value and restrictions.
:return: Xmlschema compliant dictionary.
:rtype: dict
"""
if isinstance(parameter, str):
parameter_dict = {"simpleValue": parameter}
elif isinstance(parameter, restriction):
parameter_dict = {"xs:restriction": [parameter.asdict()]}
elif isinstance(parameter, list):
restrictions = {"@base": "xs:" + parameter[0].base}
for p in parameter:
x = p.asdict()
restrictions[list(x)[1]] = x[list(x)[1]]
parameter_dict = {"xs:restriction": [restrictions]}
return parameter_dict
class boolean_logic:
"""Boolean conjunction over a collection of functions"""
def __init__(self, terms):
self.terms = terms
def __call__(self, *args):
eval = [t(*args) for t in self.terms]
join = [" and ", " or "][self.fold == any]
return facet_evaluation(self.fold(eval), join.join(map(str, eval)))
def __str__(self):
return [" and ", " or "][self.fold == any].join(map(str, self.terms))
class boolean_and(boolean_logic):
fold = all
class boolean_or(boolean_logic):
fold = any
class restriction:
"""
The value restriction from XSD implemented as a list of values and a containment test
"""
def __init__(self):
"""Create a restriction that can be used instead of value of a parameter."""
self.type = ""
self.options = []
@staticmethod
def parse(ids_dict):
"""Parse xml restriction to python object.
:param ids_dict:
:type ids_dict: dict
"""
r = restriction()
if ids_dict:
# TODO 'base' missing in some IDS?!
r.base = ids_dict["@base"][3:]
for n in ids_dict:
if n == "enumeration":
r.type = "enumeration"
for x in ids_dict[n]:
r.options.append(x["@value"])
elif n[-7:] == "clusive":
r.type = "bounds"
r.options.append({n: ids_dict[n]["@value"]})
elif n[-5:] == "ength":
r.type = "length"
if n[3:6] == "min":
r.options.append(">=")
elif n[3:6] == "max":
r.options.append("<=")
else:
self.options.append("==")
r.options[-1] += str(ids_dict[n]["@value"])
elif n == "pattern":
r.type = "pattern"
r.options.append(ids_dict[n]["@value"])
# TODO add fractionDigits
# TODO add totalDigits
# TODO add whiteSpace
elif n == "@base":
pass
else:
print("Error! Restriction not implemented")
return r
def asdict(self):
"""Converts object to a dictionary, adding required attributes.
:return: Xmlschema compliant dictionary.
:rtype: dict
"""
rest_dict = {"@base": "xs:" + self.base}
if self.type == "enumeration":
for option in self.options:
if "xs:enumeration" not in rest_dict:
rest_dict["xs:enumeration"] = [{"@value": option}]
else:
rest_dict["xs:enumeration"].append({"@value": option})
elif self.type == "bounds":
for option in self.options:
if "xs:option" not in rest_dict:
rest_dict["xs:" + option] = [{"@value": option}]
else:
rest_dict["xs:" + option].append({"@value": self.options[option], "@fixed": False})
elif self.type == "pattern":
if "xs:pattern" not in rest_dict:
rest_dict["xs:pattern"] = [{"@value": self.options}]
else:
rest_dict["xs:pattern"].append({"@value": self.options})
return rest_dict
@staticmethod
def create(options, type="pattern", base="string"):
"""Create restriction instead of simpleValue
:param type: One of "enumeration"|"pattern"|"bounds", defaults to "pattern"
:type type: str, optional
:param options: if enumeration: list of possible values
if pattern: xml regular expression string
if bounds: dictionary with possible keys: 'minInclusive', 'maxInclusive', 'minExclusive', 'maxExclusive'
:type options: list|str|dict
:param base: One of "string"|"boolean"|"decimal"|"integer", defaults to "string"
:type base: str, optional
:raises Exception: If not properly defined restriction.
:return: restriction object
:rtype: restriction
"""
rest = restriction()
if type in ["enumeration", "pattern", "bounds"]:
rest.type = type
rest.base = base
rest.options = options
if (
(type == "enumeration" and isinstance(options, list))
or (type == "bounds" and isinstance(options, dict))
or (type == "pattern" and isinstance(options, str))
):
rest.options = options
else:
Exception("Options were not properly defined.")
return rest
else:
raise Exception(
"Such restriction not implemented. Try: 'enumeration', 'pattern' or 'min/maxInclusive' or 'min/maxExclusive'."
)
def __eq__(self, other):
"""Evaluate the restriction using equality sign.
:param other: value to compare with the restriction.
:type other: str|float|int
:return: True if 'other' match the restriction, False if not.
:rtype: bool
"""
result = False
# TODO implement data type comparison