-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSimpleFunctions.py
More file actions
661 lines (469 loc) · 26.5 KB
/
SimpleFunctions.py
File metadata and controls
661 lines (469 loc) · 26.5 KB
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
import matplotlib.pyplot as plt # Allows to do plots
import fenics as fe # Allors to use the FEniCS functions
import os # Allows to use path
import pandas as pd # Allows to use data in tables
from IPython.display import display, clear_output
from scipy.interpolate import interp1d
from scipy.optimize import minimize, fmin
import numpy as np
import time
# ----------------------------------------------------------------------------
# Mesh Generation
# ----------------------------------------------------------------------------
def MeshDefinition(Dimensions, NumberElements, Type='Lagrange', PolynomDegree=1):
# Mesh
Mesh = fe.BoxMesh(fe.Point(-Dimensions[0]/2, -Dimensions[1]/2, -Dimensions[2]/2), fe.Point(Dimensions[0]/2, Dimensions[1]/2, Dimensions[2]/2), NumberElements, NumberElements, NumberElements)
# Functions spaces
V_ele = fe.VectorElement(Type, Mesh.ufl_cell(), PolynomDegree)
V = fe.VectorFunctionSpace(Mesh, Type, PolynomDegree)
# Finite element functions
du = fe.TrialFunction(V)
v = fe.TestFunction(V)
u = fe.Function(V)
return [Mesh, V, u, du, v]
# ----------------------------------------------------------------------------
# Kinematics Variables Computation
# ----------------------------------------------------------------------------
def Kinematics(u):
# Kinematics
d = u.geometric_dimension()
I = fe.Identity(d) # Identity tensor
F = I + fe.grad(u) # Deformation gradient
F = fe.variable(F) # To differentiate Psi(F)
J = fe.det(F) # Jacobian of F
C = F.T*F # Right Cauchy-Green deformation tensor
Ic = fe.tr(C) # Trace of C
return [F, J, C, Ic]
# ----------------------------------------------------------------------------
# Load Case Definition
# ----------------------------------------------------------------------------
def LoadCaseDefinition(LoadCase, FinalRelativeStretch, RelativeStepSize, Dimensions, BCsType=False):
Normal = fe.Constant((0, 0, 1)) # Normal to moving side
if LoadCase == 'Compression':
InitialState = 1
if BCsType == 'Ideal':
u_0 = fe.Constant((1E-3)) # Little displacement to avoid NaN values (Ogden)
u_1 = fe.Expression(('(s-1)*h'), degree=1, s = InitialState, h = Dimensions[2] ) # Displacement imposed
else:
u_0 = fe.Constant((0, 0, 1E-3)) # Little displacement to avoid NaN values (Ogden)
u_1 = fe.Expression(('0', '0', '(s-1)*h'), degree=1, s = InitialState, h = Dimensions[2] ) # Displacement imposed
Dir = fe.Constant((0,0,1)) # Deformation direction
NumberSteps = FinalRelativeStretch / RelativeStepSize # Number of steps
DeltaStretch = -RelativeStepSize
elif LoadCase == 'Tension':
InitialState = 1
if BCsType == 'Ideal':
u_0 = fe.Constant((-1E-3)) # Little displacement to avoid NaN values (Ogden)
u_1 = fe.Expression(('(s-1)*h'), degree=1, s = InitialState, h = Dimensions[2] ) # Displacement imposed
else:
u_0 = fe.Constant((0, 0, -1E-3)) # Little displacement to avoid NaN values (Ogden)
u_1 = fe.Expression(('0', '0', '(s-1)*h'), degree=1, s = InitialState, h = Dimensions[2] ) # Displacement imposed
Dir = fe.Constant((0,0,1)) # Deformation direction
NumberSteps = FinalRelativeStretch / RelativeStepSize # Number of steps
DeltaStretch = RelativeStepSize
elif LoadCase == 'SimpleShear':
InitialState = 0
if BCsType == 'Ideal':
u_0 = fe.Constant((-1E-3, 0, 0)) # Little displacement to avoid NaN values
u_1 = fe.Expression(('s*h', '0', '0'), degree=1, s = InitialState, h = Dimensions[2] ) # Displacement imposed
else:
u_0 = fe.Constant((-1E-3, 0, 0)) # Little displacement to avoid NaN values
u_1 = fe.Expression(('s*h', '0', '0'), degree=1, s = InitialState, h = Dimensions[2] ) # Displacement imposed
Dir = fe.Constant((1,0,0)) # Deformation direction
NumberSteps = FinalRelativeStretch / RelativeStepSize # Number of steps
DeltaStretch = RelativeStepSize
else :
print('Incorrect load case name')
print('Load cases available are:')
print('Compression')
print('Tension')
print('SimpleShear')
return [u_0, u_1, InitialState, Dir, Normal, NumberSteps, DeltaStretch]
# ----------------------------------------------------------------------------
# Subdomains definition and Boundary conditions application
# ----------------------------------------------------------------------------
def BCsDefinition(Dimensions, Mesh, V, u_0, u_1, LoadCase, BCsType=False):
# Define geometric spaces
class LowerSide(fe.SubDomain):
def inside(self, x, on_boundary):
tol = 1E-14
return on_boundary and fe.near(x[2], -Dimensions[2]/2, tol)
class UpperSide(fe.SubDomain):
def inside(self, x, on_boundary):
tol = 1E-14
return on_boundary and fe.near(x[2], Dimensions[2]/2, tol)
# Define integration over subdpmains
Domains_Facets = fe.MeshFunction('size_t', Mesh, Mesh.geometric_dimension()-1)
ds = fe.Measure('ds', domain=Mesh, subdomain_data=Domains_Facets)
# Mark all domain facets with 0
Domains_Facets.set_all(0)
# Mark bottom facets with 1
bottom = LowerSide()
bottom.mark(Domains_Facets, 1)
# Mark upper facets with 2
upper = UpperSide()
upper.mark(Domains_Facets, 2)
# Apply boundary conditions
if BCsType == 'Ideal':
if LoadCase == 'SimpleShear':
bcl = fe.DirichletBC(V, u_0, Domains_Facets, 1)
bcu = fe.DirichletBC(V, u_1, Domains_Facets, 2)
else:
bcl = fe.DirichletBC(V.sub(2), u_0, Domains_Facets, 1)
bcu = fe.DirichletBC(V.sub(2), u_1, Domains_Facets, 2)
else:
bcl = fe.DirichletBC(V, u_0, Domains_Facets, 1)
bcu = fe.DirichletBC(V, u_1, Domains_Facets, 2)
# Set of boundary conditions
BoundaryConditions = [bcl, bcu]
return [BoundaryConditions, ds]
# ----------------------------------------------------------------------------
# Constitutive Models Definition
# ----------------------------------------------------------------------------
def CompressibleNeoHookean(Mu, Lambda, Ic, J):
Psi = (Mu/2)*(Ic - 3) - Mu*fe.ln(J) + (Lambda/2)*(fe.ln(J))**2
return Psi
def CompressibleOgden(Mu, Alpha, D, C, Ic, J):
# Invariant of Right Cauchy-Green deformation tensor
def I1(C):
return fe.tr(C)
def I2(C):
c1 = C[0,0]*C[1,1] + C[0,0]*C[2,2] + C[1,1]*C[2,2]
c2 = C[0,1]*C[0,1] + C[0,2]*C[0,2] + C[1,2]*C[1,2]
return c1 - c2
def I3(C):
return fe.det(C)
# Define function necessary for eigenvalues computation
def v_inv(C):
return (I1(C)/3.)**2 - I2(C)/3.
def s_inv(C):
return (I1(C)/3.)**3 - I1(C)*I2(C)/6. + I3(C)/2.
def phi_inv(C):
arg = s_inv(C)/v_inv(C)*fe.sqrt(1./v_inv(C))
# numerical issues if arg~0
# https://fenicsproject.org/qa/12299
# /nan-values-when-computing-arccos-1-0-bug/
arg_cond = fe.conditional( fe.ge(arg, 1-fe.DOLFIN_EPS),
1-fe.DOLFIN_EPS,fe.conditional( fe.le(arg, -1+fe.DOLFIN_EPS),
-1+fe.DOLFIN_EPS, arg ))
return fe.acos(arg_cond)/3.
# Eigenvalues of the strech tensor C
lambda_1 = Ic/3. + 2*fe.sqrt(v_inv(C))*fe.cos(phi_inv(C))
lambda_2 = Ic/3. - 2*fe.sqrt(v_inv(C))*fe.cos(fe.pi/3. + phi_inv(C))
lambda_3 = Ic/3. - 2*fe.sqrt(v_inv(C))*fe.cos(fe.pi/3. - phi_inv(C))
# Constitutive model
Psi = 2 * Mu * (J**(-1/3)*lambda_1**(Alpha/2.) + J**(-1/3)*lambda_2**(Alpha/2.) + J**(-1/3)*lambda_3**(Alpha/2.) - 3) / Alpha**2 + 1/D * (J-1)**2
return Psi
# ----------------------------------------------------------------------------
# Displacement Field Estimation
# ----------------------------------------------------------------------------
def Estimate(Ic, J, u, v, du, BoundaryConditions, InitialState, u_1):
# Use Neo-Hookean constitutive model
Nu_H = 0.49 # (-)
Mu_NH = 1.15 # (kPa)
Lambda = 2*Mu_NH*Nu_H/(1-2*Nu_H) # (kPa)
Psi = CompressibleNeoHookean(Mu_NH, Lambda, Ic, J)
Pi = Psi * fe.dx
# First directional derivative of the potential energy
Fpi = fe.derivative(Pi,u,v)
# Jacobian of Fpi
Jac = fe.derivative(Fpi,u,du)
# Define option for the compiler (optional)
ffc_options = {"optimize": True, \
"eliminate_zeros": True, \
"precompute_basis_const": True, \
"precompute_ip_const": True }
# Define the problem
Problem = fe.NonlinearVariationalProblem(Fpi, u, BoundaryConditions, Jac, form_compiler_parameters=ffc_options)
# Define the solver
Solver = fe.NonlinearVariationalSolver(Problem)
# Set solver parameters (optional)
Prm = Solver.parameters
Prm['nonlinear_solver'] = 'newton'
Prm['newton_solver']['linear_solver'] = 'cg' # Conjugate gradient
Prm['newton_solver']['preconditioner'] = 'icc' # Incomplete Choleski
Prm['newton_solver']['krylov_solver']['nonzero_initial_guess'] = True
# Set initial displacement
u_1.s = InitialState
# Compute solution and save displacement
Solver.solve()
return u
# ----------------------------------------------------------------------------
# Problem Solving
# ----------------------------------------------------------------------------
def SolveProblem(LoadCase, ConstitutiveModel, BCsType, FinalRelativeStretch, RelativeStepSize, Dimensions, NumberElements, Mesh, V, u, du, v, Ic, J, F, Psi, Plot = False, Paraview = False):
if LoadCase == 'Compression':
# Load case
[u_0, u_1, InitialState, Direction, Normal, NumberSteps, DeltaStretch] = LoadCaseDefinition(LoadCase, FinalRelativeStretch, RelativeStepSize, Dimensions, BCsType)
elif LoadCase == 'Tension':
# Load case
[u_0, u_1, InitialState, Direction, Normal, NumberSteps, DeltaStretch] = LoadCaseDefinition(LoadCase, FinalRelativeStretch, RelativeStepSize, Dimensions, BCsType)
elif LoadCase == 'SimpleShear':
# Load case
[u_0, u_1, InitialState, Direction, Normal, NumberSteps, DeltaStretch] = LoadCaseDefinition(LoadCase, FinalRelativeStretch*2, RelativeStepSize*2, Dimensions, BCsType)
# Boundary conditions
[BoundaryConditions, ds] = BCsDefinition(Dimensions, Mesh, V, u_0, u_1, LoadCase, BCsType)
# Estimation of the displacement field using Neo-Hookean model (necessary for Ogden)
u = Estimate(Ic, J, u, v, du, BoundaryConditions, InitialState, u_1)
# Reformulate the problem with the correct constitutive model
Pi = Psi * fe.dx
# First directional derivative of the potential energy
Fpi = fe.derivative(Pi,u,v)
# Jacobian of Fpi
Jac = fe.derivative(Fpi,u,du)
# Define option for the compiler (optional)
ffc_options = {"optimize": True, \
"eliminate_zeros": True, \
"precompute_basis_const": True, \
"precompute_ip_const": True }
# Define the problem
Problem = fe.NonlinearVariationalProblem(Fpi, u, BoundaryConditions, Jac, form_compiler_parameters=ffc_options)
# Define the solver
Solver = fe.NonlinearVariationalSolver(Problem)
# Set solver parameters (optional)
Prm = Solver.parameters
Prm['nonlinear_solver'] = 'newton'
Prm['newton_solver']['linear_solver'] = 'cg' # Conjugate gradient
Prm['newton_solver']['preconditioner'] = 'icc' # Incomplete Choleski
Prm['newton_solver']['krylov_solver']['nonzero_initial_guess'] = True
# Data frame to store values
cols = ['Stretches','P']
df = pd.DataFrame(columns=cols, index=range(int(NumberSteps)+1), dtype='float64')
if Paraview == True:
# Results File
Output_Path = os.path.join('OptimizationResults', BCsType, ConstitutiveModel)
ResultsFile = xdmffile = fe.XDMFFile(os.path.join(Output_Path, str(NumberElements) + 'Elements_' + LoadCase + '.xdmf'))
ResultsFile.parameters["flush_output"] = True
ResultsFile.parameters["functions_share_mesh"] = True
if Plot == True:
plt.rc('figure', figsize=[12,7])
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
# Set the stretch state to initial state
StretchState = InitialState
# Loop to solve for each step
for Step in range(int(NumberSteps+1)):
# Update current state
u_1.s = StretchState
# Compute solution and save displacement
Solver.solve()
# First Piola Kirchoff (nominal) stress
P = fe.diff(Psi, F)
# Nominal stress vectors normal to upper surface
p = fe.dot(P,Normal)
# Reaction force on the upper surface
f = fe.assemble(fe.inner(p,Direction)*ds(2))
# Mean nominal stress on the upper surface
Pm = f/fe.assemble(1*ds(2))
# Save values to table
df.loc[Step].Stretches = StretchState
df.loc[Step].P = Pm
# Plot
if Plot == True:
ax.cla()
ax.plot(df.Stretches, df.P, color = 'r', linestyle = '--', label = 'P', marker = 'o', markersize = 8, fillstyle='none')
ax.set_xlabel('Stretch ratio (-)')
ax.set_ylabel('Stresses (kPa)')
ax.xaxis.set_major_locator(plt.MultipleLocator(0.02))
ax.legend(loc='upper left', frameon=True, framealpha=1)
display(fig)
clear_output(wait=True)
if Paraview == True:
# Project the displacement onto the vector function space
u_project = fe.project(u, V, solver_type='cg')
u_project.rename('Displacement (mm)', '')
ResultsFile.write(u_project,Step)
# Compute nominal stress vector
p_project = fe.project(p, V)
p_project.rename("Nominal stress vector (kPa)","")
ResultsFile.write(p_project,Step)
# Update the stretch state
StretchState += DeltaStretch
return df
# ----------------------------------------------------------------------------
# Interpolation Definition
# ----------------------------------------------------------------------------
def Interpolation(LoadCase, DataFrame, FinalRelativeStretch, RelativeStepSize, Plot = False):
# Experimental Data
FolderPath = os.path.join('/home/msimon/Desktop/FEniCS/ExperimentalData/')
FilePath = os.path.join(FolderPath, 'CR_' + LoadCase + '_ExpDat.csv')
ExpData = pd.read_csv(FilePath, sep=';', header=None, decimal=',')
# Interpolation
InterpExpData = interp1d(ExpData[0], ExpData[1], kind='linear', fill_value='extrapolate')
InterpSimPred = interp1d(DataFrame.Stretches, DataFrame.P, kind='linear', fill_value='extrapolate')
NumberPoints=int(FinalRelativeStretch / RelativeStepSize +1)
XInterp = np.linspace(DataFrame.iloc[0][0],DataFrame.iloc[-1][0],NumberPoints)
# Control Plot
if Plot == True :
plt.rc('figure', figsize=[12,7])
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.cla()
ax.plot(XInterp, InterpExpData(XInterp), color = 'g', linestyle = '--', label = 'Interpolated data', marker = 'o', markersize = 15, fillstyle='none')
ax.plot(ExpData[0], ExpData[1], color = 'b', linestyle = '--', label = 'Original Data', marker = 'o', markersize = 8, fillstyle='none')
ax.plot(XInterp, InterpSimPred(XInterp), color = 'k', linestyle = '--', label = 'Interpolated data', marker = 'o', markersize = 15, fillstyle='none')
ax.plot(DataFrame.Stretches, DataFrame.P, color = 'r', linestyle = '--', label = 'Simulation Prediction', marker = 'o', markersize = 8, fillstyle='none')
ax.set_xlabel('Stretch ratio (-)')
ax.set_ylabel('Stresses (kPa)')
ax.xaxis.set_major_locator(plt.MultipleLocator(0.02))
ax.legend(loc='upper left', frameon=True, framealpha=1)
plt.title(LoadCase)
return [XInterp, InterpExpData, InterpSimPred]
# ----------------------------------------------------------------------------
# Cost Function Definition
# ----------------------------------------------------------------------------
def CostFunction(Parameters, ConstitutiveModel, BCsType, Dimensions, NumberElements, LoadCases, RelativeWeights, FinalRelativeStretch, RelativeStepSize, Plot = False):
# Mesh
[Mesh, V, u, du, v] = MeshDefinition(Dimensions, NumberElements)
[F, J, C, Ic] = Kinematics(u)
Nu = Parameters[0]
Mu = Parameters[1]
if len(Parameters) == 3:
Alpha = Parameters[2]
D = 3*(1-2*Nu)/(Mu*(1+Nu)) # (1/kPa)
elif len(Parameters) == 2:
Lambda = 2*Mu*Nu/(1-2*Nu) # (kPa)
Output_Path = os.path.join('OptimizationResults', BCsType, ConstitutiveModel)
FileName = open(Output_Path + str(NumberElements) + 'Elements.txt', 'a+')
if len(Parameters) == 3:
FileName.write('%.3f %.3f %.3f' % (Nu, Mu, Alpha))
elif len(Parameters) == 2:
FileName.write('%.3f %.3f %.3f' % (Nu, Mu, Lambda))
FileName.close()
if 'Compression' in LoadCases:
LoadCase = 'Compression'
# Mesh
[Mesh, V, u, du, v] = MeshDefinition(Dimensions, NumberElements)
[F, J, C, Ic] = Kinematics(u)
if len(Parameters) == 3:
Psi = CompressibleOgden(Mu, Alpha, D, C, Ic, J)
elif len(Parameters) == 2:
Psi = CompressibleNeoHookean(Mu, Lambda, Ic, J)
# Solve
DataFrame = SolveProblem(LoadCase, ConstitutiveModel, BCsType, FinalRelativeStretch, RelativeStepSize, Dimensions, NumberElements, Mesh, V, u, du, v, Ic, J, F, Psi)
# Interpolation
[XInterp, InterpExpData, InterpSimPred] = Interpolation(LoadCase, DataFrame, FinalRelativeStretch, RelativeStepSize, Plot)
# Compute partial compression cost
CompressionDelta2 = []
for X in XInterp:
CompressionDelta2.append(((InterpExpData(X)-InterpSimPred(X))/ InterpExpData(XInterp[-1]))**2)
if 'Tension' in LoadCases:
LoadCase = 'Tension'
# Mesh
[Mesh, V, u, du, v] = MeshDefinition(Dimensions, NumberElements)
[F, J, C, Ic] = Kinematics(u)
if len(Parameters) == 3:
Psi = CompressibleOgden(Mu, Alpha, D, C, Ic, J)
elif len(Parameters) == 2:
Psi = CompressibleNeoHookean(Mu, Lambda, Ic, J)
# Solve
DataFrame = SolveProblem(LoadCase, ConstitutiveModel, BCsType, FinalRelativeStretch, RelativeStepSize, Dimensions, NumberElements, Mesh, V, u, du, v, Ic, J, F, Psi)
# Interpolation
[XInterp, InterpExpData, InterpSimPred] = Interpolation(LoadCase, DataFrame, FinalRelativeStretch, RelativeStepSize, Plot)
# Compute partial tension cost
TensionDelta2 = []
for X in XInterp:
TensionDelta2.append(((InterpExpData(X)-InterpSimPred(X))/ InterpExpData(XInterp[-1]))**2)
if 'SimpleShear' in LoadCases:
LoadCase = 'SimpleShear'
# Mesh
[Mesh, V, u, du, v] = MeshDefinition(Dimensions, NumberElements)
[F, J, C, Ic] = Kinematics(u)
if len(Parameters) == 3:
Psi = CompressibleOgden(Mu, Alpha, D, C, Ic, J)
elif len(Parameters) == 2:
Psi = CompressibleNeoHookean(Mu, Lambda, Ic, J)
# Solve
DataFrame = SolveProblem(LoadCase, ConstitutiveModel, BCsType, FinalRelativeStretch, RelativeStepSize, Dimensions, NumberElements, Mesh, V, u, du, v, Ic, J, F, Psi)
# Interpolation
[XInterp, InterpExpData, InterpSimPred] = Interpolation(LoadCase, DataFrame, FinalRelativeStretch, RelativeStepSize, Plot)
# Compute partial simple shear cost
SimpleShearDelta2 = []
for X in XInterp:
SimpleShearDelta2.append(((InterpExpData(X)-InterpSimPred(X))/ InterpExpData(XInterp[-1]))**2)
# Compute total cost
if 'Compression' in LoadCases and 'Tension' in LoadCases and 'SimpleShear' in LoadCases:
TotalCost = np.sum(CompressionDelta2) * RelativeWeights[0] + np.sum(TensionDelta2) * RelativeWeights[1] + np.sum(SimpleShearDelta2) * RelativeWeights[2]
TotalCost = TotalCost / np.sum(RelativeWeights)
elif 'Compression' in LoadCases and 'Tension' in LoadCases and 'SimpleShear' not in LoadCases:
TotalCost = np.sum(CompressionDelta2) * RelativeWeights[0] + np.sum(TensionDelta2) * RelativeWeights[1]
TotalCost = TotalCost / np.sum(RelativeWeights)
elif 'Compression' in LoadCases and 'Tension' not in LoadCases and 'SimpleShear' in LoadCases:
TotalCost = np.sum(CompressionDelta2) * RelativeWeights[0] + np.sum(SimpleShearDelta2) * RelativeWeights[1]
TotalCost = TotalCost / np.sum(RelativeWeights)
elif 'Compression' not in LoadCases and 'Tension' in LoadCases and 'SimpleShear' in LoadCases:
TotalCost = np.sum(TensionDelta2) * RelativeWeights[0] + np.sum(SimpleShearDelta2) * RelativeWeights[1]
TotalCost = TotalCost / np.sum(RelativeWeights)
elif 'Compression' in LoadCases and 'Tension' not in LoadCases and 'SimpleShear' not in LoadCases:
TotalCost = np.sum(CompressionDelta2) * RelativeWeights[0]
TotalCost = TotalCost / np.sum(RelativeWeights)
elif 'Compression' not in LoadCases and 'Tension' in LoadCases and 'SimpleShear' not in LoadCases:
TotalCost = np.sum(TensionDelta2) * RelativeWeights[0]
TotalCost = TotalCost / np.sum(RelativeWeights)
elif 'Compression' not in LoadCases and 'Tension' not in LoadCases and 'SimpleShear' in LoadCases:
TotalCost = np.sum(SimpleShearDelta2) * RelativeWeights[0]
TotalCost = TotalCost / np.sum(RelativeWeights)
print('Cost:', np.sum(TotalCost))
FileName = open(os.path.join(Output_Path, str(NumberElements) + 'Elements.txt'), 'a+')
FileName.write(' %.3f\n' % (TotalCost))
FileName.close()
return np.sum(TotalCost)
# ----------------------------------------------------------------------------
# Optimization Function
# ----------------------------------------------------------------------------
def ParametersOptimization(ConstitutiveModel, NumberElements, BCsType, LoadCases, RelativeWeights, FinalRelativeStretch, RelativeStepSize, Dimensions=[5,5,5], Plot = False):
# Initialize time tracking
start = time.time()
# Folder for the results
Output_Path = os.path.join('OptimizationResults', BCsType, ConstitutiveModel)
os.makedirs(Output_Path, exist_ok=True)
FileName = open(os.path.join(Output_Path, str(NumberElements) + 'Elements.txt'), 'a+')
if ConstitutiveModel == 'Ogden':
# Ogden initial guessed parameters
Nu = 0.49 # (-)
Mu = 0.66 # (kPa)
Alpha = -24.3 # (-)
InitialGuess = np.array([Nu, Mu, Alpha])
Bounds = [(0.4, 0.495), (1E-3, 2), (-100, -1E-3)]
FileName.write('Nu Mu Alpha TotalCost\n')
elif ConstitutiveModel == 'Neo-Hookean':
# Neo-Hookean initial guessed parameters
Nu = 0.49 # (-)
Mu = 1.15 # (kPa)
InitialGuess = np.array([Nu, Mu])
Bounds = [(0.4, 0.495), (0.5, 2)]
FileName.write('Nu Mu Lambda TotalCost\n')
FileName.close()
ResultsOptimization = minimize(CostFunction, InitialGuess, args = (ConstitutiveModel, BCsType, Dimensions, NumberElements, LoadCases, RelativeWeights, FinalRelativeStretch, RelativeStepSize), method = 'L-BFGS-B', bounds = Bounds)
if ConstitutiveModel == 'Ogden':
[Nu, Mu, Alpha] = ResultsOptimization.x
print('Final Nu = %1.3f' % (Nu))
print('Final Mu = %1.3f' % (Mu))
print('Final Alpha = %1.3f' % (Alpha))
elif ConstitutiveModel == 'Neo-Hookean':
[Nu, Mu] = ResultsOptimization.x
print('Final Nu = %1.3f' % (Nu))
print('Final Mu = %1.3f' % (Mu))
TimeName = open(os.path.join(Output_Path, 'OptimizationTime.txt'), 'a+')
TimeName.write('%1.3f\n' % (time.time() - start))
TimeName.close()
if Plot == True :
df = pd.read_csv(os.path.join(Output_Path, str(NumberElements) + 'Elements.txt'), sep=' ', decimal='.')
plt.rc('figure', figsize=[36,7])
fig = plt.figure()
ax = fig.add_subplot(1, 3, 1)
ax.cla()
ax.plot(df.Mu, color = 'r', linestyle = '--', marker = 'o', markersize = 8, fillstyle='none')
ax.set_xlabel('Iteration number(-)')
ax.set_ylabel('Mu (kPa)')
ax = fig.add_subplot(1, 3, 2)
ax.cla()
ax.plot(df.Alpha, color = 'b', linestyle = '--', marker = 'o', markersize = 8, fillstyle='none')
ax.set_xlabel('Iteration number(-)')
ax.set_ylabel('Alpha (-)')
ax = fig.add_subplot(1, 3, 3)
ax.cla()
ax.plot(df.TotalCost, color = 'g', linestyle = '--', marker = 'o', markersize = 8, fillstyle='none')
ax.set_xlabel('Iteration number(-)')
ax.set_ylabel('Cost (-)')
return ResultsOptimization