Practical considerations for high-fidelity wavefront shaping experiments

Wavefront shaping (WFS) is a technique for directing light through turbid media. The theoretical aspects of WFS are well understood, and under near-ideal experimental conditions, accurate predictions for the expected signal enhancement can be given. In practice, however, there are many experimental factors that negatively affect the outcome of the experiment. Here, we present a comprehensive overview of these experimental factors, including the effect of sample scattering properties, noise, and response of the spatial light modulator. We present simple means to identify experimental imperfections and to minimize their negative effect on the outcome of the experiment. This paper is accompanied by Python code for automatically quantifying experimental problems using the OpenWFS framework for running and simulating WFS experiments.


Introduction
The ability to focus light through scattering media is critical for a wide range of applications, including deep tissue microscopy.However, it is challenging to focus light deep inside opaque media due to inhomogeneities in the refractive index of the medium.These inhomogeneities cause aberrations and scattering that prevent light from forming a diffraction-limited focus, thereby reducing the imaging resolution and contrast [16].
Wavefront shaping (WFS) is a powerful method for focusing light at target positions inside or behind scattering materials.The basic idea of WFS for microscopy is illustrated in Fig. 1.Here, it is assumed that we use a scanning microscope, and we are interested in focusing the light inside the sample.In the ideal case (Fig. 1a), the sample is transparent and the microscope objective focuses the light at the desired spot.We can describe this focusing as constructive interference, where each part of the converging wavefront interferes constructively at the focal point.When trying to focus light into an aberrating or scattering sample, (Fig. 1b), light coming from different parts of the incident wave picks up different random phase deviations, causing random interference rather than constructive interference.As a result, the intensity in the focus is reduced, and the focus is spread out spatially.In the case of strong scattering, a disordered speckle pattern is formed.
Wavefront shaping works by spatially modulating the incident wavefront to exactly compensate these random phase deviations, restoring constructive interference, causing the light to form a high-contrast, highintensity focus inside the scattering sample (Fig. 1c).Since the first demonstration of focusing light through opaque scattering objects [38], the field has seen rapid development towards applications in fundamental research, microscopy, endoscopy, communication, and cryptography [15,26,8,2,11].
The key goal in WFS is to find the unique incident wavefront that maximizes constructive interference in the target focus.A wide range of techniques are already available (see e.g.Refs.[15,12]), and exciting new approaches based on digital twins [31,44,24,46] or deep learning [8] are actively being developed.Focusing inside a non-aberrating sample.b.Focusing inside an aberrating sample results in a distorted focus.c.Focusing inside an aberrating sample with a WFS microscope.By shaping the incoming wavefront with a spatial light modulator, the focus can be restored.
One can easily compute the theoretical expected improvement of the focus quality under ideal circumstances [38].In an actual experiment, however, the measured improvement may be significantly lower.Here, we address the following questions: • How much can I expect WFS to improve the focus?
• Why does my WFS experiment perform worse than expected?
• What can I do about it?This paper is supported by our Python package OpenWFS [34], which includes code for automated analysis and troubleshooting of WFS experiments.The package is available through the standard PyPI package repository [35], and documentation can be found at the Read the Docs website [36].Throughout this paper, we will refer to the relevant functions for detecting specific problems in WFS experiments.
For most of the analysis, we will assume that a 'classical' WFS approach is used to find the optimized wavefront, that is, a phase-stepping technique that uses feedback from the desired focal point [33,25,30,21,20].Although this covers only a fraction of the approaches in use, these classical algorithms have the advantage that they can be described analytically, allowing one to prove the convergence, analyze the effect of noise, and compute the expected improvement under a large range of circumstances.Moreover, many of the considerations here are generally valid regardless of the WFS algorithm used to find the optimal wavefront.
After introducing the basic concepts that are needed to understand, run, quantify, and predict the outcome of a WFS experiment, we cover the most common issues influencing the outcome.We will explain how each of these issues affect the enhancement, how we detect or quantify them, and how to reduce their impact.In addition, we will show that the effect of most of these issues can be quantified from regular phase-stepping measurements directly.This allows for an approach where troubleshooting metrics are conveniently built into the WFS algorithm at no extra cost.In addition, we provide a troubleshooter for detecting issues that do require specific measurement procedures to quantify them.We explain how to run the troubleshooter and analyze the troubleshooting metrics in section 10.

Theory
We can describe propagation of light through an arbitrary object with a matrix: where E a is the incident field for mode a, and the summation runs over all optical modes.E b is the field at point b where we want to focus the light.When focusing light through a scattering object, t is the transmission matrix.Note, however, that this formalism is valid for any linear system, so t ba may also refer to propagation to a point inside a sample, or reflection, or in fact any linear system.Also note that the formalism does not depend on how we represent these modes (e.g. as a Hadamard or Fourier basis).We do restrict ourselves to orthonormal sets of modes, so that we have the simple expression P in = a |E a |2 for the the total incident power.
The aim of WFS is to find the incident field E a that maximizes the intensity 1 ).The answer to this optimization problem is given by the Cauchy-Schwartz inequality, which states that: The first term on the right hand side is a property of the sample.It can be understood in terms of a phase conjugation experiment: imagine we would place a point source in b, and observe the fraction of the total emitted power that propagates to all modes a together.In this case, this fraction is exactly given by a |t ba | 2 , which we will denote T b from here forward.
For a given sample and incident power, the right hand side of this inequality is fixed.It directly follows that at most a fraction T b of the incident light can be focused at I b .This maximum is reached when both sides of Eq. ( 2) are equal, which is the case when E a ∝ t * ba , leading to an optimal value of All wavefront shaping algorithms for focusing light, in one way or the other, are aimed at determining t ba and subsequently displaying t * ba on the SLM.

