-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathWBInterface.py
2662 lines (2251 loc) · 109 KB
/
WBInterface.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 -*-
""" Script by Toybich Egor
Note: Workbench uses IronPython (Python 2.7)!
"""
#__________________________________________________________
from __future__ import print_function
import os
import shutil
from glob import glob
from functools import partial
from collections import defaultdict
from csv import reader as csvreader
from csv import writer as csvwriter
from csv import QUOTE_MINIMAL
from datetime import datetime
from datetime import timedelta
try:
from System.Threading import Thread, ThreadStart
import clr
clr.AddReference("System.Management")
from System.Management import ManagementObjectSearcher
except: pass
# Import global from main to access Workbench commands
import __main__ as workbench
# Import Logger module from working directory
def find_module(st_in):
res = []
stlist = st_in if isinstance(st_in, list) else [st_in]
for st in stlist:
try:
srch = [f for f in glob('{}*.py'.format(st))]
print('WBInterface| Found: {}'.format(srch))
srch = srch[0] if srch[0] == '{}.py'.format(st) else srch[-1]
srch = srch.replace('.py','')
except:
res.append(None)
else:
res.append(srch)
return tuple(res) if len(stlist) > 1 else res[0]
log_module = find_module('Logger')
print('WBInterface| Using: {}'.format(log_module))
if log_module: exec('from {} import Logger'.format(log_module))
__version__ = '3.1.6'
#__________________________________________________________
class WBInterface(object):
"""
A class to open Workbench project/archive, input/output parameters
and start calculations
Arg:
logger (object with logger.log(str) method): Used for creating log file. Autocreates one if not defined
out_file (str): Output file name; defaults to 'output.txt'
full_report_file (str): Workbench parametric report file; defaults to 'full_report.txt'
control_file_template (str): String template for search of control file; defaults to '*_control.csv'
input_file_template (str): String template for search of input file; defaults to '*_input.csv'
csv_delim (str): Delimiter used in csv file; defaults to ','
csv_skip (str): Read as 'no parameters' if found; defaults to 'no'
loginfo (str): Prefix for logger to use; defaults to WBInterface
wb_log: str; file for collecting solver logs, defaults to logger file
async_timer: float; how often to check for solver logs, default to 0.5 sec
Use method log() to write into a log file (see Logger class)
Use method blank() to write a blank line
"""
__version__ = '3.1.4'
_macro_def_dir = '_TempScript'
__macro_dir_path = ''
__macros_count = 0
# ---------------------------------------------------------------
# Public attributes
# ---------------------------------------------------------------
@property
def DPs(self):
"""Design Points list"""
return self.__DPs
@property
def DPs_count(self):
"""Design Points count (imported, present)"""
return (self.__DPs_imported, self.__DPs_present)
@property
def filename(self):
"""Opened project"""
return self.__workfile
@property
def out_file(self):
"""Output file for parameters"""
return self._out_file
@out_file.setter
def out_file(self, filename):
"""Supports manual change of output file"""
self._out_file = filename
@property
def full_file(self):
"""Workbench project summary file"""
return self._full_file
@full_file.setter
def full_file(self, filename):
"""Supports manual change of summary file"""
self._full_file = filename
@property
def logfile(self):
"""Log file of script execution"""
return self._logger.filename
@property
def active(self):
"""Returns if there is an opened Workbench project"""
return self.__active
@property
def parameters(self):
"""Returns IO parameters as dictionaries"""
return (self._param_in_value, self._param_out_value)
@property
def failed_to_update(self):
"""Returns if project failed to update as bool"""
return self.__failed_to_update
@property
def solved(self):
"""Returns if project is solved as bool"""
return self.__solved
@property
def failed_to_open(self):
"""Returns if project failed to open as bool"""
return self.__failed_to_open
@property
def not_up_to_date(self):
"""Returns if project is not up-to-date as bool"""
return self.__not_up_to_date
@property
def ansys_version(self):
"""Returns ANSYS version string"""
if 193 <= self.__ansys_version < 194:
return '2019R1'
elif 194 <= self.__ansys_version < 195:
return '2019R2'
elif 195 <= self.__ansys_version < 196:
return '2019R3'
elif 200 <= self.__ansys_version < 210:
return '2020R2'
else:
ver = str(self.__ansys_version).split('.')[0]
return ver[0:2] + '.' + ver[2:]
@property
def _ansys_version(self):
"""Returns ANSYS version float number """
return self.__ansys_version
# ---------------------------------------------------------------
# Magic methods
# ---------------------------------------------------------------
def __init__(self, logger = None, out_file='output.txt', full_report_file='full_report.txt',
control_file_template='*_control.csv', input_file_template='*_input.csv', csv_delim=',',
csv_skip='no', loginfo=None, wb_log='', async_timer=None):
"""
Constructor, duh. Check class docstr for info
"""
self._logger = logger if logger is not None else Logger('log.txt')
log_prefix = str(self.__class__.__name__) if loginfo is None else loginfo
# Partial logger method with prefix at the start of every line
try: self._log_ = partial(self._logger.log, info=log_prefix)
except: self._log_ = self._logger.log
self._log_('Class version: ' + self.__version__ )
self.log = self._logger.log #: original logger method
self._out_file = out_file #: file for outputting
self._full_file = full_report_file #: file for workbench parametric report
self._control_file = None #: csv file with io parameter list
self._input_file = None #: csv file with input parameters
self._control_srch = control_file_template #: key string to search for cotrol file
self._input_srch = input_file_template #: key string to search for input file
self._param_in = [] #: list of workbench input parameters
self._param_out = [] #: list of workbench output parameters
self._param_in_value = defaultdict(list) #: dictionary with input parameters (keys=self._param_in)
self._param_out_value = defaultdict(list) #: dictionary with output parameters (keys=self._param_out)
self._csv_delim = csv_delim #: csv file delimiter
self._csv_skip = csv_skip.lower() #: string placeholder if no parameter is specified in csv file
self.__workfile = None #: opened workbench project
self.__DPs_imported = 0 #: Design Points imported from input file
self.__DPs_present = 0 #: Design Points already present in project
self.__DPs = None
self.__active = False
self.__failed_to_update = False
self.__solved = False
self.__failed_to_open = False
self.__not_up_to_date = False
self.blank = self._logger.blank
self.runtime = self._logger.runtime
try: ver = workbench.GetFrameworkBuildVersion().split('.')
except: ver = '0'
self.__ansys_version = float(''.join(ver[0:2]) + '.' + ''.join(ver[2:]))
self._log_('ANSYS Workbench: %s' % self.ansys_version, 1)
self.__control_srch_default = '*.control' #: default key string to search for cotrol file
self.__input_srch_default = '*.input' #: default key string to search for input file
self.__workbench_log = wb_log if wb_log else self._logger.filename
try:
searcher = ManagementObjectSearcher("Select * from Win32_Processor").Get()
for i in searcher: self.__machine_core_count = int(i["NumberOfCores"])
except: self.__machine_core_count = 0
# Search for logs in this directories
dir = [
os.path.join(os.getcwd(),'_ProjectScratch')
]
# Search for this log files
logs = [
'solve.out'
]
if async_timer:
args = dict(outfile=wb_log, watch_dir=dir, watchfile=logs, timer=async_timer, logger=self._logger)
else:
args = dict(outfile=wb_log, watch_dir=dir, watchfile=logs, logger=self._logger)
self.__async_log = AsyncLogChecker(**args)
self.start_logwatch = self.__async_log.start
self.stop_logwatch = self.__async_log.stop
# --------------------------------------------------------------------
def __del__(self):
if self.__macro_dir_path and os.path.exists(__macro_dir_path):
shutil.rmtree(self.__macro_dir_path, ignore_errors=True)
def __bool__(self):
return self.__active
def __str__(self):
return self.__workfile
# ---------------------------------------------------------------
# Public methods
# ---------------------------------------------------------------
def read_control(self, control_file_template=None, csv_delim=None, csv_skip=None):
"""
Read csv file with IO parameter list
Example of control file format with 2 inputs and 3 outputs:
#type 'no' to skip inputs
p3,p2
#type 'no' to skip outputs
p1,p4,p5
Note that lines with '#' will be skipped.
Arg:
control_file_template: str; search file wioth this pattern, defaults to an init value
csv_delim: str; csv delimiterl, defaults to an init value
csv_skip: str; tells if no parameters a defined, defaults to an init value
"""
if control_file_template is None: control_file_template=self._control_srch
if csv_delim is None: csv_delim=self._csv_delim
if csv_skip is None: csv_skip=self._csv_skip
if csv_delim is None or csv_skip is None:
self._log_('Missing csv delimiter or skipper!', 1)
raise MissingCSVParameter
for defiter in range(2):
control_used = control_file_template if not defiter else self.__control_srch_default
msg_mod = '' if not defiter else ' default'
if control_used:
self._log_('Searching for{} control file...'.format(msg_mod))
try:
file_list = [f for f in glob(control_used)]
self._control_file = file_list[0]
except:
self._log_('Control file not found! No parameters will be used', 1)
else:
self._log_('Control file found: ' + self._control_file)
self._log_('Reading parameter list...')
try:
with open(self._control_file, 'r') as csvfile:
spamreader = csvreader(self.decomment(csvfile), delimiter=csv_delim)
for i, row in enumerate(spamreader):
for rlin in row:
skip = rlin.lower().find(csv_skip)
if i == 0 and skip == -1:
self._param_in.append(self._safeguard(rlin))
elif i == 1 and skip == -1:
self._param_out.append(self._safeguard(rlin))
except Exception as err_msg:
self._log_('An error occured wile reading control file!')
self._log_(err_msg, 1)
raise
self._log_('Reading successful: ' + str(len(self._param_in)) + ' input(s), '
+ str(len(self._param_out)) + ' output(s)', 1)
break
# --------------------------------------------------------------------
def read_input(self, input_file_template=None, csv_delim=None):
"""
Read csv file with input parameters
Example of format for 2 parameters and 3 Design Points:
#p3,p2
10,200
30,400
50,600
Note that lines with '#' will be skipped
Arg:
input_file_template: str; search file wioth this pattern, defaults to an init value
csv_delim: str; csv delimiterl, defaults to an init value
"""
if input_file_template is None: input_file_template=self._input_srch
if csv_delim is None: csv_delim=self._csv_delim
if csv_delim is None:
self._log_('Missing csv delimiter or skipper!', 1)
raise MissingCSVParameter
if not self._param_in:
self._log_('No parameters to input!', 1)
return
for defiter in range(2):
input_used = input_file_template if not defiter else self.__input_srch_default
msg_mod = '' if not defiter else ' default'
if input_used:
self._log_('Searching for{} input file...'.format(msg_mod))
try:
file_list = [f for f in glob(input_used)]
self._input_file = file_list[0]
except:
self._log_('Input file not found!', 1)
else:
self._log_('Input file found: ' + self._input_file, 1)
self._log_('Reading input parameters...')
try:
with open(self._input_file, 'r') as csvfile:
spamreader = csvreader(self.decomment(csvfile), delimiter=csv_delim)
for row in spamreader:
for key, elem in zip(self._param_in, row):
self._param_in_value[key.upper()].append(elem.strip())
except Exception as err_msg:
self._log_('An error occured while reading input file!')
self._log_(err_msg, 1)
raise
self.__DPs_imported = len(self._param_in_value[self._param_in[0]])
self._log_('Reading successful: ' + str(self.__DPs_imported) + ' Design Point(s) found', 1)
break
# --------------------------------------------------------------------
def find_and_import_parameters(self, control_file=None, input_file=None):
"""
Automatically find and set parameters in Workbench
Arg:
control_file: str; search file wioth this pattern, defaults to an init value
input_file: str; search file wioth this pattern, defaults to an init value
"""
self.read_control(control_file_template=control_file)
self.read_input(input_file_template=input_file)
self.import_parameters()
# --------------------------------------------------------------------
def input_by_name(self, inp):
"""
Allows directly feed input parameters as list of dict
Example of format for 2 parameters and 3 Design Points:
list = [[1, 2, 3], [10, 20, 30]]
dict = {'p1':[1, 2, 3], 'p2':[10, 20, 30]}
Arg:
inp: list or dict
"""
self._log_('Direct data input by name issued')
if not self.is_matrix(inp):
self._log_('Incorrect input format!')
raise ValueError('Incorrect input format!')
if isinstance(inp, list):
if not self._param_in:
self._log_('No parameter keys found!')
raise KeysNotFound
self._input_list_by_name(inp)
if isinstance(inp, dict):
self._input_dict_by_name(inp)
self._log_('Input successful: {} input(s) in {} Design Point(s)'.format(len(self._param_in),self.__DPs_imported), 1)
# --------------------------------------------------------------------
def input_by_DPs(self, inp, keys=None):
"""
Allows directly feed input parameters as list with list of keys
Example of format for 2 parameters and 3 Design Points:
inp = [[1, 10], [2, 20], [3, 30]]
keys = ['p1', 'p2']
Arg:
inp: list, values for parameters
keys: list, parameter names, defaults to already existing keys
"""
self._log_('Direct data input by DPs issued')
if not self.is_matrix(inp):
self._log_('Incorrect input format!')
raise ValueError('Incorrect input format!')
if not self._param_in and keys is None:
self._log_('No parameter keys found!')
raise KeysNotFound
if len(inp[0]) != len(self._param_in) and keys is None:
self._log_('Incorrect input format!')
raise ValueError('Incorrect input format!')
vkeys = keys if keys is not None else self._param_in
self._param_in = []
self._param_in_value = defaultdict(list)
for row in inp:
for key, elem in zip(vkeys, row):
elem_s = str(elem).strip()
self._param_in.append(self._safeguard(key))
self._param_in_value[self._safeguard(key)].append(elem_s)
self.__DPs_imported = len(inp)
self._log_('Input successful: {} input(s) in {} Design Point(s)'.format(len(self._param_in),self.__DPs_imported), 1)
# --------------------------------------------------------------------
def open_archive(self, archive='*.wbpz'):
"""
Search for Workbench archive in working directory and open it
Arg:
archive: str, search for this pattern
"""
self._log_('Searching for Workbench archive...')
try:
file_list = [f for f in glob(archive)]
wbpz_file = file_list[0]
except Exception as err_msg:
self._log_('Archive not found!', 1)
self.__failed_to_open = True
return False
self.__workfile = wbpz_file.replace('.wbpz','.wbpj')
self._log_('Archive found: ' + self.__workfile, 1)
self._log_('Unpacking archive...')
try:
args = dict(ArchivePath=wbpz_file, ProjectPath=self.__workfile, Overwrite=True)
workbench.Unarchive(**args)
workbench.ClearMessages()
except Exception as err_msg:
self._log_('Unpacking failed!')
self._log_(err_msg, 1)
self.__failed_to_open = True
return False
self.__failed_to_open = False
self.__active = True
self.__DPs = self._get_DPs()
self.__DPs_present = len(self.__DPs)
self._log_('Unpacking successful!', 1)
return True
# --------------------------------------------------------------------
def open_project(self, project='*.wbpj', refresh=False):
"""
Search for Workbench project in working directory and open it
Arg:
project: str, search for this pattern
refresh: bool, refresh project after opening
"""
self._log_('Searching for Workbench project...')
try:
file_list = [f for f in glob(project)]
wbpj_file = file_list[0]
except Exception as err_msg:
self._log_('Project not found!', 1)
self.__failed_to_open = True
return False
self.__workfile = wbpj_file
self._log_('Project found: ' + self.__workfile, 1)
self._log_('Opening project...')
try:
workbench.Open(FilePath=self.__workfile)
workbench.ClearMessages()
if refresh: workbench.Refresh()
except Exception as err_msg:
self._log_('Opening failed!')
self._log_(err_msg, 1)
self.__failed_to_open = True
return False
self.__failed_to_open = False
self.__active = True
self.__DPs = self._get_DPs()
self.__DPs_present = len(self.__DPs)
self._log_('Success', 1)
return True
# --------------------------------------------------------------------
def open_any(self, archive_first=True, arch='*.wbpz', prj='*.wbpj'):
"""
Tries to open any project or archive in the current working directory
Arg:
archive_first: bool, try to open archive first
arch: str, search for archive with this pattern
prj: str, search for project with this pattern
"""
if archive_first:
open_1 = partial(self.open_archive, archive=arch)
open_2 = partial(self.open_project, project=prj)
else:
open_1 = partial(self.open_project, project=prj)
open_2 = partial(self.open_archive, archive=arch)
if not open_1(): open_2()
if self.__failed_to_open: self._log_('Nothing to open!')
# --------------------------------------------------------------------
def import_parameters(self, save=True):
"""
Set imported parameters into Workbench
Use this method instead of set_parameters()
Args:
save: bool, save after importing parameters
"""
self.set_parameters(saveproject=save)
def set_parameters(self, saveproject=True):
"""Set imported parameters into Workbench"""
if not self.__active:
self._log_('Cannot set parameters: No active project found!', 1)
raise NoActiveProjectFound
self._log_('Setting Workbench parameters...')
if self.__DPs_imported <= 0:
self._log_('No parameters to set!', 1)
return
self._clear_DPs()
while self.__DPs_imported > self.__DPs_present:
self._add_DP(exported=True, retained=True)
try:
for i, (par, par_values) in enumerate(self._param_in_value.items()):
for j, par_value in enumerate(par_values):
self._set_parameter(self.__DPs[j], par, par_value)
except Exception as err_msg:
self._log_('An error occured while setting parameters!')
self._log_(err_msg, 1)
raise
self._log_('Success', 1)
if saveproject: self._save_project()
# --------------------------------------------------------------------
def update_project(self, skip_error=True, skip_uncomplete=True, save=True):
"""
Update Workbench project
Arg:
skip_error: bool, skip errors and continue updating
skip_uncomplete: bool, skip uncomplete Design Points and continue
save: bool, save project after updating
"""
if not self.__active:
self._log_('Cannot update project: No active project found!', 1)
raise NoActiveProjectFound
self._log_('Updating Workbench project...', 1)
workbench.Parameters.ClearDesignPointsCache()
self.__failed_to_update = False
self.__solved = False
self.__not_up_to_date = False
self._param_out_value = defaultdict(list)
self.start_logwatch()
start_time = datetime.now()
try:
if self.__DPs_present == 1: workbench.Update()
else:
args = dict(ErrorBehavior='SkipDesignPoint' if skip_error else 'Stop',
CannotCompleteBehavior='Continue' if skip_uncomplete else 'Stop',
DesignPoints=self.__DPs)
workbench.UpdateAllDesignPoints(**args)
except Exception as err_msg:
self._log_('Project failed to update!')
self._log_(err_msg, 1)
self.__failed_to_update = True
finally:
self.__solved = True
self.stop_logwatch()
if save: self._save_project()
sol_time = datetime.now() - start_time
sol_time = timedelta(days=sol_time.days, seconds=sol_time.seconds, microseconds=0)
self._log_('Elapsed solution time: {}'.format(sol_time) ,)
if workbench.IsProjectUpToDate():
self._log_('Update successful', 1)
else:
self.__not_up_to_date = True
self._log_('Project is not up-to-date, see messages below')
for msg in workbench.GetMessages():
try: self._log_(msg.MessageType + ": " + msg.Summary)
except: pass
self._logger.blank()
return True
# --------------------------------------------------------------------
def archive_project(self, filename=None, save_external_files=True, save_results=True, save_userfiles=True):
"""
Archives Workbench project
Arg:
filename: str, archive filename; can be relative or absolute, can be just a directory;
defaults to project name with '_result' postfix
save_external_files: bool, saves external files; defaults to True
save_results: bool, saves result files; defaults to True
save_userfiles: bool, saves files in user_files directory; defaults to True
"""
if not self.__active:
self._log_('Cannot archive project: No active project found!', 1)
raise NoActiveProjectFound
self._save_project()
self._log_('Archiving Workbench project...')
try:
if filename is None:
head, tail = os.path.split(self.__workfile)
# if not head: head = os.getcwd()
if not head: head = workbench.GetProjectDirectory()
wbpz_name = tail.split('.')[0] + '_result'
wbpz_file = os.path.join(head, ('{}.{}').format(wbpz_name ,'wbpz'))
elif filename:
head, tail = os.path.split(filename)
if not tail: tail = os.path.basename(self.__workfile).replace('.wbpj','.wbpz')
if not head: head = workbench.GetProjectDirectory()
wbpz_name = tail.split('.')[0]
try: ext = tail.split('.')[1]
except: ext = 'wbpz'
wbpz_file = os.path.join(head, ('{}.{}').format(wbpz_name , ext))
else:
self._log_('Cannot archive project: filename is missing!', 1)
return False
except Exception as err_msg:
self._log_('Cannot archive project: bad filename!')
self._log_(err_msg, 1)
return False
args = dict(FilePath=wbpz_file, FailIfMissingFiles=False, IncludeExternalImportedFiles=bool(save_external_files),
IncludeSkippedFiles=bool(save_results), IncludeUserFiles=bool(save_userfiles))
try:
workbench.Archive(**args)
except Exception as err_msg:
self._log_('Archiving failed!')
self._log_(err_msg, 1)
return False
else:
self._log_('Project archived successfully to {}'.format(wbpz_file), 1)
return True
# --------------------------------------------------------------------
def archive_if_complete(self, threshold_status=2):
"""
Archives project if project status is less or equal to threshold_status
Args:
threshold_status: int, see status() method for more information; defaults to 'FAILED TO UPDATE!' status
"""
if not (0 <= threshold_status <= 4) or not isinstance(threshold_status, int):
self._log_('Cannot archive project: incorrect status threshold!', 1)
return False
if self.status(suppress=True) <= threshold_status:
res = self.archive_project()
return res
# --------------------------------------------------------------------
def set_output(self, out_par=None):
"""
Set list of output parameters by list
Example: ['p1', 'p3', 'p4']
Args:
out_par: list, output parameters
"""
self._log_('Setting output parameters...')
if not out_par:
self._log_('No output parameters specified!')
raise AttributeError
self._param_out_value = defaultdict(list)
try:
self._param_out = [self._safeguard(par) for par in out_par]
except Exception as err_msg:
self._log_('Failed to set parameters!')
self._log_(err_msg, 1)
self._log_('Success: {} outputs specified'.format(len(self._param_out)), 1)
# --------------------------------------------------------------------
def save_project(self):
"""Save Workbench project"""
if not self.__active:
self._log_('Cannot save project: No active project found!', 1)
raise NoActiveProjectFound
workbench.Save(Overwrite=True)
self._log_('Project Saved', 1)
# --------------------------------------------------------------------
def output_parameters(self, output_file_name=None, csv_delim=None, fkey='wb'):
"""
Output parameters in a file. Set output_file_name = '' to suppress
output to a file
Args:
output_file_name: str, write to this file, if empty - output internally only
full_report_file: str, Workbench parametric report file
csv_delim: str, csv delimiter
fkey: str, file opening mode
"""
if not self.__active:
self._log_('Cannot output parameters: No active project found!', 1)
raise NoActiveProjectFound
if output_file_name is None: output_file_name=self._out_file
if csv_delim is None: csv_delim=self._csv_delim
if self._param_out:
if csv_delim is None:
self._log_('Missing csv delimiter or skipper!', 1)
raise MissingCSVParameter
self._param_out_value = defaultdict(list)
self._log_('Retrieving output parameters... ')
try:
for key in self._param_out:
for dp in self.__DPs:
val = self._get_parameter_value(dp, key)
self._param_out_value[key.upper()].append(val)
# Group values by Design Point
out_map = self._output_group_by_DPs()
except Exception as err_msg:
self._log_('Failed to retriev parameters!')
self._log_(err_msg, 1)
return None
if output_file_name is None or output_file_name == '':
self._log_('No output file defined! Results were stored internally', 1)
return out_map
self._log_('Outputing parameters to {}...'.format(output_file_name))
try:
with open(output_file_name, mode=fkey) as out_file:
out_writer = csvwriter(out_file, delimiter=csv_delim, quotechar='"', quoting=QUOTE_MINIMAL)
for row in out_map: out_writer.writerow(row)
except Exception as err_msg:
self._log_('An error occured while outputting parameters!')
self._log_(err_msg, 1)
return None
else:
self._log_('Output successful', 1)
return out_map
else:
self._log_('No parameters to output!', 1)
return None
# --------------------------------------------------------------------
def set_active_DP(self, dp):
"""Sets active DP"""
try: workbench.Parameters.SetBaseDesignPoint(DesignPoint=dp)
except: pass
# --------------------------------------------------------------------
def export_wb_report(self, full_report_file=None):
"""
Exports Workbench parametric report
Args:
full_report_file: str, Workbench parametric report file
"""
if not self.__active:
self._log_('Cannot output parameters: No active project found!', 1)
raise NoActiveProjectFound
if full_report_file is None: full_report_file=self._full_file
if full_report_file:
try:
workbench.Parameters.ExportAllDesignPointsData(FileName=full_report_file)
self._log_('Workbench parametric report written to {}'.format(full_report_file), 1)
except:
self._log_('Cannot generate Workbench report!', 1)
else:
self._log_('Cannot export Workbench report: file name is not defined!', 1)
def copy_from_userfiles(self, template_str, target):
self.copy_files(template_str, workbench.GetUserFilesDirectory() , target)
def move_from_userfiles(self, template_str, target):
self.move_files(template_str, workbench.GetUserFilesDirectory() , target)
def delete_from_userfiles(self, template_str):
self.delete_files(template_str, workbench.GetUserFilesDirectory())
# ---------------------------------------------------------------
# Messenger Methods
# ---------------------------------------------------------------
def success_status(self, suppress=False):
"""
Prints if project run considered as successful
Args:
suppress: bool; suppress output to log file
"""
msg_dict = {
0 : 'OVERALL RUN STATUS: SUCCESS',
1 : 'OVERALL RUN STATUS: FAILED'
}
key = 0 if self.status() < 2 else 1
if not suppress: self._log_(msg_dict[key])
return key
def status(self, suppress=False):
"""
Prints project status to log filem returns a status key
Args:
suppress: bool; suppress output to log file
"""
msg = 'SOLUTION STATUS: '
msg_dict = {
0 : msg + 'SOLVE SUCCESSFUL',
1 : msg + 'NOT UP-TO-DATE',
2 : msg + 'FAILED TO UPDATE!',
3 : msg + 'NOT SOLVED',
4 : msg + 'FAILED TO OPEN',
5 : msg + 'NOT OPENED',
}
if self.active:
if self.failed_to_update: key = 2
elif self.not_up_to_date: key = 1
elif self.solved: key = 0
else: key = 3
elif self.failed_to_open: key = 4
else: key = 5
if not suppress: self._log_(msg_dict[key])
return key
def fatal_error(self, msg):
"""
Method to write a fatal error to log
Args:
msg: str; log this message as fatal error
"""
msg_str = 'FATAL ERROR'
msg_send = str(msg).splitlines()
for m in msg_send:
self._log_('{}: {}'.format(msg_str, m))
def issue_end(self):
"""
Call this at the end of your script. Calls success_status() and runtime()
"""
self.success_status()
self._log_('END RUN', 1)
self.runtime()
# ---------------------------------------------------------------
# JScript Wrappers
# ---------------------------------------------------------------
def set_cores_number(self, container, value=0, module='Model', ignore_js_err=True):
"""
Sets number of cores in Mechanical
Warning: number of cores for Mechanical is a global setting and will be
saved as default. Next project run on this machine will use this setting!
Arg:
container: str; specify a Mechanical system, e.g. 'SYS'
value: int
module: str; module to open
ignore_js_err: bool; wraps js main cammands in a try block
"""
if self.__ansys_version < 194:
self._log_('Cannot change number of cores')
self._log_('Older ANSYS versions do not support this function!', 1)
return False
if not value and self.__machine_core_count:
value = self.__machine_core_count
self._log_('Requesting maximum number of cores on this machine')
elif not value and not self.__machine_core_count:
self._log_('Could not set core count to maximum: core count undefined')
return False
if not isinstance(value, int) or value < 0:
self._log_('Error: Attempted to set incorrect number of cores: {}'.format(value))
self._log_('Number of cores used unchanged!', 1)
return False
if value > self.__machine_core_count:
self._log_('Error: Cannot set number of cores bigger than %s on this machine' % self.__machine_core_count)
value = self.__machine_core_count
self._log_('Setting number of cores to {}'.format(value))
# jscode = 'DS.Script.Configure_setNumberOfCores("{}")'.format(value)
jsfun = '''
function setNumberOfCores(value)
{
var jobHandlerManager = DS.Script.getJobHandlerManager();
if (jobHandlerManager == null)
{
return;
}
var defaultHandler = DS.Script.getDefaultHandler(jobHandlerManager);
if (defaultHandler == null)
{
return;
}
var numProcessors = parseInt(value);
if (!isNaN(numProcessors) && numProcessors >= 1 && defaultHandler.MaxNumberProcessors != numProcessors)
{
defaultHandler.MaxNumberProcessors = numProcessors;
jobHandlerManager.Save();
return;
}
}
'''
jsmain = 'setNumberOfCores("{}");'.format(value)
if ignore_js_err: jscode = jsfun + self._try_wrapper_js(jsmain)
else: jscode = jsfun + jsmain
try:
self._send_js_macro(container, jscode, module)
except Exception as err_msg:
self._log_('An error occured!')
self._log_(err_msg, 1)
return False
else: return True
# --------------------------------------------------------------------
def set_distributed(self, container, value, module='Model', ignore_js_err=True):
"""
Activates/deactivates DMP in Mechanical
Warning: this property is a global setting and will be
saved as default. Next project run on this machine will use this setting!
Arg: