File: waveguide_crossing.py

package info (click to toggle)
meep-mpi-default 1.29.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 79,148 kB
  • sloc: cpp: 32,541; python: 31,061; lisp: 1,225; makefile: 516; sh: 249; ansic: 131; javascript: 5
file content (639 lines) | stat: -rw-r--r-- 21,131 bytes parent folder | download | duplicates (2)
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
"""waveguide_crossing.py - Using meep's adjoint solver, designs a waveguide
crossing that maximizes transmission at a single frequency.

Two approaches are demonstrated: (1) start with the nominal crossing shape and
perform shape optimization via meep's smoothed projection feature; (2) run a
full topology optimization starting from an initial grayscale. Evolve the design
until β=∞.

Importantly, this particular example highlights some of the ways one can use the
novel smoothed projection function to perform both shape and topology
optimization.
"""

from typing import Callable, List, Optional, Tuple

import meep.adjoint as mpa
import nlopt
import numpy as np
from autograd import grad
from autograd import numpy as npa
from autograd import tensor_jacobian_product
from matplotlib import pyplot as plt

import meep as mp

mp.quiet()

DEFAULT_MIN_LENGTH = 0.09
DEFAULT_DESIGN_REGION_WIDTH = 3.0
DEFAULT_DESIGN_REGION_HEIGHT = 3.0
DEFAULT_WAVEGUIDE_WIDTH = 0.5
DEFAULT_ETA = 0.5
DEFAULT_ETA_E = 0.75
DEFAULT_MAX_EVAL = 30


def build_optimization_problem(
    resolution: float,
    beta: float,
    use_smoothed_projection: bool,
    min_length: float = DEFAULT_MIN_LENGTH,
    dx: float = DEFAULT_DESIGN_REGION_WIDTH,
    dy: float = DEFAULT_DESIGN_REGION_HEIGHT,
    waveguide_width: float = DEFAULT_WAVEGUIDE_WIDTH,
    eta: float = DEFAULT_ETA,
    eta_e: float = DEFAULT_ETA_E,
    damping_factor: float = 0.0,
) -> Tuple[mpa.OptimizationProblem, Callable]:
    """Build the waveguide-crossing optimization problem.

    The waveguide crossing is a cononical inverse design problem with both
    shape- and topology-optimization implementations. The idea is to find the
    optimal structure that maximizes transmission from one side to the other. It
    exhibits C4 symmetry, and generally resembles the following structure:

         |  |
         |  |
    -----    ------
    -----    ------
         |  |
         |  |

    Args:
        resolution: Simulation resolution in pixels/micron.
        beta: Tanh function projection strength parameter, ranging from [0,∞].
        use_smoothed_projection: Whether or not to use the smoothed projection.
        min_length: Minimum length scale in microns.
        dx: Design region width in microns.
        dy: Design region height in microns.
        waveguide_width: Waveguide width in microns.
        eta: Projection function threshold parameter.
        eta_e: Projection function eroded threshold parameter.
        damping_factor: The material grid damping scalar factor.

    Returns:
        The corresponding optimization problem object and the mapping function
        that applies the linear and nonlinear transformations.
    """
    # Map the design region resolution to the yee grid, which is twice the standard resolution.
    design_region_resolution = int(2 * resolution)

    # pml thickness
    dpml = 1.0

    filter_radius = mpa.get_conic_radius_from_eta_e(min_length, eta_e)

    sxy = dx + 1 + 2 * dpml

    silicon = mp.Medium(epsilon=12)
    cell_size = mp.Vector3(sxy, sxy, 0)
    boundary_layers = [mp.PML(thickness=dpml)]

    eig_parity = mp.EVEN_Y + mp.ODD_Z

    design_region_size = mp.Vector3(dx, dy)
    Nx = int(design_region_resolution * design_region_size.x) + 1
    Ny = int(design_region_resolution * design_region_size.y) + 1

    waveguide_geometry = [
        mp.Block(material=silicon, size=mp.Vector3(mp.inf, waveguide_width, mp.inf)),
        mp.Block(material=silicon, size=mp.Vector3(waveguide_width, mp.inf, mp.inf)),
    ]

    # Source centered in optical c-band
    fcen = 1 / 1.55
    df = 0.23 * fcen
    sources = [
        mp.EigenModeSource(
            src=mp.GaussianSource(fcen, fwidth=df),
            center=mp.Vector3(-0.5 * sxy + dpml + 0.1, 0),
            size=mp.Vector3(0, sxy - 2 * dpml),
            eig_band=1,
            eig_parity=eig_parity,
        )
    ]

    damping = damping_factor * fcen
    matgrid = mp.MaterialGrid(
        mp.Vector3(Nx, Ny),
        mp.air,
        silicon,
        weights=np.ones((Nx, Ny)),
        beta=0,  # disable meep's internal smoothing
        do_averaging=False,  # disable meep's internal mg smoothing
        damping=damping,
    )

    matgrid_region = mpa.DesignRegion(
        matgrid,
        volume=mp.Volume(
            center=mp.Vector3(),
            size=mp.Vector3(design_region_size.x, design_region_size.y, 0),
        ),
    )

    matgrid_geometry = [
        mp.Block(
            center=matgrid_region.center, size=matgrid_region.size, material=matgrid
        )
    ]

    geometry = waveguide_geometry + matgrid_geometry

    sim = mp.Simulation(
        resolution=resolution,
        cell_size=cell_size,
        boundary_layers=boundary_layers,
        sources=sources,
        geometry=geometry,
    )

    frequencies = [fcen]

    obj_list = [
        mpa.EigenmodeCoefficient(
            sim,
            mp.Volume(
                center=mp.Vector3(-0.5 * sxy + dpml + 0.2),
                size=mp.Vector3(0, sxy - 2 * dpml, 0),
            ),
            1,
            eig_parity=eig_parity,
        ),
        mpa.EigenmodeCoefficient(
            sim,
            mp.Volume(
                center=mp.Vector3(0.5 * sxy - dpml - 0.2),
                size=mp.Vector3(0, sxy - 2 * dpml, 0),
            ),
            1,
            eig_parity=eig_parity,
        ),
    ]

    def J(input, output):
        """Simple objective function to minimize loss."""
        return 1 - npa.power(npa.abs(output / input), 2)

    opt = mpa.OptimizationProblem(
        simulation=sim,
        maximum_run_time=500,
        objective_functions=J,
        objective_arguments=obj_list,
        design_regions=[matgrid_region],
        frequencies=frequencies,
    )

    def mapping(x: npa.ndarray):
        """Applies the smoothing and projection."""
        x = x.reshape(Nx, Ny)
        x = mpa.conic_filter(
            x,
            filter_radius,
            design_region_size.x,
            design_region_size.y,
            design_region_resolution,
        )

        # Enforce the square symmetry
        x = (x + npa.rot90(x) + npa.rot90(x, 2) + npa.rot90(x, 3)) / 4

        # Only used the smoothed projection if prompted.
        if use_smoothed_projection:
            x = mpa.smoothed_projection(
                x, beta=beta, eta=eta, resolution=design_region_resolution
            )
        else:
            x = mpa.tanh_projection(x, beta=beta, eta=eta)

        return x.flatten()

    return opt, mapping


def nlopt_fom(
    x: np.ndarray,
    gradient: np.ndarray,
    opt: mpa.OptimizationProblem,
    mapping: Callable,
    data: List,
    results: List,
):
    """Wrapper for NLopt FOM.

    Args:
        x: Degrees of freedom array.
        gradient: Gradient of FOM.
        opt: Optimization problem object.
        mapping: Mapping function.
        data: Structure to store the simulated design each iteration.
        results: Structure to store the simulated FOM each iteration.

    Returns:
        The FOM value at the current iteration.
    """
    grid_size = opt.design_regions[0].design_parameters.grid_size
    Nx, Ny = int(grid_size.x), int(grid_size.y)

    f0, dJ_du = opt([mapping(x)])
    backprop_gradient = tensor_jacobian_product(mapping, 0)(x, dJ_du)
    if gradient.size > 0:
        gradient[:] = backprop_gradient

    data.append(
        [
            np.squeeze(x.copy().reshape(Nx, Ny)),
            np.squeeze(mapping(x).copy().reshape(Nx, Ny)),
            np.squeeze(backprop_gradient.reshape(Nx, Ny)),
        ]
    )

    print(
        f"FOM: {np.real(f0)} | x NaNs:{np.sum(np.isnan(backprop_gradient))} | grad NaNs: {np.sum(np.isnan(backprop_gradient))}"
    )
    results.append(np.real(f0))

    return float(np.real(f0))