Setup
A typical setup for WFS experiments is shown in Fig. 2. In this setup, HeNe laser light (Thorlabs, 2 mW, λ = 632.8nm) is expanded by a beam expander (Thorlabs BE15M-A), and then modulated by a phase-only spatial light modulator (SLM, Hamamatsu LCoS-SLM, X13138 SLM) using a 50% beam splitter (Thorlabs CM1-BS013).A polariser (P 1 , Thorlabs LPVISE100-A) is used to rotate the polarization to the linear polarization required by the SLM.A half wave plate (HWP, Thorlabs WPH10M-633) is used to control the total power entering the system.A 4f system images the SLM onto the back focal plane of a microscope objective (Zeiss A-Plan 100×/0.8M27), which focuses the light onto the sample.After transmitting through the sample, the light is collected by another objective lens (Zeiss A-Plan 100×/0.8M27), and recorded by a CMOS camera (Basler acA640-750um).A 4f system images the back surface of the sample onto a CMOS camera.This camera provides the feedback signal for WFS.
Note that there are many other options to provide the feedback signal.A mechanism to obtain a feedback signal that is correlated with localized light intensity is referred to as a 'guidestar'.This guidestar can be a localized physical object (e.g. a fluorescent particle), as well as a localized physical phenomenon (e.g.multi-photon fluorescence or the photo-acoustic effect).[12]

Phase-stepping interferometry
Each element of the transmission matrix t ba corresponds to an initially unknown complex optical field that must be measured.The phase of optical fields can typically not be measured directly.However, we can indirectly measure the relative phase of the field with a technique known as phase-stepping or phase-shifting interferometry [17].
We will explain the use of phase-stepping interferometry with the Stepwise Sequential Algorithm (SSA) as an example, but the technique is generally applicable.For SSA, the SLM pixels are divided into segments.We iterate over each segment a to measure its contribution M a = t ba E 0 to the field at feedback location b.E 0 is the field amplitude at the SLM surface, which is assumed to be equal for all segments.If the SLM is illuminated unevenly, we can include the illumination profile in the matrix element t ba (c.f.Section 6.2).The rest of the segments are used as static reference and produce the field R at b.
In each iteration, we phase-modulate the segment of interest by a set of phases ϕ p to produce the field M a e iϕp at b.In other words, the relative phase between the fields is varied between 0 (including) and 2π (excluding) in P ≥ 3 steps.Due to the interference between light originating from the modulated segment M a e iϕp and light originating from the other segments R, the feedback intensity will respond sinusoidally: where ba corresponds to the intensity in mode b, measured when applying phase ϕ p to the modulated input mode a.Note that the terms with M a R * and M * a R carry a factor e ±iϕp .By combining the measurements ba in a Discrete Fourier Transform (DFT), these terms can be isolated: where k is an integer in the range: k = −P/2, . . ., P/2 − 1, if P is even −(P − 1)/2, . . ., (P − 1)/2, if P is odd (7) It follows that F 1,a = M a R * = t ba E 0 R * ∝ t ba .So we can find the optimal input wavefront as: In theory ba follows a sinusoid with an offset, hence only F −1,a , F 0,a and F 1,a are non-zero.However, in real measurements, the values for |k| > 1 are never exactly zero, due to noise in the measurements and imperfect SLM response calibration (see Section 8.1).

Enhancement
One way to quantify the improvement of the focus, is the fraction of the incident power that is focused into mode b, i.e., the fraction S ≡ I b /P in .In adaptive optics, it is usually assumed that all light is scattered in the forward direction, so that T b = 1, and S is called the Strehl ratio [16].From Eq. (3), it is direct that in this case the optimal wavefront achieves perfect diffraction-limited focusing: S = 1.
For a scattering sample, it is often not possible to determine exactly what fraction of the incident power reached the focus.Therefore, it makes more sense to use a relative measure η ≡ I b /I 0 , which is called the enhancement [38].The reference intensity I 0 is technically defined as the intensity in point b, averaged over all possible 'similar' samples for a given optimized incident wavefront [33], i. e.
where tba is the transmission matrix for a different sample with the same scattering strength, thickness, etc., and ⟨•⟩ denotes averaging over all such samples.For strongly scattering samples, tba and t ba will be completely uncorrelated.Moreover, we assume that all elements t ba are statistically independent and identically distributed for all modes a [9], so that ⟨t * ba t ba ′ ⟩ = δ aa ′ τ where δ aa ′ is the Kronecker delta, and the value τ = |t ba | 2 is an average 'mode-to-mode' transmission coefficient which does not depend on mode index a.We can now use these statistical properties and insert E a = E 0 t * ba into Eq.( 12) to find In practice, I 0 can be determined by translating the sample, while keeping the shaped wavefront constant, and averaging measurements taken at different positions.Alternatively, the average speckle background can often be used [33].Expressions for the expected enhancement as a function of the number of modes, and for phase-only light modulation are given in Section 6.1 and Section 6.2, respectively.

Fidelity
In an experimental setting, the generated wavefront always deviates from the optimal one, so that the fraction of light that reaches the focus is always lower than T b .To account for these imperfections, we describe the incident field as a superposition of the optimal field and a residual field that is orthogonal to the optimal one [40]: Here, the incident fields are normalized such that a |E opt a | 2 = a |E res a | 2 .The factor γ denotes the fraction of the incident field that is shaped correctly.It is defined as the correlation coefficient of the ideal wavefront E opt a and the actual wavefront E a [40]: By definition, the residual field does not contribute to the target intensity at all.Therefore, the fraction of light that reaches the focus equals |γ| 2 T b .The factor |γ| 2 is called the fidelity, and equals the fraction of the incident power that is shaped correctly.For ideal control over the incident wavefront |γ| 2 = 1.In practice, however, there are many effects that reduce the fidelity.In this paper, we will treat the following effects: For each of these values, we will estimate the expected value, averaged over noise and over all 'statistically similar' samples; that is, samples that are macroscopically the same, but differ in the microscopic placement of the scattering particles.This averaging is denoted by ⟨•⟩.
We assume that each of these effects is uncorrelated with the other, meaning that we can multiply the fidelities and simply estimate the expected intensity in the target focus as Here, all factors were assumed to act independently, except for the terms |γ A | 2 |γ N | 2 T b , which were averaged together, as described in Sections 6.1 and 6.2.Clearly, it is essential that all fidelities are as close to 1 as possible.For each of these factors, we now describe how to estimate it from the experimental data, and what measures can be taken to increase it if it is too far below 1.
6 Limited control

Finite number of modes
So far, we considered a a summation over all optical modes.In practice however, a WFS experiment only controls a fraction of the incident angles and positions, and often only a single polarization.We now analyze how this limitation affects WFS fidelity.
First, consider the case of ideal phase and amplitude modulation, where the SLM generates the optimal field E a = E 0 t * ba for a finite number of modes a ≤ N , and that E a = 0 for a > N .Inserting this field into Eq.( 14) gives Unsurprisingly, this ratio equals 1 when all optical modes are considered, and it reduces when N decreases.
2 as the fraction of the light that would propagate from a light source at point b into the N modes controlled by the SLM in a 'time-reversal' experiment.
For each additional mode, we need additional measurements to determine t ba .When fewer modes are considered, the WFS process will be faster, at the cost of reducing the fidelity.In general, not all modes contribute equally.In this case, it is beneficial to choose a set of modes that contributes most to the intensity, and discard all other modes.For example, for a sample that mainly scatters light in the forward direction, one can choose a basis consisting of smooth modes that correspond to small angular deviations [20].For a homogeneously illuminated SLM, we can thus use the same expression as for ideal phase and amplitude modulation (Eq.( 16)).
A similar approach is taken in adaptive optics, where a set of low-order Zernike modes may be used [16].There is, however, a key difference: in adaptive optics the modes are used to express the phase of the light rather than the field.This results in a highly non-linear response for phase variations >1 rad, causing many of the algorithms used in adaptive optics to fail if aberrations are strong [27].
In practice, the set of modes should be chosen correctly even for a strongly scattering sample.For example, in the pupil-conjugate geometry shown in Fig. 2, the SLM is mapped to the back pupil of a microscope objective.If we choose modes that correspond to (groups of) pixels, some modes may correspond to pixels that are blocked by the back pupil of the objective (see Fig. 3).Clearly, including these modes in the WFS process costs time and does not contribute to the enhancement of the focus.

Enhancement in strongly scattering samples
For strongly scattering samples, we can use the assumptions described in Section 2 to compute the estimated enhancement.Firstly, we use the fidelity in Eq. ( 16) to find the optimized intensity of Together with the reference intensity I 0 = τ P in (Eq.( 12)), we get an enhancement of Which averages to ⟨η⟩ = N.
Therefore, for strongly scattering samples and ideal WFS, the expected enhancement is equal to the number of segments.Due to the experimental factors discussed below, in practice a lower value (around 0.5 N for strongly scattering samples in our typical experiments) results.

Automatic detection and quantification
After running a WFS algorithm, we have access to the measured values of |t ba | 2 for each mode a (see Section 3.2), which we call the contribution of that mode.By plotting the contribution for each mode, as in Fig. 3, we can verify if all modes contribute approximately equally, or whether some modes may be omitted.In practice, the modes that contribute will often have a different contribution depending on their position on the SLM or shape of the generated optical mode.In Section.6.2, we explain how to quantify the effect of this distribution automatically.

Mitigation
If the center and the size of the SLM pattern do not match the beam center and size observed in the above measurement, these parameters must be manually corrected.In OpenWFS the pattern can be translated and scaled with the transform argument of the SLM object.In addition, the algorithm may be written to skip modes that do not contribute strongly.Large gains can selecting only the modes that contribute most, such as the modes in a Fourier basis that correspond to small angle scattering [20].
When modes correspond to physical (groups of) pixels on a phase-only SLM, care must be taken not to choose the pattern too small.If there is a significant contribution of non-modulated light (from pixels outside the pattern), this will also negatively affect the fidelity.See Section 7.1.

Phase only modulation
Often, a phase-only SLM is used in experiments.As a result, it is not possible to match the amplitude distribution of the incident field to that of t ba , resulting in a reduction of the fidelity.We now analyze how this effect reduces the fidelity beyond the reduction caused by selecting a finite number of modes, |γ N | 2 .For ideal phase-only light modulation, we have an incident field E a = E 0 t * ba / |t ba |, in a basis where indices a correspond to pixels on the SLM.Using the definition of the fidelity (Eq.( 14)) again, we find where denotes the averaging over all pixels of the spatial light modulator.Note that we assumed here that the SLM is illuminated homogeneously.However, the illuminated beam on the modulator usually has Gaussian beam profile resulting in a lower fidelity.We can simply include this illumination profile in t ba so that E 0 is a constant, and we can still use Eq.(20).

