-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathtopo_opt.py
More file actions
3220 lines (2630 loc) · 99.2 KB
/
Copy pathtopo_opt.py
File metadata and controls
3220 lines (2630 loc) · 99.2 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
import argparse
from collections import OrderedDict
import multiprocessing as multiprocessing
import os
import shutil as shutil
from shutil import rmtree
from timeit import default_timer as timer
from icecream import ic
import matplotlib.pylab as plt
import matplotlib.tri as tri
import mpmath as mp
import numpy as np
from paropt import ParOpt
from scipy import sparse, spatial
from scipy.linalg import eigh
from scipy.sparse import coo_matrix, linalg
from other.utils import time_this, timer_set_log_path
class Logger:
log_name = "stdout.log"
@staticmethod
def set_log_path(log_path):
Logger.log_name = log_path
@staticmethod
def log(txt="", end="\n"):
with open(Logger.log_name, "a") as f:
f.write("%s%s" % (txt, end))
return
def _populate_Be(nelems, xi, eta, xe, ye, Be):
"""
Populate B matrices for all elements at a quadrature point
"""
J = np.zeros((nelems, 2, 2))
invJ = np.zeros(J.shape)
Nxi = 0.25 * np.array([-(1.0 - eta), (1.0 - eta), (1.0 + eta), -(1.0 + eta)])
Neta = 0.25 * np.array([-(1.0 - xi), -(1.0 + xi), (1.0 + xi), (1.0 - xi)])
# Compute the Jacobian transformation at each quadrature points
J[:, 0, 0] = np.dot(xe, Nxi)
J[:, 1, 0] = np.dot(ye, Nxi)
J[:, 0, 1] = np.dot(xe, Neta)
J[:, 1, 1] = np.dot(ye, Neta)
# Compute the inverse of the Jacobian
detJ = J[:, 0, 0] * J[:, 1, 1] - J[:, 0, 1] * J[:, 1, 0]
invJ[:, 0, 0] = J[:, 1, 1] / detJ
invJ[:, 0, 1] = -J[:, 0, 1] / detJ
invJ[:, 1, 0] = -J[:, 1, 0] / detJ
invJ[:, 1, 1] = J[:, 0, 0] / detJ
# Compute the derivative of the shape functions w.r.t. xi and eta
# [Nx, Ny] = [Nxi, Neta]*invJ
Nx = np.outer(invJ[:, 0, 0], Nxi) + np.outer(invJ[:, 1, 0], Neta)
Ny = np.outer(invJ[:, 0, 1], Nxi) + np.outer(invJ[:, 1, 1], Neta)
# Set the B matrix for each element
Be[:, 0, ::2] = Nx
Be[:, 1, 1::2] = Ny
Be[:, 2, ::2] = Ny
Be[:, 2, 1::2] = Nx
return detJ
def _populate_Be_single(xi, eta, xe, ye, Be):
"""
Populate B matrix for a single element at a quadrature point
"""
J = np.zeros((2, 2))
invJ = np.zeros(J.shape)
Nxi = 0.25 * np.array([-(1.0 - eta), (1.0 - eta), (1.0 + eta), -(1.0 + eta)])
Neta = 0.25 * np.array([-(1.0 - xi), -(1.0 + xi), (1.0 + xi), (1.0 - xi)])
# Compute the Jacobian transformation at each quadrature points
J[0, 0] = np.dot(xe, Nxi)
J[1, 0] = np.dot(ye, Nxi)
J[0, 1] = np.dot(xe, Neta)
J[1, 1] = np.dot(ye, Neta)
# Compute the inverse of the Jacobian
detJ = J[0, 0] * J[1, 1] - J[0, 1] * J[1, 0]
invJ = np.linalg.inv(J)
# Compute the derivative of the shape functions w.r.t. xi and eta
# [Nx, Ny] = [Nxi, Neta]*invJ
Nx = np.outer(invJ[0, 0], Nxi) + np.outer(invJ[1, 0], Neta)
Ny = np.outer(invJ[0, 1], Nxi) + np.outer(invJ[1, 1], Neta)
# Set the B matrix for each element
Be[0, ::2] = Nx
Be[1, 1::2] = Ny
Be[2, ::2] = Ny
Be[2, 1::2] = Nx
return detJ
def _populate_He_single(xi, eta, xe, ye, He):
"""
Populate a single H matrix at a quadrature point
"""
J = np.zeros((2, 2))
N = 0.25 * np.array(
[
(1.0 - xi) * (1.0 - eta),
(1.0 + xi) * (1.0 - eta),
(1.0 + xi) * (1.0 + eta),
(1.0 - xi) * (1.0 + eta),
]
)
Nxi = 0.25 * np.array([-(1.0 - eta), (1.0 - eta), (1.0 + eta), -(1.0 + eta)])
Neta = 0.25 * np.array([-(1.0 - xi), -(1.0 + xi), (1.0 + xi), (1.0 - xi)])
# Compute the Jacobian transformation at each quadrature points
J[0, 0] = np.dot(xe, Nxi)
J[1, 0] = np.dot(ye, Nxi)
J[0, 1] = np.dot(xe, Neta)
J[1, 1] = np.dot(ye, Neta)
# Compute the inverse of the Jacobian
detJ = J[0, 0] * J[1, 1] - J[0, 1] * J[1, 0]
# Set the B matrix for each element
He[0, ::2] = N
He[1, 1::2] = N
return detJ
def _populate_He(nelems, xi, eta, xe, ye, He):
"""
Populate H matrices for all elements at a quadrature point
"""
J = np.zeros((nelems, 2, 2))
N = 0.25 * np.array(
[
(1.0 - xi) * (1.0 - eta),
(1.0 + xi) * (1.0 - eta),
(1.0 + xi) * (1.0 + eta),
(1.0 - xi) * (1.0 + eta),
]
)
Nxi = 0.25 * np.array([-(1.0 - eta), (1.0 - eta), (1.0 + eta), -(1.0 + eta)])
Neta = 0.25 * np.array([-(1.0 - xi), -(1.0 + xi), (1.0 + xi), (1.0 - xi)])
# Compute the Jacobian transformation at each quadrature points
J[:, 0, 0] = np.dot(xe, Nxi)
J[:, 1, 0] = np.dot(ye, Nxi)
J[:, 0, 1] = np.dot(xe, Neta)
J[:, 1, 1] = np.dot(ye, Neta)
# Compute the inverse of the Jacobian
detJ = J[:, 0, 0] * J[:, 1, 1] - J[:, 0, 1] * J[:, 1, 0]
# Set the B matrix for each element
He[:, 0, ::2] = N
He[:, 1, 1::2] = N
return detJ
class NodeFilter:
"""
A node-based filter for topology optimization
"""
def __init__(
self, conn, X, r0=1.0, ftype="spatial", beta=10.0, eta=0.5, projection=False
):
"""
Create a filter
"""
self.conn = np.array(conn)
self.X = np.array(X)
self.nelems = self.conn.shape[0]
self.nnodes = int(np.max(self.conn)) + 1
# Store information about the projection
self.beta = beta
self.eta = eta
self.projection = projection
# Store information about the filter
self.F = None
self.A = None
self.B = None
if ftype == "spatial":
self._initialize_spatial(r0)
else:
self._initialize_helmholtz(r0)
return
def _initialize_spatial(self, r0):
"""
Initialize the spatial filter
"""
# Create a KD tree
tree = spatial.KDTree(self.X)
F = sparse.lil_matrix((self.nnodes, self.nnodes))
for i in range(self.nnodes):
indices = tree.query_ball_point(self.X[i, :], r0)
Fhat = np.zeros(len(indices))
for j, index in enumerate(indices):
dist = np.sqrt(
np.dot(
self.X[i, :] - self.X[index, :], self.X[i, :] - self.X[index, :]
)
)
Fhat[j] = r0 - dist
Fhat = Fhat / np.sum(Fhat)
F[i, indices] = Fhat
self.F = F.tocsr()
self.FT = self.F.transpose()
return
def _initialize_helmholtz(self, r0):
i = []
j = []
for index in range(self.nelems):
for ii in self.conn[index, :]:
for jj in self.conn[index, :]:
i.append(ii)
j.append(jj)
# Convert the lists into numpy arrays
i_index = np.array(i, dtype=int)
j_index = np.array(j, dtype=int)
# Quadrature points
gauss_pts = [-1.0 / np.sqrt(3.0), 1.0 / np.sqrt(3.0)]
# Assemble all of the the 4 x 4 element stiffness matrices
Ae = np.zeros((self.nelems, 4, 4))
Ce = np.zeros((self.nelems, 4, 4))
Be = np.zeros((self.nelems, 2, 4))
He = np.zeros((self.nelems, 1, 4))
J = np.zeros((self.nelems, 2, 2))
invJ = np.zeros(J.shape)
# Compute the x and y coordinates of each element
xe = self.X[self.conn, 0]
ye = self.X[self.conn, 1]
for j in range(2):
for i in range(2):
xi = gauss_pts[i]
eta = gauss_pts[j]
N = 0.25 * np.array(
[
(1.0 - xi) * (1.0 - eta),
(1.0 + xi) * (1.0 - eta),
(1.0 + xi) * (1.0 + eta),
(1.0 - xi) * (1.0 + eta),
]
)
Nxi = 0.25 * np.array(
[-(1.0 - eta), (1.0 - eta), (1.0 + eta), -(1.0 + eta)]
)
Neta = 0.25 * np.array(
[-(1.0 - xi), -(1.0 + xi), (1.0 + xi), (1.0 - xi)]
)
# Compute the Jacobian transformation at each quadrature points
J[:, 0, 0] = np.dot(xe, Nxi)
J[:, 1, 0] = np.dot(ye, Nxi)
J[:, 0, 1] = np.dot(xe, Neta)
J[:, 1, 1] = np.dot(ye, Neta)
# Compute the inverse of the Jacobian
detJ = J[:, 0, 0] * J[:, 1, 1] - J[:, 0, 1] * J[:, 1, 0]
invJ[:, 0, 0] = J[:, 1, 1] / detJ
invJ[:, 0, 1] = -J[:, 0, 1] / detJ
invJ[:, 1, 0] = -J[:, 1, 0] / detJ
invJ[:, 1, 1] = J[:, 0, 0] / detJ
# Compute the derivative of the shape functions w.r.t. xi and eta
# [Nx, Ny] = [Nxi, Neta]*invJ
Nx = np.outer(invJ[:, 0, 0], Nxi) + np.outer(invJ[:, 1, 0], Neta)
Ny = np.outer(invJ[:, 0, 1], Nxi) + np.outer(invJ[:, 1, 1], Neta)
# Set the B matrix for each element
He[:, 0, :] = N
Be[:, 0, :] = Nx
Be[:, 1, :] = Ny
Ce += np.einsum("n,nij,nil -> njl", detJ, He, He)
Ae += np.einsum("n,nij,nil -> njl", detJ * r0**2, Be, Be)
# Finish the computation of the Ae matrices
Ae += Ce
A = sparse.coo_matrix((Ae.flatten(), (i_index, j_index)))
A = A.tocsc()
self.A = linalg.factorized(A)
B = sparse.coo_matrix((Ce.flatten(), (i_index, j_index)))
self.B = B.tocsr()
self.BT = self.B.transpose()
return
def apply(self, x):
if self.F is not None:
rho = self.F.dot(x)
else:
rho = self.A(self.B.dot(x))
if self.projection:
denom = np.tanh(self.beta * self.eta) + np.tanh(
self.beta * (1.0 - self.eta)
)
rho = (
np.tanh(self.beta * self.eta) + np.tanh(self.beta * (rho - self.eta))
) / denom
return rho
def applyGradient(self, g, x, rho=None):
if self.projection:
if self.F is not None:
rho = self.F.dot(x)
else:
rho = self.A(self.B.dot(x))
denom = np.tanh(self.beta * self.eta) + np.tanh(
self.beta * (1.0 - self.eta)
)
grad = g * (
(self.beta / denom) * 1.0 / np.cosh(self.beta * (rho - self.eta)) ** 2
)
else:
grad = g
if self.F is not None:
return self.FT.dot(grad)
else:
return self.BT.dot(self.A(grad))
def plot(self, u, ax=None, **kwargs):
"""
Create a plot
"""
# Create the triangles
triangles = np.zeros((2 * self.nelems, 3), dtype=int)
triangles[: self.nelems, 0] = self.conn[:, 0]
triangles[: self.nelems, 1] = self.conn[:, 1]
triangles[: self.nelems, 2] = self.conn[:, 2]
triangles[self.nelems :, 0] = self.conn[:, 0]
triangles[self.nelems :, 1] = self.conn[:, 2]
triangles[self.nelems :, 2] = self.conn[:, 3]
# Create the triangulation object
tri_obj = tri.Triangulation(self.X[:, 0], self.X[:, 1], triangles)
if ax is None:
fig, ax = plt.subplots()
# Set the aspect ratio equal
ax.set_aspect("equal")
# Create the contour plot
ax.tricontourf(tri_obj, u, **kwargs)
return
class TopologyAnalysis:
def __init__(
self,
fltr,
conn,
X,
bcs,
forces={},
m=None,
D_index=None,
E=10.0 * 1e6,
nu=0.3,
ptype_K="ramp",
ptype_M="ramp",
rho0_K=1e-3,
rho0_M=1e-7,
p=3.0,
q=5.0,
density=1.0,
epsilon=0.3,
assume_same_element=False,
):
self.ptype_K = ptype_K.lower()
self.ptype_M = ptype_M.lower()
self.rho0_K = rho0_K
self.rho0_M = rho0_M
self.fltr = fltr
self.conn = np.array(conn)
self.X = np.array(X)
self.p = p
self.q = q
self.density = density
self.epsilon = epsilon
self.assume_same_element = assume_same_element
# C1 continuous mass penalization coefficients if ptype_M == msimp
self.simp_c1 = 6e5
self.simp_c2 = -5e6
self.nelems = self.conn.shape[0]
self.nnodes = int(np.max(self.conn)) + 1
self.nvars = 2 * self.nnodes
self.D_index = D_index
self.K0 = None
self.M0 = None
self.Q = None
self.eigs = None
# Compute the constitutivve matrix
self.C0 = E * np.array(
[[1.0, nu, 0.0], [nu, 1.0, 0.0], [0.0, 0.0, 0.5 * (1.0 - nu)]]
)
self.C0 *= 1.0 / (1.0 - nu**2)
self.reduced = self._compute_reduced_variables(self.nvars, bcs)
self.f = self._compute_forces(self.nvars, forces)
# Set up the i-j indices for the matrix - these are the row
# and column indices in the stiffness matrix
self.var = np.zeros((self.conn.shape[0], 8), dtype=int)
self.var[:, ::2] = 2 * self.conn
self.var[:, 1::2] = 2 * self.conn + 1
i = []
j = []
for index in range(self.nelems):
for ii in self.var[index, :]:
for jj in self.var[index, :]:
i.append(ii)
j.append(jj)
# Convert the lists into numpy arrays
self.i = np.array(i, dtype=int)
self.j = np.array(j, dtype=int)
return
def _compute_reduced_variables(self, nvars, bcs):
"""
Compute the reduced set of variables
"""
reduced = list(range(nvars))
# For each node that is in the boundary condition dictionary
for node in bcs:
uv_list = bcs[node]
# For each index in the boundary conditions (corresponding to
# either a constraint on u and/or constraint on v
for index in uv_list:
var = 2 * node + index
reduced.remove(var)
return reduced
def _compute_forces(self, nvars, forces):
"""
Unpack the dictionary containing the forces
"""
f = np.zeros(nvars)
for node in forces:
f[2 * node] += forces[node][0]
f[2 * node + 1] += forces[node][1]
return f
def set_K0(self, K0):
self.K0 = K0
return
def set_M0(self, M0):
self.M0 = M0
return
@time_this
def assemble_stiffness_matrix(self, rho):
"""
Assemble the stiffness matrix
"""
# Average the density to get the element-wise density
rhoE = 0.25 * (
rho[self.conn[:, 0]]
+ rho[self.conn[:, 1]]
+ rho[self.conn[:, 2]]
+ rho[self.conn[:, 3]]
)
# Compute the element stiffnesses
if self.ptype_K == "simp":
C = np.outer(rhoE**self.p + self.rho0_K, self.C0)
else: # ramp
C = np.outer(rhoE / (1.0 + self.q * (1.0 - rhoE)) + self.rho0_K, self.C0)
C = C.reshape((self.nelems, 3, 3))
# Compute the element stiffness matrix
gauss_pts = [-1.0 / np.sqrt(3.0), 1.0 / np.sqrt(3.0)]
# Assemble all of the the 8 x 8 element stiffness matrix
Ke = np.zeros((self.nelems, 8, 8))
if self.assume_same_element:
Be_ = np.zeros((3, 8))
# Compute the x and y coordinates of the first element
xe_ = self.X[self.conn[0], 0]
ye_ = self.X[self.conn[0], 1]
for j in range(2):
for i in range(2):
xi = gauss_pts[i]
eta = gauss_pts[j]
detJ = _populate_Be_single(xi, eta, xe_, ye_, Be_)
# This is a fancy (and fast) way to compute the element matrices
Ke += detJ * np.einsum("ij,nik,kl -> njl", Be_, C, Be_)
else:
Be = np.zeros((self.nelems, 3, 8))
# Compute the x and y coordinates of each element
xe = self.X[self.conn, 0]
ye = self.X[self.conn, 1]
for j in range(2):
for i in range(2):
xi = gauss_pts[i]
eta = gauss_pts[j]
detJ = _populate_Be(self.nelems, xi, eta, xe, ye, Be)
# This is a fancy (and fast) way to compute the element matrices
Ke += np.einsum("n,nij,nik,nkl -> njl", detJ, Be, C, Be)
K = sparse.coo_matrix((Ke.flatten(), (self.i, self.j)))
K = K.tocsr()
if self.K0 is not None:
K += self.K0
return K
@time_this
def stiffness_matrix_derivative(self, rho, psi, u):
"""
Compute the derivative of the stiffness matrix times the vectors psi and u
"""
# Average the density to get the element-wise density
rhoE = 0.25 * (
rho[self.conn[:, 0]]
+ rho[self.conn[:, 1]]
+ rho[self.conn[:, 2]]
+ rho[self.conn[:, 3]]
)
dfdC = np.zeros((self.nelems, 3, 3))
# Compute the element stiffness matrix
gauss_pts = [-1.0 / np.sqrt(3.0), 1.0 / np.sqrt(3.0)]
# The element-wise variables
ue = np.zeros((self.nelems, 8))
psie = np.zeros((self.nelems, 8))
ue[:, ::2] = u[2 * self.conn]
ue[:, 1::2] = u[2 * self.conn + 1]
psie[:, ::2] = psi[2 * self.conn]
psie[:, 1::2] = psi[2 * self.conn + 1]
if self.assume_same_element:
Be_ = np.zeros((3, 8))
xe_ = self.X[self.conn[0], 0]
ye_ = self.X[self.conn[0], 1]
for j in range(2):
for i in range(2):
xi = gauss_pts[i]
eta = gauss_pts[j]
detJ = _populate_Be_single(xi, eta, xe_, ye_, Be_)
dfdC += detJ * np.einsum("im,jl,nm,nl -> nij", Be_, Be_, psie, ue)
else:
Be = np.zeros((self.nelems, 3, 8))
xe = self.X[self.conn, 0]
ye = self.X[self.conn, 1]
for j in range(2):
for i in range(2):
xi = gauss_pts[i]
eta = gauss_pts[j]
detJ = _populate_Be(self.nelems, xi, eta, xe, ye, Be)
dfdC += np.einsum("n,nim,njl,nm,nl -> nij", detJ, Be, Be, psie, ue)
dfdrhoE = np.zeros(self.nelems)
for i in range(3):
for j in range(3):
dfdrhoE[:] += self.C0[i, j] * dfdC[:, i, j]
if self.ptype_K == "simp":
dfdrhoE[:] *= self.p * rhoE ** (self.p - 1.0)
else: # ramp
dfdrhoE[:] *= (1.0 + self.q) / (1.0 + self.q * (1.0 - rhoE)) ** 2
dfdrho = np.zeros(self.nnodes)
for i in range(4):
np.add.at(dfdrho, self.conn[:, i], dfdrhoE)
dfdrho *= 0.25
return dfdrho
@time_this
def assemble_mass_matrix(self, rho):
"""
Assemble the mass matrix
"""
# Average the density to get the element-wise density
rhoE = 0.25 * (
rho[self.conn[:, 0]]
+ rho[self.conn[:, 1]]
+ rho[self.conn[:, 2]]
+ rho[self.conn[:, 3]]
)
# Compute the element density
if self.ptype_M == "msimp":
nonlin = self.simp_c1 * rhoE**6.0 + self.simp_c2 * rhoE**7.0
cond = (rhoE > 0.1).astype(int)
density = self.density * (rhoE * cond + nonlin * (1 - cond))
elif self.ptype_M == "ramp":
density = self.density * (
(self.q + 1.0) * rhoE / (1 + self.q * rhoE) + self.rho0_M
)
else: # linear
density = self.density * rhoE
# Compute the element stiffness matrix
gauss_pts = [-1.0 / np.sqrt(3.0), 1.0 / np.sqrt(3.0)]
# Assemble all of the the 8 x 8 element mass matrices
Me = np.zeros((self.nelems, 8, 8))
if self.assume_same_element:
He_ = np.zeros((2, 8))
# Compute the x and y coordinates of each element
xe_ = self.X[self.conn[0], 0]
ye_ = self.X[self.conn[0], 1]
for j in range(2):
for i in range(2):
xi = gauss_pts[i]
eta = gauss_pts[j]
detJ = _populate_He_single(xi, eta, xe_, ye_, He_)
# This is a fancy (and fast) way to compute the element matrices
Me += np.einsum("n,ij,il -> njl", density * detJ, He_, He_)
else:
He = np.zeros((self.nelems, 2, 8))
# Compute the x and y coordinates of each element
xe = self.X[self.conn, 0]
ye = self.X[self.conn, 1]
for j in range(2):
for i in range(2):
xi = gauss_pts[i]
eta = gauss_pts[j]
detJ = _populate_He(self.nelems, xi, eta, xe, ye, He)
# This is a fancy (and fast) way to compute the element matrices
Me += np.einsum("n,nij,nil -> njl", density * detJ, He, He)
M = sparse.coo_matrix((Me.flatten(), (self.i, self.j)))
M = M.tocsr()
if self.M0 is not None:
M += self.M0
return M
@time_this
def mass_matrix_derivative(self, rho, u, v):
"""
Compute the derivative of the mass matrix
"""
# Average the density to get the element-wise density
rhoE = 0.25 * (
rho[self.conn[:, 0]]
+ rho[self.conn[:, 1]]
+ rho[self.conn[:, 2]]
+ rho[self.conn[:, 3]]
)
# Derivative with respect to element density
dfdrhoE = np.zeros(self.nelems)
# Compute the element stiffness matrix
gauss_pts = [-1.0 / np.sqrt(3.0), 1.0 / np.sqrt(3.0)]
# The element-wise variables
ue = np.zeros((self.nelems, 8))
ve = np.zeros((self.nelems, 8))
ue[:, ::2] = u[2 * self.conn]
ue[:, 1::2] = u[2 * self.conn + 1]
ve[:, ::2] = v[2 * self.conn]
ve[:, 1::2] = v[2 * self.conn + 1]
if self.assume_same_element:
# The interpolation matrix for each element
He_ = np.zeros((2, 8))
# Compute the x and y coordinates of each element
xe_ = self.X[self.conn[0], 0]
ye_ = self.X[self.conn[0], 1]
for j in range(2):
for i in range(2):
xi = gauss_pts[i]
eta = gauss_pts[j]
detJ = _populate_He_single(xi, eta, xe_, ye_, He_)
eu_ = np.einsum("ij,nj -> ni", He_, ue)
ev_ = np.einsum("ij,nj -> ni", He_, ve)
dfdrhoE += detJ * np.einsum("ni,ni -> n", eu_, ev_)
else:
# The interpolation matrix for each element
He = np.zeros((self.nelems, 2, 8))
# Compute the x and y coordinates of each element
xe = self.X[self.conn, 0]
ye = self.X[self.conn, 1]
for j in range(2):
for i in range(2):
xi = gauss_pts[i]
eta = gauss_pts[j]
detJ = _populate_He(self.nelems, xi, eta, xe, ye, He)
eu = np.einsum("nij,nj -> ni", He, ue)
ev = np.einsum("nij,nj -> ni", He, ve)
dfdrhoE += np.einsum("n,ni,ni -> n", detJ, eu, ev)
if self.ptype_M == "msimp":
dnonlin = (
6.0 * self.simp_c1 * rhoE**5.0 + 7.0 * self.simp_c2 * rhoE**6.0
)
cond = (rhoE > 0.1).astype(int)
dfdrhoE[:] *= self.density * (cond + dnonlin * (1 - cond))
elif self.ptype_M == "ramp":
dfdrhoE[:] *= self.density * (1.0 + self.q) / (1.0 + self.q * rhoE) ** 2
else: # linear
dfdrhoE[:] *= self.density
dfdrho = np.zeros(self.nnodes)
for i in range(4):
np.add.at(dfdrho, self.conn[:, i], dfdrhoE)
dfdrho *= 0.25
return dfdrho
def reduce_vector(self, forces):
"""
Eliminate essential boundary conditions from the vector
"""
return forces[self.reduced]
def reduce_matrix(self, matrix):
"""
Eliminate essential boundary conditions from the matrix
"""
temp = matrix[self.reduced, :]
return temp[:, self.reduced]
def full_vector(self, vec):
"""
Transform from a reduced vector without dirichlet BCs to the full vector
"""
temp = np.zeros(self.nvars)
temp[self.reduced] = vec[:]
return temp
def solve(self, x):
"""
Perform a linear static analysis
"""
# Compute the density at each node
rho = self.fltr.apply(x)
K = self.assemble_stiffness_matrix(rho)
Kr = self.reduce_matrix(K)
fr = self.reduce_vector(self.f)
ur = sparse.linalg.spsolve(Kr, fr)
u = self.full_vector(ur)
return u
def compliance(self, x):
self.u = self.solve(x)
return self.f.dot(self.u)
def compliance_gradient(self, x):
rho = self.fltr.apply(x)
dfdrho = -1.0 * self.stiffness_matrix_derivative(rho, self.u, self.u)
return self.fltr.applyGradient(dfdrho, x)
def eval_area(self, x):
rho = self.fltr.apply(x)
# Average the density to get the element-wise density
rhoE = 0.25 * (
rho[self.conn[:, 0]]
+ rho[self.conn[:, 1]]
+ rho[self.conn[:, 2]]
+ rho[self.conn[:, 3]]
)
# Quadrature points
gauss_pts = [-1.0 / np.sqrt(3.0), 1.0 / np.sqrt(3.0)]
# Jacobian transformation
J = np.zeros((self.nelems, 2, 2))
# Compute the x and y coordinates of each element
xe = self.X[self.conn, 0]
ye = self.X[self.conn, 1]
area = 0.0
for j in range(2):
for i in range(2):
xi = gauss_pts[i]
eta = gauss_pts[j]
Nxi = 0.25 * np.array(
[-(1.0 - eta), (1.0 - eta), (1.0 + eta), -(1.0 + eta)]
)
Neta = 0.25 * np.array(
[-(1.0 - xi), -(1.0 + xi), (1.0 + xi), (1.0 - xi)]
)
# Compute the Jacobian transformation at each quadrature points
J[:, 0, 0] = np.dot(xe, Nxi)
J[:, 1, 0] = np.dot(ye, Nxi)
J[:, 0, 1] = np.dot(xe, Neta)
J[:, 1, 1] = np.dot(ye, Neta)
# Compute the inverse of the Jacobian
detJ = J[:, 0, 0] * J[:, 1, 1] - J[:, 0, 1] * J[:, 1, 0]
area += np.sum(detJ * rhoE)
return area
def eval_area_gradient(self, x):
dfdrhoE = np.zeros(self.nelems)
# Quadrature points
gauss_pts = [-1.0 / np.sqrt(3.0), 1.0 / np.sqrt(3.0)]
# Jacobian transformation
J = np.zeros((self.nelems, 2, 2))
# Compute the x and y coordinates of each element
xe = self.X[self.conn, 0]
ye = self.X[self.conn, 1]
for j in range(2):
for i in range(2):
xi = gauss_pts[i]
eta = gauss_pts[j]
Nxi = 0.25 * np.array(
[-(1.0 - eta), (1.0 - eta), (1.0 + eta), -(1.0 + eta)]
)
Neta = 0.25 * np.array(
[-(1.0 - xi), -(1.0 + xi), (1.0 + xi), (1.0 - xi)]
)
# Compute the Jacobian transformation at each quadrature points
J[:, 0, 0] = np.dot(xe, Nxi)
J[:, 1, 0] = np.dot(ye, Nxi)
J[:, 0, 1] = np.dot(xe, Neta)
J[:, 1, 1] = np.dot(ye, Neta)
# Compute the inverse of the Jacobian
detJ = J[:, 0, 0] * J[:, 1, 1] - J[:, 0, 1] * J[:, 1, 0]
dfdrhoE[:] += detJ
dfdrho = np.zeros(self.nnodes)
for i in range(4):
np.add.at(dfdrho, self.conn[:, i], dfdrhoE)
dfdrho *= 0.25
return self.fltr.applyGradient(dfdrho, x)
@time_this
def solve_eigenvalue_problem(
self, x, k=5, sigma=0.0, nodal_sols=None, nodal_vecs=None
):
"""
Compute the k-th smallest natural frequencies
Populate nodal_sols and cell_sols if provided
"""
if k > len(self.reduced):
k = len(self.reduced)
# Compute the density at each node
rho = self.fltr.apply(x)
K = self.assemble_stiffness_matrix(rho)
Kr = self.reduce_matrix(K)
M = self.assemble_mass_matrix(rho)
Mr = self.reduce_matrix(M)
# Find the eigenvalues closest to zero. This uses a shift and
# invert strategy around sigma = 0, which means that the largest
# magnitude values are closest to zero.
if k == len(self.reduced):
eigs, Qr = eigh(Kr.todense(), Mr.todense())
else:
eigs, Qr = sparse.linalg.eigsh(
Kr, M=Mr, k=k, sigma=sigma, which="LM", tol=1e-10
)
Q = np.zeros((self.nvars, k))
for i in range(k):
Q[self.reduced, i] = Qr[:, i]
# Save vtk output data
if nodal_sols is not None:
nodal_sols["x"] = np.array(x)
nodal_sols["rho"] = np.array(rho)
if nodal_vecs is not None:
for i in range(k):
nodal_vecs["phi%d" % i] = [Q[0::2, i], Q[1::2, i]]
# Save the eigenvalues and eigenvectors
self.eigs = eigs
self.Q = Q
# Return natural frequencies
omega = np.sqrt(self.eigs)
return omega
def ks_omega(self, ks_rho=100.0):
"""
Compute the ks minimum eigenvalue
"""
omega = np.sqrt(self.eigs)
c = np.min(omega)
eta = np.exp(-ks_rho * (omega - c))
a = np.sum(eta)
ks_min = c - np.log(a) / ks_rho