OPTICSIN 5 MINUTES

E10 / AN INTERACTIVE OPTICS LESSON

One error field.
Every pixel’s gradient.

Design a phase mask by measuring how each parameter affects an image, then replace thousands of separate perturbations with one adjoint calculation.

12–15-minute lesson · 25–30-minute Python lab
Prerequisites & recommended learning resources ↓

Computed illustration from this lesson’s numerical model.
COMPUTED FROM THE LESSON MODEL

CONCEPTS IN THIS EPISODE

See this episode in the concept map ↓

E10 / WHY LEARN THIS?

How do you improve a design with thousands of controls?

You want a phase mask to produce a chosen intensity pattern, but each pixel is a design variable. Perturbing every pixel separately makes each optimization step expensive. You need the sensitivity of one objective to all those variables at once.

What you gain: Compute and verify a gradient with an adjoint calculation, use it to improve the pattern, and assess the resulting design without assuming that a lower error proves a global optimum.

BEFORE E10 / PREREQUISITES

Check your starting point.

Useful earlier lessons: E01, E05, E09

  • Chain rule and gradients. Apply the multivariable chain rule to one scalar objective.Used here: The gradient measures how each phase pixel changes the image mismatch.
  • Complex inner products. Use a complex inner product and conjugate transpose.Used here: Moving a linear operator across that inner product produces the adjoint operation.
  • Fourier transforms and convolution. Follow a complex field through a forward and inverse Fourier transform.Used here: The core design example uses a unitary Fourier propagation model.
Need a refresher? Open the recommended reading.

Use the indicated sections for an unfamiliar idea, then return to this lesson.

For the notebook: Use complex arrays and compare an analytic derivative with a finite-difference perturbation.
NumPy · The absolute basics for beginners ↗ · NumPy · Discrete Fourier Transform ↗

Developed in this lesson: Derive, check, and use an adjoint phase gradient. Prior knowledge of adjoint optimization is not required.

Browse all prerequisites and learning resources →

Designing light with gradients

Watch the story, then use the experiment below to test the ideas yourself.

5:15 · E10 · Designing light with gradientsWatch on YouTube ↗

The film’s logic, step by step.

How can one extra solve give a design gradient for thousands of parameters?

Follow the film’s argument, then open an explanation where a step feels too fast. Times are approximate; select one to replay that part of the film.

Logic flow

  1. 0:00

    Replace a hand-drawn shape with an objective

    A compact splitter is scored by useful output power. The reported efficiencies belong to the film’s particular simulated examples; the general question is how to improve the score systematically.

  2. 0:28

    Parameterize the device and expose the finite-difference cost

    Changing one pixel and rerunning estimates one derivative. Repeating for every parameter makes each optimization step expensive, so the bottleneck is the whole gradient.

    Open the missing step →
  3. 1:08

    Differentiate the field equation

    Write the fixed-frequency simulation as A(p)x = b. Differentiation relates a material change to the resulting field change, but naïvely solving that relation still costs one solve per parameter.

    Open the missing step →
  4. 1:28

    Reorder the derivative contraction

    Solve once for the objective’s adjoint field, then contract it with each local material perturbation and the forward field. The expensive solve count no longer scales with parameter count.

    Open the missing step →
  5. 1:57

    Interpret the adjoint as sensitivity from the outputs

    A parameter perturbation scatters the forward field locally. The adjoint weights how that scattered field changes the selected objective at the outputs, including its phase.

    Open the missing step →
  6. 2:44

    Recognize reverse-mode differentiation in a propagation chain

    Backpropagation applies the adjoint of each operation in reverse order. For a phase mask and unitary propagating-wave model, this looks like propagating a sensitivity field backward.

    Open the missing step →
  7. 3:33

    Optimize the complete imaging task

    An optical design can be scored after noisy measurement and reconstruction. A depth-stable, recoverable PSF may be preferable to a perfect focus at just one depth.

    Open the missing step →
  8. 4:10

    Add fabrication constraints and independent validation

    A gradient improves the stated model and objective locally. Binarization, feature size, diverse operating conditions, and a more accurate validation model determine whether the design remains useful outside that optimization.

    Open the missing step →

Unpack the difficult steps

Where do the thousands of solves disappear?

1:23 · Replay this part

A x = b ⇒ A (∂x/∂pj) = ∂b/∂pj − (∂A/∂pj)x
real-variable form: Aᵀλ = ∂F/∂x
dF/dpj = ∂F/∂pj + λᵀ[∂b/∂pj − (∂A/∂pj)x]

A direct sensitivity method solves for ∂x/∂pj separately for every parameter. The adjoint instead solves for one λ that represents how the scalar objective responds to the entire field. Once x and λ are known, each parameter derivative needs only the corresponding contraction. Local material parameters make those contractions especially cheap.

Two solves means one forward plus one adjoint for one scalar objective and one source/frequency state of a linear field problem. Multiple independent states generally need additional forward/adjoint work, and every optimization iteration repeats it. The cheap contractions and parameter filtering still scale with design size.

Does “send light backward” literally mean reversing the simulation?

1:57 · Replay this part

complex convention: δF = 2 Re(q†δx) + explicit parameter terms
A†λ = q
dF/dpj = explicit term + 2 Re{λ†[∂b/∂pj − (∂A/∂pj)x]}

For complex fields and a real objective, the derivative convention must be stated. The Hermitian-adjoint form above uses A†. An equivalent derivation can use a transpose solve after conjugating the adjoint variable and source appropriately. The film’s Aᵀ picture assumes a reciprocal, suitably represented operator; symmetry is not a statement that A is real or Hermitian.

The adjoint source is weighted by the objective derivative, not simply an identical source placed at every output. Loss, nonreciprocity, absorbing boundaries, and discretization make a literal time-reversal story insufficient. What must hold is the discrete adjoint equation for the exact forward computation being differentiated.

When is the adjoint propagator different from backward propagation?

2:59 · Replay this part

propagating: H(z) = e^(ikz z), H* = H(−z) = H⁻¹
evanescent: H(z) = e^(−αz), H* = e^(−αz) ≠ H⁻¹ = e^(+αz)

For real kz in a lossless medium, H has unit magnitude, so conjugating it is equivalent to reversing z. For an evanescent component, the adjoint retains the decay; the mathematical inverse would amplify it. Aperture clipping and loss also make the adjoint different from an inverse. A sensitivity backpass does not recover information erased by the forward model.

Likewise, the adjoint of a discrete FFT includes normalization factors unless the transform is defined to be unitary. Automatic differentiation tracks the actual implementation, including those factors. Check a directional derivative against finite differences before trusting a custom backward operator.

If the score improves, why might the manufactured design still fail?

4:16 · Replay this part

An optimizer finds opportunities in the model it sees. Intermediate material values, sub-grid features, omitted vector effects, a narrow training wavelength, or an unrealistic reconstruction noise model can all improve the simulated score without improving the real device. A good gradient cannot correct an incomplete objective or forward model.

Parameterize or constrain manufacturable structures, include relevant wavelengths, sources, depths, and noise in the objective, and validate the final geometry with refined settings or an independent solver. Compare against the same baseline and operating conditions. Gradient-based improvement is local; it does not certify a global optimum.

Further reading for these explanations

Explore the full experiment →

What to notice first.

Forward modeling answers what a device does. Design asks which parameters make it do something useful. Here the parameters are the phase delays of a fixed-amplitude pupil. A unitary Fourier transform produces the output field, and its intensity is compared with a target.

u = a eiφ   ·   v = Fu   ·   J = ½ Σ(|v|² − T)² / ΣT²

The aperture a and target T are normalized once so their total powers agree. The loss is an intensity mismatch, not an amplitude mismatch. A central finite difference would perturb each φ separately in both directions, costing roughly twice as many forward evaluations as there are parameters.

Reverse differentiation shares the effect of the final error. First compute the output field v and residual r = |v|² − T. Weight that field by the residual and propagate it through the Hermitian adjoint F†. One overlap with the input field then gives every real phase derivative.

b = F†[rv / ΣT²]   ·   ∂J/∂φ = 2 Im(u* b)

The complex conjugate and the factor of two are essential. The notebook derives this expression from dJ = 2 Re(q†dv), then compares it with numerical perturbations. A visually plausible sensitivity map is not a gradient check.

By the end, you can

  1. Derive a real phase gradient through a complex Fourier operator.
  2. Verify that gradient with central finite differences.
  3. Explain why adjoints are not generally inverse propagation and why gradients do not guarantee global optimality.

PREDICT BEFORE YOU CHANGE A CONTROL

A mask has 4,096 adjustable phase pixels and one scalar loss. How many perturbed simulations would a central finite-difference gradient require? What calculation could share work across all pixels?

Change one thing.
Follow what changes.

All plotted fields and curves are calculated from the stated model. Keep the other controls fixed while testing a prediction.

Model: 64 × 64 scalar phase-only pupil with a circular fixed amplitude and a unitary Fourier propagation operator. Targets have equal total power. No pixel coupling, material dispersion, noise, or fabrication constraints are included in the browser optimization. The optional Helmholtz example has a lossy boundary layer, explicitly not a PML.

  1. Run the two-spot design. Compare target and output with their common intensity scale, and follow the accepted-step loss curve.
  2. Change only the initialization seed. Compare final losses and phase masks; different solutions can have similar performance.
  3. Increase the maximum phase step. Watch backtracking add forward evaluations when needed, rather than assuming every larger step improves the design.

The adjoint follows the computation backward.

For a linear field operator P, the adjoint P† is defined by the complex inner product: ⟨Px,y⟩ = ⟨x,P†y⟩. It transports sensitivity to a scalar objective back through the model. For a unitary Fourier transform, the adjoint equals the inverse, which makes this example especially simple.

That equality is not general. If propagation is diagonal in a spectral basis with factors H, the adjoint uses H*, whereas an inverse uses 1/H. Evanescent attenuation remains attenuation under the adjoint; inverse propagation would amplify it. Lossy systems therefore make a useful counterexample to the phrase run the light backward.

The same idea applies to a matrix wave solver.

Suppose a discretized frequency-domain model is A(p)x = b. A real scalar objective gives an output sensitivity q = ∂J/∂x*. Solve A†λ = q. If b has no parameter dependence, each real parameter derivative is −2 Re[λ†(∂A/∂p)x], plus any explicit objective dependence.

The optional sparse Helmholtz example uses precisely this Hermitian convention and checks all pixel derivatives. An equivalent transpose convention can be used if its source and overlap are conjugated consistently. Mixing the two conventions is a common source of gradients with convincing structure and incorrect signs.

Accurate derivatives are the beginning of design.

The browser uses a seeded initial phase and backtracking descent. Every accepted step must lower the stated loss. Computing the gradient needs one forward and one adjoint operation per scalar objective, while line search adds forward trials. The counter reports those additional evaluations rather than hiding them in a two-simulation claim.

The objective is nonconvex. Multiple starts can end at different local solutions. A phase pattern that works in the numerical model can also fail after quantization, smoothing, or a more accurate wave model. The notebook applies a fabrication projection and evaluates the resulting device again. A lower training loss is useful evidence, but it is not a certificate of global optimality or experimental performance.

Make a prediction before checking the explanation.

Can you explain the change?

1. For thousands of phase parameters and one scalar loss, the adjoint gradient needs…
2. For an attenuating transfer factor H, the adjoint uses…
3. A finite-difference gradient check establishes…

Your own computational experiment.

The standalone notebook builds the model in small steps, draws the results, and checks the calculation against independent predictions. It runs on CPU using NumPy, SciPy, and Matplotlib. No repository clone, GPU, or external dataset is needed.

In Colab, sign in with a Google account and select Runtime → Run all. Save a copy in Drive to retain edits. Saved notebook outputs and downloadable PNG figures provide a fallback if Colab’s output frame cannot load.

A short lab report

  1. Check derivatives. Compare an analytic phase gradient with central differences at several perturbation sizes.
  2. Count actual work. Report gradient evaluations and extra forward trials for two maximum step sizes.
  3. Test the manufactured design. Quantize the final phase and re-evaluate the unchanged objective and intensity normalization.
Compare your reasoning

Check derivatives

Look for an intermediate step-size range where truncation and roundoff are both small; compare relative and absolute errors.

Count actual work