Enhancement in strongly scattering samples
If all modes contribute equally on average, we can multiply the enhancement η in Eq. ( 18) by the fidelity in Eq. ( 20) to find the enhancement for phase-only modulation To compute the expected value for η we use the fact that the elements t ba for a strongly scattering sample follow a circular Gaussian distribution [9].This distribution has the property that ⟨|t ba |⟩ 2 = π 4 |t ba | 2 = π 4 τ .Expanding the Eq. ( 25) , and ensemble averaging, we find Figure 4: SLM screen with a random wavefront displayed on the circular geometry.Each segment's displayed brightness corresponds to the applied phase.The segment sizes are adjusted to compensate for the beam intensity profile.
giving the well known result [38] Note that the conditions leading to this result are almost never fulfilled exactly.If the SLM is not illuminated evenly, or not all modes contribute equally, we have to fall back to Eq. (20).For example, even if the sample is completely random and |t ba | 2 does not depend on a, we have to take into account the illumination profile on the SLM, giving [32] |γ with A a the field amplitude of the illumination at mode a. Finally, note that for weak, forward scattering, we can approximate t ba = e iϕ ba .This means that there is no need to modulate the intensity of the light and |γ A | 2 = 1.

Automatic detection and quantification
This fidelity |γ A | 2 in Eq. ( 20) is computed in OpenWFS as the fidelity_amplitude attribute in the WFSResult object returned by a WFS algorithm.If this value drops below π/4 ≈ 0.79 significantly, this is an indication that not all modes contribute equally, which may be caused by an uneven illumination of the SLM.

Mitigation
Ref. [21] pioneered the use of a circular geometry to mitigate the effect of a non-uniform illumination of the SLM (see Fig. 4).The idea is to adjust the segment size to the intensity of the illumination, using larger segments in regions where the intensity is lower.This way, we are able to have each segment, on average, contribute equally to the WFS procedure.For this geometry, the segment size can be changed by adjusting the number of segments per ring and the ring radii.In OpenWFS, this segment distribution is available as the function slm.geometry.circular.

Imperfections of the spatial light modulator
In this section, we describe the typical limitations of liquid crystal on silicon (LCoS) phase only SLMs, describe how these limitations affect the fidelity, and provide strategies to mitigate these effects.

Non-modulated light
Most liquid-crystal SLM devices operate in reflection mode.As a result of the layer structure of the SLM there are two main reflections.Fig. 5 shows the simplified layer structure and the predominant transmitted/reflected beams.The first reflection (I 1 ) is generated on the front surface of the protective glass.The main beam (I 2 ), is reflected at the back surface, thus traversing the liquid-crystal (LC) layer, and is the most intense reflection.Finally, internal reflections inside the protective glass can result in dim higher order reflections (I 3 ) [19].
The front surface reflection (I 1 ) of the SLM is not modulated and thus does not contribute to the shaped wave.The reflection coefficient at the air-glass interface depends on the SLM model and the wavelength of the incident beam.For instance, the amplitude reflection coefficient at the air-glass interface of the SLM, model X10468-08 from Hamamatsu, is measured as 0.198 for λ = 647 nm [19].
If we assume that the non-modulated light does not contribute to the intensity in the focus, we can find the fidelity Note that for nearly transparent samples, the non-modulated light may still contribute to the focus, so that this equation is not generally valid.Finally, it should be noted that the popular parallel-aligned (PAL-LCoS) SLMs only modulate one of the polarization states.Any component of the light in the perpendicular polarization state contributes to non-modulated light.

Automatic detection and quantification
OpenWFS provides a simple means to estimate the amount of non-modulated light originating from the front surface reflection of the SLM.It simply performs phase stepping with a flat wavefront.This results in an intensity of with γ 0 the fraction of the field that is not modulated, and I offset the offset in the detector signal caused by non-coherent sources, such as amplifier bias or ambient light.We first determine I offset by closing the shutter of the laser, and subsequently subtract this value from the signal.The amount of non-modulated light can now be estimated from the phase-stepping data as Assuming that γ 2 0 > 1 2 , we find which is output by the troubleshoot function of OpenWFS in the property fidelity_non_modulated.
Note that this function produces incorrect results in the extreme case that more than half of the light is not modulated, such as when the SLM is accidentally turned off.

Mitigation
High ratio's of non-modulated light can be caused by a pattern of SLM segments that underfills the illuminated SLM area, which can be solved by adjusting the mapping of segments to the SLM surface (see Section 6.1.2).
A different source of non-modulated can be the previously explained front reflection (see Fig. 5).The reflectivity of the surface depends on the model of the SLM, and on the wavelength-specific anti-reflection coating applied to it.If the front reflection is too strong, it is possible to tilt the SLM, and aim the front reflection I 1 onto a beam dump.Of course this also introduces tilt in the main reflection I 2 , but this tilt can conveniently be compensated for with a phase gradient on the SLM.Note that this technique is typically unsuitable for pulsed light.The steep phase gradient typically surpasses well beyond 2π and must therefore be phase-wrapped.Hence, the pulse is delayed by different amounts on different parts of the SLM due to phase wrapping.
Lastly, non-modulated light may be caused by the light not having the correct polarization.PAL-SLMs only modulate one polarization component of the light.By choosing an appropriate state of the incident polarization, we can minimize the non-modulated light and thus optimize the fidelity.