def _plot_optimization_results(
    data: List,
    results: List,
    num_samples: int = 4,
):
    samples = np.linspace(0, len(results), num_samples, dtype=int, endpoint=False)
    plt.figure(figsize=(5.25, 4.0))
    plt.subplot(2, 1, 1)
    plt.plot(results, "o-")
    plt.xlabel("Optimization Iteration")
    plt.ylabel("FOM")
    for k in range(len(samples)):
        plt.subplot(2, 4, 5 + k)
        plt.imshow(data[samples[k]], cmap="binary", vmin=0.0, vmax=1.0)
        plt.axis("off")
        plt.title(f"It. {samples[k]+1}")
    plt.tight_layout()
    plt.show()


def run_shape_optimization(
    resolution: float,
    beta: float,
    maxeval: int,
    use_smoothed_projection: bool = True,
    damping_factor: float = 0.0,
    dx: float = DEFAULT_DESIGN_REGION_WIDTH,
    dy: float = DEFAULT_DESIGN_REGION_HEIGHT,
    waveguide_width: float = DEFAULT_WAVEGUIDE_WIDTH,
    output_filename_prefix: Optional[str] = None,
    plot_results: bool = True,
):
    """Run shape optimization using a cross as a starting guess.

    Args:
        resolution: Simulation resolution in pixels/micron.
        beta: Tanh function projection strength parameter, ranging from [0,∞].
        maxeval: Maximum number of optimization iterations to run.
        use_smoothed_projection: Whether or not to use the smoothed projection.
        dx: Design region width in microns.
        dy: Design region height in microns.
        waveguide_width: Waveguide width in microns.
        output_filename_prefix: The filename prefix that will store the
            optimization results. If `None`, no file is saved.
        plot_results: Whether or not to plot results.

    Returns:
        The design and FOM result arrays, along with the optimization problem
        and mapping function.

    """
    # Initialize the optimization problem and mapping functions
    opt, mapping = build_optimization_problem(
        resolution=resolution,
        beta=beta,
        dx=dx,
        dy=dy,
        waveguide_width=waveguide_width,
        use_smoothed_projection=use_smoothed_projection,
        damping_factor=damping_factor,
    )

    # pull number of parameters from the design region
    n = opt.design_regions[0].design_parameters.weights.size
    grid_size = opt.design_regions[0].design_parameters.grid_size
    Nx, Ny = int(grid_size.x), int(grid_size.y)

    # Set up the optimizer
    algorithm = nlopt.LD_CCSAQ
    solver = nlopt.opt(algorithm, n)
    solver.set_lower_bounds(0)
    solver.set_upper_bounds(1)
    solver.set_maxeval(maxeval)

    # initial guess, which is just a simple waveguide crossing
    x = np.linspace(-dx / 2, dy / 2, Nx)
    y = np.linspace(-dx / 2, dy / 2, Ny)
    X, Y = np.meshgrid(x, y)
    mask = (np.abs(Y) <= waveguide_width / 2.0) + (np.abs(X) <= waveguide_width / 2.0)
    x0 = np.zeros((Nx, Ny))
    x0[mask.T] = 1
    x0 = mapping(x0)

    # Create empty datastructures we can use to log the results
    data = []
    results = []

    # prepare the optimizer objective function. We need to wrap the above fom in
    # a format that nlopt expects.
    nlopt_fom_simple = lambda x, gradient: nlopt_fom(
        x, gradient, opt=opt, mapping=mapping, data=data, results=results
    )
    solver.set_min_objective(nlopt_fom_simple)

    # Run the optimization
    x_final = solver.optimize(x0)

    # Log the final results
    opt.update_design([x_final.copy(), mapping(x_final)])
    f0, final_grad = opt(need_gradient=False)
    final_backprop_gradient = tensor_jacobian_product(mapping, 0)(x_final, final_grad)
    results.append(np.real(f0))
    data.append(
        [
            np.squeeze(x_final.copy().reshape(Nx, Ny)),
            np.squeeze(mapping(x_final).copy().reshape(Nx, Ny)),
            np.squeeze(final_backprop_gradient.reshape(Nx, Ny)),
        ]
    )

    if plot_results:
        _plot_optimization_results(data, results)

    # Save to disk
    if mp.am_really_master() and (output_filename_prefix is not None):
        np.savez(output_filename_prefix + "_data.npz", data=data, results=results)

    return data, results, opt, mapping


def run_topology_optimization(
    resolution: float,
    beta_evolution: List[float],
    maxeval: int,
    use_smoothed_projection: bool = True,
    dx: float = DEFAULT_DESIGN_REGION_WIDTH,
    dy: float = DEFAULT_DESIGN_REGION_HEIGHT,
    waveguide_width: float = DEFAULT_WAVEGUIDE_WIDTH,
    output_filename_prefix: Optional[str] = None,
    damping_factor: float = 0.0,
):
    """Run shape optimization using a cross as a starting guess.

    Args:
        resolution: Simulation resolution in pixels/micron.
        beta_evolution: List of Tanh function projection strength parameter,
            ranging from [0,∞], for each optimization epoch.
        maxeval: Maximum number of optimization iterations to run.
        use_smoothed_projection: Whether or not to use the smoothed projection.
        dx: Design region width in microns.
        dy: Design region height in microns.
        waveguide_width: Waveguide width in microns.
        output_filename_prefix: The filename prefix that will store the
            optimization results. If `None`, no file is saved.

    Returns:
        The design and FOM result arrays, along with the optimization problem
        and mapping function.

    """
    # Initialize the optimization problem and mapping functions so that we can
    # set up the problem.
    opt, mapping = build_optimization_problem(
        resolution=resolution,
        beta=beta_evolution[0],
        dx=dx,
        dy=dy,
        waveguide_width=waveguide_width,
        use_smoothed_projection=use_smoothed_projection,
        damping_factor=damping_factor,
    )

    # pull number of parameters from the design region
    n = opt.design_regions[0].design_parameters.weights.size
    grid_size = opt.design_regions[0].design_parameters.grid_size
    Nx, Ny = int(grid_size.x), int(grid_size.y)

    # Set up the optimizer
    algorithm = nlopt.LD_CCSAQ
    solver = nlopt.opt(algorithm, n)
    solver.set_lower_bounds(0)
    solver.set_upper_bounds(1)
    solver.set_maxeval(maxeval)

    # initial guess, which is just a uniform gray region
    x0 = 0.5 * np.ones((Nx, Ny))
    x0 = mapping(x0)

    # Create empty datastructures we can use to log the results
    data = []
    results = []

    for beta in beta_evolution:
        # Re-initialize the optimization problem and mapping functions
        opt, mapping = build_optimization_problem(
            resolution=resolution,
            beta=beta,
            dx=dx,
            dy=dy,
            waveguide_width=waveguide_width,
            use_smoothed_projection=use_smoothed_projection,
            damping_factor=damping_factor,
        )

        # prepare the optimizer objective function. We need to wrap the above fom in
        # a format that nlopt expects.
        nlopt_fom_simple = lambda x, gradient: nlopt_fom(
            x, gradient, opt=opt, mapping=mapping, data=data, results=results
        )
        solver.set_min_objective(nlopt_fom_simple)

        # Run the optimization
        x0 = solver.optimize(x0)

    x_final = x0

    # Log the final results
    opt.update_design([mapping(x_final)])
    f0, final_grad = opt(need_gradient=False)
    final_backprop_gradient = tensor_jacobian_product(mapping, 0)(x_final, final_grad)
    results.append(np.real(f0))
    data.append(
        [
            np.squeeze(x_final.copy().reshape(Nx, Ny)),
            np.squeeze(mapping(x_final).copy().reshape(Nx, Ny)),
            np.squeeze(final_backprop_gradient.reshape(Nx, Ny)),
        ]
    )

    _plot_optimization_results(data, results)

    # Save to disk
    if mp.am_really_master() and (output_filename_prefix is not None):
        np.savez(output_filename_prefix + "_data.npz", data=data, results=results)

    return data, results, opt, mapping


def analyze_gradient_convergence(
    resolution: float,
    beta_range: List[float],
    dx: float = DEFAULT_DESIGN_REGION_WIDTH,
    dy: float = DEFAULT_DESIGN_REGION_HEIGHT,
    waveguide_width: float = DEFAULT_WAVEGUIDE_WIDTH,
) -> Tuple[List[float], List[float]]:
    """Analyze the norm of the gradient vs beta.

    This experiment plots the norm of the gradient vector as a function of beta
    for both the smoothed projection and standard projection functions. As seen
    here, the smoothed projection function has a well-defined.

    Args:
        resolution: Simulation resolution in pixels/micron.
        beta_range: List of projection threshold parameters to test.
        dx: Design region width in microns.
        dy: Design region height in microns.
        waveguide_width: Waveguide width in microns.

    Returns:
        The norm of the gradient array when using smoothing and when not using
        smoothing as a function of beta.
    """

    # Initialize the optimization problem and mapping functions
    opt, mapping = build_optimization_problem(
        resolution=resolution,
        beta=beta_range[0],
        dx=dx,
        dy=dy,
        waveguide_width=waveguide_width,
        use_smoothed_projection=True,
    )

    # pull number of parameters from the design region
    n = opt.design_regions[0].design_parameters.weights.size
    grid_size = opt.design_regions[0].design_parameters.grid_size
    Nx, Ny = int(grid_size.x), int(grid_size.y)

    # initial guess, which is just a simple waveguide crossing
    x = np.linspace(-dy / 2, dy / 2, Nx)
    y = np.linspace(-dx / 2, dy / 2, Ny)
    X, Y = np.meshgrid(x, y)
    mask = (np.abs(Y) <= waveguide_width / 2.0) + (np.abs(X) <= waveguide_width / 2.0)
    x0 = np.zeros((Nx, Ny))
    x0[mask.T] = 1
    x0 = mapping(x0)

    # Initialize storage structures
    with_smoothing = []
    without_smoothing = []

    for beta in beta_range:
        # Compute the norm with smoothing
        opt, mapping = build_optimization_problem(
            resolution=resolution,
            beta=beta,
            dx=dx,
            dy=dy,
            waveguide_width=waveguide_width,
            use_smoothed_projection=True,
        )
        _, dJ_du = opt([mapping(x0)])
        backprop_gradient = tensor_jacobian_product(mapping, 0)(x0, dJ_du)
        norm_gradient_smoothing = np.linalg.norm(backprop_gradient.flatten())
        with_smoothing.append(norm_gradient_smoothing)

        # Compute the norm without smoothing
        opt, mapping = build_optimization_problem(
            resolution=resolution,
            beta=beta,
            dx=dx,
            dy=dy,
            waveguide_width=waveguide_width,
            use_smoothed_projection=False,
        )
        _, dJ_du = opt([mapping(x0)])
        backprop_gradient = tensor_jacobian_product(mapping, 0)(x0, dJ_du)
        norm_gradient_no_smoothing = np.linalg.norm(backprop_gradient.flatten())
        without_smoothing.append(norm_gradient_no_smoothing)

    # plot results
    plt.figure(figsize=(5.2, 2.5), constrained_layout=True)
    plt.loglog(beta_range, without_smoothing, "o-", label="W/o smoothing")
    plt.loglog(beta_range, with_smoothing, "o-", label="W/ smoothing")
    plt.legend()
    plt.xlabel("β")
    plt.ylabel("|df/dx|")
    plt.show()

    return with_smoothing, without_smoothing


def analyze_FOM_convergence(
    resolution: float, beta: float, maxeval: int, damping_factor: float = 0.0
) -> Tuple[List[float], List[float]]:
    """Analyze the convergence of the new projection method.

    Because the smoothed projection has a well-defined gradient for all values
    of beta, it should exhibit better convergence properties than the standard
    projection step, which grows increasingly more ill-conditioned as
    beta->infinity. This experiment runs the same shape optimization problem for
    both projection functions and plots the results.

    Args:
        resolution: Simulation resolution in pixels/micron.
        beta: Tanh function projection strength parameter, ranging from [0,∞].
        maxeval: Maximum number of optimization iterations to run.

    Returns:
        The FOM evolution for both the smoothed and not smoothed case as a
        function of optimization iteration.

    """
    print("Running shape optimization WITHOUT smoothing...")
    _, results, _, _ = run_shape_optimization(
        beta=beta,
        resolution=resolution,
        maxeval=maxeval,
        use_smoothed_projection=False,
        plot_results=False,
        output_filename_prefix=f"without_smoothing_grad_{beta}",
        damping_factor=damping_factor,
    )
    print("Running shape optimization WITH smoothing...")
    (_, results_smoothed, _, _,) = run_shape_optimization(
        beta=beta,
        resolution=resolution,
        maxeval=maxeval,
        use_smoothed_projection=True,
        plot_results=False,
        output_filename_prefix=f"with_smoothing_grad_{beta}",
        damping_factor=damping_factor,
    )

    plt.figure(figsize=(5.2, 2.0), constrained_layout=True)
    plt.loglog(results, "o-", label="W/o smoothing")
    plt.loglog(results_smoothed, "o-", label="W/ smoothing")
    plt.legend()
    plt.xlabel("Optimization iteration")
    plt.ylabel("FOM")
    plt.show()

    return results, results_smoothed


if __name__ == "__main__":

    analyze_gradient_convergence(
        beta_range=np.logspace(1, 3, base=10, num=10), resolution=20
    )