# Noise characterization and reconstruction

### Reconstructing noise spectra using shaped control pulses

The Q-CTRL Python Package enables you to characterize and then reconstruct power spectral densities for noise processes affecting your system. These power spectral densities can provide useful information for designing robust controls that improve the performance of the system in the presence of noise. In this notebook we show how to characterize and reconstruct noise spectra using the Q-CTRL Python Package.

## Theory of SVD-based noise reconstruction

Before presenting specific examples using the Q-CTRL Python Package, we give an overview of the singular value decomposition (SVD)-based algorithm underlying the reconstruction.

The general idea is to use the system to probe the spectral properties of the noise process, using the following steps:

- generate a set of control pulses that effect identity gates but are sensitive to noises at different frequencies,
- run the control pulses on the system and record the resulting infidelities,
- reconstruct the spectrum based on the control pulse sensitivities (specifically their filter functions) and measured infidelities.

More precisely, consider an arbitrary qubit system. We define the noise Hamiltonian, which adds perturbatively to the noise-free Hamiltonian, as a sum of individual noise channels:

$$ H_\text{noise}(t) = \sum_{i=1}^n \beta_i(t)N_i(t), $$where $N_i$ is a noise axis operator corresponding $i$-th noise channel.

We assume that we have some array of different control pulses (resulting from step 1 above). The filter function associated with the $i$-th noise channel and the $j$-th control is defined as:

$$ F_{i,j}(\omega) = \frac{1}{D}\texttt{Tr}\left(\mathcal{F}[\tilde{N}_{i,j}]\mathcal{F}[\tilde{N}_{i,j}]^\dagger\right) $$where $D$ is the Hilbert space dimension, $\mathcal{F}$ is the Fourier transform operator and $\tilde{N}_{i,j}:=U_j^\dagger N_iU_j$ is the $i$-th noise operator in the control frame (where $U_j$ is the time evolution operator due to the $j$-th control).

Using filter function theory, the infidelity measurement collected for the $j$-th control is:

$$ I_j = \sum_{i=1}^n \frac{1}{2\pi} \int_{-\infty}^{\infty} S_i(\omega)F_{i,j}(\omega) d\omega, $$where $S_i(\omega)$ is the power spectral density for the $i$-th noise channel. This integral can be approximated as a discrete summation:

$$ \tilde{I}_j = \sum_{i=1}^n \frac{1}{2\pi} \sum_p S_i[\omega_p]F_{i,j}[\omega_p] \Delta\omega. $$Accumulating the infidelities from all the controls into a vector, concatenating the noise spectral densities associated with all noises into a vector, and flattening the discretized filter functions into a matrix with rows corresponding to controls and columns corresponding to noises and frequencies, we have:

$$ \tilde{\mathbf{I}} = \frac{\Delta\omega}{2\pi}\mathbf{FS} = \mathbf{F'S}, $$where $\mathbf{F'}:=\frac{\Delta\omega}{2\pi}\mathbf{F}$. The noise spectrum $\mathbf{S}$ is thus:

$$ \mathbf{S} = \mathbf{F'}^{-1}\tilde{\mathbf{I}}. $$The singular value decomposition (SVD) gives $\mathbf{F'} = \mathbf{UDV}^\dagger$ where $\mathbf{U}$, $\mathbf{V}^\dagger$ are unitary matrices and $\mathbf{D}$ is a diagonal matrix of singular values $s_i$. Therefore, the pseudoinverse is easily calculated as:

$$ \mathbf{F'}^{-1} = \mathbf{VD}^{+}\mathbf{U}^\dagger, $$where $\mathbf{D}^+$ is a diagonal matrix of reciprocal singular values $\frac{1}{s_i}$. Combining this pseudoinverse with the previous expression for $\mathbf S$, we have:

$$ \mathbf{S} = \mathbf{VD}^{+}\mathbf{U}^\dagger\tilde{\mathbf{I}}. $$There may be several infidelity values collected for each control pulse, which gives rise to a distribution of infidelities with standard deviation $\sigma_{j}$. This translates to uncertainty in the reconstructed noise spectrum estimation. The correlation matrix for infidelity is $\Sigma_I=\texttt{diag}(\sigma_0, \ldots, \sigma_C)$. Due to linear transformation, the corresponding uncertainty in the noise spectrum estimation is given by:

$$ \Sigma_S = \mathbf{VD}^{+}\mathbf{U}^\dagger\Sigma_I\mathbf{UD}^{+}\mathbf{V}^\dagger. $$The final issue we consider is numerical instability. Small singular values in the decomposition may give rise to instabilities during the inversion process, which may necessitate truncation of singular values. Singular values may be truncated manually, or using entropy-based selection. For the latter, the entropy of the normalized singular values is calculated as:

$$ E = - \sum_i \frac{s_i}{\sum_i s_i} \texttt{log}_2\left(\frac{s_i}{\sum_i s_i}\right), $$and then only the largest $\lfloor{2^E}\rfloor$ singular values are retained.

With this in theory in hand, we now show how to perform noise reconstruction using the Q-CTRL Python Package.

```
# Essential imports
import numpy as np
from qctrl import Qctrl
# Plotting imports
import matplotlib.pyplot as plt
from qctrlvisualizer import (
plot_controls,
plot_filter_functions,
)
# Convenience imports
from tqdm import tqdm
# Starting a session with the API
qctrl = Qctrl()
```

## Worked example: amplitude noise

In this example we consider a one-qubit system driven by a controllable Rabi rate that is subject to amplitude noise. The Hamiltonian of the system is:

\begin{align*} H(t) = &\frac{1+\beta_\Omega(t)}{2} \Omega(t) \sigma_x, \end{align*}where $\Omega(t)$ is the controllable Rabi rate, $\beta_\Omega(t)$ is a fractional time-dependent amplitude fluctuation process and $\sigma_x$ is the Pauli X matrix. We assume that the noise process $\beta_\Omega(t)$ consists of pink noise with a small Gaussian feature, as shown below.

```
def gaussian(frequencies, offset, width):
return np.exp(-0.5*(frequencies - offset)**2 / width**2) / (np.sqrt(2*np.pi)*width)
def pink(frequencies, frequency_cutoff, power):
return frequency_cutoff**(power-1)/(frequencies**power + frequency_cutoff**power)
frequencies = np.linspace(0, 0.5*1e6, 1000)
amplitude_noise = 0.5e-11*(
25*pink(frequencies=frequencies, frequency_cutoff=0.1*1e6, power=6)
+ gaussian(frequencies=frequencies, offset=0.2*1e6, width=10*1e3)
)
plt.plot(frequencies/1e6, amplitude_noise*1e6)
plt.fill_between(frequencies/1e6, 0, amplitude_noise*1e6, alpha=0.25)
plt.xlabel("Frequency (MHz)")
plt.ylabel("Power density (1/MHz)")
plt.title("Amplitude noise spectrum")
plt.show()
```

We will demonstrate how this spectrum, which would initially be unknown in practice, can be reconstructed using the Q-CTRL Python Package.

As described in the introduction to this guide, the reconstruction proceeds in three stages:

- generate a set of control pulses that are sensitive to noises at different frequencies
- run the control pulses on the system and record the resulting infidelities
- reconstruct the spectrum based on the control pulse sensitivities and measured infidelities.

The Q-CTRL Python Package provides functionality to perform steps 1 and 3 of this procedure.

### Creating the noise characterization

The first step is to generate the set of control pulses that will be used to probe the system. This process is known as noise characterization. To perform a noise characterization, we start by creating a `noise_characterization`

object, which requires:

- maximum pulse duration,
- minimum time step (which describes the resolution for pulse shaping),
- maximum Rabi rate,
- pulse count (which affects the resolution of the eventual reconstruction).

```
# Define system parameters
omega_max = 2*np.pi * 250 * 1e6 #Hz
maximum_duration = 100 * 1e-6 #s
minimum_timestep = 1 * 1e-6 #s
pulse_count = 30
# Define noise characterization object
noise_characterization = qctrl.factories.noise_characterizations.create(
maximum_duration=maximum_duration,
minimum_timestep=minimum_timestep,
upper_bound=omega_max,
pulse_count=pulse_count,
noise_type="amplitude")
```

```
noise_characterization_result = qctrl.services.noise_characterization.calculate(noise_characterization)
```

```
# Print some segments from the first pulse.
print(f"First 5 segments from pulse #0: {noise_characterization_result.pulses[0].segments[:5]}")
# Visualize every 5th pulse.
plot_controls(plt.figure(), {f'Pulse #{n}': noise_characterization_result.pulses[n].segments
for n in range(0, len(noise_characterization_result.pulses), 5)})
plt.show()
```

### Run the characterization pulses on your system to obtain infidelities

In a noise-free system, each of the generated control pulses would effect in identity gate. In the presence of noise, however, there will be some non-zero infidelity. The next step of the reconstruction process is to calculate these infidelities. This process requires an actual system, which we do not have in this sample case, so instead we provide simulated infidelities (as a list of pairs containing infidelities and the corresponding uncertainties). Note also that the order of the characterization pulses produced above may change, so we need to ensure the simulated infidelities are matched to the correct pulse (which we achieve by identifying each pulse by its rounded first segment value).

```
infidelity_results = [
{7516: (0.007048632668801616, 0.0007048632668801617),
8928: (0.004774844356753105, 0.0004774844356753105),
9727: (0.005910859634251226, 0.0005910859634251226),
9945: (0.0061237002332896594, 0.000612370023328966),
9056: (0.00470285142015325, 0.00047028514201532504),
7701: (0.0027878935754919736, 0.0002787893575491974),
7236: (0.0016619188733463948, 0.0001661918873346395),
7075: (0.0009686447806666752, 9.686447806666752e-05),
6985: (0.0005477584527334665, 5.477584527334665e-05),
6717: (0.00026097917879606915, 2.6097917879606917e-05),
6879: (0.00024768130962015826, 2.4768130962015826e-05),
6420: (0.0003545783175592041, 3.5457831755920414e-05),
6188: (0.0004223634174282583, 4.223634174282583e-05),
6091: (0.00014731160827016906, 1.4731160827016906e-05),
5758: (5.550691649601601e-05, 5.5506916496016015e-06),
5561: (5.937826353887565e-05, 5.9378263538875655e-06),
5361: (4.817894939064e-05, 4.8178949390640006e-06),
5094: (3.7761696322994185e-05, 3.776169632299419e-06),
4285: (4.022393562967939e-05, 4.022393562967939e-06),
5135: (3.08321084534512e-05, 3.0832108453451204e-06),
3827: (2.2885482108824496e-05, 2.28854821088245e-06),
3256: (7.0350843116335715e-06, 7.035084311633572e-07),
2883: (3.929807075234855e-06, 3.929807075234855e-07),
2432: (3.306595880606712e-05, 3.306595880606712e-06),
2237: (1.7080847865961018e-06, 1.708084786596102e-07),
1780: (2.8789751179167244e-06, 2.8789751179167246e-07),
1298: (2.8256229444691974e-05, 2.8256229444691977e-06),
831: (1.4546300021453161e-05, 1.4546300021453161e-06),
460: (2.6710303642853825e-05, 2.6710303642853827e-06),
84: (0.00030468792002851793, 3.0468792002851794e-05)}[int(pulse.segments[0]['value'])]
for pulse in noise_characterization_result.pulses]
```

### Creating the noise reconstruction

With the infidelities in hand (which, we recall, in practice would be obtained from running the characterization pulses on an actual system rather than a simulation), we may proceed with the noise reconstruction. The next step is to create a `noise_reconstruction`

object, which encapsulates the type of singular value truncation to use (in this case we use entropy-based truncation) and will contain the result of the reconstruction.

```
noise_reconstruction = qctrl.factories.entropy_noise_reconstructions.create()
```

### Creating a system for each characterization pulse

Next we need to populate a `system`

object corresponding to each characterization experiment. This object is what combines the measured infidelities with the applied control pulses, in the context of a noise reconstruction. The general process for creating `system`

, `control`

and `pulse`

objects is described in the Setup feature guide.

```
# Define standard matrices
sigma_x = np.array([[0., 1.], [1., 0.]], dtype=np.complex)
# Store information about each characterization pulse in a dictionary
pulses_info = [{} for _ in noise_characterization_result.pulses]
# Create the system, control and pulse objects corresponding to each characterization pulse
for index, (pulse_info, pulse, infidelity_result) in enumerate(zip(tqdm(pulses_info),
noise_characterization_result.pulses,
infidelity_results)):
# Create the system, providing the noise reconstruction and measured infidelity
system = qctrl.factories.systems.create(
name=f"System {index}",
hilbert_space_dimension=2,
noise_reconstruction=noise_reconstruction,
measured_infidelity=infidelity_result[0],
measured_infidelity_uncertainty=infidelity_result[1],
)
# Create the control, with custom pulse matching the characterization pulse
control = qctrl.factories.shift_controls.create(
system=system,
name="Rabi rate",
operator=sigma_x/2,
)
control_pulse = qctrl.factories.custom_pulses.create(
control=control,
segments=pulse.segments,
)
# Save objects for later use
pulse_info['system'] = system
pulse_info['control'] = control
```

### Creating the noises

For noise reconstruction, we use a special type of "reconstructed" `noise`

object, which specifies (in addition to the standard fields like system and control) the details to use when reconstructing the noise. In particular, we must specify minimum frequency, maximum frequency and sample count for the reconstructed spectrum, and a sample count to use for the internal filter function calculation.

```
# Define system parameters
minimum_frequency = 1. #Hz (must be >0)
maximum_frequency = 0.5*1e6 #Hz
noise_spectral_density_point_count = 1000
filter_function_sample_count = 200
for index, pulse_info in enumerate(tqdm(pulses_info)):
pulse_info['noise'] = qctrl.factories.reconstructed_control_noises.create(
name="Amplitude",
control=pulse_info['control'],
system=pulse_info['system'],
minimum_frequency=minimum_frequency,
maximum_frequency=maximum_frequency,
filter_function_sample_count=filter_function_sample_count,
noise_spectral_density_point_count=noise_spectral_density_point_count,
)
```

```
for index, pulse_info in enumerate(tqdm(pulses_info)):
qctrl.factories.filter_functions.create(
noise=pulse_info['noise'],
sample_count=filter_function_sample_count,
interpolated_frequencies=np.linspace(
minimum_frequency, maximum_frequency, noise_spectral_density_point_count),
)
```

### Calculating the noise reconstruction

We have now set up, for each characterization pulse, objects that describe the pulse used for the experiment, the resulting infidelity, and the requirements for the reconstructed noise spectral density. We may now proceed to perform the noise reconstruction, using the `noise_reconstructions`

service.

```
noise_reconstruction_result = qctrl.services.noise_reconstructions.calculate(noise_reconstruction)
```

### Extracting and visualizing the filter functions

Before presenting the final reconstructed noise, we note that an intermediate step of the noise reconstruction computation is calculation of the filter functions associated with each characterization experiment. Extracting and visualizing these filter functions can provide valuable insights into the mechanism underlying the reconstruction. Here, we see that each characterization experiment is highly sensitive to noise only in the vicinity of a specific frequency. This property ensures that we can produce an accurate reconstruction even with only a small number of measurements.

```
filter_functions = [system.controls[0].noise.filter_functions[0]
for system in noise_reconstruction_result.systems]
# Plot all filter functions.
_, ax = plt.subplots(figsize=(10,5))
for filter_function in filter_functions:
ax.plot([point['frequency']*1e-6 for point in filter_function.interpolated_points],
[point['inverse_power'] for point in filter_function.interpolated_points])
plt.xlabel("Frequency (MHz)")
plt.ylabel("Inverse power")
plt.show()
```

### Extracting and visualizing the reconstructed noise spectral density

Finally, we may extract the reconstructed noise spectral density out of any of the "reconstructed" `noise`

objects. Here we use the noise in the system corresponding to the first pulse, and plot the reconstructed spectrum against the original spectrum.

```
sampled_points = noise_reconstruction_result.systems[0].controls[0].noise.noise_spectral_density.sampled_points
# Print some samples from the reconstructed noise spectral density.
print(f"First 5 samples: {sampled_points[:5]}")
# Plot the entire noise spectral density, including uncertainties.
_, ax = plt.subplots(figsize=(10,5))
sampled_frequencies = np.array([point['frequency'] for point in sampled_points])
sampled_power_densities = np.array([point['power'] for point in sampled_points])
sampled_power_densities_uncertainties = np.array([point['power_uncertainty'] for point in sampled_points])
ax.plot(frequencies*1e-6, amplitude_noise*1e6, label="Original")
lines = ax.plot(sampled_frequencies*1e-6, sampled_power_densities*1e6, label="Reconstructed")
ax.fill_between(
frequencies*1e-6,
(sampled_power_densities-sampled_power_densities_uncertainties)*1e6,
(sampled_power_densities+sampled_power_densities_uncertainties)*1e6,
alpha=0.35,
hatch='||',
facecolor='none',
edgecolor=lines[0].get_color(),
linewidth=0)
ax.legend()
ax.set_xlabel("Frequency (MHz)")
ax.set_ylabel("Power density (1/MHz)")
plt.show()
```

### Summary

We see that the reconstructed noise spectral density matches the original noise spectral density very closely. We have thus demonstrated how to use the Q-CTRL Python Package to reconstruct the noise spectral density of an amplitude noise process affecting a single qubit system. Similar procedures may be employed to reconstruct noise spectral densities for other noise processes (for example stochastic dephasing noises) in other types of systems.