-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmaterial.py
More file actions
2169 lines (1769 loc) · 65.9 KB
/
Copy pathmaterial.py
File metadata and controls
2169 lines (1769 loc) · 65.9 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
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
from functools import partial
from math import log, exp, sin, cos, acos, radians, pi, inf
from typing import Callable, Tuple
import chaospy # TODO: just need quadrature points
import numpy as np
from numpy import dot, trace, eye, outer
from numpy.linalg import det
# Same-package modules
from .core import CONSTANT_R, CONSTANT_F, Sequence, ScaledSequence
from .exceptions import InvalidParameterError
from .math import dyad, dyad_odot
_DEFAULT_ORIENT_RANK1 = np.array([1, 0, 0])
_DEFAULT_ORIENT_RANK2 = (np.array([1, 0, 0]), np.array([0, 1, 0]), np.array([0, 0, 1]))
# Precalculated ellipsoidal fiber orientation distribution integration terms from
# FEBio geodesic.h. Each row is cos(Θ) * sin(φ), sin(Θ) * sin(φ), cos(φ), weight;
# θ ∈ [0, π/2], φ ∈ [0, π/2]. The weights sum to π/2.
# TODO: double precision
FIBER_OCTANT_INTEGRATION_WEIGHTS = np.array(
[
[1, 0, 0, 0.003394024],
[0, 1, 0, 0.003394024],
[0, 0, 1, 0.003394024],
[0.7071068, 0.7071068, 0, 0.02550091],
[0, 0.7071068, 0.7071068, 0.02550091],
[0.7071068, 0, 0.7071068, 0.02550091],
[0.9486833, 0.3162278, 0, 0.0180476],
[0.3162278, 0.9486833, 0, 0.0180476],
[0, 0.9486833, 0.3162278, 0.0180476],
[0, 0.3162278, 0.9486833, 0.0180476],
[0.9486833, 0, 0.3162278, 0.0180476],
[0.3162278, 0, 0.9486833, 0.0180476],
[0.4082483, 0.8164966, 0.4082483, 0.06535968],
[0.4082483, 0.4082483, 0.8164966, 0.06535968],
[0.8164966, 0.4082483, 0.4082483, 0.06535968],
[0.9899495, 0.1414214, 0, 0.01273219],
[0.8574929, 0.5144958, 0, 0.02322682],
[0.5144958, 0.8574929, 0, 0.02322682],
[0.1414214, 0.9899495, 0, 0.01273219],
[0, 0.9899495, 0.1414214, 0.01273219],
[0, 0.8574929, 0.5144958, 0.02322682],
[0, 0.5144958, 0.8574929, 0.02322682],
[0, 0.1414214, 0.9899495, 0.01273219],
[0.9899495, 0, 0.1414214, 0.01273219],
[0.8574929, 0, 0.5144958, 0.02322682],
[0.5144958, 0, 0.8574929, 0.02322682],
[0.1414214, 0, 0.9899495, 0.01273219],
[0.5883484, 0.7844645, 0.1961161, 0.05866665],
[0.1961161, 0.7844645, 0.5883484, 0.05866665],
[0.5883484, 0.1961161, 0.7844645, 0.05866665],
[0.1961161, 0.5883484, 0.7844645, 0.05866665],
[0.7844645, 0.5883484, 0.1961161, 0.05866665],
[0.7844645, 0.1961161, 0.5883484, 0.05866665],
[0.9128709, 0.3651484, 0.1825742, 0.04814243],
[0.9128709, 0.1825742, 0.3651484, 0.04814243],
[0.9733285, 0.1622214, 0.1622214, 0.03438731],
[0.1622214, 0.9733285, 0.1622214, 0.03438731],
[0.1825742, 0.9128709, 0.3651484, 0.04814243],
[0.3651484, 0.9128709, 0.1825742, 0.04814243],
[0.1825742, 0.3651484, 0.9128709, 0.04814243],
[0.1622214, 0.1622214, 0.9733285, 0.03438731],
[0.3651484, 0.1825742, 0.9128709, 0.04814243],
[0.6396021, 0.4264014, 0.6396021, 0.07332545],
[0.4264014, 0.6396021, 0.6396021, 0.07332545],
[0.6396021, 0.6396021, 0.4264014, 0.07332545],
]
)
def pdf3d_spherical():
return 1 / 4 / pi
def pdf3d_ellipsoidal(r: np.ndarray, d: np.ndarray):
# TODO: normalize so this is actually a pdf
# return ((r[0] / d[0]) ** 2 + (r[1] / d[1]) ** 2 + (r[2] / d[2]) ** 2) ** -0.5
return 1 / np.linalg.norm(r / d)
def integrate_sph2_oct(summand, f):
"""Integrate f over unit half-sphere
45 points per octant
"""
for octant_signs in (
np.array([1, 1, 1]),
np.array([-1, 1, 1]),
np.array([-1, -1, 1]),
np.array([1, -1, 1]),
):
for i in range(FIBER_OCTANT_INTEGRATION_WEIGHTS.shape[0]):
N = octant_signs * FIBER_OCTANT_INTEGRATION_WEIGHTS[i, :3]
w = FIBER_OCTANT_INTEGRATION_WEIGHTS[i, -1]
summand += w * f(N)
return summand
def integrate_sph2_gkt(summand, f, o_φ, n_θ):
"""Integrate f over unit half-sphere by GKT
Implemented based on Hou_Ateshian_2016, but integrating the whole sphere.
"""
# FEBio weights sum to 2; these weights sum to 1. That doesn't affect the FEBio
# results because they normalize by the integrated fiber density.
ζ_points, ζ_weights = chaospy.quadrature.kronrod(o_φ, chaospy.Uniform(-1, 1))
# ^ takes 2.2 ms; maybe call it once (cache it?) Whole integration takes 3 ms.
ζ_points = ζ_points.squeeze()
ζ_weights = ζ_weights.squeeze()
def φ_from_ζ(ζ):
return acos(0.5 * (ζ * (cos(φb) - cos(φa)) + cos(φa) + cos(φb)))
# θ is azimuth
# φ is declination
dθ = 2 * pi / n_θ
φa = 0
φb = pi / 2
# ζa = -1
# ζb = 1
# h_ζ = 0.5 * (ζb - ζa)
# center_ζ = 0.5 * (ζb + ζa)
for ζ, w in zip(ζ_points, ζ_weights):
for i in range(n_θ):
θ = i * dθ
φ = φ_from_ζ(ζ)
N = np.array([cos(θ) * sin(φ), sin(θ) * sin(φ), cos(φ)])
# np.testing.assert_almost_equal(np.linalg.norm(N), 1, decimal=14)
summand += w * dθ * f(N)
return summand
def deviatoric_stress(σ_tilde):
"""Return deviatoric stress from σ_tilde"""
# The np.trace(σ_tilde) / 3 * np.eye(3) forces the stress to be deviatoric.
# It feels like a properly constructed deviatoric constitutive equation
# should already produce deviatoric stress. Simply discarding the
# hydrostatic part feels wrong.
return σ_tilde - np.trace(σ_tilde) / 3 * np.eye(3)
def stress_1d_N(F, stress: Callable, N, **kwargs):
"""Return stress along (material config) unit vector N
:param F: Deformation gradient tensor.
:param stress: Function of stretch ratio λ that returns 1D stress; scalar → scalar.
:param N: Unit vector along which to calculate stress. N is defined in the
(unstrained) material configuration. N is not renormalized during the calculation,
so if it is not a unit vector you will get incorrect results.
"""
λ = np.linalg.norm(F @ N) # np.sqrt(Q @ F.T @ F @ Q.T)
P = stress(λ, **kwargs) * np.outer(N, N) # PK2 stress
J = np.linalg.det(F)
σ = 1 / J * F @ P @ F.T
return σ
def to_Lamé(E, v):
"""Convert Young's modulus & Poisson ratio to Lamé parameters."""
if v <= -1 or v >= 0.5:
raise InvalidParameterError(
f"ν = {v} cannot be converted to Lamé parameters; -1 < ν < 0.5 required."
)
y = v * E / ((1.0 + v) * (1.0 - 2.0 * v)) # TODO: handle ν = 0.5 or -1
mu = E / (2.0 * (1.0 + v))
return y, mu
def from_Lamé(y, u):
"""Convert Lamé parameters to modulus & Poisson's ratio."""
E = u / (y + u) * (2.0 * u + 3.0 * y)
v = 0.5 * y / (y + u)
return E, v
def invariants(F):
C = F.T @ F
I1 = np.linalg.trace(C)
I2 = 0.5 * (I1**2 - np.linalg.trace(C @ C))
I3 = np.linalg.det(C)
M0 = np.array([[1, 0, 0], [0, 0, 0], [0, 0, 0]])
I4 = np.tensordot(M0, C)
I5 = np.tensordot(M0, C @ C)
return I1, I2, I3, I4, I5, M0
def orthotropic_elastic_compliance_matrix(E1, E2, E3, G12, G23, G31, ν12, ν23, ν31):
"""Return stiffness matrix for an orthotropic material with standard E, G, ν"""
ν13 = ν31 * E1 / E3
ν21 = ν12 * E2 / E1
ν32 = ν23 * E3 / E2
S = np.array(
[
[1 / E1, -ν21 / E2, -ν31 / E3, 0, 0, 0],
[-ν12 / E1, 1 / E2, -ν32 / E3, 0, 0, 0],
[-ν13 / E1, -ν23 / E2, 1 / E3, 0, 0, 0],
[0, 0, 0, 1 / G12, 0, 0],
[0, 0, 0, 0, 1 / G23, 0],
[0, 0, 0, 0, 0, 1 / G31],
]
)
return S
def orthotropic_elastic_compliance_matrix_from_mat(material):
"""Return stiffness matrix for an orthotropic material with standard E, G, ν"""
return orthotropic_elastic_compliance_matrix(
E1=material.E1,
E2=material.E2,
E3=material.E3,
G12=material.G12,
G23=material.G23,
G31=material.G31,
ν12=material.ν12,
ν23=material.ν23,
ν31=material.ν31,
)
def orthotropic_elastic_stiffness_matrix(E1, E2, E3, G12, G23, G31, ν12, ν23, ν31):
"""Return stiffness matrix for an orthotropic material with standard E, G, ν"""
ν13 = ν31 * E1 / E3
ν21 = ν12 * E2 / E1
ν32 = ν23 * E3 / E2
a = 1 - ν12 * ν21 - ν23 * ν32 - ν31 * ν13 - 2 * ν12 * ν23 * ν31
C = np.array(
[
[
(1 - ν23 * ν32) * E1 / a,
(ν21 + ν31 * ν23) * E1 / a,
(ν31 + ν21 * ν32) * E1 / a,
0,
0,
0,
],
[
(ν12 + ν13 * ν32) * E2 / a,
(1 - ν31 * ν13) * E2 / a,
(ν32 + ν31 * ν12) * E2 / a,
0,
0,
0,
],
[
(ν13 + ν12 * ν23) * E3 / a,
(ν23 + ν13 * ν21) * E3 / a,
(1 - ν21 * ν12) * E3 / a,
0,
0,
0,
],
[0, 0, 0, G12, 0, 0],
[0, 0, 0, 0, G23, 0],
[0, 0, 0, 0, 0, G31],
]
)
return C
def orthotropic_elastic_stiffness_matrix_from_mat(material):
"""Return stiffness matrix for an orthotropic material with standard E, G, ν"""
return orthotropic_elastic_stiffness_matrix(
E1=material.E1,
E2=material.E2,
E3=material.E3,
G12=material.G12,
G23=material.G23,
G31=material.G31,
ν12=material.ν12,
ν23=material.ν23,
ν31=material.ν31,
)
def trans_iso_elastic_stiffness_matrix(E1, E2, G12, ν12, ν23):
"""Return stiffness matrix for a transversely isotropic elastic material"""
ν21 = ν12 * E2 / E1
return orthotropic_elastic_stiffness_matrix(
E1=E1,
E2=E2,
E3=E2,
G12=G12,
G31=G12,
G23=0.5 * E2 / (1 + ν23),
ν12=ν12,
ν23=ν23,
ν31=ν21,
)
def trans_iso_elastic_compliance_matrix(E1, E2, G12, ν12, ν23):
"""Return compliance matrix for a transversely isotropic elastic material"""
ν21 = ν12 * E2 / E1
return orthotropic_elastic_compliance_matrix(
E1=E1,
E2=E2,
E3=E2,
G12=G12,
G31=G12,
G23=0.5 * E2 / (1 + ν23),
ν12=ν12,
ν23=ν23,
ν31=ν21,
)
def to_voigt_matrix(C):
"""Return Voigt matrix representation of elasticity or compliance tensor
:param C: 3x3x3x3 elasticity or compliance tensor
Index conversion (full → Voigt):
- 00 → 0
- 11 → 1
- 22 → 2
- 12 and 21 → 3
- 02 and 20 → 4
- 01 and 10 → 5
"""
# Voigt notation requires these major and minor symmetries
if not tens4_is_major_symmetric(C):
raise ValueError("C is not major symmetric")
if not tens4_is_left_minor_symmetric(C):
raise ValueError("C is not left minor symmetric")
if not tens4_is_right_minor_symmetric(C):
raise ValueError("C is not right minor symmetric")
C_voigt = np.full((6, 6), np.nan)
voigt_indices = [(0, 0), (1, 1), (2, 2), (1, 2), (0, 2), (0, 1)]
for I, (i, j) in enumerate(voigt_indices):
for J, (k, l) in enumerate(voigt_indices):
C_voigt[I, J] = C[i, j, k, l]
return C_voigt
def is_positive_definite(C):
"""Return True if order-2 or elasticity/compliance tensor is positive definite
:param C: Order-2 tensor or 3x3x3x3 order-4 (elasticity/compliance) tensor.
"""
if len(C.shape) == 4 and np.all(np.array(C.shape) == 3):
C = to_voigt_matrix(C)
elif len(C.shape) == 2:
if not C.shape[0] == C.shape[1]:
raise ValueError("Matrix must be square")
if not is_symmetric(C, (1, 0)):
raise ValueError("Matrix must be symmetric")
else:
raise ValueError(f"Matrix with shape {C.shape} is not supported")
# Determinant of minors method
# for i in range(1, C.shape[0] + 1):
# if np.linalg.det(C[:i, :i]) <= 0:
# return False
# return True
# Eigenvalue method
λ = np.linalg.eigvals(C)
if np.all(λ > 0):
return True
else:
return False
def is_symmetric(C: np.ndarray, permutation, atol=None, rtol=1e-7, as_assert=False):
"""Return True if tensor A has indicated symmetry
:param C: 4th-order tensor of shape (n, n, n, n)
:param permutation: Ordered axis indices after "transpose".
:param atol: Absolute tolerance passed to numpy.is_allclose. Default = epsilon for C's data type.
:param rtol: Relative tolerance passed to numpy.is_allclose. Default = epsilon for C's data type.
:param as_assert: If True, run the comparison as an assertion. This is useful
in tests because it will print the observed difference.
If C is an array of integers, comparison will be by equality. If C is an array of
floats, comparison will use np.is_allclose.
"""
dtype = C.dtype
C_T = np.transpose(C, axes=permutation)
if np.issubdtype(dtype, np.integer):
if as_assert:
assert np.all(C == C_T)
else:
return np.all(C == C_T)
else: # float
if atol is None:
atol = np.finfo(dtype).resolution
if as_assert:
np.testing.assert_allclose(C, C_T, atol=atol, rtol=rtol)
else:
return np.allclose(C, C_T, atol=atol, rtol=rtol)
def tens4_is_major_symmetric(C, **kwargs):
"""Return True if C_ijkl == C_klij"""
return is_symmetric(C, (2, 3, 0, 1), **kwargs)
def tens4_is_left_minor_symmetric(C, **kwargs):
"""Return True if C_ijkl == C_jikl"""
return is_symmetric(C, (1, 0, 2, 3), **kwargs)
def tens4_is_right_minor_symmetric(C, **kwargs):
"""Return True if C_ijkl == C_ijlk"""
return is_symmetric(C, (0, 1, 3, 2), **kwargs)
def unit_step(x):
"""Unit step function."""
if x > 0.0:
return 1.0
else:
return 0.0
def _is_fixed_property(p):
if isinstance(p, Sequence) or isinstance(p, ScaledSequence):
return False
else:
return True
class Constituent:
"""Mixin class for a constitutive law (any object with constitutive parameters)
A class that does not have parameters should not inherit from `ConLaw`. E.g.,
mixture classes do not inherit from `ConLaw` because all the parameters are in
the constituents.
Classes inheriting from Constituent should call `super().__init__()` after setting
all constitutive parameters.
"""
bounds = {} # expect subclasses to override
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.check_parameters_bounds()
def check_parameters_bounds(self):
def _check(v, bounds):
if not bounds[0] <= v <= bounds[1]:
raise InvalidParameterError(
f"{k} = {v} must be within {self.bounds[k]}"
)
for k in self.bounds:
values = np.atleast_1d(getattr(self, k)) # handle vector params
for v in values:
if isinstance(v, (Sequence, ScaledSequence)):
# TODO: Figure out how to check whole sequence
for _, y in v.points:
_check(y, self.bounds[k])
else:
_check(v, self.bounds[k])
class Uncoupled:
"""Mixin class for uncoupled materials
Classes inheriting from `Uncoupled` need only define `tilde_stress(F, **kwargs)`.
The other stress functions will be provided by `Uncoupled`.
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def tilde_stress(self, F, **kwargs):
"""Return σ_tilde stress
Cauchy stress σ = dev(σ_tilde). σ_tilde gets a separate function to support
use of the material both alone and in a deviatoric mixture.
This is a stub; override it when subclassing.
"""
raise NotImplementedError
def tstress(self, F, **kwargs):
"""Cauchy stress tensor"""
return deviatoric_stress(self.tilde_stress(F, **kwargs))
class D1:
"""Marks a 1-dimensional material or fiber"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
class D3:
"""Marks a 3-dimensional material"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
class OrientedMaterial:
"""A material with an orientation matrix"""
def __init__(self, material, Q=np.eye(3)):
self.material = material
Q = np.array(Q)
Q = Q / np.linalg.norm(Q, axis=0)
if isinstance(material, D1):
if Q.ndim != 1:
raise ValueError(
f"1D materials must have an R3 vector orientation. Got {Q}."
)
elif isinstance(material, D3):
if Q.ndim == 1:
# Inflate orientation matrix to 3D
e1 = Q
i = np.where(Q)[0][0]
j = (i + 1) % len(e1)
e2 = np.zeros(3)
e2[j] = -e1[i]
e2[i] = e1[j]
e2 = e2 / np.linalg.norm(e2)
e3 = np.linalg.cross(e1, e2)
Q = np.stack([e1, e2, e3])
else:
if Q.ndim != 2:
raise ValueError(
f"A 3D material must have a 3x3 orientation matrix. Got {Q}."
)
else:
raise ValueError(
f"{type(material)} must inherit from D1 or D3, so it has a known dimensionality, to become an oriented material."
)
self.orientation = Q
def w(self, F):
return self.material.w(F)
def tstress(self, F, **kwargs):
Q = self.orientation
if Q.ndim == 1:
# 1D material ("fiber")
return stress_1d_N(F, self.material.stress, Q)
elif Q.ndim == 2:
# 3D material ("solid")
σ_loc = self.material.tstress(F @ Q, **kwargs)
# ^ Stress in own local basis. This is a change of coordinate system for
# the material, not an observer change, such that material anisotropy is
# accounted for.
else:
raise ValueError(
f"Orientation matrix should be 1st or 2nd order, not {Q.ndim}"
)
return σ_loc
def pstress(self, F, **kwargs):
Q = self.orientation
return Q @ self.material.pstress(Q.T @ F) # TODO: Check
def sstress(self, F, **kwargs):
Q = self.orientation
if Q.ndim == 1:
# 1D material ("fiber")
N = Q
λ = np.linalg.norm(F @ Q)
s_loc = self.material.stress(λ) * np.outer(N, N)
elif Q.ndim == 2:
raise NotImplementedError # Needs test case
# 3D material ("solid")
s_loc = Q @ self.material.sstress(Q.T @ F) @ Q.T # TODO: Check
else:
raise ValueError
return s_loc
class DeviatoricFiber(Uncoupled, D3):
def __init__(self, fiber, Q=np.array([1, 0, 0]), *args, **kwargs):
self.material = fiber
Q = np.array(Q)
if not Q.ndim == 1:
raise ValueError(f"Fiber orientation must be a direction vector. Got {Q}.")
self.orientation = Q
super().__init__(*args, **kwargs)
def tilde_stress(self, F, **kwargs):
F_tilde = np.linalg.det(F) ** (-1 / 3) * F
N = self.orientation
λ_tilde = np.linalg.norm(F_tilde @ N)
σ_tilde = (
F_tilde
@ (self.material.stress(λ_tilde) * np.outer(N, N))
@ F_tilde.T
/ np.linalg.det(F)
)
return σ_tilde
def __getattr__(self, item):
# Intended so parameters of the underlying fiber material can be easily
# accessed. Make sure any functions that do calculation using deviatoric
# strain are defined on DeviatoricFiber.
return getattr(self.material, item)
class EllipsoidalDistribution(Constituent, D3):
def __init__(self, d, mat_fiber):
"""Return fibers with ellipsoidal orientation distribution
a, b, and c are not independent; their ratios matter, their scale does not.
FEBio XML type attribute = "ellipsoidal".
"""
self.d = np.array(d)
self.fiber = mat_fiber
# TODO: not sure integration scheme belongs here
self.integration = ("fibers-3d-gkt", 11, 31) # max needed in Hou_Ateshian_2016
self.o_φ = (self.integration[1] - 1) // 2
self.n_θ = self.integration[2]
super().__init__()
def tstress(self, F, **kwargs):
def σ(N):
"""Return fiber direction stress"""
return stress_1d_N(F, self.fiber.stress, N)
R = partial(pdf3d_ellipsoidal, d=self.d)
integrated_density = integrate_sph2_gkt(0, R, self.o_φ, self.n_θ)
σ = (
integrate_sph2_gkt(
np.zeros((3, 3)), lambda N: R(N) * σ(N), self.o_φ, self.n_θ
)
) / integrated_density
return σ
class Permeability:
"""Parent type for Permeability implementations."""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
class IsotropicConstantPermeability(Constituent, Permeability):
"""Isotropic strain-independent permeability"""
bounds = {"k": (0, inf)}
def __init__(self, k, **kwargs):
self.k = k
super().__init__()
@classmethod
def from_feb(cls, perm, **kwargs):
return cls(perm)
class IsotropicExponentialPermeability(Constituent, Permeability):
"""Isotropic exponential permeability"""
bounds = {"k0": (0, inf), "M": (0, inf), "φ0_s": (0, 1)}
def __init__(self, k0, M, φ0_s, **kwargs):
self.k0 = k0
self.M = M
self.φ0_s = φ0_s
super().__init__()
class IsotropicHolmesMowPermeability(Constituent, Permeability):
"""Isotropic Holmes-Mow permeability"""
# The strain-free solid volume fraction also appears in PoroelasticSolid. Keeping
# them consistent is currently left up to the user. Should their consistency be
# enforced? Usually the material is not updated in-place and may as well be
# immutable.
bounds = {
"k0": (0, inf),
"M": (0, inf),
"α": (0, inf),
"φ0_s": (0, 1),
}
def __init__(self, k0, M, α, φ0_s, **kwargs):
self.k0 = k0
self.M = M
self.α = α
self.φ0_s = φ0_s
super().__init__()
@classmethod
def from_feb(cls, perm, M, alpha, phi0, **kwargs):
# φ0_s is not included in the FEBio <permeability> element, but is nonetheless a
# parameter of the permeability equation. Handling this discrepancy has to be
# done in the FEBio XMl parsing phase.
return cls(perm, M, alpha, phi0)
class TransIsoHolmesMowPermeability(Constituent, Permeability):
"""Transversely isotropic Holmes-Mow permeability
"perm-ref-trans-iso" in FEBio.
"""
# The strain-free solid volume fraction also appears in PoroelasticSolid. Keeping
# them consistent is currently left up to the user. Should their consistency be
# enforced? Usually the material is not updated in-place and may as well be
# immutable.
bounds = {
"k0": (0, inf), # cannot be zero
"M0": (0, inf),
"α0": (0, inf),
"k1a": (0, inf), # *can* be zero
"k2a": (0, inf), # *can* be zero
"Ma": (0, inf),
"αa": (0, inf),
"k1t": (0, inf), # *can* be zero
"k2t": (0, inf), # *can* be zero
"Mt": (0, inf),
"αt": (0, inf),
"φ0_s": (0, 1),
}
def __init__(self, k0, M0, α0, k1a, k2a, Ma, αa, k1t, k2t, Mt, αt, φ0_s, **kwargs):
self.k0 = k0
self.M0 = M0
self.α0 = α0
self.k1a = k1a
self.k2a = k2a
self.Ma = Ma
self.αa = αa
self.k1t = k1t
self.k2t = k2t
self.Mt = Mt
self.αt = αt
self.φ0_s = φ0_s
class PronyViscoelasticity(Constituent):
"""Prony series relaxation fucntion viscoelasticity
Approximates QLV.
"""
# TODO: Not sure yet how to implement time-dependent calculations. Viscoelasticity
# needs the whole stress history, which would need an interpolant for numerical
# integration.
bounds = {
"γ": (0, 1), # 0 ≤ γ ≤ 1
"τ": (0, inf), # 0 < τ < ∞
}
def __init__(self, material, γ, τ):
self.material = material
self.γ = np.atleast_1d(γ)
if sum(self.γ) > 1:
raise InvalidParameterError(f"sum(γ) ≤ 1 required.")
self.τ = np.atleast_1d(τ)
if len(self.γ) != len(self.τ):
raise ValueError(
f"len(γ)={len(self.γ)} and len(τ)={len(self.τ)}. γ and τ must have the same number of values."
)
super().__init__()
class PoroelasticSolid(D3):
"""Fluid-saturated solid"""
def __init__(
self, solid, permeability: Permeability, solid_fraction, fluid_density=0
):
"""Return PoroelasticSolid instance
solid := Solid material instance.
permeability := Permeability instance.
solid_fraction := Volume fraction of solid. Volume fraciton of
solid + volume fraction of fluid = 1.
"""
super().__init__()
self.fluid_density = fluid_density
self.solid_material = solid
self.solid_fraction = solid_fraction
if not isinstance(permeability, Permeability):
# If the value is not a Permeability instance and is valid, it must be a
# number, implicitly assuming isotropic constant permeability
permeability = IsotropicConstantPermeability(permeability)
self.permeability = permeability
class DonnanSwelling(Constituent, D3):
"""Swelling pressure of the Donnan equilibrium type."""
bounds = {
"fcd0": (0, inf),
"phi0_w": (0, 1), # open interval
"ext_osm": (0, inf),
"osm_coef": (0, 1),
}
def __init__(self, phi0_w, fcd0, ext_osm, osm_coef, **kwargs):
# Bounds checks
if _is_fixed_property(phi0_w) and not (0 <= phi0_w <= 1):
raise InvalidParameterError(
f"phi0_w = {phi0_w}; it is required that 0 ≤ phi0_w ≤ 1"
)
if _is_fixed_property(fcd0) and not (fcd0 >= 0):
raise InvalidParameterError(f"fcd0 = {fcd0}; it is required that 0 < fcd0")
if _is_fixed_property(ext_osm) and not (ext_osm >= 0):
raise InvalidParameterError(
f"ext_osm = {ext_osm}; it is required that 0 < ext_osm"
)
# Store values
self.phi0_w = phi0_w
self.fcd0 = fcd0
self.ext_osm = ext_osm
self.osm_coef = osm_coef
super().__init__(**kwargs)
@classmethod
def from_feb(cls, phiw0, cF0, bosm, Phi=1, **kwargs):
return cls(phiw0, cF0, bosm, Phi)
# TODO: find a way to pass T
def tstress(self, F, T, R=CONSTANT_R, **kwargs):
"""Return Cauchy stress tensor"""
# TODO: R units are going to be a constant source of bugs in user code until
# waffleiron is fully units-aware
J = np.linalg.det(F)
FCD = self.phi0_w / (J - 1 + self.phi0_w) * self.fcd0
p = R * T * self.osm_coef * ((FCD**2 + self.ext_osm**2) ** 0.5 - self.ext_osm)
return -p * np.eye(3)
class Multigeneration:
"""Mixture of materials created at and referenced to a given time."""
def __init__(self, generations, **kwargs):
"""Return Multigeneration object.
generations := a list of tuples (start_time <float>, material
<Material>), each tuple defining a material created at and
referenced to `start_time`.
"""
t, materials = zip(*generations)
self.generation_times = t
self.materials = materials
class SolidMixture(D3):
"""Mixture of solids with no interdependencies or residual stress.
The strain energy of the mixture is defined as the sum of the strain energies for
each component.
"""
def __init__(self, solids, **kwargs):
"""Mixture of elastic solids
:param solids: List of material instances comprising the mixture.
"""
if not solids:
raise ValueError(
"SolidMixture requires at least one solid, but none were provided."
)
self.materials = [m for m in solids]
super().__init__(**kwargs)
def w(self, F):
return sum(material.w(F) for material in self.materials)
def tstress(self, F, *args, **kwargs):
return sum(material.tstress(F, *args, **kwargs) for material in self.materials)
def pstress(self, F, *args, **kwargs):
return sum(material.pstress(F, *args, **kwargs) for material in self.materials)
def sstress(self, F, *args, **kwargs):
return sum(
[material.sstress(F, *args, **kwargs) for material in self.materials]
)
class DeviatoricSolidMixture(D3, Uncoupled):
"""Mixture of solids with no interdependencies or residual stress.
The strain energy of the mixture is defined as the sum of the strain energies for
each component.
"""
def __init__(self, solids, *args, **kwargs):
"""Mixture of elastic solids
:param solids: List of uncoupled material instances comprising the mixture.
"""
if not solids:
raise ValueError(
"DeviatoricSolidMixture requires at least one solid, but none were provided."
)
self.materials = [m for m in solids]
super().__init__(*args, **kwargs)
def tstress(self, F, *args, **kwargs):
σ = deviatoric_stress(
sum(
material.tilde_stress(F, *args, **kwargs) for material in self.materials
)
)
return σ
class Rigid:
"""Pseudo-material used for elements in rigid bodies"""
def __init__(self, props={}, **kwargs):
self.density = 0
if "density" in props:
self.density = props["density"]
class NeoHookeanFiber(Constituent, D1):
"""1D fiber with σ ~ λ^2 − 1 relation
Same as "fiber-NH" in FEBio.
"""
bounds = {
"E": (0, inf),
}
def __init__(self, E):
self.E = E
super().__init__()
def stress(self, λ):
"""Return fiber stress scalar along original orientation
If embedding in R3, treat this as 2nd Piola–Kirchoff stress.
"""
if λ <= 1:
return 0
else:
return self.E * (λ**2 - 1)
class NaturalNeoHookeanFiber(Constituent, D1):
"""1D fiber with σ ~ ln(λ) / λ^2 relation
Also called "natural neo-Hookean".
Same as "fiber-natural-NH" in FEBio; available in FEBio ≥ 3.5.1 (2021-09-28).
"""
bounds = {
"E": (0, inf),
"λ0": (1, inf),
}
def __init__(self, E, λ0):
self.E = E
self.λ0 = λ0
super().__init__()
def stress(self, λ):
"""Return fiber stress scalar along original orientation
If embedding in R3, treat this as 2nd Piola–Kirchoff stress.
"""
if λ <= self.λ0:
return 0
else: