-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathADAPT.py
2557 lines (2147 loc) · 101 KB
/
ADAPT.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
# Authors: Alexander Schowtjak, Robin Schulte, Robin Gitschel
# e-mail: alexander.schowtjak@tu-dortmund.de
# robin.schulte@tu-dortmund.de
# Creative Commons Attribution 3.0 Unported License.
# You should have received a copy of the license along with this
# work. If not, see <http://creativecommons.org/licenses/by/3.0/>.
from scipy.optimize import fmin
import scipy.optimize as sopt
import time
from scipy import interpolate
from scipy import special
from numpy import *
from math import sqrt
import os as os
import sys
from collections import defaultdict
from imp import reload
from matplotlib import cm as cm
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon
from matplotlib.patches import Rectangle
from matplotlib.collections import PatchCollection
import numpy as np
import shutil
from itertools import islice
import subprocess
from sklearn.neighbors import NearestNeighbors
import platform
import matplotlib.path as mpltPath
from random import uniform
# define global variables
global fLDC0, fDIC0
global feIn
global colorterm
global weighting
global DisableAllGraphs
global firstRun
global x_start
global x_end
global TempDir
global cwd
global DICPropList
#==============================================================================
############################ START OF USER INPUT ##############################
#==============================================================================
#==============================================================================
# GENERAL SETTINGS
#==============================================================================
#FortDir = None # needs to be initialized for if FortDir: ...
AbaqusCmd = '' # if not specified, 'abq2016' is used for Windows and '/opt/abaqus/2018/SIMULIA/Commands/abq*' for Linux
# restart an aborted simulation by using the name of the iter-file as a restart file
# does not work with evolutionary optimization algorithms
restartFile = None
# specify the amount of CPUs to use for FE-simulations
NumCPUs = 2
#==============================================================================
# DEBUGGING SETTINGS
#==============================================================================
noAbaqus = False # set to true in order to not compute the abaqus job
oneIter = False # if only one iteration should be accomplished
validationFlag = False # set to true when using FE-data as input for validation pruposes
#==============================================================================
# SETTINGS FOR THE PARAMETER IDENTIFICATION
#==============================================================================
# optimisation algorithm
OptimAlg = 1 # 1: simplex, 2: steepest decent, 3: differential evolution
# define the maximum number of iterations to be performed
IterNum = 1000
# perturbation parameters for gradient based optimization methods
eps = 1e-6
# parameters to be optimized
ParString = ['A','eps0','n']
# initial guess
x0 = [ 800.0, 0.001, 0.1]
# bounds must be any positive number, need at minimum as many tuples as parameters (there can be more bounds than parameters)
bnds = ((0., 999999.0),(0., 999999.0),(0., 999999.0),(0., 999999.0),(0., 999999.0),(0., 999999.0),(0., 999999.0),(0., 999999.0))
# specify the type of data to be used
objectiveField = 'strain' # possible options are 'displacement' or 'strain'
# specify the weighting for load and displacement field contributions to the objective function
weighting = {'LDC': 0.5, 'strain': 0.5} #, 'displacement': 0.5} # weigthing factors (only the relative size matters and not the absolute values)
normFlag = False # divide DIC data by frame displacement and LDC data by frame force (this helps to better interpret the objective function value)
# further settings
firstRunNorm = False # activate to normalize objective function values by values of first run (this is useful if the minima of the objective function w.r.t. each parameter haven't been found)
# global criterion method vector (values have been identified by optimising w.r.t. to each quantity separately)
idealVector = {'LDC': 907.302196,'strain': 1.879976772186068e-05}
#==============================================================================
# SETTINGS REGARDING THE FE-SIMULATION
#==============================================================================
DataPrec = '' # set to "double", if double precision is used within Abaqus
# specify your list of abaqus job-names, the postprocessing script (if different from standard) and the required node sets
JobNames = ['r15'] #,'r5'] # uncomment this if two experiments should be used
PostProcessingScript = 'getAbqDisp' # post processing script (without file extension)
NeckNodeSet = 'NSETDISPFIELD' # name of node set in Abaqus to be analyzed, None for all
ForceSet = 'NSETFORCE' # name of the node set in Abaqus for the force
NeckElemSet = 'ESETSTRAIN' # element set that should likely corrsepond to the node set in NeckNodeSet
# name your user material and whether the material parameters are specified in the input file or user material - automatic replacement by the algorithm with the current node set
UserMat = None # e.g. 'C02_UMAT_clean_v1d'
LocMatParInp = True # set to true if material parameters are defined in the input file - False if in the UMAT
YieldLimitCorrection = True # set to true if yield limit needs to be corrected within the UMAT
AbqMode = '3D' # let the program know if the Abaqus test will be 2D or 3D
autodelInnerNoodes = True # automatically delete FE-nodes that are not on the top surface area
# symmetry assumptions
ForceScale = 4
DispScale = 1
#==============================================================================
# SETTINGS FOR EXPERIMENTAL DATA
#==============================================================================
# name of the folder the experimental data is in
ExpFolder = 'Experimental Results'
# specify the names of your DIC frame data, the number of lines of the header and the quadrant of the DIC-data to use
FrameLabelsDIC = ['r15_t2p5_00'] #,'r5_t2p5_6'] # labels to identify Aramis frame data. Need to be in same order as jobnames!
DICheaderLines = 4 # number of header lines in DIC-files
quadrantDIC = {'r15': 3} #,'r5': 3} # specify the qudrant of the DIC-data to use.
# specify your files containing the load-displacement-data
LabelsLDC = ['LDC_ref.txt'] #,'LDC_ref.txt'] # uncomment this if two experiments should be used
LDCFileDelimiter = ',' # delimiter between the columns in the LDC-file, e.g. ',' or '\t'
# specify the loading directions for the FE and DIC-data
LoadDirFE = 'y'
LoadDirDIC = 'y'
# displacement interval considered in LDC-objective-function (used to neglect elastic regime)
x_start = -np.inf
x_end = np.inf
# domain to compare DIC and FE-displacements
xDIC_min = -np.inf
xDIC_max = np.inf
yDIC_min = -np.inf
yDIC_max = np.inf
# List of the properties as a string expected from the DIC input
if validationFlag:
DICPropList = ['x','y','z','ux','uy','uz']
elif LoadDirFE == LoadDirDIC:
DICPropList = ['ID','x','y','z','ux','uy','uz','eps11','eps22']
else:
DICPropList = ['ID','y','x','z','ux','uy','uz','eps11','eps22']
#==============================================================================
# INTERPOLATION SETTINGS
#==============================================================================
# interpolation data
EquidistantSamples = False
NumPoints = 50
DynamicWeight = True
# interpolation once at the beginning
interonce = True
#==============================================================================
# OUTPUT SETTINGS
#==============================================================================
# colored terminal output - should only sometimes (e.g. some clusters) lead to problems
colorterm = True
# disable all graphical output - only sometimes necessary (e.g. some clusters)
DisableAllGraphs = False
# create distance plots for the interpolation
CreateInterpDistPlots = False
# select frequency of output
OutputFlag = 1 # 0 is for minimal output, 1 gives developer output, 2 enables command lines
LogOutputFlag = 1 # same as above but no option for 2
#==============================================================================
############################# END OF USER INPUT ###############################
#==============================================================================
#==============================================================================
# INITIALISATION
#==============================================================================
RawDir = 'RawFrameData'# place where raw data for each frame is temporarily saved
# variable to determine first run
firstRun = True
if colorterm: from colorama import Fore, Back, Style #colored terminal outputs
# check operating platform
Platform = platform.system()
if Platform == 'Windows':
WinPlat = True
elif Platform == 'Linux':
WinPlat = False
else:
SendError('Operating system not properly detected or not compatible with routine. Use Windows or Linux.')
# set commands for calling Abaqus
if not AbaqusCmd:
if WinPlat:
AbaqusCmd = 'abq2016' # version 2016
else:
AbaqusCmd = '/opt/abaqus/2018/SIMULIA/Commands/abq*'
# depending on the computer used, fortran needs to be called explicitly
if WinPlat:
FortDir = '\"C:\Program Files (x86)\Intel\Composer XE 2013 SP1'+os.path.sep+'bin\ifortvars_intel64.bat\"'
else:
FortDir = None
if FortDir:
FortDir = FortDir + ' && '
else:
FortDir = ''
# set up user material
if UserMat:
if WinPlat:
UserMatABQ = ' user=' + UserMat + '.for'
else:
UserMatABQ = ' user=' + UserMat + '.f'
else:
UserMatABQ = ''
# name of the file containing the material parameters to be identified
if LocMatParInp:
ParameterFileName = JobNames[0]
ParameterFileNameExt = '.inp'
else:
ParameterFileName = UserMat
if WinPlat:
ParameterFileNameExt = '.for'
else:
ParameterFileNameExt = '.f'
# set up everything for storage of temporary files
cwd = os.getcwd() # current work directory
TempFolder = os.path.sep+'temp' # Folder for temporary files
TempDir = cwd + TempFolder # Directory to TempFolder
ResDir = cwd+os.path.sep+'Optimization_Results' # Directory to optimization results
# delete old job files and corresponding results while avoiding deletion of other job results
icount = 0
tResDir = ResDir +os.path.sep+str(icount)
if os.path.exists(tResDir):
while os.path.exists(tResDir):
icount += 1
if os.path.exists(tResDir):
tResDir = ResDir+os.path.sep+str(icount)
ResDir = tResDir
GraphDir = ResDir+os.path.sep+'FrameGraphs'
LdcDir = ResDir+os.path.sep+'LDCplots'
if not noAbaqus:
if os.path.exists(TempDir):
for idel,ijob in enumerate(JobNames):
cJDir = TempDir + os.path.sep + ijob
if os.path.exists(cJDir):
shutil.rmtree(cJDir)
DispScaleX = DispScale # scale displacements in x-direction
DispScaleY = DispScale # scale displacements in y-direction
# for postprocessing purposes
SaveInitGuessData = 0
SaveLastIterationData = 0
# perturbation parameters for gradient based optimization methods
epsilon = np.asarray(x0)*eps
# helper to determine dicts to save obj. fun. value of 1st iteration
fDIC0, fLDC0 = {}, {}
terminalWidth = shutil.get_terminal_size().columns
print('\n\n')
message = 'S T A R T I N G O P T I M I Z A T I O N R O U T I N E\n'
print(message.center(terminalWidth))
#==============================================================================
# FUNCTION DEFINITIONS
#==============================================================================
def AdjustData(Data1,Data2,EquidistantSamples=False,NumPoints=100):
'''
Rearrange Data1 and Data2, such that both have the same format for the
evaluation of the objective function, the Load-Displacement-Curve needs to
be evaluated at the same sample points. Therefore the data with higher
resolution (more sample points) is interpolated on the sample points with
lower resolution.
Info in case of errors: Scale factors or the adaption of the
PostProcessingScript might be incorrect.
Parameters
----------
Data1 : numpy.array
Numerical data
Data2 : numpy.array
Experimental data
EquidistantSamples : Boolean
True: data samples with equivalent distance are generated
False: original and probably non-equidistant samples are used,
resulting in non-uniform weights
NumPoints : integer
Number of points, default set to 100
Returns
-------
[x1,y1] : numpy.array
Numerical input data that has been adjusted and interpolated to the
same data points than the experimental data.
[x2,y2] : numpy.array
Experimental input data that has been adjusted and interpolated to the
same data points than the numerical data.
'''
# rearrange data
x1 = abs(Data1[0]) # simulation
y1 = abs(Data1[1]) # simulation
x2 = abs(Data2[0]) # experiment
y2 = abs(Data2[1]) # experiment
# if simulation data shows higher maximum displacement than experimental data
if x1[-1] > x2[-1]:
if len(fvec) == 0:
message = 'The simulation shows larger displacements than the experiment. Hence, the displacements exceeding the experimental values are ignored.'
SendWarning(message,True)
searching = True
for eCt,entry in enumerate(x1):
#find first entry of sim data that is higher than max exp displacement
if entry > x2[-1] and searching:
# if simulation is finer (interpolation from simulation to experiment)
if len(x1[:eCt]) > len(x2[:eCt]):
x1, y1 = x1[:eCt+1], y1[:eCt+1]
else:
x1, y1 = x1[:eCt], y1[:eCt]
searching = False
# if experimental data shows higher maximum displacement than simulation data
elif x2[-1] > x1[-1]:
if len(fvec) == 0:
message = 'The simulation shows lower displacements than the experiment. Hence, the experimental displacements exceeding the simulation values are ignored.'
SendWarning(message,True)
searching = True
for eCt,entry in enumerate(x2):
if entry > x1[-1] and searching:
# if simulation is finer (interpolation from simulation to experiment)
if len(x2[:eCt]) > len(x1[:eCt]):
x2, y2 = x2[:eCt+1], y2[:eCt+1]
else:
x2, y2 = x2[:eCt], y2[:eCt]
searching = False
# define interpolation function
try:
f1 = interpolate.interp1d(x1,y1,fill_value='extrapolate')
f2 = interpolate.interp1d(x2,y2,fill_value='extrapolate')
except ValueError:
if DisableAllGraphs == False:
plt.figure(figsize=(8,0.5))
plt.title('Sample points plot')
plt.vlines(Data1[0],0,0.66,'red',alpha=0.6,linewidth=1,label='Simulation sample points(Data1)')
plt.vlines(Data2[0],0.33,1,'blue',alpha=0.6,linewidth=1,label='Experimental sample points(Data2)')
plt.gca().axes.get_yaxis().set_visible(False)
plt.xlabel('displacement in mm')
plt.legend(loc=9, bbox_to_anchor=(0.5, -1), ncol=2)
message = 'ERROR: LDC data interpolation failed! Check sample points plot. Each line represents a sample point. Sample points should overlap in the region of interest.'
SendError(message)
if EquidistantSamples == True:
# create equidistant x vector
x1 = np.linspace(x1[0],x1[-1],num=NumPoints,endpoint=True)
x2 = x1
else:
# interpolate from fine to coarse resolution
if len(x1) > len(x2):
x1 = x2
# print('interpolating from simulation to experimental data')
elif len(x2) > len(x1):
x2 = x1
# print('interpolating from experimental to simulation data')
else: # if both have the same length, but different sample points
x2 = x1
# interpolate data
y1 = f1(x1)
y2 = f2(x2)
SaveLDC_Optimum([x1,y1])
return [x1,y1],[x2,y2]
def Call_abaqus_single(job):
'''
This function starts and evaluates a single Abaqus job. First, all
associated files like the ODB and DAT files are deleted. Subsequently,
the Abaqus job is submitted using the batch or shell script. Here, the
interactive keyword guarantees, that the computation is finished. Finally,
when the job has finished and no error occured, the output data base is
evaluated using the postprocessing script.
Using Windows, the job is started as a subprocess to avoid the terminal
popping up regularly with each job submission.
Info: The job cannot be terminated upon user interrupt of the script.
Parameters
----------
job : string
name of the Abaqus input file
'''
# command = AbaqusCmd + ' cae noGUI=' + PostProcessingScript # command to call post processing script
os.chdir(job)
try:
os.remove('abaqus.rpy')
except OSError:
pass
# all file extensions to be deleted
DelString = ['.dat','.com','.odb','.msg','.prt','.sta','.log','.sim',
'.lck','.fil','.par','.pes','.pmg','.tec','.txt']
UpdateLogfile('Running Abaqus job ...')
print('Running Abaqus job ...')
# delete old job-files
for ext in DelString:
try:
os.remove(job + ext)
except OSError:
pass
# submit Abaqus job
if WinPlat:
startupinfo = subprocess.STARTUPINFO()
if OutputFlag <= 2:
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
ErrorCode = subprocess.call('run_'+job+'.bat', startupinfo=startupinfo, shell=False)
else:
ErrorCode = os.system('./run_'+job+'.sh > /dev/null')
if ErrorCode == 0:
error_bool = False
if LogOutputFlag >= 0: UpdateLogfile('Abaqus job has finished. Call post processing script ...')
if OutputFlag >= 0: print('Abaqus job has finished. Call post processing script ...')
# call post processing script
command = AbaqusCmd + ' cae noGUI=' + PostProcessingScript
if WinPlat:
startupinfo = subprocess.STARTUPINFO()
if OutputFlag <= 2:
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
PPerror = subprocess.call(command, startupinfo=startupinfo, shell=True)
else:
PPerror = os.system(command + ' > /dev/null')
if PPerror != 0:
error_bool = True
if OutputFlag >= 0: print('Potential error in the post processing script')
if LogOutputFlag >= 0: UpdateLogfile('Potential error in the post processing script')
elif PPerror == 0:
if OutputFlag > 0: print('Post processing script has finished')
if LogOutputFlag >= 0: UpdateLogfile('Post processing script has finished')
else:
error_bool = True
print('WARNING: Abaqus job did not finish properly.\n')
UpdateLogfile('WARNING: Abaqus job did not finish properly')
# change back to temp directory
os.chdir('..')
return error_bool
def Call_abaqus_multi(JobList):
'''
This function starts and evaluates all specified Abaqus jobs
simulateneously to ensure maximum efficiency due to parallelisation. First,
all associated files like the ODB and DAT files are deleted. Subsequently,
the Abaqus job is submitted using the batch or shell script. Using multiple
jobs simulateneously, the interactive keyword cannot be used and the status
of the jobs is monitored by reading the status files. Finally, when the job
has finished and no error occured, the output data base is evaluated using
the postprocessing script.
Using Windows, the job is started as a subprocess to avoid the terminal
popping up regularly with each job submission.
Parameters
----------
job : list of strings
names of all Abaqus input files
'''
#command to call post processing script
command = AbaqusCmd + ' cae noGUI=' + PostProcessingScript
for job in JobList:
# change to directory of current job
os.chdir(job)
try:
os.remove('abaqus.rpy')
except OSError:
pass
# all file extensions to be deleted
DelString = ['.dat','.com','.odb','.msg','.prt','.sta','.log','.sim',
'.lck','.fil','.par','.pes','.pmg','.tec','.txt','.abq',
'.mdl','.pac','.res','.sel','.stt']
# delete old job-files
for ext in DelString:
try:
os.remove(job + ext)
except OSError:
pass
UpdateLogfile('Call Abaqus job '+job+' ...')
print('Call Abaqus job '+job+' ...')
# call abaqus
if WinPlat:
startupinfo = subprocess.STARTUPINFO()
if OutputFlag <= 2:
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
subprocess.call('run_'+job+'.bat', startupinfo=startupinfo, shell=False)
else:
os.system('./run_'+job+'.sh > /dev/null')
# change back to temp directory
os.chdir('..')
# monitor all jobs
# create bool array to save job status
jobCompleted = np.full(len(JobList),False, dtype=bool)
# set boolean to false
error_bool = False
PPerror = 0
error_string = 'Abaqus/Analysis exited with errors' # string if sim. failed
time.sleep(5) # initial pause
while (not all(jobCompleted) and error_bool == False and PPerror == 0):
pp_called = False # marker to check if post processing script was called
# loop over jobs
for ind,job in enumerate(JobList):
# check only jobs that are not completed yet
if not jobCompleted[ind]:
compl_string = 'Abaqus JOB '+ job +' COMPLETED' # string if sim. completed
os.chdir(job)
with open(job+'.log','r') as fidc: # check log-file for strings
for i,line in enumerate(fidc):
if line.startswith(compl_string):
jobCompleted[ind] = True
if LogOutputFlag > 0: UpdateLogfile('Abaqus job ' + job + ' has finished. Call post processing script ...')
if OutputFlag > 0: print('Abaqus job ' + job + ' has finished. Call post processing script ...')
# call post processing script
if WinPlat:
startupinfo = subprocess.STARTUPINFO()
if OutputFlag <= 2:
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
PPerror = subprocess.call(command, startupinfo=startupinfo, shell=True)
else:
PPerror = os.system(command + ' > /dev/null')
if PPerror != 0:
if OutputFlag > 0: print('Potential error in the post processing script')
if LogOutputFlag > 0: UpdateLogfile('Potential error in the post processing script')
elif PPerror == 0:
if OutputFlag > 0: print('Post processing script for job '+job+' has finished')
if LogOutputFlag > 0: UpdateLogfile('Post processing script for job '+job+' has finished')
pp_called = True
elif line.startswith(error_string):
error_bool = True
message = 'Abaqus job ' + job + ' did not finish properly.'
SendWarning(message)
# kill all remaining jobs
for job2kill in JobList:
if not job2kill == job:
os.chdir('..')
os.chdir(job2kill)
if LogOutputFlag > 0: UpdateLogfile('Terminate '+job2kill)
if OutputFlag > 0: print('Terminate job '+job2kill)
startupinfo = subprocess.STARTUPINFO()
if OutputFlag <= 2:
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
subprocess.call('kill_'+job2kill+'.bat', startupinfo=startupinfo, shell=False)
fidc.close()
os.chdir('..')
# pause for each time, only if pp script was not called
if not pp_called:
time.sleep(5)
if error_bool == False and PPerror == 0:
print('All jobs have finished successfully')
UpdateLogfile('All jobs have finished successfully')
return error_bool
def CopyFilesToTempDir(FileList,labelDIC,labelLDC,destination):
'''
All specified files are copied to the temporary directory to ensure that
the original data is unchanged while allowing to keep track of all files
that are being used.
Parameters
----------
FileList : list of strings
labelDIC : string
labelLDC : string
'''
# copy all files to temporary directory
for e in FileList:
try:
shutil.copy(e,os.path.join(TempDir,destination))
except OSError:
pass
for roots, dirs, files in os.walk(ExpFolder):
padLen = len(str(len(files)))
fcount = 0
for frame in files:
# copy DIC frame files
if labelDIC in frame:
numStr = Int2strPad(fcount,padLen)
fcount = fcount+1
RawFile = destination + '_DICFrame' + numStr + '.txt'
shutil.copy(os.path.join(ExpFolder,frame),os.path.join(TempDir,destination,RawDir,RawFile))
# copy LDC file
elif labelLDC in frame:
shutil.copy(os.path.join(ExpFolder,frame),os.path.join(TempDir,destination,RawDir,frame))
def Distance2D(point1,point2):
'''
Compute the distance between the points point1 and point2.
Parameters
----------
point1 : list
Contains all coordinates of point1
point2 : list
Contains all coordinates of point2
Returns
-------
dist : double
Scalard valued distance
'''
dist = 0
for i in range(2):
dist = dist + np.square(point1[i] - point2[i])
dist = sqrt(dist)
return dist
def GetDirs(JobNames):
'''
Get names of directories containing Abaqus input files.
Parameters
----------
JobNames : list of strings
Contains all jobnames
Returns
-------
dirNames : list of strings
List of all directory names
'''
dirNames = {}
for root, dirs, files in os.walk("."):
for name in files:
for job in JobNames:
if job in name and not 'temp' in root and not 'Experimental Results' in root and not 'Optimization_Results' in root:
dirNames[job] = (os.path.split(root)[-1])
return dirNames
def GetObjectiveFunctionValueDIC(DICdata,FEdata,normFlag=False):
'''
Get objective function value f for the DIC/field data that is computed
based on a mean squared error function normalised by the number of data
points.
Parameters
----------
DICdata : np.array
Contains all experimental data points
FEdata : np.array
Contains all numerical data points
normFlag : Boolean
True: divide DIC-data by extensometer displacement
False: no weights are being used
Returns
-------
f : float
Value of the objective function
'''
# divide DIC-data by frame displacement
if normFlag:
Weight = np.copy(DICdata)
for i in range(len(Weight)):
if abs(DICdata[i]) > 0.001:
Weight[i] = abs(1/Weight[i])
else:
Weight[i] = 0
else:
Weight=np.ones(len(DICdata))
# check assumptions about length
tempSum = [abs(x) - abs(y) for x,y in zip(DICdata,FEdata)]
# number of data points that are used in objective function / dont have zero weight
# exeption frame 1: weight of all datapoints is zero --> set ndp to 1 to avoid devision by zero
ndp = 1
if np.count_nonzero(Weight)>0: ndp = np.count_nonzero(Weight)
f = sum((tempSum*Weight)**2)/ndp
return f
def GetObjectiveFunctionValueLDC(Data1,Data2,DynamicWeight=True,Weight=None):
'''
Get objective function value f for the load-displacement-data that is
computed based on a mean squared error function normalised by the number of
data points. If DynamicWeight is true, the weights for all points are
computed based on its distance to their neighbours to prevent intrinsic
biases for non-equidistant sample point distribution. If weights are
specified, they are multiplied with the associated values of the data
points.
In case of an error, the objective function value is returned as 100000000.
Parameters
----------
Data1 : np.array
Contains all numerical data points
Data2 : np.array
Contains all experimental data points
DynamicWeight : Boolean (optional)
True: use weights based on distance to each point's neighbours
False: no weights are being used
Weight : np.array (optional)
Returns
-------
f : float
Value of the objective function
'''
global x_start
global x_end
# if no weight is specified, set to ones
if Weight==None:
Weight=np.ones(len(Data1[0]))
ErrFlag = 0
if DynamicWeight == True:
DWeight = []
for i in range(len(Data1[0])):
if np.isnan(Data1[0][i]) == True or np.isnan(Data1[1][i]) == True \
or np.isnan(Data2[0][i]) == True or np.isnan(Data1[0][i]) == True:
message = 'Corrupt simulation results! (LDC) Some data is nan.'
SendWarning(message)
ErrFlag = 1
break
# for first element only
if i == 0:
w = Data1[0][i+1]/2
# for last element only
elif i == len(Data1[0])-1:
w = (Data1[0][i]-Data1[0][i-1])/2
# for all elements between the first and last ones
else:
w = (Data1[0][i+1]-Data1[0][i-1])/2
DWeight.append(w)
# convert to numpy array
DWeight = np.array(DWeight/np.linalg.norm(DWeight))
else: DWeight=np.ones(len(Data1[0]))
# set weights to zero for all points with greater displacement than xcrit
for i in range(len(Data1[0])):
if Data1[0][i] < x_start or Data1[0][i] > x_end:
Weight[i] = 0
# error catcher, if weight is not given correctly
if len(Weight) != len(Data1[0]):
Weight=np.ones(len(Data1[0]))
print('Error! Dimension mismatch in getObjectiveFunction(...)')
print('Continuing computation with Weight = ones ...')
if ErrFlag == 0:
f = np.sum(((abs(Data1[1][:len(Weight)])-abs(Data2[1][:len(Weight)]))*Weight*DWeight)**2)/np.count_nonzero(Weight)
else:
f = 100000000
return f
def Int2strPad(integer,padLength=3):
'''
Rename frame number in order to ensure correct ordering by beginning with
x leading zeros. Additionally, the frame number is returned as string.
Parameters
----------
integer: integer
Current frame number
padLength: integer
Number of digits, default set to 3
Returns
-------
outStr: string
Properly renamed frame number
'''
outStr = ''
if integer >= 10**padLength: print('Padding length may be insufficient to ensure ordering')
if integer == 0: outStr = str('0'*padLength)
else:
for i in reversed(range(padLength+1)):
if integer < 10**i and integer >= 10**(i-1):
outStr = str('0'*(padLength-i) + str(integer))
return outStr
def Interpolate2DSpace (mainList,interList,objectiveField): # normally FE is main and DIC inter
'''
Two-dimensional spatial interpolation according to the ADAPT publication.
To minimise the interpolation error, the support points for the
interpolation are chosen such that they comprise a trigangle surrounding
the query point with minimum distance to the vertices. This is done with a
nearest neighbour search. The ray casting algorithm ensures that the query
point lies within the triangle formed by the support points.
In case of an error, the objective function value is returned as 100000000.
Parameters
----------
mainList : list
List of points that is being interpolated
interList : list
List of points that is being interpolated to
objectiveField : Boolean (optional)
True: use weights based on distance to each point's neighbours
False: no weights are being used
Returns
-------
errorFlag : Boolean
True: Error within the interpolation
False: No error within the interpolation
d1List : list
X-coordinate of the interpolated data set
d2List : list
X-coordinate of the interpolated data set
d3List : list
X-coordinate of the interpolated data set
'''
NumNeigh = 7 # number of neighbors
Radius = 10 # radius for the nearest neighbor search
neigh = NearestNeighbors(n_neighbors=NumNeigh,radius=Radius)
# extract coordinates from input
inter_data = [i[0:2] for i in interList]
neigh.fit(inter_data)
main_data = [i[0:2] for i in mainList]
neighbors = neigh.kneighbors(main_data, NumNeigh, return_distance=False)
# print("--- %s seconds ---" % (time.time() - start_time))
if objectiveField == 'displacement' or objectiveField == 'strain':
d1List, d2List, d3List, sumDist = [], [], [], []
polygon = [([],[]),([],[]),([],[])]
x1,y1 = [0,0,0],[0,0,0]
errorFlag = False
# assemble combinations for choosing neighbors
m=0
combinations = np.zeros((int(special.binom(NumNeigh-1,2)),3))
for k in range(1,NumNeigh):
for l in range(k+1,NumNeigh):
combinations[m] = [0,k,l]
m = m+1
combinations = combinations.astype(int)
# loop through the list to be interpolated to
for i,item in enumerate(mainList):
if objectiveField == 'displacement':
xneigh,yneigh,Dux,Duy,Duz = [],[],[],[],[]
elif objectiveField == 'strain':
xneigh,yneigh,Deps11,Deps22 = [],[],[],[]
# determine where the NumNeigh closest points in each list are
interInd = neighbors[i]
# define the variables needed for the interpolation equation
x,y = item[0],item[1]
if validationFlag:
# nearest neighbor interpolation
if objectiveField == 'displacement':
projCalcx = interList[interInd[0]][-3]
projCalcy = interList[interInd[0]][-2]
projCalcz = interList[interInd[0]][-1]
elif objectiveField == 'strain':
projCalcx = interList[interInd[0]][-2]
projCalcy = interList[interInd[0]][-1]
distHold = Distance2D((interList[interInd[0]][0],interList[interInd[0]][1]),(x,y))
else:
# get coordinates of NumNeigh neighbors
for j in range(NumNeigh):
xneigh.append(interList[interInd[j]][0])
yneigh.append(interList[interInd[j]][1])
# make sure query point is inside a triangle (=> no extrapolation)
# this also guarantees that the three support points are not on one line
activeNeigh = combinations[0]
isInside = False
itr = 0
while not isInside:
# get polygon of the 3 active neighbors
for k,n in enumerate(activeNeigh):
polygon[k] = (xneigh[n],yneigh[n])
if not RayTracingMethod(x,y,polygon):
# choose new neighbors
itr = itr + 1
if itr > len(combinations)-1:
errorFlag = True
break
activeNeigh = combinations[itr]
else:
isInside = True
# save the total distance of the chosen neighbors
# and get displacements and coordinates of chosen neighbors
distHold = 0.0
for j,n in enumerate(activeNeigh):
distHold = distHold + Distance2D((xneigh[n],yneigh[n]),(x,y))
x1[j] = xneigh[n]
y1[j] = yneigh[n]
if objectiveField == 'displacement':
Dux.append(interList[interInd[n]][-3])
Duy.append(interList[interInd[n]][-2])
Duz.append(interList[interInd[n]][-1])
elif objectiveField == 'strain':
Deps11.append(interList[interInd[n]][-2])
Deps22.append(interList[interInd[n]][-1])
# calcualte u and v for both lists
uTop = (y1[2]-y1[0])*(x-x1[0]) - (x1[2]-x1[0])*(y-y1[0])
vTop = (y1[0]-y1[1])*(x-x1[0]) + (x1[1]-x1[0])*(y-y1[0])
bot = (y1[2]-y1[0])*(x1[1]-x1[0]) - (x1[2]-x1[0])*(y1[1]-y1[0])
# added to prevent random zero occurences
if bot == 0:
bot = bot + 1e-10
message = 'Denominator of interpolation equation evaluated to zero'
SendWarning(message)
u = uTop/bot
v = vTop/bot