One forward plus one adjoint produces a gradient for one objective. Backtracking and validation add separate evaluations.

Test the manufactured design

Fabrication projection can worsen performance. A model-aware optimization can include such constraints, but a continuous-mask result alone is insufficient.

Optional deeper extension

Check every gradient component in a small lossy sparse Helmholtz model, compare adjoint conventions, and evaluate quantized or smoothed phase masks after optimization.

The notebook marks the extension clearly. Complete the core experiment and its checks first.

Instructor notes and assessment rubric ↗ · Model, setup, and reproducibility ↗

Know what the model leaves out.

64 × 64 scalar phase-only pupil with a circular fixed amplitude and a unitary Fourier propagation operator. Targets have equal total power. No pixel coupling, material dispersion, noise, or fabrication constraints are included in the browser optimization. The optional Helmholtz example has a lossy boundary layer, explicitly not a PML.

Video companion: watch the E10 film above (5:15).

Calculations and concept checks run locally in your browser. Quiz answers are not uploaded or stored.

Keep exploring from this episode.

Highlighted concepts appear in this episode. Select any concept to find related episodes.

In this episodeUnderstanding foundationCross-topic connection

Connections describe ideas, not a required episode order.

SELECTED CONCEPT

Complex field & phase

In this episode

Keep amplitude and phase together to describe what light does before a detector measures intensity.

Other episodes with this concept

Explore through connected ideas

Foundations & connections

Refresh the foundations

Connected ideas

SELECTED CONCEPT

Fourier representation

In this episode

Describe a field by its spatial-frequency components. The same representation connects propagation, imaging, reconstruction, and design.

Other episodes with this concept

Foundations & connections

Refresh the foundations

Connected ideas

SELECTED CONCEPT

Wave propagation

Follow a field through space by advancing its components and combining them again.

Other episodes with this concept

Explore through connected ideas

Foundations & connections

Refresh the foundations

Connected ideas

SELECTED CONCEPT

Interference & coherence

Connect field correlations to what survives a camera's averaging: interference, fringe visibility, and speckle.

Other episodes with this concept

Explore through connected ideas

Foundations & connections

Refresh the foundations

Connected ideas

SELECTED CONCEPT

Imaging & resolution

Use point responses and frequency transfer to understand which details an optical image can carry.

Other episodes with this concept

Explore through connected ideas

Foundations & connections

Refresh the foundations

Connected ideas

SELECTED CONCEPT

Holography & phase recovery

Recover information about an optical field using a reference or constraints on intensity measurements.

Other episodes with this concept

Explore through connected ideas

Foundations & connections

Refresh the foundations

Connected ideas

SELECTED CONCEPT

Phase control

In this episode

Turn a desired phase profile into an optical element, then examine wrapping, quantization, and wavelength dependence.

Other episodes with this concept

Explore through connected ideas

Foundations & connections

Refresh the foundations

Connected ideas

SELECTED CONCEPT

Periodicity & band gaps

Use repetition to connect diffraction directions, Bloch propagation, and frequency bands that a structure rejects.

Other episodes with this concept

Explore through connected ideas

Foundations & connections

Refresh the foundations

Connected ideas

SELECTED CONCEPT

Eigenmodes & resonance

Find field patterns adapted to an operator or structure. Related eigenvalue methods also describe Bloch waves and statistical coherent modes.

Other episodes with this concept

Explore through connected ideas

Foundations & connections

Refresh the foundations

Connected ideas

SELECTED CONCEPT

Sampling & discretization

Understand what changes when continuous fields become arrays: sampling limits, computational windows, and derivative approximations.

Other episodes with this concept

Explore through connected ideas

Foundations & connections

Refresh the foundations

Connected ideas

SELECTED CONCEPT

Maxwell & FDTD

Evolve coupled electric and magnetic fields on a grid, and test the accuracy of time steps and boundaries.

Other episodes with this concept

Explore through connected ideas

Foundations & connections

Refresh the foundations

Connected ideas

SELECTED CONCEPT

Adjoints & inverse design

In this episode

Use a scalar objective and an adjoint calculation to find how every design parameter changes the result.

Explore through connected ideas

Foundations & connections

Refresh the foundations

Connected ideas