-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathetabs_obj.py
1469 lines (1386 loc) · 60.3 KB
/
etabs_obj.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
import comtypes.client
comtypes.client.gen_dir = None
from pathlib import Path
from typing import Tuple, Union
import shutil
import math
import sys
import json
from load_patterns import LoadPatterns
from load_cases import LoadCases
from load_combinations import LoadCombination
from story import Story
from frame_obj import FrameObj
from analyze import Analyze
from view import View
from database import DatabaseTables
# from sections.sections import Sections
from results import Results
from points import Points
from group import Group
from select_obj import SelectObj
from material import Material
from area import Area
from design import Design
from prop_frame import PropFrame
from diaphragm import Diaphragm
from func import Func
__all__ = ['EtabsModel']
class EtabsModel:
force_units = dict(Ib=1, kip=2, N=3, kN=4, KN=4, kgf=5, Kgf=5, tonf=6, Tonf=6)
length_units = dict(inch=1, ft=2, micron=3, mm=4, cm=5, m=6)
length_units['in'] = 1
enum_units = {
'ib_inch': 1,
'ib_ft': 2,
'kip_inch': 3,
'kip_ft': 4,
'kn_mm' : 5,
'kn_m' : 6,
'kgf_mm' : 7,
'kgf_m' : 8,
'n_mm' : 9,
'n_m' : 10,
'tonf_mm' : 11,
'tonf_m' : 12,
'kn_cm' : 13,
'kgf_cm' : 14,
'n_cm' : 15,
'tonf_cm' : 16,
}
def __init__(
self,
attach_to_instance: bool = True,
backup : bool = True,
software : str = 'ETABS', # 'SAFE', 'SAP2000'
model_path: Union[str, Path] = '',
software_exe_path: str = '',
):
self.software = software
self.etabs = None
self.success = False
helper = comtypes.client.CreateObject(f'{software}v1.Helper')
exec(f"helper = helper.QueryInterface(comtypes.gen.{software}v1.cHelper)")
if attach_to_instance:
try:
if software in ("ETABS", "SAFE"):
self.etabs = helper.GetObject(f"CSI.{software}.API.ETABSObject")
elif software == "SAP2000":
self.etabs = helper.GetObject(f"CSI.{software}.API.SapObject")
self.success = True
except (OSError, comtypes.COMError):
print("No running instance of the program found or failed to attach.")
self.success = False
finally:
if not self.success and hasattr(helper, 'GetObjectProcess'):
try:
import psutil
except ImportError:
import subprocess
package = 'psutil'
subprocess.check_call(['python', "-m", "pip", "install", package])
import psutil
pid = None
for proc in psutil.process_iter():
if software.lower() in proc.name().lower():
pid = proc.pid
break
if pid is not None:
if software in ("ETABS", "SAFE"):
self.etabs = helper.GetObjectProcess(f"CSI.{software}.API.ETABSObject", pid)
elif software == 'SAP2000':
self.etabs = helper.GetObjectProcess(f"CSI.{software}.API.SapObject", pid)
self.success = True
# sys.exit(-1)
else:
# sys.exit(-1)
helper = comtypes.client.CreateObject('ETABSv1.Helper')
helper = helper.QueryInterface(comtypes.gen.ETABSv1.cHelper)
if software_exe_path:
try:
self.etabs = helper.CreateObject(software_exe_path)
except (OSError, comtypes.COMError):
print(f"Cannot start a new instance of the program from {software_exe_path}")
sys.exit(-1)
else:
try:
self.etabs = helper.CreateObjectProgID("CSI.ETABS.API.ETABSObject")
except (OSError, comtypes.COMError):
print("Cannot start a new instance of the program.")
sys.exit(-1)
self.success = True
self.etabs.ApplicationStart()
if model_path:
self.etabs.SapModel.File.OpenFile(str(model_path))
if self.success:
self.SapModel = self.etabs.SapModel
if backup:
self.backup_model()
# solver_options = self.SapModel.Analyze.GetSolverOption_2()
# solver_options[1] = 1
# self.SapModel.Analyze.SetSolverOption_2(*solver_options[:-1])
# self.SapModel.File.Save()
self.load_patterns = LoadPatterns(None, self)
self.load_cases = LoadCases(self)
self.load_combinations = LoadCombination(self)
self.story = Story(None, self)
self.frame_obj = FrameObj(self)
self.analyze = Analyze(self.SapModel, None)
self.view = View(self.SapModel, None)
self.database = DatabaseTables(None, self)
# self.sections = Sections(self.SapModel, None)
self.results = Results(None, self)
self.points = Points(None, self)
self.group = Group(self)
self.select_obj = SelectObj(self)
self.material = Material(self)
self.area = Area(self)
self.design = Design(self)
self.prop_frame = PropFrame(self)
self.diaphragm = Diaphragm(self)
self.func = Func(self)
self.etabs_main_version = self.get_etabs_main_version()
if self.etabs_main_version < 20:
self.seismic_drift_text = 'Seismic (Drift)'
self.seismic_drift_load_type = 37
self.ecc_overwrite_story = 'Ecc Overwrite Story'
self.auto_seismic_user_coefficient_columns_part1 = [
'Name',
'Is Auto Load',
'X Dir?',
'X Dir Plus Ecc?',
'X Dir Minus Ecc?',
'Y Dir?',
'Y Dir Plus Ecc?',
'Y Dir Minus Ecc?',
'Ecc Ratio',
'Top Story',
'Bottom Story',
]
self.auto_seismic_user_coefficient_columns_part2 = [
self.ecc_overwrite_story,
'Ecc Overwrite Diaphragm',
'Ecc Overwrite Length',
]
self.auto_notional_loads_columns = ['Load Pattern', 'Base Load Pattern', 'Load Ratio', 'Load Direction']
else:
self.seismic_drift_text = 'QuakeDrift'
self.seismic_drift_load_type = 61
self.ecc_overwrite_story = 'OverStory'
self.auto_seismic_user_coefficient_columns_part1 = [
'Name',
'IsAuto',
'XDir',
'XDirPlusE',
'XDirMinusE',
'YDir',
'YDirPlusE',
'YDirMinusE',
'EccRatio',
'TopStory',
'BotStory',
]
self.auto_seismic_user_coefficient_columns_part2 = [
self.ecc_overwrite_story,
'OverDiaph',
'OverEcc',
]
self.auto_notional_loads_columns = ['LoadPattern', 'BasePattern', 'LoadRatio', 'LoadDir']
def get_etabs_main_version(self):
ver = self.SapModel.GetVersion()
return int(ver[0].split('.')[0])
def close_etabs(self):
self.SapModel.SetModelIsLocked(False)
self.etabs.ApplicationExit(False)
self.SapModel = None
self.etabs = None
def backup_model(self, name=None):
max_num = 0
backup_path=None
asli_file_path = self.get_filename()
suffix = asli_file_path.suffix
if name is None:
filename = self.get_file_name_without_suffix()
file_path = self.get_filepath()
backup_path = file_path / 'backups'
if not backup_path.exists():
import os
os.mkdir(str(backup_path))
for edb in backup_path.glob(f'BACKUP_{filename}*{suffix}'):
num = edb.name.rstrip(suffix)[len('BACKUP_') + len(filename) + 1:]
try:
num = int(num)
max_num = max(max_num, num)
except ValueError:
continue
name = f'BACKUP_{filename}_{max_num + 1}{suffix}'
if not name.lower().endswith(suffix.lower()):
name += suffix
asli_file_path = asli_file_path.with_suffix(suffix)
if backup_path is None:
new_file_path = asli_file_path.parent / name
else:
new_file_path = backup_path / name
shutil.copy(asli_file_path, new_file_path)
return new_file_path
def remove_backups(self):
file_path = self.get_filepath() / 'backups'
asli_file_path = self.get_filename()
suffix = asli_file_path.suffix
for edb in file_path.glob(f'BACKUP_*{suffix}'):
edb.unlink()
return None
def restore_backup(self, filepath):
current_file_path = self.get_filename()
self.SapModel.File.OpenFile(str(filepath))
self.SapModel.File.Save(str(current_file_path))
def lock_model(self):
self.SapModel.SetModelIsLocked(True)
def unlock_model(self):
self.SapModel.SetModelIsLocked(False)
def lock_and_unlock_model(self):
self.SapModel.SetModelIsLocked(True)
self.SapModel.SetModelIsLocked(False)
def run_analysis(self, open_lock=False):
if self.SapModel.GetModelIsLocked():
if open_lock:
self.SapModel.SetModelIsLocked(False)
print('Run Analysis ...')
self.SapModel.analyze.RunAnalysis()
else:
print('Run Analysis ...')
self.SapModel.analyze.RunAnalysis()
def start_design(self,
type_: str = 'Concrete', # Steel
check_designed: bool=True,
):
if check_designed and self.design.model_designed(type_=type_):
return
print(f"Starting Design {type_}")
exec(f"self.SapModel.Design{type_}.StartDesign()")
def start_slab_design(self):
if self.etabs_main_version < 20:
raise NotImplementedError
self.run_analysis()
print("Starting Design Slabs")
self.SapModel.DesignConcreteSlab.StartSlabDesign()
def set_current_unit(self, force, length):
# force_enum = EtabsModel.force_units[force]
# len_enum = EtabsModel.length_units[length]
number = self.enum_units.get(f"{force}_{length}".lower(), None)
if number is None:
raise KeyError
self.SapModel.SetPresentUnits(number)
def get_current_unit(self):
unit_num = self.SapModel.GetPresentUnits()
for unit_str, n in self.enum_units.items():
if n == unit_num:
force, length = unit_str.split("_")[0:2]
# for key, value in EtabsModel.force_units.items():
# if force_enum == value:
# force = key
# break
# for key, value in EtabsModel.length_units.items():
# if len_enum == value:
# length = key
# break
return force, length
def get_file_name_without_suffix(self):
f = Path(self.SapModel.GetModelFilename())
name = f.name.replace(f.suffix, '')
return name
def get_filename_with_suffix(self,
suffix: str= '.EDB',
):
f = Path(self.SapModel.GetModelFilename())
f = f.with_suffix(suffix)
return f.name
def get_filename_path_with_suffix(self,
suffix: str= '.EDB',
):
file_path = Path(self.etabs.SapModel.GetModelFilename())
return file_path.with_suffix(suffix)
def add_prefix_suffix_name(self,
prefix : str = '',
suffix : str = '',
open : bool = False,
) -> Path:
'''
adding prefix and suffix string to the current filename
'''
name = self.get_file_name_without_suffix()
new_name = f'{prefix}{name}{suffix}.EDB'
new_path = self.get_filepath() / new_name
if open:
self.SapModel.File.Save(str(new_path))
return new_path
def get_filename(self) -> Union[Path, None]:
'''
return: WindowsPath('H:/1402/montazer/rashidzadeh/etabs/test.EDB')
'''
filename = self.SapModel.GetModelFilename()
if filename is None:
return None
return Path(filename)
def get_filepath(self) -> Path:
return Path(self.SapModel.GetModelFilename()).parent
def save(self):
self.SapModel.File.Save()
def save_as(self, name):
if not name.lower().endswith('.edb'):
name += '.EDB'
asli_file_path = Path(self.SapModel.GetModelFilename())
asli_file_path = asli_file_path.with_suffix('.EDB')
new_file_path = asli_file_path.with_name(name)
self.SapModel.File.Save(str(new_file_path))
return asli_file_path, new_file_path
def get_new_filename_in_folder_and_add_name(self,
folder_name: str,
name: str,
):
'''
Get the current file with FILENAME_name in folder_name
forlder of etabs file
'''
asli_file_path = Path(self.SapModel.GetModelFilename())
if asli_file_path.suffix.lower() != '.edb':
asli_file_path = asli_file_path.with_suffix(".EDB")
# Create folder if not exists
file_path = self.get_filepath()
folder_path = file_path / folder_name
if not folder_path.exists():
import os
os.mkdir(str(folder_path))
filename_without_suffix = self.get_file_name_without_suffix()
filename = filename_without_suffix + f"_{name}.EDB"
filename = folder_path / filename
return asli_file_path, filename
def save_in_folder_and_add_name(self,
folder_name: str,
name: str,
):
'''
Save the current file with FILENAME_name in folder_name
folder of etabs file
'''
asli_file_path, new_filename = self.get_new_filename_in_folder_and_add_name(
folder_name=folder_name,
name=name,
)
self.SapModel.File.Save(str(new_filename))
return asli_file_path, new_filename
def export(self, suffix='.e2k') -> Tuple[Path, Path]:
asli_file_path = Path(self.SapModel.GetModelFilename())
asli_file_path = asli_file_path.with_suffix('.EDB')
new_file_path = asli_file_path.with_suffix(suffix)
self.SapModel.File.Save(str(new_file_path))
return asli_file_path, new_file_path
@staticmethod
def get_from_list_table(
list_table: list,
columns: list,
values: list,
) -> filter:
from operator import itemgetter
itemget = itemgetter(*columns)
assert len(columns) == len(values)
if len(columns) == 1:
result = filter(lambda x: itemget(x) == values[0], list_table)
else:
result = filter(lambda x: itemget(x) == values, list_table)
return result
@staticmethod
def save_to_json(json_file, data):
import json
with open(json_file, 'w') as f:
json.dump(data, f)
@staticmethod
def load_from_json(json_file):
import json
with open(json_file, 'r') as f:
data = json.load(f)
return data
def save_to_json_in_edb_folder(self, json_name, data):
json_file = Path(self.SapModel.GetModelFilepath()) / json_name
self.save_to_json(json_file, data)
def get_main_periods(self,
modal_case: str='',
):
print("start running T file analysis")
if not modal_case:
modal_case = self.load_cases.get_modal_loadcase_name()
self.analyze.set_load_cases_to_analyze([modal_case])
self.SapModel.Analyze.RunAnalysis()
table_key = "Modal Participating Mass Ratios"
df = self.database.read(table_key=table_key, to_dataframe=True)
df = df.astype({'UX': float, 'UY': float})
self.SapModel.SetModelIsLocked(False)
max_value_index = df['UX'].idxmax()
tx_drift = df.loc[max_value_index, 'Period']
max_value_index = df['UY'].idxmax()
ty_drift = df.loc[max_value_index, 'Period']
print(f"Tx_drift = {tx_drift}, Ty_drift = {ty_drift}\n")
return float(tx_drift), float(ty_drift)
def get_drift_periods(
self,
t_filename: str="",
structure_type: str='concrete',
):
'''
This function creates an Etabs file called T.EDB from current open Etabs file,
then in T.EDB file change the stiffness properties of frame elements according
to ACI 318 to get periods of structure, for this it set M22 and M33 stiffness of
beams to 0.5 and column and wall to 1.0. Then it runs the analysis and get the x
and y period of structure.
'''
print(10 * '-' + "Get drift periods" + 10 * '-' + '\n')
self.SapModel.File.Save()
asli_file_path = Path(self.SapModel.GetModelFilename())
if asli_file_path.suffix.lower() != '.edb':
asli_file_path = asli_file_path.with_suffix(".EDB")
# Create periods folder if not exists
file_path = self.get_filepath()
period_path = file_path / 'periods'
if not period_path.exists():
import os
os.mkdir(str(period_path))
filename_without_suffix = self.get_file_name_without_suffix()
if not t_filename:
t_filename = filename_without_suffix + "_T.EDB"
t_file_path = period_path / t_filename
print(f"Saving file as {t_file_path}\n")
self.SapModel.File.Save(str(t_file_path))
# for steel structure
self.SapModel.DesignSteel.SetCode('AISC ASD 89')
# for steel structures create a copy of main file
if structure_type == 'steel':
t_steel_filename = filename_without_suffix + "_drift.EDB"
drift_file_path = period_path / t_steel_filename
shutil.copy(t_file_path, drift_file_path)
print("get frame property modifiers and change I values\n")
IMod_beam = 0.5
IMod_col_wall = 1
IMod_Floors = 0.25 * 1.5
for label in self.SapModel.FrameObj.GetLabelNameList()[1]:
if self.SapModel.FrameObj.GetDesignProcedure(label)[0] == 2: # concrete
modifiers = list(self.SapModel.FrameObj.GetModifiers(label)[0])
if self.SapModel.FrameObj.GetDesignOrientation(label)[0] == 1: # Column
modifiers[:6] = 6 * [IMod_col_wall]
elif self.SapModel.FrameObj.GetDesignOrientation(label)[0] == 2: # Beam
modifiers[4:6] = [IMod_beam, IMod_beam]
self.SapModel.FrameObj.SetModifiers(label, modifiers)
# Area Objects
self.area.reset_slab_sections_modifiers()
for label in self.SapModel.AreaObj.GetLabelNameList()[1]:
modifiers = list(self.SapModel.AreaObj.GetModifiers(label)[0])
if self.SapModel.AreaObj.GetDesignOrientation(label)[0] == 1: # Wall
modifiers[:6] = 6 * [IMod_col_wall]
elif self.SapModel.AreaObj.GetDesignOrientation(label)[0] == 2: # Floor
weight_factor = modifiers[-1]
for i in range(3, 6):
modifiers[i] = IMod_Floors * weight_factor
self.SapModel.AreaObj.SetModifiers(label, modifiers)
# run model (this will create the analysis model)
tx_drift, ty_drift = self.get_main_periods()
if structure_type == 'concrete':
print("opening the main file\n")
self.SapModel.File.OpenFile(str(asli_file_path))
else:
# for steel structure
print("opening the Drift file\n")
self.SapModel.File.OpenFile(str(drift_file_path))
return tx_drift, ty_drift, asli_file_path
def get_diaphragm_max_over_avg_drifts(
self,
loadcases=[],
only_ecc=True,
cols=None,
):
self.run_analysis()
if not loadcases:
xy_names = self.load_patterns.get_xy_seismic_load_patterns(only_ecc)
all_load_case_names = self.load_cases.get_load_cases()
loadcases = set(xy_names).intersection(all_load_case_names)
x_names, y_names = self.load_patterns.get_load_patterns_in_XYdirection()
self.load_cases.select_load_cases(loadcases)
table_key = 'Diaphragm Max Over Avg Drifts'
if cols is None:
cols = ['Story', 'OutputCase', 'Max Drift', 'Avg Drift', 'Label', 'Ratio', 'Item']
df = self.database.read(table_key, to_dataframe=True, cols=cols)
if len(df) == 0:
return
df['Dir'] = df['Item'].str[-1]
df.drop(columns=['Item'], inplace=True)
mask = (
(df['Dir'] == 'X') & (df['OutputCase'].isin(x_names))) ^ (
(df['Dir'] == 'Y') & (df['OutputCase'].isin(y_names)))
df = df.loc[mask]
df = df.astype({'Max Drift': float, 'Avg Drift': float, 'Ratio': float})
return df
def get_drifts(self,
no_story,
cdx,
cdy,
loadcases=None,
x_loadcases=None,
y_loadcases=None,
):
if loadcases is None:
loadcases = self.load_cases.get_seismic_drift_load_cases()
print(loadcases)
x_cases, y_cases = self.load_cases.get_xy_seismic_load_cases()
if x_loadcases is None:
x_loadcases = x_cases
if y_loadcases is None:
y_loadcases = y_cases
self.analyze.change_run_status_of_load_cases(
loadcases + x_loadcases + y_loadcases,
True,
)
self.run_analysis()
self.load_cases.select_load_cases(loadcases)
TableKey = 'Diaphragm Max Over Avg Drifts'
ret = self.database.read_table(TableKey)
if ret is None:
return None
_, _, FieldsKeysIncluded, _, TableData, _ = ret
data = self.database.reshape_data(FieldsKeysIncluded, TableData)
try:
item_index = FieldsKeysIncluded.index("Item")
case_name_index = FieldsKeysIncluded.index("OutputCase")
except ValueError:
return None, None
# average_drift_index = FieldsKeysIncluded.index("Avg Drift")
if no_story <= 5:
limit = .025
else:
limit = .02
new_data = []
for row in data:
name = row[case_name_index]
if row[item_index].endswith("X"):
if not name in x_loadcases:
continue
cd = cdx
elif row[item_index].endswith("Y"):
if not name in y_loadcases:
continue
cd = cdy
allowable_drift = limit / cd
row.append(f'{allowable_drift:.4f}')
new_data.append(row)
fields = list(FieldsKeysIncluded)
fields.append('Allowable Drift')
return new_data, fields
def apply_cfactor_to_tabledata(self, TableData, FieldsKeysIncluded, building,
bot_story : str = '',
top_story : str = '',
):
data = self.database.reshape_data(FieldsKeysIncluded, TableData)
names_x, names_y = self.load_patterns.get_load_patterns_in_XYdirection()
i_c = FieldsKeysIncluded.index('C')
i_k = FieldsKeysIncluded.index('K')
i_top_story = FieldsKeysIncluded.index('TopStory')
i_bot_story = FieldsKeysIncluded.index('BotStory')
cx, cy = str(building.results[1]), str(building.results[2])
kx, ky = str(building.kx), str(building.ky)
cx_drift, cy_drift = str(building.results_drift[1]), str(building.results_drift[2])
kx_drift, ky_drift = str(building.kx_drift), str(building.ky_drift)
drift_load_pattern_names = self.load_patterns.get_drift_load_pattern_names()
i_name = FieldsKeysIncluded.index("Name")
for earthquake in data:
if bot_story:
earthquake[i_bot_story] = bot_story
if top_story:
earthquake[i_top_story] = top_story
if not earthquake[i_c]:
continue
name = earthquake[i_name]
if name in drift_load_pattern_names:
if name in names_x:
earthquake[i_c] = str(cx_drift)
earthquake[i_k] = str(kx_drift)
elif name in names_y:
earthquake[i_c] = str(cy_drift)
earthquake[i_k] = str(ky_drift)
elif name in names_x:
earthquake[i_c] = str(cx)
earthquake[i_k] = str(kx)
elif name in names_y:
earthquake[i_c] = str(cy)
earthquake[i_k] = str(ky)
table_data = self.database.unique_data(data)
return table_data
def apply_cfactor_to_edb(
self,
building,
bot_story : str = '',
top_story : str = '',
):
print("Applying cfactor to edb\n")
self.SapModel.SetModelIsLocked(False)
self.load_patterns.select_all_load_patterns()
table_key = 'Load Pattern Definitions - Auto Seismic - User Coefficient'
[_, _, fields_keys_included, _, table_data, _] = self.database.read_table(table_key)
table_data = self.apply_cfactor_to_tabledata(table_data, fields_keys_included, building, bot_story, top_story)
num_fatal_errors, ret = self.database.write_seismic_user_coefficient(table_key, fields_keys_included, table_data)
print(f"num_fatal_errors, ret = {num_fatal_errors}, {ret}")
return num_fatal_errors
def apply_cfactors_to_edb(
self,
data: list,
d: dict={},
):
'''
data is a list contain lists, each list contain two list, first
list is list of earthquakes names and second list is in format
['TopStory', 'BotStory', 'C', 'K']
example:
data = [
(['QX', 'QXN'], ["STORY5", "STORY1", '0.128', '1.37']),
(['QY', 'QYN'], ["STORY4", "STORY2", '0.228', '1.39']),
]
d: dictionary of etabs config file
'''
df = self.check_seismic_names(d=d)
print("Applying cfactor to edb\n")
for earthquakes, new_factors in data:
df.loc[df.Name.isin(earthquakes), ['TopStory', 'BotStory', 'C', 'K']] = new_factors
num_fatal_errors, ret = self.database.write_seismic_user_coefficient_df(df)
print(f"num_fatal_errors, ret = {num_fatal_errors}, {ret}")
return num_fatal_errors
def is_etabs_running(self):
try:
comtypes.client.GetActiveObject("CSI.ETABS.API.ETABSObject")
return True
except OSError:
return False
def get_magnification_coeff_aj(self):
story_length = self.story.get_stories_length()
cols = ['Story', 'OutputCase', 'Max Drift', 'Avg Drift', 'Ratio', 'Item']
df = self.get_diaphragm_max_over_avg_drifts(cols=cols)
df['aj'] = (df['Ratio'] / 1.2) ** 2
df['aj'].clip(1,3, inplace=True)
filt = df['aj'] > 1
df = df.loc[filt]
df['Ecc. Ratio'] = df['aj'] * .05
conditions =[]
choices = []
for story, xy_lenght in story_length.items():
conditions.append(df['Dir'].eq('Y') & df['Story'].eq(story))
conditions.append(df['Dir'].eq('X') & df['Story'].eq(story))
choices.extend(xy_lenght)
import numpy as np
df['Length (Cm)'] = np.select(conditions, choices)
df['Ecc. Length (Cm)'] = df['Ecc. Ratio'] * df['Length (Cm)']
story_names = df['Story'].unique()
story_diaphs = self.story.get_stories_diaphragms(story_names)
df['Diaph'] = df['Story'].map(story_diaphs)
if not df.empty:
df['Diaph'] = df['Diaph'].str.join(',')
return df
def get_static_magnification_coeff_aj(self,
df : Union['pandas.DataFrame', bool] = None,
):
if df is None:
df = self.get_magnification_coeff_aj()
df = df.groupby(['OutputCase', 'Story', 'Diaph'], as_index=False)['Ecc. Length (Cm)'].max()
df = df.astype({'Ecc. Length (Cm)': int})
return df
def get_dynamic_magnification_coeff_aj(self,
df : Union['pandas.DataFrame', bool] = None,
):
if df is None:
df = self.get_magnification_coeff_aj()
df = df.groupby(['OutputCase', 'Story', 'Diaph', 'Dir'], as_index=False)['Ecc. Length (Cm)'].max()
df = df.astype({'Ecc. Length (Cm)': int})
import pandas as pd
ret_df = pd.DataFrame(columns=['OutputCase', 'Story', 'Diaph', 'Ecc. Length (Cm)'])
x_names, y_names = self.load_cases.get_response_spectrum_xy_loadcases_names()
all_specs = self.load_cases.get_response_spectrum_loadcase_name()
angular_names = set(all_specs).difference(x_names + y_names)
if x_names:
new_df = df[df['Dir'] == 'X'].groupby(['Story', 'Diaph'], as_index=False)['Ecc. Length (Cm)'].max()
for name in x_names:
new_df['OutputCase'] = name
ret_df = ret_df.append(new_df)
if y_names:
new_df = df[df['Dir'] == 'Y'].groupby(['Story', 'Diaph'], as_index=False)['Ecc. Length (Cm)'].max()
for name in y_names:
new_df['OutputCase'] = name
ret_df = ret_df.append(new_df)
if angular_names:
new_df = df.groupby(['Story', 'Diaph'], as_index=False)['Ecc. Length (Cm)'].max()
for name in angular_names:
new_df['OutputCase'] = name
ret_df = ret_df.append(new_df)
return ret_df
def apply_aj_df(self, df):
print("Applying cfactor to edb\n")
self.SapModel.SetModelIsLocked(False)
self.load_patterns.select_all_load_patterns()
table_key = 'Load Pattern Definitions - Auto Seismic - User Coefficient'
input_df = self.database.read(table_key, to_dataframe=True)
self.database.write_aj_user_coefficient(table_key, input_df, df)
def get_irregularity_of_mass(self, story_mass=None):
if not story_mass:
story_mass = self.database.get_story_mass()
for i, sm in enumerate(story_mass):
m_neg1 = float(story_mass[i - 1][1]) * 1.5
m = float(sm[1])
if i != len(story_mass) - 1:
m_plus1 = float(story_mass[i + 1][1]) * 1.5
else:
m_plus1 = m
if i == 0:
m_neg1 = m
sm.extend([m_neg1, m_plus1])
fields = ('Story', 'Mass X', '1.5 * Below', '1.5 * Above')
return story_mass, fields
def add_load_case_in_center_of_rigidity(self, story_name, x, y):
self.set_current_unit('kgf', 'm')
z = self.SapModel.story.GetElevation(story_name)[0]
point_name = self.SapModel.PointObj.AddCartesian(float(x),float(y) , z)[0]
diaph = self.story.get_story_diaphragms(story_name).pop()
self.SapModel.PointObj.SetDiaphragm(point_name, 3, diaph)
LTYPE_OTHER = 8
lp_name_x = f'X_STIFFNESS_{story_name}'
lp_name_y = f'Y_STIFFNESS_{story_name}'
for lp_name in (lp_name_x, lp_name_y):
self.SapModel.LoadPatterns.Add(lp_name, LTYPE_OTHER, 0, True)
load = 100000
point_load_value_x = [load, 0, 0, 0, 0, 0]
point_load_value_y = [0, load, 0, 0, 0, 0]
self.SapModel.PointObj.SetLoadForce(point_name, lp_name_x, point_load_value_x)
self.SapModel.PointObj.SetLoadForce(point_name, lp_name_y, point_load_value_y)
self.analyze.set_load_cases_to_analyze([lp_name_x, lp_name_y])
return point_name, lp_name_x, lp_name_y
def get_story_stiffness_modal_way(self):
story_mass = self.database.get_story_mass()[::-1]
story_mass = {key: value for key, value in story_mass}
stories = list(story_mass.keys())
dx, dy, wx, wy = self.database.get_stories_displacement_in_xy_modes()
story_stiffness = {}
n = len(story_mass)
for i, (phi_x, phi_y) in enumerate(zip(dx.values(), dy.values())):
if i == n - 1:
phi_neg_x = 0
phi_neg_y = 0
else:
story_neg = stories[i + 1]
phi_neg_x = dx[story_neg]
phi_neg_y = dy[story_neg]
d_phi_x = phi_x - phi_neg_x
d_phi_y = phi_y - phi_neg_y
sigma_x = 0
sigma_y = 0
for j in range(0, i + 1):
story_j = stories[j]
m_j = float(story_mass[story_j])
phi_j_x = dx[story_j]
phi_j_y = dy[story_j]
sigma_x += m_j * phi_j_x
sigma_y += m_j * phi_j_y
kx = wx ** 2 * sigma_x / d_phi_x
ky = wy ** 2 * sigma_y / d_phi_y
story_stiffness[stories[i]] = [kx, ky]
return story_stiffness
def get_story_stiffness_2800_way(self):
asli_file_path = Path(self.SapModel.GetModelFilename())
if asli_file_path.suffix.lower() != '.edb':
asli_file_path = asli_file_path.with_suffix(".EDB")
dir_path = asli_file_path.parent.absolute()
center_of_rigidity = self.database.get_center_of_rigidity()
story_names = center_of_rigidity.keys()
story_stiffness = {}
name = self.get_file_name_without_suffix()
folder_name = "story_stiffness"
folder_path = dir_path / folder_name
if not folder_path.exists():
import os
os.mkdir(str(folder_path))
for story_name in story_names:
story_file_path = folder_path / f'{name}_STIFFNESS_{story_name}.EDB'
print(f"Saving file as {story_file_path}\n")
shutil.copy(asli_file_path, story_file_path)
print(f"Opening file {story_file_path}\n")
self.SapModel.File.OpenFile(str(story_file_path))
x, y = center_of_rigidity[story_name]
point_name, lp_name_x, lp_name_y = self.add_load_case_in_center_of_rigidity(
story_name, x, y)
self.story.fix_below_stories(story_name)
self.SapModel.View.RefreshView()
self.SapModel.Analyze.RunAnalysis()
disp_x = self.results.get_point_xy_displacement(point_name, lp_name_x)[0]
disp_y = self.results.get_point_xy_displacement(point_name, lp_name_y)[1]
kx, ky = 100000 / abs(disp_x), 100000 / abs(disp_y)
story_stiffness[story_name] = [kx, ky]
self.SapModel.File.OpenFile(str(asli_file_path))
return story_stiffness
def get_story_stiffness_earthquake_way(
self,
loadcases: list=None,
):
if loadcases is None:
loadcases = self.load_patterns.get_EX_EY_load_pattern()
assert len(loadcases) == 2
EX, EY = loadcases
self.run_analysis()
self.set_current_unit('kgf', 'm')
self.load_cases.select_load_cases(loadcases)
TableKey = 'Story Stiffness'
[_, _, FieldsKeysIncluded, _, TableData, _] = self.database.read_table(TableKey)
i_story = FieldsKeysIncluded.index('Story')
i_case = FieldsKeysIncluded.index('OutputCase')
i_stiff_x = FieldsKeysIncluded.index('StiffX')
i_stiff_y = FieldsKeysIncluded.index('StiffY')
data = self.database.reshape_data(FieldsKeysIncluded, TableData)
columns = (i_case,)
values_x = (EX,)
values_y = (EY,)
result_x = self.get_from_list_table(data, columns, values_x)
result_y = self.get_from_list_table(data, columns, values_y)
story_stiffness = {}
for x, y in zip(list(result_x), list(result_y)):
story = x[i_story]
stiff_x = float(x[i_stiff_x])
stiff_y = float(y[i_stiff_y])
story_stiffness[story] = [stiff_x, stiff_y]
return story_stiffness
def get_story_stiffness_table(self, way='2800', story_stiffness=None):
'''
way can be '2800', 'modal' , 'earthquake'
'''
name = self.get_file_name_without_suffix()
if not story_stiffness:
if way == '2800':
story_stiffness = self.get_story_stiffness_2800_way()
elif way == 'modal':
story_stiffness = self.get_story_stiffness_modal_way()
elif way == 'earthquake':
story_stiffness = self.get_story_stiffness_earthquake_way()
stories = list(story_stiffness.keys())
retval = []
for i, story in enumerate(stories):
stiffness = story_stiffness[story]
kx = stiffness[0]
ky = stiffness[1]
if i == 0:
stiffness.extend(['-', '-'])
else:
k1 = story_stiffness[stories[i - 1]]
stiffness.extend([
kx / k1[0] if k1[0] != 0 else '-',
ky / k1[1] if k1[1] != 0 else '-',
])
if len(stories[:i]) >= 3:
k2 = story_stiffness[stories[i - 2]]
k3 = story_stiffness[stories[i - 3]]
ave_kx = (k1[0] + k2[0] + k3[0]) / 3
ave_ky = (k1[1] + k2[1] + k3[1]) / 3
stiffness.extend([kx / ave_kx, ky / ave_ky])
else:
stiffness.extend(['-', '-'])
retval.append((story, *stiffness))
fields = ('Story', 'Kx', 'Ky', 'Kx / kx+1', 'Ky / ky+1', 'Kx / kx_3ave', 'Ky / ky_3ave')
json_file = f'{name}_story_stiffness_{way}_table.json'
self.save_to_json_in_edb_folder(json_file, (retval, fields))
return retval, fields
def get_story_forces_with_percentages(
self,
loadcases: list=None,
):
vx, vy = self.results.get_base_react()
story_forces, _ , fields = self.database.get_story_forces(loadcases)
new_data = []
i_vx = fields.index('VX')
i_vy = fields.index('VY')
for story_force in story_forces:
fx = float(story_force[i_vx])
fy = float(story_force[i_vy])
story_force.extend([f'{fx/vx:.3f}', f'{fy/vy:.3f}'])
new_data.append(story_force)
fields = list(fields)
fields.extend(['Vx %', 'Vy %'])
return new_data, fields
def scale_response_spectrums(self,
ex_name : Union[str, list],
ey_name : Union[str, list],
x_specs : list,
y_specs : list,
x_scale_factor : float = 0.9, # 0.85, 0.9, 1
y_scale_factor : float = 0.9, # 0.85, 0.9, 1
num_iteration : int = 3,
tolerance : float = .05,
reset_scale : bool = True,
analyze : bool = True,
consider_min_static_base_shear : bool = False,
d: Union[None, dict] = None,
):
assert x_scale_factor in (0.85, 0.9, 1)
assert y_scale_factor in (0.85, 0.9, 1)
if isinstance(ex_name, str):
ex_name = [ex_name]
if isinstance(ey_name, str):
ey_name = [ey_name]
ex_names = ex_name
ey_names = ey_name
print(f'{ex_names=}, {ey_names=}, {x_specs=}, {y_specs=}, {x_scale_factor=}, {y_scale_factor=}, {tolerance=}')
self.SapModel.File.Save()
if reset_scale:
self.load_cases.reset_scales_for_response_spectrums(loadcases=x_specs+y_specs)
self.set_current_unit('kgf', 'm')
self.analyze.set_load_cases_to_analyze(ex_names + ey_names + x_specs + y_specs)
V = self.results.get_base_react(
loadcases=ex_names + ey_names,
directions=len(ex_names) * ['x'] + len(ey_names) * ['y'],
absolute=True,
)
vexes = V[0:len(ex_names)]
veyes = V[len(ex_names):]
vex = sum(vexes)
vey = sum(veyes)