Imperfect SLM calibration
In order to display an image on the SLM, the SLM hardware receives the image and converts pixel values to voltages with the use of an internal lookup table.Each SLM requires calibration to attain a linear phase response between 0 to 2π for the wavelength of the incident laser light.Any deviation from this linearity introduces a phase error for each input mode, and reduces the fidelity of the WFS experiment.Therefore, it is crucial to calibrate the SLM properly and load the correct lookup table to the SLM hardware.Alternatively, OpenWFS provides the option to specify a software lookup table, which is accelerated by the GPU using OpenGL.
Figure 6 shows an example of the measured phase response for the SLM (Hamamatsu X13138-07) averaged over three trials.The measured phase response closely matches the ideal linear phase response (dashed line) between 0 to 2π, which demonstrates that the proper lookup table is loaded on the SLM for the chosen wavelength of incident laser light.
If the response of the SLM deviates from a linear phase response, the fidelity of displaying the wavefront reduces.To account for this effect, we assume that the light modulator only modulates the phase, which is appropriate for parallel-aligned (PAL) SLMs, but only approximately so for the older twisted-nematic (TN) SLMs.Let f (ϕ p ) denote the actual phase as a function of the intended modulation phase ϕ p .The response of the light modulator can now be written as a Fourier series where the sum is over the range of k as in Eq. ( 7).Since we assumed phase-only modulation, the coefficient c 0 = 0. Note that this coefficient, if present, would not effect the quantification measurements described below anyway, and the effect of this non-modulated light is already accounted for in |γ 0 | 2 , as explained in Section 7.1.The c 1 component corresponds to the intended phase response, and all other components correspond to orthogonal modes that on average do not contribute to the focus.We can thus quantify this effect with the fidelity Figure 6: Measured SLM phase response and the ideal phase response (dashed line) versus the gray values displayed on the SLM.
Note that for a perfect calibration f (ϕ) = ϕ, c 1 = 1 and all other c k = 0. Also note that an imperfect phase calibration also reduces the signal-to-noise ratio (SNR) in a measurement, causing an additional drop in the fidelity (see Section 8.1).

Automatic detection and quantification
The effect of an imperfect calibration on the phase-stepping response Eq. ( 4) can be written as: The response is no longer a single sinusoid.This fact emerges in the form of non-zero higher frequency components F k,a for |k| > 1. Taking the DFT as defined in Eq. ( 6) now yields: For phase stepping, we only use F 1,a .Note that if non-modulated light is present, we can include it in the R term and still choose c 0 = 0. Also note that the signal is affected by the c −1 component of the phase response.The effect of a non-zero c −1 component cannot be separated from the measured response directly.Here, we assume that c −1 ≪ c 1 , so that we can neglect it.In this case, F 1,a ≈ c 1 M a R * and To isolate the c k components, we perform a linear-least-squares fit.This is done by constructing a matrix with two columns: F 1,a and F * 1,a , and computing the Moore-Penrose pseudoinverse of this matrix: F + .The components of c are then estimated from the measurements as Figure 7: Schematic of the setup for calibrating the SLM lookup table.M: mirror, BS: beam splitter.
giving a fidelity which equals 1 for a perfectly calibrated SLM.Computing |γ ϕ | 2 ≤ 1 provides a way to check for systematic phase errors in the SLM response directly from the WFS measurements.Note the pseudoinverse optimally uses the data of all measurements, making it robust even in the presence of noise.Lastly, note that if c −1 is not negligible, some of the other components c k need to be non-zero as well, in order to fulfill the phase-only constraint e if (ϕ) = 1.Therefore, we find a fidelity < 1 in this case too, so we can still detect a problem with the SLM calibration.The only exception is when c −1 = 1, meaning that the SLM modulates the phase in the exact opposite direction we expect.This case cannot be detected with this method.For feedback-based WFS this is not a problem at all, since the phase sign flips occur both in the measurements and the construction of the focus and thus cancel out.For model-based WFS, however, the sign of the phase modulation is important and should be checked independently [31].
The value of |γ ϕ | 2 is computed automatically from the WFS measurements if the number of phase steps is larger than three.It is available in the WFSResults structure as fidelity_calibration.

Mitigation
A common method to calibrate the phase response of the SLM is using a Michelson-Morley interferometer.Figure 7 shows a simplified schematic of the calibration setup.The laser beam reflected from a mirror (M) interferes with the modulated beam reflected from the SLM.The SLM is divided horizontally in two halves.The phase of the top half (or the bottom half) is modulated from 0 to 2π.This causes the fringe pattern in the top half to shift with respect to the fringes in the bottom half.Since both top and bottom halves of the beam follow the same path, this approach is insensitive to drift in the path length of one of the arms of the interferometer.To define the phase shift value in the fringes, we first perform Fourier transforms of the top and bottom quarters of the fringes image.Neglecting the offset value (first Fourier component), we find the Fourier component having the maximum amplitude which corresponds to the spatial frequency of the fringes.The phase difference of this maximum-amplitude component defines the phase of the fringes.Finally, the measured phase response is inverted and loaded into the SLM hardware as a lookup table.Lastly, note that several other calibration procedures exist.[18]

SLM phase jitter
For LCoS SLMs, the effective phase applied by each pixel is not perfectly stationary.Typically, the phase fluctuates periodically with a frequency equal to the SLM refresh rate or a multiple thereof.This effect is known as phase jitter or flicker [7], and it causes the displayed phase pattern to deviate periodically from the phase pattern that was sent to the SLM.For a uniformly distributed phase error between −∆ϕ and ∆ϕ, the fidelity reduction is given by [3] It can be seen that small errors in the phase do not contribute significantly to the overall fidelity.However, this phase jitter also causes noise during the measurements, which is especially prominent if the algorithm needs to isolate a small variation on top of a large background of modulated light.The phase jitter also adds noise to the WFS measurements, causing a further reduction of |γ| 2 (see Section 8.1).

Automatic detection and quantification
The SLM phase jitter can be distinguished from regular noise by physically turning off the SLM and observing the effect on the noise.The phase jitter may be quantified by performing the interference calibration explained in Section 7.2, but instead of modulating the phase of one of the halves, both SLM halves remain constant and are observed at a high frame rate.Hence, for this method the required observation frame rate is several times higher than the refresh rate of the SLM.

Mitigation
The effect of phase jitter on the measurements can be reduced by setting the exposure time of a camera, or the integration time of a detector, to a multiple of the period of the jitter.This way, the jitter largely averages out over the measurement.However, this does not reduce the effect of jitter in constructing the wavefront, so a factor of |γ J | 2 still arises there.
To reduce the amount of phase jitter, we may use the lowest possible voltages on the SLM that still cause a full 2π phase shift, and choose zero grey value for flat reference wavefronts whenever possible because the jitter is typically higher at higher voltages.It may also be higher for specific gray values due to the pulse code modulation scheme applied in many SLMs.The amount of jitter is also dependent on the model and vendor of the SLM, and can be further reduced by cooling the SLM [7].

SLM timing
An important aspect in optimizing SLM performance is correct timing of the measurements.If the measurement is started too early, the liquid crystals are not yet settled into their new state.If the measurement is started too late, it wastes photon budget and needlessly increases the duration of the experiment.
The image on the modulator is updated with the specified refresh rate.For some SLMs, a hardware clock output is available, or may be isolated from the video signal.OpenWFS, instead, automatically syncrhonizes the measurements using a software triggering mechanism, where OpenGL is used to wait for the vertical retrace event, a historical name for the start of a new frame, and update the image during that event.It is essential to only update the SLM image during the vertical retrace: if it is updated before or after tearing occurs, causing the SLM to display part of the old frame and part of the new frame simultaneously.
After the vertical retrace, it takes some time for the image information to be transferred from the PC to the SLM hardware, and it may also take some additional time for the SLM hardware to start updating the voltages on the SLM pixels.During this latency, or idle time, there is no optical response of the SLM at all.We found that an idle time of 1-3 frame periods is typical, depending on the SLM hardware.
The second interval, the settle time, is the time that is needed for the liquid crystals of the SLM to stabilize.We should not perform measurements during the settle time, and we need to take into account both time intervals for proper synchronization.
If the timing of the SLM is known exactly, we can partially overcome the latency by updating the image on the SLM before the current measurement has finished.Once the SLM starts responding (that is, after the Figure 8: Measured SLM response (a) when the SLM grey value is changed from 0 to 255, and (b) when the grey value is changed from 255 to 0. latency), the measurement will have completed.With these 'pipelined' measurements, enabled by default in OpenWFS, an experiment can be run significantly than without, especially if the settle time is short [39].

Automatic detection and quantification
To measure idle and settle time interval, the phase of the SLM screen is switched between two phase values while recording the reflected beam from the SLM using a photodiode.Figure 8 shows an example of the detected signal measured for Hamamatsu X13138-07 SLM.The image on this SLM is updated with a refresh rate of 60 frames per second.When we change the grey value from 0 (black screen) to 255 (white screen) the SLM responds as shown in Fig. 8(a) (red curve).The blue pulse represents the input signal whose peak indicates the moment that the new grey value is sent to the SLM.From Fig. 8(a) it can also be estimated that the signal oscillates with a period of 8.3 ms (half a frame) representing the phase jitter period.
After sending the new grey value (white screen) on the SLM, the image on the SLM does not change for at least 33 ms, which corresponds to 2 frame periods of latency.After this latency, the SLM takes between 20 and 40 ms to stabilize (the settle time).It can be seen that the settle time is different for switching from white to black or from black to white.

Mitigation
The idle time and settle time should be adjusted to match the measured times (See Fig. 8).Comparing the responses in Fig. 8(a) and Fig. 8(b), we can conclude that the SLM (Hamamatsu X13138-07) responds faster when the grey value is switched from 0 to 255 than when the grey value is changed from 255 to 0. Such information about the SLM timing helps us to design the fast WFS more effectively.For instance, if we arrange the phase stepping for WFS in ascending order, equivalently changing the grey values from 0 to 255 with a chosen number of steps.It causes the grey value to fall from 255 to 0 in the first iteration of the stepping which takes longer than when the grey value rises from 0 to 255.Therefore, arranging the phase steps in descending order results in avoiding the grey value to fall from 255 to 0, consequently making the WFS faster.

Noise in the feedback signal
As explained in Section 3.2, the WFS measurements consist of modulating part of the SLM segments and finding the required phase essentially by fitting sinusoids.In practice, the recorded feedback signal includes the effect of different types of noise such as read-out noise, shot noise, and laser excess noise.In the presence of noise, the measured feedback signal has deviations from the ideal sinusoid, causing the fidelity to decrease by a factor of [45] where SNR is the signal-to-noise ratio, and P sig and P noise are the signal and noise components of the measurement, respectively.

Automatic detection and quantification
In the DFT of the phase-stepping experiments (see Section 3.2) component F 0 refers to the signal offset, and F −1 and F 1 correspond to the sinusoidal response.All remaining components in the Fourier transform correspond to noise, imperfections in the calibration, or non-linear response from the sample.Here, we assume that the response is perfectly linear, so that the only effect comes from noise.We furthermore assume white noise, meaning that the noise is distributed equally over all Fourier components.In particular, this means that the total power of the noise in the 1 st Fourier component, which also includes the signal, can be estimated as where the sum is over all P frequency components of the Fourier transform, excluding the −1 and 1 terms (which include the signal) and the 0 component (which is the signal offset).Assuming that the noise is independent of the signal, we can estimate the total signal power as which can be inserted into Eq.( 40) to compute the fidelity reduction caused by noise.A further refinement can be done by not treating F 1,a as the signal, but to take into account the calibration error and also include all other components c k in Eq. (36).We do so by constructing a 'filtered' signal using the matrix F and its pseudo-inverse F + as defined in Eq. (37).We now treat F as the signal instead of F k,1 .With a perfect calibration of the SLM, these two approaches are equivalent.With a poorly calibrated SLM, however, this approach allows separating the effect of noise and poor calibration to avoid 'double counting' of the calibration fidelity.OpenWFS computes |γ N | 2 from F and stores the value as fidelity_noise.

