-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathBuildingPy-gis2bim.py
8506 lines (7022 loc) · 299 KB
/
BuildingPy-gis2bim.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
#[BuildingPy] DO NOT EDIT THIS FILE. IT IS GENERATED FROM THE SOURCE CODE
try:
from collections.abc import MutableSequence
except ImportError:
from collections import MutableSequence
import sys
from pathlib import Path
from typing import Any, List
import copy
import pickle
from functools import reduce
import struct
from typing import Self
import json
import importlib
from typing import List
from packages.svg.path import parse_path
import math
import operator
from typing import Self, Union
import sys, math
import sys, os, math
import urllib.request
import re
from typing import Union
import string, random, json
import urllib
import xml.etree.ElementTree as ET
from math import sqrt, cos, sin, acos, degrees, radians, log, pi
from bisect import bisect
from abc import ABC, abstractmethod
import sys, os, math, json
from collections import defaultdict
class Serializable:
@property
def type(self):
return __class__.__name__
@staticmethod
def serialize_type(obj) -> dict:
"""Save the type of an object to a dictionary.
Args:
obj: the object to get the type of
Returns:
dict: a dictionary with keys 'module' and 'type'
"""
return {
'module': obj.__module__,
'type': obj.__class__.__name__
}
def serialize(self) -> dict:
"""serialize members of this object into a dictionary
Returns:
dict: a dictionary of all members. the members will serialize themselves, when necessary.
"""
return self.__dict__
def toJson(self) -> str:
"""converts a serializable object to json
Returns:
str: a json string
"""
return json.dumps(self, default=lambda x:
#when a variable is not compatible with the standard json serialization functions, it's probably one of our classes.
x.serialize() | self.serialize_type(x)
)
@staticmethod
def deserialize_type(data):
"""Creates an new object from the provided data."""
if isinstance(data, dict):
if 'type' in data:
#module_name = # data.pop('__module__')
module = importlib.import_module(data.pop('module'))
type = getattr(module, data.pop('type'))
if hasattr(type, 'deserialize'):
obj = type.deserialize(data)
else:
obj = type.__new__(type)
#we assume obj is an instance of Serializable
obj.deserialize_members(data)
#obj.deserialize(data)
return obj
#else:
# return {key: Serializable.deserialize_type(value) for key, value in data.items()}
elif isinstance(data, list):
return [Serializable.deserialize_type(item) for item in data]
return data
def deserialize_members(self, data : dict):
"""Deserializes the object from the provided data."""
# #raise NotImplementedError()
for key, value in data.items():
setattr(self, key, self.deserialize_type(value))
def save(self, file_name):
# we can possibly add an override function we can call on class objects. but for now, this will work fine
serialized_data = self.toJson()
with open(file_name, 'w') as file:
file.write(serialized_data)
def open(self, file_name):
with open(file_name) as file:
self.deserialize_members(json.load(file))
# self.__dict__ = json.load(file)
def __repr__(self) -> str:
return str(self)
def to_array(*args) -> list:
"""converts the arguments into an array.
Returns:
list: the arguments provided, converted to a list.
"""
return args[0] if len(args) == 1 and hasattr(args[0], "__getitem__") else list(args)
class Coords(Serializable, list):
"""
a shared base class for point and vector. contains the x, y and z coordinates.
operations you do with these coords will apply for the children.
for example: Vector(2, 4, 6) / 2 = Vector(1, 2, 3)
or: Vector(2,5) ** 2 = Vector(4, 25)
Vectors can also be nested.
"""
def __init__(self, *args, **kwargs) -> 'Coords':
arrayArgs:list = to_array(*args)
list.__init__(self, arrayArgs)
Serializable.__init__(self)
for kwarg in kwargs.items():
self.set_axis_by_name(kwarg[0], kwarg[1])
def __str__(self):
return self.__class__.__name__ + '(' + ','.join([f'{axis_name}={((v * 100) // 1 ) / 100 }' for v, axis_name in zip(self, self.axis_names)]) + ')'
axis_names = ['x', 'y', 'z', 'w']
@property
def x(self): return self[0]
@x.setter
def x(self, value): self[0] = value
@property
def y(self): return self[1]
@y.setter
def y(self, value): self[1] = value
@property
def z(self): return self[2]
@z.setter
def z(self, value): self[2] = value
@property
def w(self): return self[3]
@w.setter
def w(self, value): self[3] = value
@property
def squared_magnitude(self):
result = 0
for axis_value in self:
result += axis_value * axis_value
return result
squared_length = squared_magnitude
@property
def magnitude(self):
"""the 'length' could also mean the axis count. this makes it more clear.
Returns:
the length
"""
return math.sqrt(self.squared_magnitude)
length = magnitude
@magnitude.setter
def magnitude(self, value):
"""Rescales the vector to have the specified length.
#### Parameters:
- `vector_1` (`Vector`): The vector to be rescaled.
- `newlength` (float): The desired length of the vector.
#### Returns:
`Vector`: A new Vector object representing the rescaled vector.
#### Example usage:
```python
vector = Vector(3, 4, 0)
new_vector = Vector.new_length(vector, 5)
# Vector(X = 3.000, Y = 4.000, Z = 0.000)
```
"""
self *= value / self.magnitude
@property
def normalized(self):
"""Returns the normalized form of the vector.
The normalized form of a vector is a vector with the same direction but with a length (magnitude) of 1.
#### Returns:
`Vector`: A new Vector object representing the normalized form of the input vector.
#### Example usage:
```python
vector1 = Vector(3, 0, 4)
normalized_vector = vector1.normalized
# Vector(X = 0.600, Y = 0.000, Z = 0.800)
```
"""
sqm = self.squared_magnitude
return self / math.sqrt(sqm) if sqm > 0 else Coords()
@property
def angle(self) -> float:
"""output range: -PI to PI
Returns:
float: the arc tangent of y / x in radians
"""
#treat this normal vector as a triangle. we know all sides but want to know the angle.
#tan(deg) = other side / straight side
#deg = atan(other side / straight side)
return math.atan2(self.y, self.x)
@staticmethod
def by_coordinates(x: float, y: float, z:float = None):
return Coords(x, y, z) if z is not None else Coords(x, y)
@staticmethod
def by_list(coordinate_list: list):
return Coords(coordinate_list)
@staticmethod
def by_angle(angle:float) -> 'Coords':
"""generates a 2d normal using the angle passed
Args:
angle (float): a number in radians
Returns:
Coords: a rotated normal (vector with length of 1)
"""
return Coords(math.cos(angle), math.sin(angle))
@staticmethod
def angle_between(vector_1: 'Coords', vector_2: 'Coords') -> float:
"""Computes the angle in degrees between two coords.
The angle between two coords is the angle required to rotate one vector onto the other, measured in degrees.
#### Parameters:
- `vector_1` (`Vector`): The first vector.
- `vector_2` (`Vector`): The second vector.
#### Returns:
`float`: The angle in degrees between the input coords.
#### Example usage:
```python
vector1 = Vector(1, 0, 0)
vector2 = Vector(0, 1, 0)
angle = Vector.angle_between(vector1, vector2)
# 90
```
"""
dot_product = Coords.dot_product(vector_1, vector_2)
length_vector_1 = vector_1.magnitude
length_vector_2 = vector_2.magnitude
if length_vector_1 == 0 or length_vector_2 == 0:
return 0
cos_angle = dot_product / (length_vector_1 * length_vector_2)
cos_angle = max(-1.0, min(cos_angle, 1.0))
return math.acos(cos_angle)
@staticmethod
def dot_product(vector_1: 'Coords', vector_2: 'Coords') -> 'float':
"""Computes the dot product of two vectors.
The dot product of two vectors is a scalar quantity equal to the sum of the products of their corresponding components. It gives insight into the angle between the vectors.
#### Parameters:
- `vector_1` (`Coords`): The first vector.
- `vector_2` (`Coords`): The second vector.
#### Returns:
`float`: The dot product of the input vectors.
#### Example usage:
```python
vector1 = Vector(1, 2, 3)
vector2 = Vector(4, 5, 6)
dot_product = Vector.dot_product(vector1, vector2)
# 32
```
"""
total = 0
for i in range(len(vector_1)):
total += vector_1[i] * vector_2 [i]
return total
@staticmethod
def distance_squared(point_1: 'Coords', point_2: 'Coords') -> float:
"""Computes the Euclidean distance between two 3D points.
#### Parameters:
- `point_1` (Coords): The first point.
- `point_2` (Coords): The second point.
#### Returns:
`float`: The Euclidean distance between `point_1` and `point_2`.
#### Example usage:
```python
point_1 = Coords(0, 0, 400)
point_2 = Coords(300, 0, 400)
output = Coords.distance(point_1, point_2)
# 90000
```
"""
return (point_2 - point_1).squared_magnitude
@staticmethod
def distance(point_1: 'Coords', point_2: 'Coords') -> float:
"""Computes the Euclidean distance between two 3D points.
#### Parameters:
- `point_1` (Coords): The first point.
- `point_2` (Coords): The second point.
#### Returns:
`float`: The Euclidean distance between `point_1` and `point_2`.
#### Example usage:
```python
point_1 = Coords(0, 0, 400)
point_2 = Coords(300, 0, 400)
output = Coords.distance(point_1, point_2)
# 90000
```
"""
return (point_2 - point_1).magnitude
@staticmethod
def axis_index(axis:str) -> int:
"""returns index of axis name.<br>
raises a valueError when the name isn't valid.
Args:
axis (str): the name of the axis
Returns:
int: the index
"""
return Coords.axis_names.index(axis.lower())
def change_axis_count(self,axis_count: int):
"""in- or decreases the amount of axes to the preferred axis count.
Args:
axis_count (int): the new amount of axes
"""
if axis_count > len(self):
diff = axis_count + 1 - len(self)
self.extend([0] * diff)
else:
self = self[:axis_count]
def set_axis(self, axis_index: int, value) -> int | None:
"""sets an axis with the specified index to the value. will resize when the coords can't contain them.
Args:
axis_index (int): the index of the axis, for example 2
value: the value to set the axis to
Returns:
int: the new size when resized, -1 when the axis is invalid, None when the value was just set.
"""
if axis_index >= len(self):
self.extend([0] * (axis_index - len(self)))
self.extend([value])
return axis_index
self[axis_index] = value
return None
def set_axis_by_name(self, axis_name: str, value) -> int | None:
"""sets an axis with the specified name to the value. will resize when the coords can't contain them.
Args:
axis_name (str): the name of the axis, for example 'x'
value: the value to set the axis to
Returns:
int: the new size when resized, -1 when the axis is invalid, None when the value was just set.
"""
return self.set_axis(Coords.axis_index(axis_name), value)
@staticmethod
def by_two_points(point_1: 'Coords', point_2: 'Coords') -> 'Coords':
"""Computes the vector between two points.
#### Parameters:
- `point_1` (`Coords`): The starting point.
- `point_2` (`Coords`): The ending point.
#### Returns:
`Vector`: A new Vector object representing the vector between the two points.
#### Example usage:
```python
point1 = Point(1, 2, 3)
point2 = Point(4, 6, 8)
vector = Vector.by_two_points(point1, point2)
# Vector(X = 3, Y = 4, Z = 5)
```
"""
return point_2 - point_1
def volume(self):
result = 1
for val in self:
result *= val
return result
#useful for sorting
def compare(self, other):
for axis in range(len(self)):
if self[axis] != other[axis]:
return other[axis] - self[axis]
return 0
def ioperate_2(self, op: operator, other):
try:
for index in range(len(self)):
self[index] = op(self[index], other[index])
except TypeError:
#variable doesn't support index
#https://stackoverflow.com/questions/7604380/check-for-operator
for index in range(len(self)):
self[index] = op(self[index], other)
return self
def operate_2(self, op:operator, other):
result = Coords([0] * len(self))
try:
for index in range(len(self)):
result[index] = op(self[index], other[index])
except TypeError:
#variable doesn't support index
#https://stackoverflow.com/questions/7604380/check-for-operator
for index in range(len(self)):
result[index] = op(self[index], other)
return result
def operate_1(self, op:operator):
result = Coords([0] * len(self))
for index in range(len(self)):
result[index] = op(self[index])
return result
def __add__(self, other):
"""Calculates the sum of two vectors.
equivalent to the + operator.
"""
return self.operate_2(operator.__add__,other)
sum = __add__
def __sub__(self, other):
"""Calculates the difference between two Vector objects.
This method returns a new Vector object that is the result of subtracting the components of `vector_2` from `vector_1`.
equivalent to the - operator.
#### Parameters:
- `vector_1` (`Vector`): The minuend vector.
- `vector_2` (`Vector`): The subtrahend vector.
#### Returns:
`Vector`: A new Vector object resulting from the component-wise subtraction of `vector_2` from `vector_1`.
#### Example usage:
```python
vector1 = Vector(5, 7, 9)
vector2 = Vector(1, 2, 3)
result = Vector.diff(vector1, vector2)
# Vector(X = 4.000, Y = 5.000, Z = 6.000)
```
"""
return self.operate_2(operator.__sub__,other)
difference = diff = substract = __sub__
def __truediv__(self, other):
"""Divides the components of the first vector by the corresponding components of the second vector.
This method performs component-wise division. If any component of `vector_2` is 0, the result for that component will be undefined.
equivalent to the / operator.
#### Parameters:
- `vector_1` (`Vector`): The numerator vector.
- `vector_2` (`Vector`): The denominator vector.
#### Returns:
`Vector`: A new Vector object resulting from the component-wise division.
#### Example usage:
```python
vector1 = Vector(10, 20, 30)
vector2 = Vector(2, 4, 5)
result = Vector.divide(vector1, vector2)
# Vector(X = 5.000, Y = 5.000, Z = 6.000)
```
"""
return self.operate_2(operator.__truediv__,other)
divide = __truediv__
def __mul__(self, other):
"""Scales the vector by the specified scale factor.
equivalent to the * operator.
#### Parameters:
- `vector` (`Vector`): The vector to be scaled.
- `scalefactor` (float): The scale factor.
#### Returns:
`Vector`: A new Vector object representing the scaled vector.
#### Example usage:
```python
vector = Vector(1, 2, 3)
scaled_vector = Vector.scale(vector, 2)
# Vector(X = 2, Y = 4, Z = 6)
```
"""
return self.operate_2(operator.__mul__,other)
product = scale = __rmul__ = __mul__
def __pow__(self, power: float) -> Self:
"""raises the vector to a certain power.
equivalent to the ** operator.
Returns:
Self: a vector with all components raised to the specified power
"""
return self.ioperate_2(operator.__pow__)
def __neg__(self) -> Self:
"""negates this vector.
equivalent to the - operator.
Returns:
Self: a vector with all components negated.
"""
return self.operate_1(operator.__neg__)
reverse = __neg__
@staticmethod
def square(self) -> 'Coords':
"""
Computes the square of each component of the input vector.
#### Parameters:
- `vector_1` (`Vector`): The input vector.
#### Returns:
`Vector`: A new Vector object representing the square of each component of the input vector.
#### Example usage:
```python
vector = Vector(2, 3, 4)
squared_vector = Vector.square(vector)
# Vector(X = 4, Y = 9, Z = 16)
```
"""
return self ** 2
#i operators. these operate on self (+=, *=, etc)
def __iadd__(self, other) -> Self:
"""Translates the point by a given vector.
equivalent to the += operator.
#### Parameters:
- `point` (Point): The point to be translated.
- `vector` (Vector): The translation vector.
#### Returns:
`Point`: Translated point.
#### Example usage:
```python
point = Point(23, 1, 23)
vector = Vector(93, 0, -19)
output = Point.translate(point, vector)
# Point(X = 116.000, Y = 1.000, Z = 4.000)
```
"""
return self.ioperate_2(operator.__iadd__,other)
translate = __iadd__
def __isub__(self, other) -> Self:
return self.ioperate_2(operator.__isub__,other)
def __imul__(self, other) -> Self:
return self.ioperate_2(operator.__imul__,other)
def __itruediv__(self, other) -> Self:
return self.ioperate_2(operator.__itruediv__,other)
X_axis = Coords(1, 0, 0)
Y_Axis = Coords(0, 1, 0)
Z_Axis = Coords(0, 0, 1)
Coords.left = Coords(-1, 0, 0)
Coords.right = Coords(1, 0, 0)
Coords.down = Coords(0, -1, 0)
Coords.up = Coords(0, 1, 0)
Coords.backward = Coords(0, 0, -1)
Coords.forward = Coords(0, 0, 1)
class Color(Coords):
"""Documentation: output returns [r, g, b]"""
def __init__(self, *args, **kwargs):
Coords.__init__(self, *args,**kwargs)
red = r = Coords.x
green = g = Coords.y
blue = b = Coords.z
alpha = a = Coords.w
@property
def int(self) -> int:
"""converts this color into an integer value
Returns:
int: the merged integer.
this is assuming the color elements are whole integer values from 0 - 255
"""
int_val = elem
mult = 0x100
for elem in self[1:]:
int_val += elem * mult
mult *= 0x100
return int_val
@property
def hex(self):
return '#%02x%02x%02x%02x' % (self.r,self.g,self.b,self.a)
@staticmethod
def axis_index(axis:str) -> int:
"""returns index of axis name.<br>
raises a valueError when the name isn't valid.
Args:
axis (str): the name of the axis
Returns:
int: the index
"""
return ['r', 'g', 'b', 'a'].index(axis)
def Components(self, colorInput=None):
"""1"""
if colorInput is None:
return f"Error: Example usage Color().{sys._getframe(0).f_code.co_name}('green')"
else:
try:
import json
JSONfile = "library/color/colorComponents.json"
with open(JSONfile, 'r') as file:
components_dict = json.load(file)
checkExist = components_dict.get(str(colorInput))
if checkExist is not None:
r, g, b, a = components_dict[colorInput]
return [r, g, b]
else:
return f"Invalid {sys._getframe(0).f_code.co_name}-color, check '{JSONfile}' for available {sys._getframe(0).f_code.co_name}-colors."
except:
return f"Error: Color {sys._getframe(0).f_code.co_name} attribute usage is incorrect. Documentation: Color().{sys._getframe(0).f_code.co_name}.__doc__"
@staticmethod
def Hex(hex:str) -> 'Color':
"""converts a heximal string to a color object.
Args:
hex (str): a heximal string, for example '#FF00FF88'
Returns:
Color: the color object
"""
return Color(int(hex[1:3], 16),int(hex[3:5], 16), int(hex[5:7], 16),int(hex[7:9], 16)) if len(hex) > 7 else Color(int(hex[1:3], 16),int(hex[3:5], 16), int(hex[5:7], 16))
def CMYK(self, colorInput=None):
"""NAN"""
if colorInput is None:
return f"Error: Example usage Color().CMYK([0.5, 0.25, 0, 0.2])"
else:
try:
c, m, y, k = colorInput
r = int((1-c) * (1-k) * 255)
g = int((1-m) * (1-k) * 255)
b = int((1-y) * (1-k) * 255)
return [r, g, b]
except:
# add check help attribute
return f"Error: Color {sys._getframe(0).f_code.co_name} attribute usage is incorrect. Documentation: Color().{sys._getframe(0).f_code.co_name}.__doc__"
def Alpha(self, colorInput=None):
"""NAN"""
if colorInput is None:
return f"Error: Example usage Color().{sys._getframe(0).f_code.co_name}([255, 0, 0, 128])"
else:
try:
r, g, b, a = colorInput
return [r, g, b]
except:
return f"Error: Color {sys._getframe(0).f_code.co_name} attribute usage is incorrect. Documentation: Color().{sys._getframe(0).f_code.co_name}.__doc__"
def Brightness(self, colorInput=None):
"""Expected value is int(0) - int(1)"""
if colorInput is None:
return f"Error: Example usage Color().{sys._getframe(0).f_code.co_name}([255, 0, 0, 128])"
else:
try:
if colorInput >= 0 and colorInput <= 1:
r = g = b = int(255 * colorInput)
return [r, g, b]
else:
return f"Error: Color {sys._getframe(0).f_code.co_name} attribute usage is incorrect. Documentation: Color().{sys._getframe(0).f_code.co_name}.__doc__"
except:
return f"Error: Color {sys._getframe(0).f_code.co_name} attribute usage is incorrect. Documentation: Color().{sys._getframe(0).f_code.co_name}.__doc__"
@staticmethod
def RGB(self, colorInput=None):
"""NAN"""
if colorInput is None:
return f"Error: Example usage Color().{sys._getframe(0).f_code.co_name}([255, 0, 0])"
else:
try:
r, g, b = colorInput
return [r, g, b]
except:
return f"Error: Color {sys._getframe(0).f_code.co_name} attribute usage is incorrect. Documentation: Color().{sys._getframe(0).f_code.co_name}.__doc__"
def HSV(self, colorInput=None):
"""NAN"""
if colorInput is None:
return f"Error: Example usage Color().{sys._getframe(0).f_code.co_name}()"
else:
try:
h, s, v = colorInput
h /= 60.0
c = v * s
x = c * (1 - abs(h % 2 - 1))
m = v - c
if 0 <= h < 1:
r, g, b = c, x, 0
elif 1 <= h < 2:
r, g, b = x, c, 0
elif 2 <= h < 3:
r, g, b = 0, c, x
elif 3 <= h < 4:
r, g, b = 0, x, c
elif 4 <= h < 5:
r, g, b = x, 0, c
else:
r, g, b = c, 0, x
return [int((r + m) * 255), int((g + m) * 255), int((b + m) * 255)]
except:
return f"Error: Color {sys._getframe(0).f_code.co_name} attribute usage is incorrect. Documentation: Color().{sys._getframe(0).f_code.co_name}.__doc__"
def HSL(self, colorInput=None):
"""NAN"""
if colorInput is None:
return f"Error: Example usage Color().{sys._getframe(0).f_code.co_name}()"
else:
try:
h, s, l = colorInput
c = (1 - abs(2 * l - 1)) * s
x = c * (1 - abs(h / 60 % 2 - 1))
m = l - c / 2
if h < 60:
r, g, b = c, x, 0
elif h < 120:
r, g, b = x, c, 0
elif h < 180:
r, g, b = 0, c, x
elif h < 240:
r, g, b = 0, x, c
elif h < 300:
r, g, b = x, 0, c
else:
r, g, b = c, 0, x
r, g, b = int((r + m) * 255), int((g + m)
* 255), int((b + m) * 255)
return [r, g, b]
except:
return f"Error: Color {sys._getframe(0).f_code.co_name} attribute usage is incorrect. Documentation: Color().{sys._getframe(0).f_code.co_name}.__doc__"
def RAL(self, colorInput=None):
"""NAN"""
if colorInput is None:
return f"Error: Example usage Color().{sys._getframe(0).f_code.co_name}(1000)"
else:
try:
# validate if value is correct/found
import json
JSONfile = "library/color/colorRAL.json"
with open(JSONfile, 'r') as file:
ral_dict = json.load(file)
checkExist = ral_dict.get(str(colorInput))
if checkExist is not None:
r, g, b = ral_dict[str(colorInput)]["rgb"].split("-")
return [int(r), int(g), int(b), 100]
else:
return f"Invalid {sys._getframe(0).f_code.co_name}-color, check '{JSONfile}' for available {sys._getframe(0).f_code.co_name}-colors."
except:
return f"Error: Color {sys._getframe(0).f_code.co_name} attribute usage is incorrect. Documentation: Color().{sys._getframe(0).f_code.co_name}.__doc__"
def Pantone(self, colorInput=None):
"""NAN"""
if colorInput is None:
return f"Error: Example usage Color().{sys._getframe(0).f_code.co_name}()"
else:
try:
import json
JSONfile = "library/color/colorPantone.json"
with open(JSONfile, 'r') as file:
pantone_dict = json.load(file)
checkExist = pantone_dict.get(str(colorInput))
if checkExist is not None:
PantoneHex = pantone_dict[str(colorInput)]['hex']
return Color().Hex(PantoneHex)
else:
return f"Invalid {sys._getframe(0).f_code.co_name}-color, check '{JSONfile}' for available {sys._getframe(0).f_code.co_name}-colors."
except:
return f"Error: Color {sys._getframe(0).f_code.co_name} attribute usage is incorrect. Documentation: Color().{sys._getframe(0).f_code.co_name}.__doc__"
def LRV(self, colorInput=None):
"""NAN"""
if colorInput is None:
return f"Error: Example usage Color().{sys._getframe(0).f_code.co_name}()"
else:
try:
b = (colorInput - 0.2126 * 255 - 0.7152 * 255) / 0.0722
b = int(max(0, min(255, b)))
return [255, 255, b]
except:
return f"Error: Color {sys._getframe(0).f_code.co_name} attribute usage is incorrect. Documentation: Color().{sys._getframe(0).f_code.co_name}.__doc__"
def __str__(self, colorInput=None):
colorattributes = ["Components", "Hex", "rgba_to_hex", "hex_to_rgba", "CMYK",
"Alpha", "Brightness", "RGB", "HSV", "HSL", "RAL", "Pantone", "LRV"]
if colorInput is None:
header = "Available attributes: \n"
footer = "\nColor().red | Color().green | Color().blue"
return header + '\n'.join([f"Color().{func}()" for func in colorattributes]) + footer
return f"Color().{colorInput}"
def Info(self, colorInput=None):
pass
Color.red = Color(255, 0, 0)
Color.green = Color(0, 255, 0)
Color.blue = Color(0, 0, 255)
class ID(Serializable):
def __init__(self) -> None:
self.id = None
self.object = None
self.name = None
self.generateID()
def generateID(self) -> None:
id = ""
lengthID = 12
random_source = string.ascii_uppercase + string.digits
for x in range(lengthID):
id += random.choice(random_source)
id_list = list(id)
self.id = f"#"+"".join(id_list)
return f"test {self.__class__.__name__}"
def str(self) -> str:
return f"{self.id}"
def generateID() -> ID:
return ID()
def find_in_list_of_list(mylist, char):
for sub_list in mylist:
if char in sub_list:
return (mylist.index(sub_list))
raise ValueError("'{char}' is not in list".format(char=char))
def findjson(id, json_string):
#faster way to search in json
results = []
def _decode_dict(a_dict):
try:
results.append(a_dict[id])
except KeyError:
pass
return a_dict
json.loads(json_string, object_hook=_decode_dict) # Return value ignored.
return results
def list_transpose(lst):
#list of lists, transpose columns/rows
newlist = list(map(list, zip(*lst)))
return newlist
def is_null(lst):
return all(el is None for el in lst)
def clean_list(input_list, preserve_indices=True):
if not input_list:
return input_list
culled_list = []
if preserve_indices:
if is_null(input_list):
return None
j = len(input_list) - 1
while j >= 0 and input_list[j] is None:
j -= 1
for i in range(j + 1):
sublist = input_list[i]
if isinstance(sublist, list):
val = clean_list(sublist, preserve_indices)
culled_list.append(val)
else:
culled_list.append(input_list[i])
else:
if is_null(input_list):
return []
for el in input_list:
if isinstance(el, list):
if not is_null(el):
val = clean_list(el, preserve_indices=False)
if val:
culled_list.append(val)
elif el is not None:
culled_list.append(el)
return culled_list
def flatten(list:list[list]):
"""convert 2d list to 1d list
Args:
list (list[list]): a list of lists
Returns:
a list containing all elements: _description_
"""
return [elem for sublist in list for elem in sublist]
#if type(lst) != list:
# lst = [lst]
#flat_list = []
#for sublist in lst: