-
Notifications
You must be signed in to change notification settings - Fork 7
/
application.py
1713 lines (1433 loc) · 69 KB
/
application.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
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import sys
import time
import operator
import functools
import multiprocessing
import logging
from collections import defaultdict, Iterable, OrderedDict
# check pyqt version and import pyqt library
QString = str
os.environ['QT_API'] = 'pyqt5'
try:
from pyqode.qt import QtCore
except BaseException:
pass
from PyQt5 import QtCore, QtGui, QtWidgets
# add python-occ library
import OCC.Core.AIS
try:
from OCC.Display.pyqt5Display import qtViewer3d
except BaseException:
import OCC.Display
try:
import OCC.Display.backend
except BaseException:
pass
try:
OCC.Display.backend.get_backend("qt-pyqt5")
except BaseException:
OCC.Display.backend.load_backend("qt-pyqt5")
from OCC.Display.qtDisplay import qtViewer3d
# add ifcopenshell library
import ifcopenshell
from ifcopenshell.geom.main import settings, iterator
from ifcopenshell.geom.occ_utils import display_shape,set_shape_transparency
from ifcopenshell import open as open_ifc_file
if ifcopenshell.version < "0.6":
# not yet ported
from .. import get_supertype
# add the functions of BIM calculation algorithm
from functions import *
class geometry_creation_signals(QtCore.QObject):
completed = QtCore.pyqtSignal('PyQt_PyObject') #name of the signal completed
progress = QtCore.pyqtSignal('PyQt_PyObject')
class geometry_creation_thread(QtCore.QThread):
def __init__(self, signals, settings, f):
QtCore.QThread.__init__(self)
self.signals = signals
self.settings = settings
self.f = f
def run(self):
t0 = time.time()
# detect concurrency from hardware, we need to have
# at least two threads because otherwise the interface
# is different
it = iterator(self.settings, self.f, max(2, multiprocessing.cpu_count()))
if not it.initialize():
self.signals.completed.emit([])
return
def _():
old_progress = -1
while True:
shape = it.get()
if shape:
yield shape
if not it.next():
break
self.signals.completed.emit((it, self.f, list(_())))
class configuration(object):
def __init__(self):
try:
import ConfigParser
Cfg = ConfigParser.RawConfigParser
except BaseException:
import configparser
def Cfg():
return configparser.ConfigParser(interpolation=None)
conf_file = os.path.expanduser(os.path.join("~", ".ifcopenshell", "app", "snippets.conf"))
if conf_file.startswith("~"):
conf_file = None
return
self.config_encode = lambda s: s.replace("\\", "\\\\").replace("\n", "\n|")
self.config_decode = lambda s: s.replace("\n|", "\n").replace("\\\\", "\\")
if not os.path.exists(os.path.dirname(conf_file)):
os.makedirs(os.path.dirname(conf_file))
if not os.path.exists(conf_file):
config = Cfg()
config.add_section("snippets")
config.set("snippets", "print all wall ids", self.config_encode("""
###########################################################################
# A simple script that iterates over all walls in the current model #
# and prints their Globally unique IDs (GUIDS) to the console window #
###########################################################################
for wall in model.by_type("IfcWall"):
print ("wall with global id: "+str(wall.GlobalId))
""".lstrip()))
config.set("snippets", "print properties of current selection", self.config_encode("""
###########################################################################
# A simple script that iterates over all IfcPropertySets of the currently #
# selected object and prints them to the console #
###########################################################################
# check if something is selected
if selection:
#get the IfcProduct that is stored in the global variable 'selection'
obj = selection
for relDefinesByProperties in obj.IsDefinedBy:
print("[{0}]".format(relDefinesByProperties.RelatingPropertyDefinition.Name))
for prop in relDefinesByProperties.RelatingPropertyDefinition.HasProperties:
print ("{:<20} :{}".format(prop.Name,prop.NominalValue.wrappedValue))
print ("\\n")
""".lstrip()))
with open(conf_file, 'w') as configfile:
config.write(configfile)
self.config = Cfg()
self.config.read(conf_file)
def options(self, s):
return OrderedDict([(k, self.config_decode(self.config.get(s, k))) for k in self.config.options(s)])
class application(QtWidgets.QApplication):
"""A pythonOCC, PyQt based IfcOpenShell application
with two tree views and a graphical 3d view"""
class abstract_treeview(QtWidgets.QTreeWidget):
"""Base class for the two treeview controls"""
instanceSelected = QtCore.pyqtSignal([object])
instanceVisibilityChanged = QtCore.pyqtSignal([object, int])
instanceDisplayModeChanged = QtCore.pyqtSignal([object, int])
def __init__(self):
QtWidgets.QTreeView.__init__(self)
self.setColumnCount(len(self.ATTRIBUTES))
self.setHeaderLabels(self.ATTRIBUTES)
self.children = defaultdict(list)
def get_children(self, inst):
c = [inst]
i = 0
while i < len(c):
c.extend(self.children[c[i]])
i += 1
return c
def contextMenuEvent(self, event):
menu = QtWidgets.QMenu(self)
visibility = [menu.addAction("Show"), menu.addAction("Hide")]
displaymode = [menu.addAction("Solid"), menu.addAction("Wireframe")]
action = menu.exec_(self.mapToGlobal(event.pos()))
index = self.selectionModel().currentIndex()
inst = index.data(QtCore.Qt.UserRole)
if hasattr(inst, 'toPyObject'):
inst = inst
if action in visibility:
self.instanceVisibilityChanged.emit(inst, visibility.index(action))
elif action in displaymode:
self.instanceDisplayModeChanged.emit(inst, displaymode.index(action))
def clicked_(self, index):
inst = index.data(QtCore.Qt.UserRole)
if hasattr(inst, 'toPyObject'):
inst = inst
if inst:
self.instanceSelected.emit(inst)
def select(self, product):
print("select in the abstract_treeview called")
itm = self.product_to_item.get(product)
if itm is None:
return
self.selectionModel().setCurrentIndex(itm,
QtCore.QItemSelectionModel.SelectCurrent | QtCore.QItemSelectionModel.Rows)
class decomposition_treeview(abstract_treeview):
"""Treeview with typical IFC decomposition relationships"""
ATTRIBUTES = ['Entity', 'GlobalId', 'Name']
def parent_overload(self, instance):
if instance.is_a("IfcOpeningElement"):
return instance.VoidsElements[0].RelatingBuildingElement
if instance.is_a("IfcElement"):
fills = instance.FillsVoids
if len(fills):
return fills[0].RelatingOpeningElement
containments = instance.ContainedInStructure
if len(containments):
return containments[0].RelatingStructure
if instance.is_a("IfcObjectDefinition"):
decompositions = instance.Decomposes
if len(decompositions):
return decompositions[0].RelatingObject
def load_file(self, f, **kwargs):
products = list(f.by_type("IfcProduct")) + list(f.by_type("IfcProject"))
parents = list(map(self.parent_overload, products))
items = {}
skipped = 0
ATTRS = self.ATTRIBUTES
while len(items) + skipped < len(products):
for product, parent in zip(products, parents):
if parent is None and not product.is_a("IfcProject"):
skipped += 1
continue
if (parent is None or parent in items) and product not in items:
sl = []
for attr in ATTRS:
if attr == 'Entity':
sl.append(product.is_a())
else:
sl.append(getattr(product, attr) or '')
itm = items[product] = QtWidgets.QTreeWidgetItem(items.get(parent, self), sl)
itm.setData(0, QtCore.Qt.UserRole, product)
self.children[parent].append(product)
self.product_to_item = dict(zip(items.keys(), map(self.indexFromItem, items.values())))
self.clicked.connect(self.clicked_)
self.expandAll()
class type_treeview(abstract_treeview):
"""Treeview with typical IFC decomposition relationships"""
ATTRIBUTES = ['Name']
def load_file(self, f, **kwargs):
products = list(f.by_type("IfcProduct"))
types = set(map(lambda i: i.is_a(), products))
items = {}
for t in types:
def add(t):
s = get_supertype(t)
if s:
add(s)
s2, t2 = map(QString, (s, t))
if t2 not in items:
itm = items[t2] = QtWidgets.QTreeWidgetItem(items.get(s2, self), [t2])
itm.setData(0, QtCore.Qt.UserRole, t2)
self.children[s2].append(t2)
if ifcopenshell.version < "0.6":
add(t)
for p in products:
t = QString(p.is_a())
itm = items[p] = QtWidgets.QTreeWidgetItem(items.get(t, self), [p.Name or '<no name>'])
itm.setData(0, QtCore.Qt.UserRole, t)
self.children[t].append(p)
self.product_to_item = dict(zip(items.keys(), map(self.indexFromItem, items.values())))
self.clicked.connect(self.clicked_)
self.expandAll()
class property_table(QtWidgets.QWidget):
def __init__(self):
QtWidgets.QWidget.__init__(self)
self.layout = QtWidgets.QVBoxLayout(self)
self.setLayout(self.layout)
self.scroll = QtWidgets.QScrollArea(self)
self.layout.addWidget(self.scroll)
self.scroll.setWidgetResizable(True)
self.scrollContent = QtWidgets.QWidget(self.scroll)
self.scrollLayout = QtWidgets.QVBoxLayout(self.scrollContent)
self.scrollContent.setLayout(self.scrollLayout)
self.scroll.setWidget(self.scrollContent)
self.prop_dict = {}
# triggered by selection event in either component of parent
def select(self, product):
print("select in the property_table called")
# Clear the old contents if any
while self.scrollLayout.count():
child = self.scrollLayout.takeAt(0)
if child is not None:
if child.widget() is not None:
child.widget().deleteLater()
self.scroll = QtWidgets.QScrollArea()
self.scroll.setWidgetResizable(True)
prop_sets = self.prop_dict.get(str(product))
if prop_sets is not None:
for k, v in prop_sets:
group_box = QtWidgets.QGroupBox()
group_box.setTitle(k)
group_layout = QtWidgets.QVBoxLayout()
group_box.setLayout(group_layout)
for name, value in v.items():
prop_name = str(name)
value_str = value
if hasattr(value_str, "wrappedValue"):
value_str = value_str.wrappedValue
#if isinstance(value_str, unicode):
if isinstance(value_str, str):
value_str = value_str.encode('utf-8')
else:
value_str = str(value_str)
if hasattr(value, "is_a"):
type_str = " <i>(%s)</i>" % value.is_a()
else:
type_str = ""
label = QtWidgets.QLabel("<b>%s</b>: %s%s" % (prop_name, value_str, type_str))
group_layout.addWidget(label)
group_layout.addStretch()
self.scrollLayout.addWidget(group_box)
self.scrollLayout.addStretch()
else:
label = QtWidgets.QLabel("No IfcPropertySets asscociated with selected entity instance")
self.scrollLayout.addWidget(label)
def load_file(self, f, **kwargs):
for p in f.by_type("IfcProduct"):
propsets = []
def process_pset(prop_def):
if prop_def is not None:
prop_set_name = prop_def.Name
props = {}
if prop_def.is_a("IfcElementQuantity"):
for q in prop_def.Quantities:
if q.is_a("IfcPhysicalSimpleQuantity"):
props[q.Name] = q[3]
elif prop_def.is_a("IfcPropertySet"):
for prop in prop_def.HasProperties:
if prop.is_a("IfcPropertySingleValue"):
props[prop.Name] = prop.NominalValue
else:
# Entity introduced in IFC4
# prop_def.is_a("IfcPreDefinedPropertySet"):
for prop in range(4, len(prop_def)):
props[prop_def.attribute_name(prop)] = prop_def[prop]
return prop_set_name, props
try:
for is_def_by in p.IsDefinedBy:
if is_def_by.is_a("IfcRelDefinesByProperties"):
propsets.append(process_pset(is_def_by.RelatingPropertyDefinition))
elif is_def_by.is_a("IfcRelDefinesByType"):
type_psets = is_def_by.RelatingType.HasPropertySets
if type_psets is None:
continue
for propset in type_psets:
propsets.append(process_pset(propset))
except Exception as e:
import traceback
print("failed to load properties: {}".format(e))
traceback.print_exc()
if len(propsets):
self.prop_dict[str(p)] = propsets
print("property set dictionary has {} entries".format(len(self.prop_dict)))
class viewer(qtViewer3d):
instanceSelected = QtCore.pyqtSignal([object])
@staticmethod
def ais_to_key(ais_handle):
def yield_shapes():
ais = ais_handle.GetObject()
if hasattr(ais, 'Shape'):
yield ais.Shape()
return
shp = OCC.Core.AIS.Handle_AIS_Shape.DownCast(ais_handle)
if not shp.IsNull():
yield shp.Shape()
return
mult = ais_handle
if mult.IsNull():
shp = OCC.Core.AIS.Handle_AIS_Shape.DownCast(ais_handle)
if not shp.IsNull():
yield shp
else:
li = mult.GetObject().ConnectedTo()
for i in range(li.Length()):
shp = OCC.Core.AIS.Handle_AIS_Shape.DownCast(li.Value(i + 1))
if not shp.IsNull():
yield shp
return tuple(shp.HashCode(1 << 24) for shp in yield_shapes())
def __init__(self, widget):
qtViewer3d.__init__(self, widget)
self.ais_to_product = {}
self.product_to_ais = {}
self.counter = 0
self.window = widget
self.thread = None
# ------------------------------------- Teng --------------------------------------------
self.floor_elements_lst = []
self.floor_compound_shapes_lst = []
def initialize(self):
self.InitDriver()
#self._display.Select = self.HandleSelection
def finished(self, file_shapes):
it, f, shapes = file_shapes
v = self._display
t = {0: time.time()}
def update(dt=None):
t1 = time.time()
if dt is None or t1 - t[0] > dt:
v.FitAll()
v.Repaint()
t[0] = t1
for shape in shapes:
ais = display_shape(shape, viewer_handle=v)
product = f[shape.data.id]
# try:
# ais.SetSelectionPriority(self.counter)
# except:
# ais.GetObject().SetSelectionPriority(self.counter)
self.ais_to_product[self.counter] = product
self.product_to_ais[product] = ais
self.counter += 1
QtWidgets.QApplication.processEvents()
if product.is_a() in {'IfcSpace', 'IfcOpeningElement'}:
v.Context.Erase(ais, True)
#update(1.)
update()
self.thread = None
def load_file(self, floor_name_lst, floor_elements_lst): # f is, ifc_file = ifcopenshell.open()
time_a = time.time()
settings = ifcopenshell.geom.settings()
settings.set(settings.USE_PYTHON_OPENCASCADE, True)
for i in range(len(floor_elements_lst)):
# -------------- create shape from BIM----------------:
floor_ifc = floor_elements_lst[i]
shapes = []
if isinstance(floor_ifc, list):
for element in floor_ifc:
try:
if element.Representation:
shape = ifcopenshell.geom.create_shape(settings, element).geometry
shapes.append(shape)
except:
print("Create shape failed, ", element.is_a(),',', element.Name)
# ------------------- create shape from BIM done -----------------------------
shapes_compound, if_all_compound = list_of_shapes_to_compound(shapes)
self.floor_compound_shapes_lst.append(shapes_compound)
v = self._display
if i != (len(floor_elements_lst)-1):
v.DisplayShape(shapes_compound, color="Black", transparency=0.9, update=False)
print("loading floor, index ",i, " floor name: ",floor_name_lst[i] )
else:
v.DisplayShape(shapes_compound, color="Black", transparency=0.9, update=True)
print("loading floor, index ",i, " floor name: ",floor_name_lst[i] )
print("load and create shape done, time: ", time.time()-time_a, "start,",time.time(),"end,", time_a)
def select(self, product):
print("select in viewer called")
ais = self.product_to_ais.get(product)
if ais is None:
return
v = self._display.Context
v.ClearSelected(False)
v.SetSelected(ais, True)
def toggle(self, product_or_products, fn):
if not isinstance(product_or_products, Iterable):
product_or_products = [product_or_products]
aiss = list(filter(None, map(self.product_to_ais.get, product_or_products)))
last = len(aiss) - 1
for i, ais in enumerate(aiss):
fn(ais, i == last)
def toggle_visibility(self, product_or_products, flag):
v = self._display.Context
if flag:
def visibility(ais, last):
v.Erase(ais, last)
else:
def visibility(ais, last):
v.Display(ais, last)
self.toggle(product_or_products, visibility)
def toggle_wireframe(self, product_or_products, flag):
v = self._display.Context
if flag:
def wireframe(ais, last):
if v.IsDisplayed(ais):
v.SetDisplayMode(ais, 0, last)
else:
def wireframe(ais, last):
if v.IsDisplayed(ais):
v.SetDisplayMode(ais, 1, last)
self.toggle(product_or_products, wireframe)
def HandleSelection(self, X, Y):
print("HandleSelection called in viewer")
v = self._display.Context
v.Select(True)
v.InitSelected()
if v.MoreSelected():
ais = v.SelectedInteractive()
inst = self.ais_to_product[ais.GetOject().SelectionPriority()]
self.instanceSelected.emit(inst)
class window(QtWidgets.QMainWindow):
TITLE = "IfcOpenShell IFC viewer"
window_closed = QtCore.pyqtSignal([])
def __init__(self):
QtWidgets.QMainWindow.__init__(self)
self.setWindowTitle(self.TITLE)
self.menu = self.menuBar()
self.menus = {}
def closeEvent(self, *args):
self.window_closed.emit()
def add_menu_item(self, menu, label, callback, icon=None, shortcut=None):
m = self.menus.get(menu)
if m is None:
m = self.menu.addMenu(menu)
self.menus[menu] = m
if icon:
a = QtWidgets.QAction(QtGui.QIcon(icon), label, self)
else:
a = QtWidgets.QAction(label, self)
if shortcut:
a.setShortcut(shortcut)
a.triggered.connect(callback)
m.addAction(a)
def makeSelectionHandler(self, component):
print("makeSelectionHandler")
def handler(inst):
for c in self.components:
if c != component:
c.select(inst)
return handler
def __init__(self, settings=None):
QtWidgets.QApplication.__init__(self, sys.argv)
self.window = application.window()
self.tree = application.decomposition_treeview()
self.tree2 = application.type_treeview()
self.propview = self.property_table()
self.canvas = application.viewer(self.window)
self.tabs = QtWidgets.QTabWidget()
self.window.resize(800, 600)
splitter = QtWidgets.QSplitter(QtCore.Qt.Horizontal)
splitter.addWidget(self.tabs)
self.tabs.addTab(self.tree, 'Decomposition')
self.tabs.addTab(self.tree2, 'Types')
self.tabs.addTab(self.propview, "Properties")
splitter2 = QtWidgets.QSplitter(QtCore.Qt.Vertical)
splitter2.addWidget(self.canvas)
splitter.addWidget(splitter2)
splitter.setSizes([200, 600])
self.window.setCentralWidget(splitter)
self.canvas.initialize()
self.components = [self.tree, self.tree2, self.propview]
self.files = {}
self.window.add_menu_item('File', '&Open', self.browse, shortcut='CTRL+O')
self.window.add_menu_item('File', '&Close', self.clear, shortcut='CTRL+W')
self.window.add_menu_item('File', '&Exit', self.window.close, shortcut='ALT+F4')
# ---------------------------default variables for BIM calculation algorithm ----------------------------------#
# DBSCAN clustering
self.s = 0.2
self.dbscan =2
# k-nearest neighbor
self.k = 16
# default ground floor number
self.floornum = int(0)
self.current_ifc_file = None
self.floor_elements_lst = []
self.floor_name_lst = []
self.base_polygon = None
self.base_overhang_obb_poly = None
self.base_obb_pt_lst = []
self.base_overhang_points =None
self.base_floor_num = 1
self.overhang_left = True
self.storeyElevation_lst=[]
# Georeference parameters
self.addGeoreference = False
self.georeference_x = 0.0
self.georeference_y = 0.0
self.georeference_z = 0.0
# --------------------------- funtion buttons on the menu ----------------------------------#
# View
self.window.add_menu_item('View', '&ClearViewer', self.clearViewer)
self.window.add_menu_item('View', '&Showfloor', self.showfloor)
self.window.add_menu_item('View', '&Show all floors', self.showallfloor)
# Preprocess
self.window.add_menu_item('Preprocess','&Set base floor number',self.setBaseFloornum)
self.window.add_menu_item('Preprocess', '&Add Georeference Point', self.addGeoreferencePoint)
self.window.add_menu_item('Preprocess', '&Set Overhang Direction', self.setOverhangdir)
self.window.add_menu_item('Preprocess', '&Set Overlap Parameters', self.setOverlapParameters)
# Overlap
self.window.add_menu_item('Overlap','&Single Floor Overlap',self.OverlapOneFloor)
self.window.add_menu_item('Overlap','&Single Floor Overlap Bounding Box',self.OverlapOneFloorOBB)
self.window.add_menu_item('Overlap','&All Floor Overlap',self.OverlapAll)
self.window.add_menu_item('Overlap','&All Floor Overlap Bounding Box',self.OverlapAllOBB)
# Overhang
self.window.add_menu_item('Overhang','&Single Floor Overhang',self.OverhangOneFloor)
self.window.add_menu_item('Overhang', '&All Floor Overhang', self.OverhangAll_new)
# Height
self.window.add_menu_item('Height','&Height',self.GetHeight)
self.window.add_menu_item('Height','&GetBaseHeight',self.GetBaseHeight)
# wkt footprint
self.window.add_menu_item('WKT', '&Write Floor Footprint to WKT', self.footprintWKT)
# Parking
self.window.add_menu_item('Parking', '&Parking Units Calculation', self.parkingCalcualate, shortcut='CTRL+F')
self.tree.instanceSelected.connect(self.makeSelectionHandler(self.tree))
self.tree2.instanceSelected.connect(self.makeSelectionHandler(self.tree2))
self.canvas.instanceSelected.connect(self.makeSelectionHandler(self.canvas))
for t in [self.tree, self.tree2]:
t.instanceVisibilityChanged.connect(functools.partial(self.change_visibility, t))
t.instanceDisplayModeChanged.connect(functools.partial(self.change_displaymode, t))
self.settings = settings
def change_visibility(self, tree, inst, flag):
insts = tree.get_children(inst)
self.canvas.toggle_visibility(insts, flag)
def change_displaymode(self, tree, inst, flag):
insts = tree.get_children(inst)
self.canvas.toggle_wireframe(insts, flag)
def start(self):
self.window.show()
sys.exit(self.exec_())
def browse(self):
filename = QtWidgets.QFileDialog.getOpenFileName(self.window, 'Open file', ".",
"Industry Foundation Classes (*.ifc)")[0]
if filename:
self.load(filename)
def clear(self):
self.canvas._display.Context.RemoveAll(True)
self.tree.clear()
self.files.clear()
def load(self, fn):
if fn in self.files:
return
f = open_ifc_file(str(fn))
#Run the floor segementation when loading
self.floor_elements_lst, self.floor_name_lst = GetElementsByStorey(f)
self.files[fn] = f
for c in self.components:
c.load_file(f, setting=self.settings)
storeys = f.by_type("IfcBuildingStorey")
for st in storeys:
self.storeyElevation_lst.append(st.Elevation/1000.0) # convert units from mm to meter
self.canvas.load_file(self.floor_name_lst,self.floor_elements_lst)
if not os.path.exists('./result'):
os.makedirs('./result/')
def showShapes(self,shapes):
v = self.canvas._display
for shape in shapes:
ais = display_shape(shape, viewer_handle=v)
v.FitAll()
v.Repaint()
def setBaseFloornum(self):
floor_num, okPressed = QtWidgets.QInputDialog.getInt(self.window, 'Set Base floor number', 'Base Floor Number=')
if okPressed:
# self.canvas._display.Context.RemoveAll(True)
self.base_polygon = None
self.base_floor_num = floor_num
print("Base floor num has been set to, " ,self.base_floor_num)
else:
return
if self.floor_name_lst:
msg = QtWidgets.QMessageBox()
msg.setIcon(QtWidgets.QMessageBox.Information)
msg.setText("Base floor number is has been set to, "+ str(floor_num)+ " floor name: "+self.floor_name_lst[floor_num] )
msg.setWindowTitle("Floor number Error")
msg.setStandardButtons(QtWidgets.QMessageBox.Ok | QtWidgets.QMessageBox.Cancel)
msg.show()
msg.exec_()
def clearViewer(self):
self.canvas._display.Context.EraseAll(True)
def showallfloor(self):
v = self.canvas._display
for i in range(len(self.floor_name_lst)):
v.DisplayShape(self.canvas.floor_compound_shapes_lst[i], color="WHITE", transparency=0.8, update=True)
def GetBaseHeight(self):
if not self.floor_name_lst:
return
floor_num, okPressed = QtWidgets.QInputDialog.getInt(self.window, 'Base Floor number', 'FloorNumber=')
if okPressed:
print("Floor name, ", self.floor_name_lst[floor_num] )
top_height = float("{:.3f}".format(self.storeyElevation_lst[floor_num+1]))
msg = QtWidgets.QMessageBox()
msg.setIcon(QtWidgets.QMessageBox.Information)
msg.setText("Base height is, "+str(top_height)+ " meter\n"+ "Floor name is ,"+self.floor_name_lst[floor_num])
msg.setWindowTitle("Base height")
msg.setStandardButtons(QtWidgets.QMessageBox.Ok | QtWidgets.QMessageBox.Cancel)
msg.show()
msg.exec_()
else:
return
def showfloor(self):
''' display all the element of the input floor in the canvas'''
if not self.floor_name_lst:
return
floor_num, okPressed =QtWidgets.QInputDialog.getInt(self.window,'InputFloorNumber','FloorNumber=')
if okPressed:
#self.canvas._display.Context.RemoveAll(True)
self.floornum = floor_num
else:
return
if floor_num>=0 and floor_num < len(self.floor_elements_lst):
v = self.canvas._display
print("Selected floor number:", floor_num, " floor name: ", self.floor_name_lst[floor_num])
v.DisplayShape(self.canvas.floor_compound_shapes_lst[floor_num], color="WHITE", transparency=0.8, update=True)
else:
print("message")
msg = QtWidgets.QMessageBox()
msg.setIcon(QtWidgets.QMessageBox.Critical)
msg.setText("Floor number is out of range")
msg.setWindowTitle("Floor number Error")
msg.setStandardButtons(QtWidgets.QMessageBox.Ok | QtWidgets.QMessageBox.Cancel)
msg.show()
msg.exec_()
def GetFloorPolygon(self, i, filepath, yamlFilepath):
''' return intersecting surface polygon of floor i, generated from floor cutting '''
floor_name = self.floor_name_lst[i]
print("current floor, ", floor_name,"******************************************************************************")
#display shapes
v = self.canvas._display
# set parameters
s = self.s
dbscan = self.dbscan
k = self.k
calcconvexhull = False
use_obb= False
# cutting_height of each building storey
cutting_height = self.storeyElevation_lst[i] + 1.0
# loading customize parameters from the .yml file
yml_file = open(yamlFilepath, 'r')
yml_data = yaml.load(yml_file, Loader=Loader)
str1 = "f"+str(i)
if str1 in yml_data.keys():
dict2 = yml_data[str1]
if 'cutting_height' in dict2.keys():
value = float(dict2['cutting_height'])
cutting_height = self.storeyElevation_lst[i] + value
if 'k' in dict2.keys():
k = float(dict2['k'])
if 'use_obb' in dict2.keys():
if dict2['use_obb'] == True:
use_obb=True
if 's' in dict2.keys():
s = float(dict2['s'])
if 'dbscan' in dict2.keys():
dbscan = float(dict2['dbscan'])
if 'calcconvexhull' in dict2.keys():
if dict2['calcconvexhull'] == True:
calcconvexhull = True
if use_obb:
print("use_obb, ", use_obb, "floor name,", floor_name, " ----------------------------------------------------------------------")
pts = GetOrientedBoundingBoxShapeCompound(self.canvas.floor_compound_shapes_lst[i], False)
Z_value = []
for pt in pts:
Z_value.append(pt.Z())
z_max = max(Z_value)
z_min = min(Z_value)
z_mid = 0.5 * (z_max + z_min)
pts_low = []
pts_up = []
for pt in pts:
if pt.Z() < z_mid:
pts_low.append(pt)
else:
pts_up.append(pt)
corners_top = pts_up
pyocc_corners_list = []
for pt in corners_top:
pyocc_corners_list.append([float("{:.3f}".format(pt.X() )), float("{:.3f}".format(pt.Y() ))])
points = np.array(pyocc_corners_list)
obb_hull = ConvexHull(points)
result = []
for idx in obb_hull.vertices:
result.append(pyocc_corners_list[idx])
poly_footprint = Polygon(result)
return [poly_footprint]
print("cutting height,", cutting_height)
section_shape = GetSectionShape(cutting_height, self.canvas.floor_compound_shapes_lst[i])
v.DisplayShape(section_shape, color="RED", update=True)
# get the section shape edges
edges = GetShapeEdges(section_shape)
if s !=0:
first_xy = GetEdgeSamplePointsPerDistance(edges, s)
else:
first_xy = GetEdges2DPT(edges)
np_points = np.array(first_xy)
corners = GetNumpyOBB(np_points, calcconvexhull=calcconvexhull, show_plot=False)
OBB_poly = Polygon(corners.tolist())
# create result dir
if not os.path.exists('./result/Overlap/' + floor_name):
os.makedirs('./result/Overlap/' + floor_name)
img_filepath = "./result/Overlap/" + floor_name + "/obbAndPoints.png"
# save result as images in the result folder
SavePloyAndPoints(OBB_poly, np_points, color='b', filepath=img_filepath)
cluster_filepath = "./result/Overlap/" + floor_name + "/clusters.png"
cluster_lst = GetDBSCANClusteringlst(np_points, dbscan, showplot=False, saveplot=cluster_filepath)
line = str()
per_floot_poly = []
poly_count = 0
for np_member_array in cluster_lst:
poly_count += 1
print(len(np_member_array))
print("starting concave hull")
hull = concaveHull(np_member_array, k=k, if_optimal=False)
self.WriteConcave2WKT(hull,floor_name,poly_count)
poly = Polygon(hull)
print("polygon validation is: ", poly.is_valid, poly.area)
poly_filepath = "./result/Overlap/" + floor_name + "/polygon" + str(poly_count) + ".png"
OBB_points = GetNumpyOBB(np_member_array, show_plot=False)
OBB_poly = Polygon(OBB_points.tolist())
print("OBB_poly area,", OBB_poly.area, " name,", floor_name,"---------------------------------------------------------------------")
if not poly.is_valid:
print("Try to repair validation:")
new_poly = poly.buffer(0)
line = line + "Repaired_" + str(new_poly.is_valid) + "_" + str(float("{:.2f}".format(new_poly.area)))
print(new_poly.is_valid, new_poly.area)
un_poly = ops.unary_union(new_poly)
print(type(un_poly), un_poly.is_valid, "Union area,", un_poly.area)
# if the poly is wrong, replace with OBB_poly
if un_poly.area < (0.3 * OBB_poly.area):
un_poly = OBB_poly
per_floot_poly.append(un_poly)
if un_poly.geom_type == 'MultiPolygon':
for geom in un_poly.geoms:
xs, ys = geom.exterior.xy
plt.plot(xs, ys, color="r")
plt.savefig(poly_filepath)
plt.close()
elif un_poly.geom_type == 'Polygon':
SavePloyAndPoints(un_poly, np_member_array, filepath=poly_filepath)
else:
print("Error polygon generation from concave hull failed!")
else:
line = line + "True, Floor Area" + str( float("{:.2f}".format(poly.area)))
print("Polygon True, no need repair")
SavePloyAndPoints(poly, np_member_array, filepath=poly_filepath)
per_floot_poly.append(poly)
return per_floot_poly # [polygon] or [polygons]
def OverlapOneFloor(self):
''' Calculate overlap percentage between input floor and ground floor and save the result in ./result/overlap folder'''
if not self.floor_name_lst:
return
dialog = OneFloorOverlapDialog()
if dialog.exec():
floornum, outputFilepath, yamlFilepath = dialog.getInputs()
floornum = int(floornum)
print(floornum, type(floornum))
else:
return
if floornum or floornum == 0:
#self.canvas._display.Context.RemoveAll(True)
if not self.canvas.floor_compound_shapes_lst[floornum]:
msg = QtWidgets.QMessageBox()
msg.setIcon(QtWidgets.QMessageBox.Critical)
msg.setText("Current floor has no shapes or geometry,"+ self.floor_name_lst[floornum])
msg.setWindowTitle("Shapes or Geometry Error")
msg.setStandardButtons(QtWidgets.QMessageBox.Ok | QtWidgets.QMessageBox.Cancel)
msg.show()
msg.exec_()
return
floor_name_lst = [self.floor_name_lst[floornum]]
storey_poly_lst = []
if self.base_polygon:
current_floor_poly_lst = self.GetFloorPolygon(floornum,outputFilepath,yamlFilepath)
storey_poly_lst.append(current_floor_poly_lst)
else:
base_poly_lst = self.GetFloorPolygon(self.base_floor_num,outputFilepath,yamlFilepath)
self.base_polygon = base_poly_lst[0]
current_floor_poly_lst= self.GetFloorPolygon(floornum,outputFilepath,yamlFilepath)
storey_poly_lst.append(current_floor_poly_lst)
GetStoreyOverlap(self.base_polygon,storey_poly_lst,floor_name_lst, outputFilepath)
def WriteConcave2WKT(self,hull_lst,floor_name,poly_count):
''' Save the concave hull in WKT format in order to load in QGIS, WKT result saved in ./result/WKT folder'''
if not os.path.exists('./result/WKT'):
os.makedirs('./result/WKT')
new_lst = []
for p in hull_lst:
new_lst.append([float("{:.3f}".format(p[0] + self.georeference_x)),
float("{:.3f}".format(p[1] + self.georeference_y))])
geo_poly = Polygon(new_lst)