Mitigation
One technique to reduce the effect of noise is to increase the size of the area where the feedback signal is collected from.Since more light is collected, the SNR of the measurement increases.However, if we take the feedback area too large, the enhancement will be distributed over multiple targets and decreases as |γ| 2 = 1/M , where M is the number of targets [41].
A different technique to improve the SNR is to perform a pre-optimization with a limited number of optical modes [38,45,30].This technique increases the strength of the reference field, thereby increasing the signal strength.The drawback of this technique is that it only works when wavefront shaping for a single target.Many algorithms allow measuring the optimal wavefront for many targets b simulaneously, for example when a camera is used as a detector [25].
It was shown in Ref. [25] that modulating multiple segments at a time can be used to greatly increase the SNR of the phase stepping measurements.In these approaches the number of controlled pixels is equal to the number of reference pixels.It leads to an optimally balanced interference of modulated and reference field.This 50/50 choice for the reference and controlled part guarantees the maximal interferometric visibility and thus maximizes P sig described above.An example of this technique is to use part of the SLM as reference, and perform measurements of the remaining part of the SLM by grouping the pixels in a Hadamard basis [25].Since the fixed reference basically corresponds to non-modulated light, this technique does reduce the fidelity a bit.This reduction can be overcome using a dual-reference technique [21], of which a version working in a Fourier basis [20] is available as the FourierDualReference algorithm.

Instability
A low fidelity may also be the result of an instability in the setup, or a time varying sample.As in any optical setup, there are possible sources of drift, vibrations, and turbulence.The transmission matrix of the sample itself may also vary on very short timescales, such as when the sample is perfused tissue [13].

Automatic detection and quantification
In a transmission geometry, a straightforward way to check the stability of the setup is to capture the transmitted light through the sample before and after the measurements.An exact value for the fidelity cannot easily be determined from these measurements only, since it strongly depends on the nature of the sample.However, it was found that for strongly scattering samples the correlation coefficient between the two images gives a good indication of the reduction of the fidelity due to the instability of the setup [13].
In OpenWFS, we estimate the effect of decorrelation using the Pearson correlation coefficient, where ⟨•⟩ b denotes averaging over all pixels of the output image.For strongly scattering samples, where the intensity has an exponential distribution, this approach is equivalent to that in Ref. [13].The advantage of Eq. ( 44) is that |γ D | 2 ≤ 1 regardless of the intensity distribution of the transmitted light, and that the effect of any background intensity I offset is removed.This estimate is available as fidelity_decorrelation in the result of the troubleshoot function.

Mitigation
There are some simple ways to increase the stability of the setup: 1) Covering the setup using boxes around the setup, with heat sources placed outside the boxes, decreases the air turbulence and temperature-induced drift.2) In the case of using a water immersion objective consider the possibility of bubbles formation and avoid it.3) Since heating of the SLM can cause drift, send randomly changing patterns to the SLM for some time to 'pre-heat' it.4) In order to define the source of instability, separating the probable source from the rest of the setup can help, for instance, turning off all equipment that may cause vibrations or heating, and comparing the long-term stability with each of these devices turned on individually.Lastly, it should be noted that one should either perform the full WFS algorithm faster than the persistence time of the dynamic sample [5], or use a dynamic algorithm designed to continuously follow the scattering behaviour of the sample [41,6].

Photobleaching
In fluorescence microscopy, another reason that the enhancement can seem lower than it should be, is due to bleaching of the fluorophores.Due to many WFS measurements done on the same volume in the sample, significant photobleaching can occur in the measured spot during the WFS measurements.For this reason, the signal can appear to not have improved all that much, while in reality, the sample simply photobleached.Moreover, a very successful WFS experiment can in some cases improve the focus so much that the sample rapidly photobleaches as soon as the computed phase correction pattern is displayed on the SLM.

Automatic detection and quantification
Photobleaching can easily be detected by measuring the same frame before and after the WFS measurements.If the fluorescence signal has significantly decreased due to photobleaching, the frame taken after the measurements will show a lower signal.Note that both frames should be taken with same phase pattern (typically a flat phase pattern) on the SLM, in order to make a fair comparison.To assess the performance of the WFS algorithm, enhancement should be quantified based only on frames frames taken after the WFS measurements.

Mitigation
Photobleaching can be reduced by simply reducing the excitation power.Of course, this comes at the cost of a lower signal to noise ratio, meaning that the mitigation strategies presented in Section 8.1 may need to be applied.9 Other considerations

Multi-target feedback
Throughout this paper, we considered the task of optimizing the intensity in a single mode b.In practice, however, the feedback often comes from a finite-size region that effectively spans multiple optical modes.In this case, WFS finds a solution that simultaneously maximizes the intensity in multiple modes simultaneously.It can be shown [41] that in this case the enhancement is distributed over these modes, effectively causing the total enhancement to reduce with a factor of the number of modes M .
In practice, this means there is a trade-off between the size of the feedback area and the enhancement.Obtaining feedback from a larger area (e.g. by averaging over multiple camera pixels, or using a larger fluorescent guide star) may result in a better SNR, but choosing this area too large causes the enhancement (and also the resolution of the focus) to decrease.

