forked from ladybug-tools/honeybee-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathface.py
2123 lines (1881 loc) · 98.4 KB
/
face.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
# coding: utf-8
"""Honeybee Face."""
from __future__ import division
import math
from ladybug_geometry.geometry2d import Vector2D, Point2D, Polygon2D, Mesh2D
from ladybug_geometry.geometry3d import Vector3D, Point3D, Plane, Face3D
from ladybug.color import Color
from ._basewithshade import _BaseWithShade
from .typing import clean_string, invalid_dict_error
from .properties import FaceProperties
from .facetype import face_types, get_type_from_normal, AirBoundary, Floor, RoofCeiling
from .boundarycondition import boundary_conditions, get_bc_from_position, \
_BoundaryCondition, Outdoors, Surface, Ground
from .shade import Shade
from .aperture import Aperture
from .door import Door
import honeybee.boundarycondition as hbc
import honeybee.writer.face as writer
class Face(_BaseWithShade):
"""A single planar face.
Args:
identifier: Text string for a unique Face ID. Must be < 100 characters and
not contain any spaces or special characters.
geometry: A ladybug-geometry Face3D.
type: Face type. Default varies depending on the direction that
the Face geometry is points.
RoofCeiling = pointing upward within 30 degrees
Wall = oriented vertically within +/- 60 degrees
Floor = pointing downward within 30 degrees
boundary_condition: Face boundary condition (Outdoors, Ground, etc.)
Default is Outdoors unless all vertices of the geometry lie
below the below the XY plane, in which case it will be set to Ground.
Properties:
* identifier
* display_name
* type
* boundary_condition
* apertures
* doors
* sub_faces
* indoor_shades
* outdoor_shades
* parent
* has_parent
* has_sub_faces
* can_be_ground
* geometry
* punched_geometry
* vertices
* punched_vertices
* upper_left_vertices
* normal
* center
* area
* perimeter
* min
* max
* aperture_area
* aperture_ratio
* tilt
* altitude
* azimuth
* type_color
* bc_color
* user_data
"""
TYPES = face_types
__slots__ = ('_geometry', '_parent', '_punched_geometry',
'_apertures', '_doors', '_type', '_boundary_condition')
TYPE_COLORS = {
'Wall': Color(230, 180, 60),
'RoofCeiling': Color(128, 20, 20),
'Floor': Color(128, 128, 128),
'AirBoundary': Color(255, 255, 200, 100),
'InteriorWall': Color(230, 215, 150),
'InteriorRoofCeiling': Color(255, 128, 128),
'InteriorFloor': Color(255, 128, 128),
'InteriorAirBoundary': Color(255, 255, 200, 100)
}
BC_COLORS = {
'Outdoors': Color(64, 180, 255),
'Surface': Color(0, 128, 0),
'Ground': Color(165, 82, 0),
'Adiabatic': Color(255, 128, 128),
'Other': Color(255, 255, 200)
}
def __init__(self, identifier, geometry, type=None, boundary_condition=None):
"""A single planar face."""
_BaseWithShade.__init__(self, identifier) # process the identifier
# process the geometry
assert isinstance(geometry, Face3D), \
'Expected ladybug_geometry Face3D. Got {}'.format(geometry)
self._geometry = geometry
self._parent = None # _parent will be set when the Face is added to a Room
# initialize with no apertures/doors (they can be assigned later)
self._punched_geometry = None
self._apertures = []
self._doors = []
# initialize properties for extensions
self._properties = FaceProperties(self)
# set face type based on normal if not provided
if type is not None:
assert type in self.TYPES, '{} is not a valid face type.'.format(type)
self._type = type or get_type_from_normal(geometry.normal)
# set boundary condition by the relation to a zero ground plane if not provided
self.boundary_condition = boundary_condition or \
get_bc_from_position(geometry.boundary)
@classmethod
def from_dict(cls, data):
"""Initialize an Face from a dictionary.
Args:
data: A dictionary representation of an Face object.
"""
try:
# check the type of dictionary
assert data['type'] == 'Face', 'Expected Face dictionary. ' \
'Got {}.'.format(data['type'])
# first serialize it with an outdoor boundary condition
face_type = face_types.by_name(data['face_type'])
face = cls(data['identifier'], Face3D.from_dict(data['geometry']),
face_type, boundary_conditions.outdoors)
if 'display_name' in data and data['display_name'] is not None:
face.display_name = data['display_name']
if 'user_data' in data and data['user_data'] is not None:
face.user_data = data['user_data']
# add sub-faces and shades
if 'apertures' in data and data['apertures'] is not None:
aps = []
for ap in data['apertures']:
try:
aps.append(Aperture.from_dict(ap))
except Exception as e:
invalid_dict_error(ap, e)
face.add_apertures(aps)
if 'doors' in data and data['doors'] is not None:
drs = []
for dr in data['doors']:
try:
drs.append(Door.from_dict(dr))
except Exception as e:
invalid_dict_error(dr, e)
face.add_doors(drs)
face._recover_shades_from_dict(data)
# get the boundary condition and assign it
try:
bc_class = getattr(hbc, data['boundary_condition']['type'])
face.boundary_condition = bc_class.from_dict(data['boundary_condition'])
except AttributeError: # extension boundary condition; default to Outdoors
pass
# assign extension properties
if data['properties']['type'] == 'FaceProperties':
face.properties._load_extension_attr_from_dict(data['properties'])
return face
except Exception as e:
cls._from_dict_error_message(data, e)
@classmethod
def from_vertices(cls, identifier, vertices, type=None, boundary_condition=None):
"""Create a Face from vertices with each vertex as an iterable of 3 floats.
Note that this method is not recommended for a face with one or more holes
since the distinction between hole vertices and boundary vertices cannot
be derived from a single list of vertices.
Args:
identifier: Text string for a unique Face ID. Must be < 100 characters and
not contain any spaces or special characters.
vertices: A flattened list of 3 or more vertices as (x, y, z).
type: Face type object (eg. Wall, Floor).
boundary_condition: Boundary condition object (eg. Outdoors, Ground)
"""
geometry = Face3D(tuple(Point3D(*v) for v in vertices))
return cls(identifier, geometry, type, boundary_condition)
@property
def type(self):
"""Get or set an object for Type of Face (ie. Wall, Floor, Roof).
Note that setting this property will reset extension attributes on this
Face to their default values.
"""
return self._type
@type.setter
def type(self, value):
assert value in self.TYPES, '{} is not a valid face type.'.format(value)
if isinstance(value, AirBoundary):
assert self._apertures == [] or self._doors == [], \
'{} cannot be assigned to a Face with Apertures or Doors.'.format(value)
self.properties.reset_to_default() # reset constructions/modifiers
self._type = value
@property
def boundary_condition(self):
"""Get or set the boundary condition of the Face. (ie. Outdoors, Ground, etc.).
"""
return self._boundary_condition
@boundary_condition.setter
def boundary_condition(self, value):
assert isinstance(value, _BoundaryCondition), \
'Expected BoundaryCondition. Got {}'.format(type(value))
if self._apertures != [] or self._doors != []:
assert isinstance(value, (Outdoors, Surface)), \
'{} cannot be assigned to a Face with apertures or doors.'.format(value)
self._boundary_condition = value
@property
def apertures(self):
"""Get a tuple of apertures in this Face."""
return tuple(self._apertures)
@property
def doors(self):
"""Get a tuple of doors in this Face."""
return tuple(self._doors)
@property
def sub_faces(self):
"""Get a tuple of apertures and doors in this Face."""
return tuple(self._apertures + self._doors)
@property
def parent(self):
"""Get the parent Room if assigned. None if not assigned."""
return self._parent
@property
def has_parent(self):
"""Get a boolean noting whether this Face has a parent Room."""
return self._parent is not None
@property
def has_sub_faces(self):
"""Get a boolean noting whether this Face has Apertures or Doors."""
return not (self._apertures == [] and self._doors == [])
@property
def can_be_ground(self):
"""Get a boolean for whether this Face can support a Ground boundary condition.
"""
return self._apertures == [] and self._doors == [] \
and not isinstance(self._type, AirBoundary)
@property
def geometry(self):
"""Get a ladybug_geometry Face3D object representing the Face.
Note that this Face3D only represents the parent face and does not have any
holes cut in it for apertures or doors.
"""
return self._geometry
@property
def punched_geometry(self):
"""Get a Face3D object with holes cut in it for apertures and doors.
"""
if self._punched_geometry is None:
_sub_faces = tuple(sub_f.geometry for sub_f in self._apertures + self._doors)
if len(_sub_faces) != 0:
self._punched_geometry = Face3D.from_punched_geometry(
self._geometry, _sub_faces)
else:
self._punched_geometry = self._geometry
return self._punched_geometry
@property
def vertices(self):
"""Get a list of vertices for the face (in counter-clockwise order).
Note that these vertices only represent the outer boundary of the face
and do not account for holes cut in the face by apertures or doors.
"""
return self._geometry.vertices
@property
def punched_vertices(self):
"""Get a list of vertices with holes cut in it for apertures and doors.
Note that some vertices will be repeated since the vertices effectively
trace out a single boundary around the whole shape, winding inward to cut
out the holes. This property should be used when exporting to Radiance.
"""
return self.punched_geometry.vertices
@property
def upper_left_vertices(self):
"""Get a list of vertices starting from the upper-left corner.
This property obeys the same rules as the vertices property but always starts
from the upper-left-most vertex. This property should be used when exporting to
EnergyPlus / OpenStudio.
"""
return self._geometry.upper_left_counter_clockwise_vertices
@property
def normal(self):
"""Get a Vector3D for the direction in which the face is pointing.
"""
return self._geometry.normal
@property
def center(self):
"""Get a ladybug_geometry Point3D for the center of the face.
Note that this is the center of the bounding rectangle around this geometry
and not the area centroid.
"""
return self._geometry.center
@property
def area(self):
"""Get the area of the face."""
return self._geometry.area
@property
def perimeter(self):
"""Get the perimeter of the face. This includes the length of holes in the face.
"""
return self._geometry.perimeter
@property
def min(self):
"""Get a Point3D for the minimum of the bounding box around the object."""
all_geo = self._outdoor_shades + self._indoor_shades
all_geo.extend(self._apertures)
all_geo.extend(self._doors)
all_geo.append(self.geometry)
return self._calculate_min(all_geo)
@property
def max(self):
"""Get a Point3D for the maximum of the bounding box around the object."""
all_geo = self._outdoor_shades + self._indoor_shades
all_geo.extend(self._apertures)
all_geo.extend(self._doors)
all_geo.append(self.geometry)
return self._calculate_max(all_geo)
@property
def aperture_area(self):
"""Get the combined area of the face's apertures."""
return sum([ap.area for ap in self._apertures])
@property
def aperture_ratio(self):
"""Get a number between 0 and 1 for the area ratio of the apertures to the face.
"""
return self.aperture_area / self.area
@property
def tilt(self):
"""Get the tilt of the geometry between 0 (up) and 180 (down)."""
return math.degrees(self._geometry.tilt)
@property
def altitude(self):
"""Get the altitude of the geometry between +90 (up) and -90 (down)."""
return math.degrees(self._geometry.altitude)
@property
def azimuth(self):
"""Get the azimuth of the geometry, between 0 and 360.
Given Y-axis as North, 0 = North, 90 = East, 180 = South, 270 = West
This will be zero if the Face3D is perfectly horizontal.
"""
return math.degrees(self._geometry.azimuth)
@property
def type_color(self):
"""Get a Color to be used in visualizations by type."""
ts = self.type.name if isinstance(self.boundary_condition, (Outdoors, Ground)) \
else 'Interior{}'.format(self.type.name)
return self.TYPE_COLORS[ts]
@property
def bc_color(self):
"""Get a Color to be used in visualizations by boundary condition."""
try:
return self.BC_COLORS[self.boundary_condition.name]
except KeyError: # extension boundary condition
return self.BC_COLORS['Other']
def horizontal_orientation(self, north_vector=Vector2D(0, 1)):
"""Get a number between 0 and 360 for the orientation of the face in degrees.
0 = North, 90 = East, 180 = South, 270 = West
Args:
north_vector: A ladybug_geometry Vector2D for the north direction.
Default is the Y-axis (0, 1).
"""
return math.degrees(
north_vector.angle_clockwise(Vector2D(self.normal.x, self.normal.y)))
def cardinal_direction(self, north_vector=Vector2D(0, 1)):
"""Get text description for the cardinal direction that the face is pointing.
Will be one of the following: ('North', 'NorthEast', 'East', 'SouthEast',
'South', 'SouthWest', 'West', 'NorthWest').
Args:
north_vector: A ladybug_geometry Vector2D for the north direction.
Default is the Y-axis (0, 1).
"""
orient = self.horizontal_orientation(north_vector)
orient_text = ('North', 'NorthEast', 'East', 'SouthEast', 'South',
'SouthWest', 'West', 'NorthWest')
angles = (22.5, 67.5, 112.5, 157.5, 202.5, 247.5, 292.5, 337.5)
for i, ang in enumerate(angles):
if orient < ang:
return orient_text[i]
return orient_text[0]
def add_prefix(self, prefix):
"""Change the identifier of this object and child objects by inserting a prefix.
This is particularly useful in workflows where you duplicate and edit
a starting object and then want to combine it with the original object
into one Model (like making a model of repeated rooms) since all objects
within a Model must have unique identifiers.
Args:
prefix: Text that will be inserted at the start of this object's
(and child objects') identifier and display_name. It is recommended
that this prefix be short to avoid maxing out the 100 allowable
characters for honeybee identifiers.
"""
self._identifier = clean_string('{}_{}'.format(prefix, self.identifier))
self.display_name = '{}_{}'.format(prefix, self.display_name)
self.properties.add_prefix(prefix)
for ap in self._apertures:
ap.add_prefix(prefix)
for dr in self._doors:
dr.add_prefix(prefix)
self._add_prefix_shades(prefix)
if isinstance(self._boundary_condition, Surface):
new_bc_objs = (clean_string('{}_{}'.format(prefix, adj_name)) for adj_name
in self._boundary_condition._boundary_condition_objects)
self._boundary_condition = Surface(new_bc_objs, False)
def remove_sub_faces(self):
"""Remove all apertures and doors from the face."""
self.remove_apertures()
self.remove_doors()
def remove_apertures(self):
"""Remove all apertures from the face."""
for aperture in self._apertures:
aperture._parent = None
self._apertures = []
self._punched_geometry = None # reset so that it can be re-computed
def remove_doors(self):
"""Remove all doors from the face."""
for door in self._apertures:
door._parent = None
self._doors = []
self._punched_geometry = None # reset so that it can be re-computed
def add_aperture(self, aperture):
"""Add an Aperture to this face.
This method does not check the co-planarity between this Face and the
Aperture or whether the Aperture has all vertices within the boundary of
this Face. To check this, the Face3D.is_sub_face() method can be used
with the Aperture and Face geometry before using this method or the
are_sub_faces_valid() method can be used afterwards.
Args:
aperture: An Aperture to add to this face.
"""
assert isinstance(aperture, Aperture), \
'Expected Aperture. Got {}.'.format(type(aperture))
self._acceptable_sub_face_check(Aperture)
aperture._parent = self
if self.normal.angle(aperture.normal) > math.pi / 2: # reversed normal
aperture._geometry = aperture._geometry.flip()
self._apertures.append(aperture)
self._punched_geometry = None # reset so that it can be re-computed
def add_door(self, door):
"""Add a Door to this face.
This method does not check the co-planarity between this Face and the
Door or whether the Door has all vertices within the boundary of
this Face. To check this, the Face3D.is_sub_face() method can be used
with the Door and Face geometry before using this method or the
are_sub_faces_valid() method can be used afterwards.
Args:
door: A Door to add to this face.
"""
assert isinstance(door, Door), \
'Expected Door. Got {}.'.format(type(door))
self._acceptable_sub_face_check(Door)
door._parent = self
if self.normal.angle(door.normal) > math.pi / 2: # reversed normal
door._geometry = door._geometry.flip()
self._doors.append(door)
self._punched_geometry = None # reset so that it can be re-computed
def add_apertures(self, apertures):
"""Add a list of Apertures to this face."""
for aperture in apertures:
self.add_aperture(aperture)
def add_doors(self, doors):
"""Add a list of Doors to this face."""
for door in doors:
self.add_door(door)
def add_sub_faces(self, sub_faces):
"""Add a list of Apertures and/or Doors to this face."""
for sub_f in sub_faces:
if isinstance(sub_f, Aperture):
self.add_aperture(sub_f)
else:
self.add_door(sub_f)
def replace_apertures(self, apertures):
"""Replace all sub-faces assigned to this Face with a new list of Apertures."""
self.remove_sub_faces()
self.add_apertures(apertures)
def set_adjacency(self, other_face, tolerance=0.01):
"""Set this face adjacent to another and set the other face adjacent to this one.
Note that this method does not verify whether the other_face geometry is
co-planar or compatible with this one so it is recommended that either the
Face3D.is_centered_adjacent() or the Face3D.is_geometrically_equivalent()
method be used with this face geometry and the other_face geometry
before using this method in order to verify these criteria.
However, this method will use the proximity of apertures and doors within
the input tolerance to determine which of the sub faces in the other_face
are adjacent to the ones in this face. An exception will be thrown if not
all sub-faces can be matched.
Args:
other_face: Another Face object to be set adjacent to this one.
tolerance: The minimum distance between the center of two aperture
geometries at which they are considered adjacent. Default: 0.01,
suitable for objects in meters.
Returns:
A dictionary of adjacency information with the following keys
- adjacent_apertures - A list of tuples with each tuple containing 2
objects for Apertures paired in the process of solving adjacency.
- adjacent_doors - A list of tuples with each tuple containing 2
objects for Doors paired in the process of solving adjacency.
"""
# check the inputs and the ability of the faces to be adjacent
assert isinstance(other_face, Face), \
'Expected honeybee Face. Got {}.'.format(type(other_face))
# set the boundary conditions of the faces
self._boundary_condition = boundary_conditions.surface(other_face)
other_face._boundary_condition = boundary_conditions.surface(self)
adj_info = {'adjacent_apertures': [], 'adjacent_doors': []}
# set the apertures to be adjacent to one another
if len(self._apertures) != len(other_face._apertures):
msg = 'Number of apertures does not match between {} and {}.'.format(
self.display_name, other_face.display_name)
if self.has_parent and other_face.has_parent:
msg = '{} Relevant rooms: {}, {}'.format(
msg, self.parent.display_name, other_face.parent.display_name)
raise AssertionError(msg)
if len(self._apertures) > 0:
found_adjacencies = 0
for aper_1 in self._apertures:
for aper_2 in other_face._apertures:
if aper_1.center.distance_to_point(aper_2.center) <= tolerance:
aper_1.set_adjacency(aper_2)
adj_info['adjacent_apertures'].append((aper_1, aper_2))
found_adjacencies += 1
break
if len(self._apertures) != found_adjacencies:
msg = 'Not all apertures of {} were found to be adjacent to ' \
'apertures in {}.'.format(self.display_name, other_face.display_name)
if self.has_parent and other_face.has_parent:
msg = '{} Relevant rooms: {}, {}'.format(
msg, self.parent.display_name, other_face.parent.display_name)
raise AssertionError(msg)
# set the doors to be adjacent to one another
assert len(self._doors) == len(other_face._doors), \
'Number of doors does not match between {} and {}.'.format(
self.display_name, other_face.display_name)
if len(self._doors) > 0:
found_adjacencies = 0
for door_1 in self._doors:
for door_2 in other_face._doors:
if door_1.center.distance_to_point(door_2.center) <= tolerance:
door_1.set_adjacency(door_2)
adj_info['adjacent_doors'].append((door_1, door_2))
found_adjacencies += 1
break
if len(self._doors) != found_adjacencies:
msg = 'Not all doors of {} were found to be adjacent to ' \
'doors in {}.'.format(self.display_name, other_face.display_name)
if self.has_parent and other_face.has_parent:
msg = '{} Relevant rooms: {}, {}'.format(
msg, self.parent.display_name, other_face.parent.display_name)
raise AssertionError(msg)
return adj_info
def rectangularize_apertures(
self, subdivision_distance=None, max_separation=None,
merge_all=False, tolerance=0.01, angle_tolerance=1.0):
"""Convert all Apertures on this Face to be rectangular.
This is useful when exporting to simulation engines that only accept
rectangular window geometry. This method will always result ing Rooms where
all Apertures are rectangular. However, if the subdivision_distance is not
set, some Apertures may extend past the parent Face or may collide with
one another.
Args:
subdivision_distance: A number for the resolution at which the
non-rectangular Apertures will be subdivided into smaller
rectangular units. Specifying a number here ensures that the
resulting rectangular Apertures do not extend past the parent
Face or collide with one another. If None, all non-rectangular
Apertures will be rectangularized by taking the bounding rectangle
around the Aperture. (Default: None).
max_separation: A number for the maximum distance between non-rectangular
Apertures at which point the Apertures will be merged into a single
rectangular geometry. This is often helpful when there are several
triangular Apertures that together make a rectangle when they are
merged across their frames. In such cases, this max_separation
should be set to a value that is slightly larger than the window frame.
If None, no merging of Apertures will happen before they are
converted to rectangles. (Default: None).
merge_all: Boolean to note whether all apertures should be merged before
they are rectangularized. If False, only non-rectangular apertures
will be merged before rectangularization. Note that this argument
has no effect when the max_separation is None. (Default: False).
tolerance: The maximum difference between point values for them to be
considered equivalent. (Default: 0.01, suitable for objects in meters).
angle_tolerance: The max angle in degrees that the corners of the
rectangle can differ from a right angle before it is not
considered a rectangle. (Default: 1).
Returns:
True if the Apertures were changed. False if they were unchanged.
"""
# sort the rectangular and non-rectangular apertures
apertures = self._apertures
if len(apertures) == 0:
return False
tol, ang_tol = tolerance, math.radians(angle_tolerance)
rect_aps, non_rect_aps, non_rect_geos = [], [], []
for aperture in apertures:
try:
clean_geo = aperture.geometry.remove_colinear_vertices(tol)
except AssertionError: # degenerate Aperture to be ignored
continue
if max_separation is None or not merge_all:
if clean_geo.polygon2d.is_rectangle(ang_tol):
rect_aps.append(aperture)
else:
non_rect_aps.append(aperture)
non_rect_geos.append(clean_geo)
else:
non_rect_aps.append(aperture)
non_rect_geos.append(clean_geo)
if not non_rect_geos: # nothing to be rectangularized
return False
# reset boundary conditions to outdoors so new apertures can be added
if not isinstance(self.boundary_condition, Outdoors):
self.boundary_condition = boundary_conditions.outdoors
for ap in rect_aps:
ap.boundary_condition = boundary_conditions.outdoors
edits_occurred = False
# try to merge the non-rectangular apertures if a max_separation is specified
ref_plane = self._reference_plane(ang_tol)
if max_separation is not None:
if merge_all or (not merge_all and len(non_rect_geos) > 1):
edits_occurred = True
if max_separation <= tol: # just join the Apertures at the tolerance
non_rect_geos = Face3D.join_coplanar_faces(non_rect_geos, tol)
else: # join the Apertures using the max_separation
# get polygons for the faces that all lie within the same plane
face_polys = []
for fg in non_rect_geos:
verts2d = tuple(ref_plane.xyz_to_xy(_v) for _v in fg.boundary)
face_polys.append(Polygon2D(verts2d))
if fg.has_holes:
for hole in fg.holes:
verts2d = tuple(ref_plane.xyz_to_xy(_v) for _v in hole)
face_polys.append(Polygon2D(verts2d))
# get the joined boundaries around the Polygon2D
joined_bounds = Polygon2D.gap_crossing_boundary(
face_polys, max_separation, tolerance)
# convert the boundary polygons back to Face3D
if len(joined_bounds) == 1: # can be represented with a single Face3D
verts3d = tuple(ref_plane.xy_to_xyz(_v) for _v in joined_bounds[0])
non_rect_geos = [Face3D(verts3d, plane=ref_plane)]
else: # need to separate holes from distinct Face3Ds
bound_faces = []
for poly in joined_bounds:
verts3d = tuple(ref_plane.xy_to_xyz(_v) for _v in poly)
bound_faces.append(Face3D(verts3d, plane=ref_plane))
non_rect_geos = Face3D.merge_faces_to_holes(bound_faces, tolerance)
clean_aps = []
for ap_geo in non_rect_geos:
try:
clean_aps.append(ap_geo.remove_colinear_vertices(tol))
except AssertionError: # degenerate Aperture to be ignored
continue
non_rect_geos = clean_aps
# convert the remaining Aperture geometries to rectangles
if subdivision_distance is None: # just take the bounding rectangle
edits_occurred = True
# get the bounding rectangle around all of the geometries
ap_geos = []
for ap_geo in non_rect_geos:
if ap_geo.polygon2d.is_rectangle(ang_tol):
ap_geos.append(ap_geo) # catch rectangles found in merging
continue
geo_2d = Polygon2D([ref_plane.xyz_to_xy(v) for v in ap_geo.vertices])
g_min, g_max = geo_2d.min, geo_2d.max
base, hgt = g_max.x - g_min.x, g_max.y - g_min.y
bound_poly = Polygon2D.from_rectangle(g_min, Vector2D(0, 1), base, hgt)
geo_3d = Face3D([ref_plane.xy_to_xyz(v) for v in bound_poly.vertices])
ap_geos.append(geo_3d)
non_rect_geos = ap_geos
# create Aperture objects from all of the merged geometries
if not edits_occurred:
new_aps = non_rect_aps
else:
new_aps = []
for i, ap_face in enumerate(non_rect_geos):
exist_ap = None
for old_ap in non_rect_aps:
if old_ap.center.is_equivalent(ap_face.center, tolerance):
exist_ap = old_ap
break
if exist_ap is None: # could not be matched; just make a new aperture
new_ap = Aperture('{}_RG{}'.format(self.identifier, i), ap_face)
else:
new_ap = Aperture(exist_ap.identifier, ap_face,
is_operable=exist_ap.is_operable)
new_ap.display_name = '{}_{}'.format(exist_ap.display_name, i)
new_aps.append(new_ap)
# we can just add the apertures if there's no subdivision going on
if subdivision_distance is None:
# remove any Apertures that are overlapping
all_aps = rect_aps + new_aps
all_aps = self._remove_overlapping_sub_faces(all_aps, tolerance)
self.remove_apertures()
self.add_apertures(all_aps)
return True
# if distance is provided, subdivide the apertures into strips
new_ap_objs = []
for ap_obj in new_aps:
ap_geo = ap_obj.geometry
if ap_geo.polygon2d.is_rectangle(ang_tol):
new_ap_objs.append(ap_obj) # catch rectangles found in merging
continue
# create a mesh grid over the Aperture in the reference plane
geo_2d = Polygon2D([ref_plane.xyz_to_xy(v) for v in ap_geo.vertices])
try:
grid = Mesh2D.from_polygon_grid(
geo_2d, subdivision_distance, subdivision_distance, False)
except AssertionError: # Aperture smaller than resolution; ignore
continue
# group face by y value. All the rows will be merged together
vertices = grid.vertices
groups = {}
start_y = None
last_y = vertices[grid.faces[0][0]].y
for i, face in enumerate(grid.faces):
min_2d = vertices[face[0]]
for xy in groups:
if abs(min_2d.x - xy[0]) < tolerance and \
abs(min_2d.y - last_y) < tolerance:
groups[(xy[0], start_y)].append(face)
break
else:
start_y = min_2d.y
groups[(min_2d.x, start_y)] = [face]
last_y = vertices[face[3]].y
# get the max and min of each group
sorted_groups = []
for group in groups.values():
# find min_2d and max_2d for each group
min_2d = vertices[group[0][0]]
max_2d = vertices[group[-1][2]]
sorted_groups.append({'min': min_2d, 'max': max_2d})
def _get_last_row(groups, start=0):
"""An internal function to return the index for the last row that can be
merged with the start row that is passed to this function.
This function compares the min and max x and y values for each row to see
if they can be merged into a rectangle.
"""
for count, group in enumerate(groups[start:]):
next_group = groups[count + start + 1]
if abs(group['min'].y - next_group['min'].y) <= tolerance \
and abs(group['max'].y - next_group['max'].y) <= tolerance \
and abs(next_group['min'].x - group['max'].x) <= tolerance:
continue
else:
return start + count
return start + count + 1
# merge the rows if they have the same number of grid cells
sorted_groups.sort(key=lambda x: x['min'].x)
merged_groups = []
start_row = 0
last_row = -1
while last_row < len(sorted_groups):
try:
last_row = _get_last_row(sorted_groups, start=start_row)
except IndexError:
merged_groups.append(
{
'min': sorted_groups[start_row]['min'],
'max': sorted_groups[len(sorted_groups) - 1]['max']
}
)
break
else:
merged_groups.append(
{
'min': sorted_groups[start_row]['min'],
'max': sorted_groups[last_row]['max']
}
)
if last_row == start_row:
# the row was not grouped with anything else
start_row += 1
else:
start_row = last_row + 1
# convert the groups into rectangular strips
for i, group in enumerate(merged_groups):
min_2d = group['min']
max_2d = group['max']
base, hgt = max_2d.x - min_2d.x, max_2d.y - min_2d.y
bound_poly = Polygon2D.from_rectangle(min_2d, Vector2D(0, 1), base, hgt)
geo_3d = Face3D([ref_plane.xy_to_xyz(v) for v in bound_poly.vertices])
new_ap = Aperture(
'{}_Glz{}'.format(ap_obj.identifier, i),
geo_3d, is_operable=ap_obj.is_operable)
new_ap.display_name = '{}_{}'.format(ap_obj.display_name, i)
new_ap_objs.append(new_ap)
# replace the apertures with the new ones
self.remove_apertures()
self.add_apertures(rect_aps + new_ap_objs)
return True
def _reference_plane(self, angle_tolerance):
"""Get a Plane for this Face geometry derived from the Face3D plane.
This will be oriented with the plane Y-Axis either aligned with the
World Z or World Y, which is helpful in rectangularization.
Args:
angle_tolerance: The max angle in radians that Face normal can differ
from the World Z before the Face is treated as being in the
World XY plane.
"""
parent_llc = self.geometry.lower_left_corner
rel_plane = self.geometry.plane
vertical = Vector3D(0, 0, 1)
vert_ang = rel_plane.n.angle(vertical)
if vert_ang <= angle_tolerance or vert_ang >= math.pi - angle_tolerance:
proj_x = Vector3D(1, 0, 0)
else:
proj_y = vertical.project(rel_plane.n)
proj_x = proj_y.rotate(rel_plane.n, math.pi / -2)
ref_plane = Plane(rel_plane.n, parent_llc, proj_x)
return ref_plane
def offset_aperture_edges(self, offset_distance, tolerance=0.01):
"""Offset the edges of all apertures by a certain distance.
This is useful for translating between interfaces that expect the window
frame to be included within or excluded from the geometry of the Aperture.
Note that this operation can often create Apertures that collide with
one another or extend past the parent Face. So it may be desirable
to run the fix_invalid_sub_faces after using this method.
Args:
offset_distance: Distance with which the edges of each Aperture will
be offset from the original geometry. Positive values will
offset the geometry outwards and negative values will offset the
geometries inwards.
tolerance: The minimum difference between point values for them to be
considered the distinct. (Default: 0.01, suitable for objects
in meters).
"""
# convert the apertures to polygons and offset them
new_apertures = []
prim_pl = self.geometry.plane
for ap in self.apertures:
try:
verts_2d = tuple(prim_pl.xyz_to_xy(pt) for pt in ap.geometry.boundary)
poly = Polygon2D(verts_2d).remove_colinear_vertices(tolerance)
off_poly = poly.offset(-offset_distance, True)
if off_poly is not None:
verts_3d = tuple(prim_pl.xy_to_xyz(pt) for pt in off_poly)
new_ap = ap.duplicate()
new_ap._geometry = Face3D(verts_3d, prim_pl)
new_apertures.append(new_ap)
else:
new_apertures.append(ap)
except AssertionError: # degenerate geometry to ignore
new_apertures.append(ap)
# assign the new apertures
self.remove_apertures()
self.add_apertures(new_apertures)
def merge_neighboring_sub_faces(self, merge_distance=0.05, tolerance=0.01):
"""Merge neighboring Apertures and/or Doors on this Face together.
This method is particularly useful for simplifying Apertures in concave
Faces since trying to simplify such Apertures down to a ratio will
produce a triangulated result that is not particularly clean.
Args:
merge_distance: Distance between Apertures and/or Doors at which point they
will be merged into a single Aperture. When this value is less than
or equal to the tolerance, apertures will only be merged if they
touch one another. (Default: 0.05, suitable for objects in meters).
tolerance: The minimum difference between point values for them to be
considered the distinct. (Default: 0.01, suitable for objects
in meters).
"""
# first, check that there are Apertures to e merged
sub_faces = self.sub_faces
if len(sub_faces) <= 1: # no apertures to be merged
return
# collect the sub-face geometries as polygons in the face plane
clean_polys, original_objs, original_area = [], [], 0
prim_pl = self.geometry.plane
for sub_f in sub_faces:
try:
verts_2d = tuple(prim_pl.xyz_to_xy(pt) for pt in sub_f.geometry.boundary)
poly = Polygon2D(verts_2d).remove_colinear_vertices(tolerance)
clean_polys.append(poly)
original_area += poly.area
original_objs.append(sub_f)
except AssertionError: # degenerate geometry to ignore
pass
original_polys = clean_polys[:]
# join the polygons together
if merge_distance <= tolerance: # only join the polygons that touch one another
clean_polys = Polygon2D.joined_intersected_boundary(clean_polys, tolerance)
else:
clean_polys = Polygon2D.gap_crossing_boundary(
clean_polys, merge_distance, tolerance)
# assuming that the operations have edited the polygons, create new sub-faces
new_area = sum(p.area for p in clean_polys)
area_diff = abs(original_area - new_area)
if len(clean_polys) != len(original_polys) or area_diff > tolerance:
clean_polys = [poly.remove_colinear_vertices(tolerance)
for poly in clean_polys]