-
Notifications
You must be signed in to change notification settings - Fork 638
/
filters.py
1038 lines (868 loc) · 34 KB
/
filters.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
"""
General filter functions to be used in other projection and morphological transform routines.
"""
import meep as mp
import numpy as np
from autograd import numpy as npa
from scipy import signal, special
def _centered(arr, newshape):
"""Helper function that reformats the padded array of the fft filter operation.
Borrowed from scipy:
https://github.com/scipy/scipy/blob/v1.4.1/scipy/signal/signaltools.py#L263-L270
"""
# Return the center newshape portion of the array.
newshape = np.asarray(newshape)
currshape = np.array(arr.shape)
startind = (currshape - newshape) // 2
endind = startind + newshape
myslice = [slice(startind[k], endind[k]) for k in range(len(endind))]
return arr[tuple(myslice)]
def _proper_pad(arr, pad_to):
"""Return a zero-padded/expanded version of filter arr (≈1/4 of kernel) to size pad_to, for convolution.
Parameters
----------
arr : 2d input array representing the nonnegative-coordinate ≈1/4 of a filter kernel.
pad_to : 1d array composed of two integers indicating the total size to be padded to.
"""
pad_size = pad_to - 2 * np.array(arr.shape) + 1
top = np.zeros((pad_size[0], arr.shape[1]))
bottom = np.zeros((pad_size[0], arr.shape[1] - 1))
middle = np.zeros((pad_to[0], pad_size[1]))
top_left = arr[:, :]
top_right = npa.flipud(arr[1:, :])
bottom_left = npa.fliplr(arr[:, 1:])
bottom_right = npa.flipud(
npa.fliplr(arr[1:, 1:])
) # equivalent to flip, but flip is incompatible with autograd
return npa.concatenate(
(
npa.concatenate((top_left, top, top_right)),
middle,
npa.concatenate((bottom_left, bottom, bottom_right)),
),
axis=1,
)
def _edge_pad(arr, pad):
# fill sides
left = npa.tile(arr[0, :], (pad[0][0], 1)) # left side
right = npa.tile(arr[-1, :], (pad[0][1], 1)) # right side
top = npa.tile(arr[:, 0], (pad[1][0], 1)).transpose() # top side
bottom = npa.tile(arr[:, -1], (pad[1][1], 1)).transpose() # bottom side)
# fill corners
top_left = npa.tile(arr[0, 0], (pad[0][0], pad[1][0])) # top left
top_right = npa.tile(arr[-1, 0], (pad[0][1], pad[1][0])) # top right
bottom_left = npa.tile(arr[0, -1], (pad[0][0], pad[1][1])) # bottom left
bottom_right = npa.tile(arr[-1, -1], (pad[0][1], pad[1][1])) # bottom right
if pad[0][0] > 0 and pad[0][1] > 0 and pad[1][0] > 0 and pad[1][1] > 0:
return npa.concatenate(
(
npa.concatenate((top_left, top, top_right)),
npa.concatenate((left, arr, right)),
npa.concatenate((bottom_left, bottom, bottom_right)),
),
axis=1,
)
elif pad[0][0] == 0 and pad[0][1] == 0 and pad[1][0] > 0 and pad[1][1] > 0:
return npa.concatenate((top, arr, bottom), axis=1)
elif pad[0][0] > 0 and pad[0][1] > 0 and pad[1][0] == 0 and pad[1][1] == 0:
return npa.concatenate((left, arr, right), axis=0)
elif pad[0][0] == 0 and pad[0][1] == 0 and pad[1][0] == 0 and pad[1][1] == 0:
return arr
else:
raise ValueError("At least one of the padding numbers is invalid.")
def simple_2d_filter(x, h, periodic_axes=None):
"""A simple 2d filter algorithm that is differentiable with autograd.
Uses a 2D fft approach since it is typically faster and preserves the shape
of the input and output arrays.
The ffts pad the operation to prevent any circular convolution garbage.
Parameters
----------
x : array_like (2D)
Input array to be filtered. Must be 2D.
h : array_like (2D)
Filter kernel (before the DFT). Must be same size as `x`
periodic_axes: array_like (1D)
List of axes (x, y = 0, 1) that are to be treated as periodic (default is none: all axes are non-periodic)
Returns
-------
array_like (2D)
The output of the 2d convolution.
"""
(sx, sy) = x.shape
if periodic_axes is None:
h = _proper_pad(h, 3 * np.array([sx, sy]))
x = _edge_pad(x, ((sx, sx), (sy, sy)))
else:
(kx, ky) = h.shape
npx = int(
np.ceil((2 * kx - 1) / sx)
) # 2*kx-1 is the size of a complete kernel in the x direction
npy = int(
np.ceil((2 * ky - 1) / sy)
) # 2*ky-1 is the size of a complete kernel in the y direction
if npx % 2 == 0:
npx += 1 # Ensure npx is an odd number
if npy % 2 == 0:
npy += 1 # Ensure npy is an odd number
# Repeat the design pattern in periodic directions according to the kernel size
x = npa.tile(
x, (npx if 0 in periodic_axes else 1, npy if 1 in periodic_axes else 1)
)
npadx = 0 if 0 in periodic_axes else sx
npady = 0 if 1 in periodic_axes else sy
x = _edge_pad(
x, ((npadx, npadx), (npady, npady))
) # pad only in nonperiodic directions
h = _proper_pad(
h,
np.array(
[
npx * sx if 0 in periodic_axes else 3 * sx,
npy * sy if 1 in periodic_axes else 3 * sy,
]
),
)
h = h / npa.sum(h) # Normalize the kernel
return _centered(
npa.real(npa.fft.ifft2(npa.fft.fft2(x) * npa.fft.fft2(h))), (sx, sy)
)
def cylindrical_filter(x, radius, Lx, Ly, resolution, periodic_axes=None):
"""A uniform cylindrical filter [1]. Typically allows for sharper transitions.
Parameters
----------
x : array_like (2D)
Design parameters
radius : float
Filter radius (in "meep units")
Lx : float
Length of design region in X direction (in "meep units")
Ly : float
Length of design region in Y direction (in "meep units")
resolution : int
Resolution of the design grid (not the meep simulation resolution)
periodic_axes: array_like (1D)
List of axes (x, y = 0, 1) that are to be treated as periodic (default is none: all axes are non-periodic)
Returns
-------
array_like (2D)
Filtered design parameters.
References
----------
[1] Lazarov, B. S., Wang, F., & Sigmund, O. (2016). Length scale and manufacturability in
density-based topology optimization. Archive of Applied Mechanics, 86(1-2), 189-218.
"""
Nx = int(round(Lx * resolution))
Ny = int(round(Ly * resolution))
x = x.reshape(Nx, Ny) # Ensure the input is 2D
xv = np.arange(0, Lx / 2, 1 / resolution)
yv = np.arange(0, Ly / 2, 1 / resolution)
# If the design pattern is periodic in a direction,
# the size of the kernel in that direction needs to be adjusted according to the filter radius.
if periodic_axes is not None:
periodic_axes = np.array(periodic_axes)
if 0 in periodic_axes:
xv = np.arange(0, np.ceil(2 * radius / Lx) * Lx / 2, 1 / resolution)
if 1 in periodic_axes:
yv = np.arange(0, np.ceil(2 * radius / Ly) * Ly / 2, 1 / resolution)
X, Y = np.meshgrid(xv, yv, sparse=True, indexing="ij")
h = np.where(X**2 + Y**2 < radius**2, 1, 0)
# Filter the response
return simple_2d_filter(x, h, periodic_axes)
def conic_filter(x, radius, Lx, Ly, resolution, periodic_axes=None):
"""A linear conic filter, also known as a "Hat" filter in the literature [1].
Parameters
----------
x : array_like (2D)
Design parameters
radius : float
Filter radius (in "meep units")
Lx : float
Length of design region in X direction (in "meep units")
Ly : float
Length of design region in Y direction (in "meep units")
resolution : int
Resolution of the design grid (not the meep simulation resolution)
periodic_axes: array_like (1D)
List of axes (x, y = 0, 1) that are to be treated as periodic (default is none: all axes are non-periodic)
Returns
-------
array_like (2D)
Filtered design parameters.
References
----------
[1] Lazarov, B. S., Wang, F., & Sigmund, O. (2016). Length scale and manufacturability in
density-based topology optimization. Archive of Applied Mechanics, 86(1-2), 189-218.
"""
Nx = int(round(Lx * resolution))
Ny = int(round(Ly * resolution))
x = x.reshape(Nx, Ny) # Ensure the input is 2D
xv = np.arange(0, Lx / 2, 1 / resolution)
yv = np.arange(0, Ly / 2, 1 / resolution)
# If the design pattern is periodic in a direction,
# the size of the kernel in that direction needs to be adjusted according to the filter radius.
if periodic_axes is not None:
periodic_axes = np.array(periodic_axes)
if 0 in periodic_axes:
xv = np.arange(0, np.ceil(2 * radius / Lx) * Lx / 2, 1 / resolution)
if 1 in periodic_axes:
yv = np.arange(0, np.ceil(2 * radius / Ly) * Ly / 2, 1 / resolution)
X, Y = np.meshgrid(xv, yv, sparse=True, indexing="ij")
h = np.where(
X**2 + Y**2 < radius**2, (1 - np.sqrt(abs(X**2 + Y**2)) / radius), 0
)
# Filter the response
return simple_2d_filter(x, h, periodic_axes)
def gaussian_filter(x, sigma, Lx, Ly, resolution, periodic_axes=None):
"""A simple gaussian filter of the form exp(-x **2 / sigma ** 2) [1].
Parameters
----------
x : array_like (2D)
Design parameters
sigma : float
Filter radius (in "meep units")
Lx : float
Length of design region in X direction (in "meep units")
Ly : float
Length of design region in Y direction (in "meep units")
resolution : int
Resolution of the design grid (not the meep simulation resolution)
periodic_axes: array_like (1D)
List of axes (x, y = 0, 1) that are to be treated as periodic (default is none: all axes are non-periodic)
Returns
-------
array_like (2D)
Filtered design parameters.
References
----------
[1] Wang, E. W., Sell, D., Phan, T., & Fan, J. A. (2019). Robust design of
topology-optimized metasurfaces. Optical Materials Express, 9(2), 469-482.
"""
Nx = int(round(Lx * resolution))
Ny = int(round(Ly * resolution))
x = x.reshape(Nx, Ny) # Ensure the input is 2D
xv = np.arange(0, Lx / 2, 1 / resolution)
yv = np.arange(0, Ly / 2, 1 / resolution)
# If the design pattern is periodic in a direction,
# the size of the kernel in that direction needs to be adjusted according to 3σ.
if periodic_axes is not None:
periodic_axes = np.array(periodic_axes)
if 0 in periodic_axes:
xv = np.arange(0, np.ceil(6 * sigma / Lx) * Lx / 2, 1 / resolution)
if 1 in periodic_axes:
yv = np.arange(0, np.ceil(6 * sigma / Ly) * Ly / 2, 1 / resolution)
X, Y = np.meshgrid(xv, yv, sparse=True, indexing="ij")
h = np.exp(-(X**2 + Y**2) / sigma**2)
# Filter the response
return simple_2d_filter(x, h, periodic_axes)
"""
# ------------------------------------------------------------------------------------ #
Erosion and dilation operators
"""
def exponential_erosion(x, radius, beta, Lx, Ly, resolution, periodic_axes=None):
"""Performs and exponential erosion operation.
Parameters
----------
x : array_like
Design parameters
radius : float
Filter radius (in "meep units")
beta : float
Thresholding parameter
Lx : float
Length of design region in X direction (in "meep units")
Ly : float
Length of design region in Y direction (in "meep units")
resolution : int
Resolution of the design grid (not the meep simulation resolution)
periodic_axes: array_like (1D)
List of axes (x, y = 0, 1) that are to be treated as periodic (default is none: all axes are non-periodic)
Returns
-------
array_like
Eroded design parameters.
References
----------
[1] Sigmund, O. (2007). Morphology-based black and white filters for topology optimization.
Structural and Multidisciplinary Optimization, 33(4-5), 401-424.
[2] Schevenels, M., & Sigmund, O. (2016). On the implementation and effectiveness of
morphological close-open and open-close filters for topology optimization. Structural
and Multidisciplinary Optimization, 54(1), 15-21.
"""
x_hat = npa.exp(beta * (1 - x))
return (
1
- npa.log(
cylindrical_filter(
x_hat, radius, Lx, Ly, resolution, periodic_axes
).flatten()
)
/ beta
)
def exponential_dilation(x, radius, beta, Lx, Ly, resolution, periodic_axes=None):
"""Performs a exponential dilation operation.
Parameters
----------
x : array_like
Design parameters
radius : float
Filter radius (in "meep units")
beta : float
Thresholding parameter
Lx : float
Length of design region in X direction (in "meep units")
Ly : float
Length of design region in Y direction (in "meep units")
resolution : int
Resolution of the design grid (not the meep simulation resolution)
periodic_axes: array_like (1D)
List of axes (x, y = 0, 1) that are to be treated as periodic (default is none: all axes are non-periodic)
Returns
-------
array_like
Dilated design parameters.
References
----------
[1] Sigmund, O. (2007). Morphology-based black and white filters for topology optimization.
Structural and Multidisciplinary Optimization, 33(4-5), 401-424.
[2] Schevenels, M., & Sigmund, O. (2016). On the implementation and effectiveness of
morphological close-open and open-close filters for topology optimization. Structural
and Multidisciplinary Optimization, 54(1), 15-21.
"""
x_hat = npa.exp(beta * x)
return (
npa.log(
cylindrical_filter(
x_hat, radius, Lx, Ly, resolution, periodic_axes
).flatten()
)
/ beta
)
def heaviside_erosion(x, radius, beta, Lx, Ly, resolution, periodic_axes=None):
"""Performs a heaviside erosion operation.
Parameters
----------
x : array_like
Design parameters
radius : float
Filter radius (in "meep units")
beta : float
Thresholding parameter
Lx : float
Length of design region in X direction (in "meep units")
Ly : float
Length of design region in Y direction (in "meep units")
resolution : int
Resolution of the design grid (not the meep simulation resolution)
periodic_axes: array_like (1D)
List of axes (x, y = 0, 1) that are to be treated as periodic (default is none: all axes are non-periodic)
Returns
-------
array_like
Eroded design parameters.
References
----------
[1] Guest, J. K., Prévost, J. H., & Belytschko, T. (2004). Achieving minimum length scale in topology
optimization using nodal design variables and projection functions. International journal for
numerical methods in engineering, 61(2), 238-254.
"""
x_hat = cylindrical_filter(x, radius, Lx, Ly, resolution, periodic_axes).flatten()
return npa.exp(-beta * (1 - x_hat)) + npa.exp(-beta) * (1 - x_hat)
def heaviside_dilation(x, radius, beta, Lx, Ly, resolution, periodic_axes=None):
"""Performs a heaviside dilation operation.
Parameters
----------
x : array_like
Design parameters
radius : float
Filter radius (in "meep units")
beta : float
Thresholding parameter
Lx : float
Length of design region in X direction (in "meep units")
Ly : float
Length of design region in Y direction (in "meep units")
resolution : int
Resolution of the design grid (not the meep simulation resolution)
periodic_axes: array_like (1D)
List of axes (x, y = 0, 1) that are to be treated as periodic (default is none: all axes are non-periodic)
Returns
-------
array_like
Dilated design parameters.
References
----------
[1] Guest, J. K., Prévost, J. H., & Belytschko, T. (2004). Achieving minimum length scale in topology
optimization using nodal design variables and projection functions. International journal for
numerical methods in engineering, 61(2), 238-254.
"""
x_hat = cylindrical_filter(x, radius, Lx, Ly, resolution, periodic_axes).flatten()
return 1 - npa.exp(-beta * x_hat) + npa.exp(-beta) * x_hat
def geometric_erosion(x, radius, alpha, Lx, Ly, resolution, periodic_axes=None):
"""Performs a geometric erosion operation.
Parameters
----------
x : array_like
Design parameters
radius : float
Filter radius (in "meep units")
beta : float
Thresholding parameter
Lx : float
Length of design region in X direction (in "meep units")
Ly : float
Length of design region in Y direction (in "meep units")
resolution : int
Resolution of the design grid (not the meep simulation resolution)
periodic_axes: array_like (1D)
List of axes (x, y = 0, 1) that are to be treated as periodic (default is none: all axes are non-periodic)
Returns
-------
array_like
Eroded design parameters.
References
----------
[1] Svanberg, K., & Svärd, H. (2013). Density filters for topology optimization based on the
Pythagorean means. Structural and Multidisciplinary Optimization, 48(5), 859-875.
"""
x_hat = npa.log(x + alpha)
return (
npa.exp(
cylindrical_filter(x_hat, radius, Lx, Ly, resolution, periodic_axes)
).flatten()
- alpha
)
def geometric_dilation(x, radius, alpha, Lx, Ly, resolution, periodic_axes=None):
"""Performs a geometric dilation operation.
Parameters
----------
x : array_like
Design parameters
radius : float
Filter radius (in "meep units")
beta : float
Thresholding parameter
Lx : float
Length of design region in X direction (in "meep units")
Ly : float
Length of design region in Y direction (in "meep units")
resolution : int
Resolution of the design grid (not the meep simulation resolution)
periodic_axes: array_like (1D)
List of axes (x, y = 0, 1) that are to be treated as periodic (default is none: all axes are non-periodic)
Returns
-------
array_like
Dilated design parameters.
References
----------
[1] Svanberg, K., & Svärd, H. (2013). Density filters for topology optimization based on the
Pythagorean means. Structural and Multidisciplinary Optimization, 48(5), 859-875.
"""
x_hat = npa.log(1 - x + alpha)
return (
-npa.exp(
cylindrical_filter(x_hat, radius, Lx, Ly, resolution, periodic_axes)
).flatten()
+ alpha
+ 1
)
def harmonic_erosion(x, radius, alpha, Lx, Ly, resolution, periodic_axes=None):
"""Performs a harmonic erosion operation.
Parameters
----------
x : array_like
Design parameters
radius : float
Filter radius (in "meep units")
beta : float
Thresholding parameter
Lx : float
Length of design region in X direction (in "meep units")
Ly : float
Length of design region in Y direction (in "meep units")
resolution : int
Resolution of the design grid (not the meep simulation resolution)
periodic_axes: array_like (1D)
List of axes (x, y = 0, 1) that are to be treated as periodic (default is none: all axes are non-periodic)
Returns
-------
array_like
Eroded design parameters.
References
----------
[1] Svanberg, K., & Svärd, H. (2013). Density filters for topology optimization based on the
Pythagorean means. Structural and Multidisciplinary Optimization, 48(5), 859-875.
"""
x_hat = 1 / (x + alpha)
return (
1
/ cylindrical_filter(x_hat, radius, Lx, Ly, resolution, periodic_axes).flatten()
- alpha
)
def harmonic_dilation(x, radius, alpha, Lx, Ly, resolution, periodic_axes=None):
"""Performs a harmonic dilation operation.
Parameters
----------
x : array_like
Design parameters
radius : float
Filter radius (in "meep units")
beta : float
Thresholding parameter
Lx : float
Length of design region in X direction (in "meep units")
Ly : float
Length of design region in Y direction (in "meep units")
resolution : int
Resolution of the design grid (not the meep simulation resolution)
periodic_axes: array_like (1D)
List of axes (x, y = 0, 1) that are to be treated as periodic (default is none: all axes are non-periodic)
Returns
-------
array_like
Dilated design parameters.
References
----------
[1] Svanberg, K., & Svärd, H. (2013). Density filters for topology optimization based on the
Pythagorean means. Structural and Multidisciplinary Optimization, 48(5), 859-875.
"""
x_hat = 1 / (1 - x + alpha)
return (
1
- 1
/ cylindrical_filter(x_hat, radius, Lx, Ly, resolution, periodic_axes).flatten()
+ alpha
)
"""
# ------------------------------------------------------------------------------------ #
Projection filters
"""
def tanh_projection(x, beta, eta):
"""Projection filter that thresholds the input parameters between 0 and 1. Typically
the "strongest" projection.
Parameters
----------
x : array_like
Design parameters
beta : float
Thresholding parameter (0 to infinity). Dictates how "binary" the output will be.
eta: float
Threshold point (0 to 1)
Returns
-------
array_like
Projected and flattened design parameters.
References
----------
[1] Wang, F., Lazarov, B. S., & Sigmund, O. (2011). On projection methods, convergence and robust
formulations in topology optimization. Structural and Multidisciplinary Optimization, 43(6), 767-784.
"""
return (npa.tanh(beta * eta) + npa.tanh(beta * (x - eta))) / (
npa.tanh(beta * eta) + npa.tanh(beta * (1 - eta))
)
def heaviside_projection(x, beta, eta):
"""Projection filter that thresholds the input parameters between 0 and 1.
Parameters
----------
x : array_like
Design parameters
beta : float
Thresholding parameter (0 to infinity). Dictates how "binary" the output will be.
eta: float
Threshold point (0 to 1)
Returns
-------
array_like
Projected and flattened design parameters.
References
----------
[1] Lazarov, B. S., Wang, F., & Sigmund, O. (2016). Length scale and manufacturability in
density-based topology optimization. Archive of Applied Mechanics, 86(1-2), 189-218.
"""
case1 = eta * npa.exp(-beta * (eta - x) / eta) - (eta - x) * npa.exp(-beta)
case2 = (
1
- (1 - eta) * npa.exp(-beta * (x - eta) / (1 - eta))
- (eta - x) * npa.exp(-beta)
)
return npa.where(x < eta, case1, case2)
"""
# ------------------------------------------------------------------------------------ #
Length scale operations
"""
def get_threshold_wang(delta, sigma):
"""Calculates the threshold point according to the gaussian filter radius (`sigma`) and
the perturbation parameter (`sigma`) needed to ensure the proper length
scale and morphological transformation according to Wang et. al. [2].
Parameters
----------
sigma : float
Smoothing radius (in meep units)
delta : float
Perturbation parameter (in meep units)
Returns
-------
float
Threshold point (`eta`)
References
----------
[1] Wang, F., Jensen, J. S., & Sigmund, O. (2011). Robust topology optimization of
photonic crystal waveguides with tailored dispersion properties. JOSA B, 28(3), 387-397.
[2] Wang, E. W., Sell, D., Phan, T., & Fan, J. A. (2019). Robust design of
topology-optimized metasurfaces. Optical Materials Express, 9(2), 469-482.
"""
return 0.5 - special.erf(delta / sigma)
def get_eta_from_conic(b, R):
"""Extracts the eroded threshold point (`eta_e`) for a conic filter given the desired
minimum length (`b`) and the filter radius (`R`). This only works for conic filters.
Note that the units for `b` and `R` can be arbitrary so long as they are consistent.
Results in paper were thresholded using a "tanh" Heaviside projection.
Parameters
----------
b : float
Desired minimum length scale.
R : float
Conic filter radius
Returns
-------
float
The eroded threshold point (1-eta)
References
----------
[1] Qian, X., & Sigmund, O. (2013). Topological design of electromechanical actuators with
robustness toward over-and under-etching. Computer Methods in Applied
Mechanics and Engineering, 253, 237-251.
[2] Wang, F., Lazarov, B. S., & Sigmund, O. (2011). On projection methods, convergence and
robust formulations in topology optimization. Structural and Multidisciplinary
Optimization, 43(6), 767-784.
[3] Lazarov, B. S., Wang, F., & Sigmund, O. (2016). Length scale and manufacturability in
density-based topology optimization. Archive of Applied Mechanics, 86(1-2), 189-218.
"""
norm_length = b / R
if norm_length < 0:
return 0
elif norm_length < 1:
return 0.25 * norm_length**2 + 0.5
elif norm_length < 2:
return -0.25 * norm_length**2 + norm_length
else:
return 1
def get_conic_radius_from_eta_e(b, eta_e):
"""Calculates the corresponding filter radius given the minimum length scale (b)
and the desired eroded threshold point (eta_e).
Parameters
----------
b : float
Desired minimum length scale.
eta_e : float
Eroded threshold point (1-eta)
Returns
-------
float
Conic filter radius.
References
----------
[1] Qian, X., & Sigmund, O. (2013). Topological design of electromechanical actuators with
robustness toward over-and under-etching. Computer Methods in Applied
Mechanics and Engineering, 253, 237-251.
[2] Wang, F., Lazarov, B. S., & Sigmund, O. (2011). On projection methods, convergence and
robust formulations in topology optimization. Structural and Multidisciplinary
Optimization, 43(6), 767-784.
[3] Lazarov, B. S., Wang, F., & Sigmund, O. (2016). Length scale and manufacturability in
density-based topology optimization. Archive of Applied Mechanics, 86(1-2), 189-218.
"""
if (eta_e >= 0.5) and (eta_e < 0.75):
return b / (2 * np.sqrt(eta_e - 0.5))
elif (eta_e >= 0.75) and (eta_e <= 1):
return b / (2 - 2 * np.sqrt(1 - eta_e))
else:
raise ValueError(
"The erosion threshold point (eta_e) must be between 0.5 and 1."
)
def indicator_solid(x, c, filter_f, threshold_f, resolution, periodic_axes=None):
"""Calculates the indicator function for the void phase needed for minimum length optimization [1].
Parameters
----------
x : array_like
Design parameters
c : float
Decay rate parameter (1e0 - 1e8)
filter_f : function_handle
Filter function. Must be differntiable by autograd.
threshold_f : function_handle
Threshold function. Must be differntiable by autograd.
periodic_axes: array_like (1D)
List of axes (x, y = 0, 1) that are to be treated as periodic (default is none: all axes are non-periodic)
Returns
-------
array_like
Indicator value
References
----------
[1] Zhou, M., Lazarov, B. S., Wang, F., & Sigmund, O. (2015). Minimum length scale in topology optimization by
geometric constraints. Computer Methods in Applied Mechanics and Engineering, 293, 266-282.
"""
filtered_field = filter_f(x)
design_field = threshold_f(filtered_field)
if periodic_axes is None:
gradient_filtered_field = npa.gradient(filtered_field)
else:
periodic_axes = np.array(periodic_axes)
if 0 in periodic_axes:
filtered_field = npa.tile(filtered_field, (3, 1))
if 1 in periodic_axes:
filtered_field = npa.tile(filtered_field, (1, 3))
gradient_filtered_field = npa.gradient(filtered_field)
gradient_filtered_field[0] = _centered(gradient_filtered_field[0], x.shape)
gradient_filtered_field[1] = _centered(gradient_filtered_field[1], x.shape)
grad_mag = (gradient_filtered_field[0] * resolution) ** 2 + (
gradient_filtered_field[1] * resolution
) ** 2
if grad_mag.ndim != 2:
raise ValueError(
"The gradient fields must be 2 dimensional. Check input array and filter functions."
)
return design_field * npa.exp(-c * grad_mag)
def constraint_solid(
x, c, eta_e, filter_f, threshold_f, resolution, periodic_axes=None
):
"""Calculates the constraint function of the solid phase needed for minimum length optimization [1].
Parameters
----------
x : array_like
Design parameters
c : float
Decay rate parameter (1e0 - 1e8)
eta_e : float
Erosion threshold limit (0-1)
filter_f : function_handle
Filter function. Must be differntiable by autograd.
threshold_f : function_handle
Threshold function. Must be differntiable by autograd.
periodic_axes: array_like (1D)
List of axes (x, y = 0, 1) that are to be treated as periodic (default is none: all axes are non-periodic)
Returns
-------
float
Constraint value
Example
-------
>> g_s = constraint_solid(x,c,eta_e,filter_f,threshold_f) # constraint
>> g_s_grad = grad(constraint_solid,0)(x,c,eta_e,filter_f,threshold_f) # gradient
References
----------
[1] Zhou, M., Lazarov, B. S., Wang, F., & Sigmund, O. (2015). Minimum length scale in topology optimization by
geometric constraints. Computer Methods in Applied Mechanics and Engineering, 293, 266-282.
"""
filtered_field = filter_f(x)
I_s = indicator_solid(
x.reshape(filtered_field.shape),
c,
filter_f,
threshold_f,
resolution,
periodic_axes,
).flatten()
return npa.mean(I_s * npa.minimum(filtered_field.flatten() - eta_e, 0) ** 2)
def indicator_void(x, c, filter_f, threshold_f, resolution, periodic_axes=None):
"""Calculates the indicator function for the void phase needed for minimum length optimization [1].
Parameters
----------
x : array_like
Design parameters
c : float
Decay rate parameter (1e0 - 1e8)
eta_d : float
Dilation threshold limit (0-1)
filter_f : function_handle
Filter function. Must be differntiable by autograd.
threshold_f : function_handle
Threshold function. Must be differntiable by autograd.
periodic_axes: array_like (1D)
List of axes (x, y = 0, 1) that are to be treated as periodic (default is none: all axes are non-periodic)
Returns
-------
array_like
Indicator value
References
----------
[1] Zhou, M., Lazarov, B. S., Wang, F., & Sigmund, O. (2015). Minimum length scale in topology optimization by
geometric constraints. Computer Methods in Applied Mechanics and Engineering, 293, 266-282.
"""
filtered_field = filter_f(x).reshape(x.shape)
design_field = threshold_f(filtered_field)
if periodic_axes is None:
gradient_filtered_field = npa.gradient(filtered_field)
else:
periodic_axes = np.array(periodic_axes)
if 0 in periodic_axes:
filtered_field = npa.tile(filtered_field, (3, 1))
if 1 in periodic_axes:
filtered_field = npa.tile(filtered_field, (1, 3))
gradient_filtered_field = npa.gradient(filtered_field)
gradient_filtered_field[0] = _centered(gradient_filtered_field[0], x.shape)
gradient_filtered_field[1] = _centered(gradient_filtered_field[1], x.shape)
grad_mag = (gradient_filtered_field[0] * resolution) ** 2 + (
gradient_filtered_field[1] * resolution
) ** 2
if grad_mag.ndim != 2:
raise ValueError(
"The gradient fields must be 2 dimensional. Check input array and filter functions."
)
return (1 - design_field) * npa.exp(-c * grad_mag)
def constraint_void(x, c, eta_d, filter_f, threshold_f, resolution, periodic_axes=None):
"""Calculates the constraint function of the void phase needed for minimum length optimization [1].
Parameters
----------
x : array_like
Design parameters
c : float
Decay rate parameter (1e0 - 1e8)
eta_d : float
Dilation threshold limit (0-1)
filter_f : function_handle
Filter function. Must be differntiable by autograd.
threshold_f : function_handle
Threshold function. Must be differntiable by autograd.
periodic_axes: array_like (1D)
List of axes (x, y = 0, 1) that are to be treated as periodic (default is none: all axes are non-periodic).
Returns
-------
float
Constraint value
Example
-------
>> g_v = constraint_void(p,c,eta_d,filter_f,threshold_f) # constraint
>> g_v_grad = tensor_jacobian_product(constraint_void,0)(p,c,eta_d,filter_f,threshold_f,g_s) # gradient
References