Non-linear feedback
Feedback in a WFS experiment can come in different forms.An interesting form of feedback is that of multi-photon excitation fluorescence (multi-PEF, or more specifically 2-PEF, 3-PEF, etc.).In multi-PEF, a fluorophore is excited by multiple photons before emitting a fluorescence photon.A 2-photon excitation spectrum of a fluorophore is typically similar to the single-photon excitation spectrum but with the wavelength doubled [43].In multi-PEF, the fluorescence signal scales non-linearly with the excitation intensity.If the fluorescence is confined to a small volume (a 'guide star'), a narrower spot size will produce a significantly higher non-linear signal.This can be used as feedback signal for WFS [29].
Despite the non-linear characteristic of the feedback, Phase stepping can still be used to retrieve the relative phase with Eq. ( 6), but ideally I p follows the shape of a cos 2n (ϕ p /2) function, with n denoting the order of non-linearity, as explained in Ref. [28].This non-sinusoidality of I p causes predictable non-zero F k for |k| ≥ 2, even in the absence of noise and for a perfect SLM response.
Lastly, if the fluorescence signal is not coming from a single point, the exact relationship between the order of the non-linearity and the achievable enhancement is complicated and depends on properties of the excitation source and the structure of the fluorescent material in the sample.[28,4,42] With 2-PEF in a fluorescent dye pool, for example, forming a single focus does not optimize the total fluorescence.Instead, WFS finds a complicated pattern of hot-spots throughout the pool [14].If the labelling density is sparse enough, however, iterative WFS converges to a tight focus [14,23].Lastly, for non-linear feedback, some amount of non-sinusoidality of I p is to be expected.See also Section 9.2.

Amplitude-only light modulators
Digital micro-mirror devices (DMDs) are light modulators that modulate only the amplitude of the incident light [5,1].DMDs have a much faster switching rate than liquid crystal SLMs, which is an advantage.However, for strongly scattering samples the amplitude-only modulation reduces the fidelity to a maximum of |γ| 2 = 1/(2π) ≈ 0.16, [1] which is significantly lower than the maximum theoretical fidelity of π/4 ≈ 0.79 for phase-only SLMs.For strongly scattering samples, the fidelity can be increased by roughly a factor of 2 by simply blocking the 0-th order reflection of the DMD [3,37].Alternatively, the DMD can be used in a configuration that enables phase modulation, or even phase-and-amplitude modulation, at the cost of reducing it's effective resolution [5,10] 10 OpenWFS for automatic troubleshooting In this section we show how to run a wavefront shaping experiment with our OpenWFS framework [34].In the Python script shown in Fig. 9, we define virtual hardware devices to run a WFS simulation.In this example, we simulate an SLM with an incorrect phase response by defining the SLM object with a custom phase_response function, and a virtual camera with significant noise.Before running the WFS algorithm, the virtual camera sensor shows a speckle pattern (Fig. 11a).After running the WFS algorithm, the virtual camera sensor shows a focus (Fig. 11b).Due to several detrimental effects, the focus is significantly lower than the theoretical maximum.We show that our troubleshooter can detect and approximately quantify the degraded quality of the result and identify the detrimental effects.
The troubleshooter extracts much of its information from the WFS measurements directly.These results are saved as properties of the WFSResult object that is returned by the algorithm.We can currently simulate the detrimental effects of unequal illumination profile, noise, incorrect phase calibration and non-modulated light.The code is generic such that it can be used both for simulations and for experiments, by replacing the virtual hardware classes with real hardware classes.
We show an example output of the troubleshoot function in Fig. 10.An enhancement of almost 16 has been reached in this experiment.Although this is already a usable enhancement, this is not quite as high as the theoretical value of 100, equal to the number of measured modes.The metrics give insight into what caused the reduced enhancement.The fidelity_amplitude is significantly lower than 1, indicating that the SLM segments were not equally illuminated.The fidelity_noise is significantly lower than 1, indicating a significant effect of noise.The fidelity_phase_calibration is significantly lower than 1, indicating a problem with the SLM phase calibration.Lastly, all these fidelity estimations are combined to compute an order of magnitude estimate of the expected enhancement.These numbers indicate which are the likely causes of the lower-than-ideal enhancement, and thus help in mitigating their detrimental effects.

Conclusion
The field of WFS is full of exciting new advances, from interesting new use cases to state-of-the-art algorithms.However, the most scientific publications only give limited attention to the the technical details of implementing these methods in practice.
In this paper, we described many of the problems that can degrade the performance of a WFS experiment.Anyone starting in this field is likely to encounter one or more of these problems, giving WFS a steep 'learning curve' that may frustrate researchers and needlessly slow down progress in this exciting field.
We gave a comprehensive overview of the most common issues that may plague WFS experiments, covering issues caused by imperfections in the feedback measurements, imperfections of the SLM, or simply properties of the modulation scheme.
We found that many of these issues can be detected and quantified automatically, often using the data that is already available from the WFS experiments themselves.These automatic troubleshooters are integrated in our open source OpenWFS Python package [34], which also provides all the essential boilerplate code to start working with spatial light modulators, WFS algorithms, and for simulating WFS under realistic experimental conditions.This way, we hope to lower the threshold for starting in this field, and to reduce much of the frustration that may be accompanied with troubleshooting experimental issues.

Figure 1 :
Figure 1: Schematic illustration of wavefront shaping.SLM: spatial light modulator.OBJ: objective.a.Focusing inside a non-aberrating sample.b.Focusing inside an aberrating sample results in a distorted focus.c.Focusing inside an aberrating sample with a WFS microscope.By shaping the incoming wavefront with a spatial light modulator, the focus can be restored.

• 2 • 2 • 2 • 2 • 2 • 2 •
The effect of a finite number of modes |γ N | The effect of phase-only modulation |γ A | The effect of non-modulated light |γ 0 | The effect of imperfect phase modulation |γ ϕ | The effect of phase jitter |γ J | The effect of a finite signal-to-noise ratio |γ S | The effect of drift and sample decorrelation |γ D | 2

Figure 3 :
Figure 3: Measured beam location on the SLM.Each segment's displayed brightness corresponds to the measured contribution |t ba | 2 for that segment.

Figure 5 :
Figure 5: The main transmitted/reflected beams in the simplified SLM layer structure.

Figure 11 :
Figure 11: Simulated wavefront shaping with OpenWFS.a.A simulated speckle pattern.b.A focus acquired after simulated wavefront shaping under imperfect circumstances.