Code Examples

Production-ready code samples for integrated CV squeezer design and analysis

Basic Examples

Device Design

Analysis

Applications

Basic Examples

Simple Squeezing Calculation

Beginner

Calculate basic squeezing levels for both SiN and TFLN platforms with typical parameters.

"""
Basic squeezing calculation for SiN and TFLN platforms.
"""
import numpy as np
from cv_squeezer import SqueezerSimulator

# Platform comparison
platforms = {
    "SiN Kerr": {
        "platform": "sin",
        "pump_power": 50e-3,      # 50 mW
        "escape_eff": 0.85
    },
    "TFLN OPA": {
        "platform": "tfln",
        "pump_power": 5e-3,       # 5 mW
        "escape_eff": 0.92
    }
}

for name, params in platforms.items():
    sim = SqueezerSimulator(
        platform=params["platform"],
        wavelength=1550e-9
    )

    result = sim.calculate_squeezing(
        pump_power=params["pump_power"],
        escape_efficiency=params["escape_eff"]
    )

    print(f"\n{name}:")
    print(f"  Squeezing: {result['squeezing_dB']:.1f} dB")
    print(f"  Anti-squeezing: +{result['antisqueezing_dB']:.1f} dB")
    print(f"  Squeezing parameter r: {result['r']:.3f}")

# Output:
# SiN Kerr:
#   Squeezing: -6.2 dB
#   Anti-squeezing: +8.4 dB
#   Squeezing parameter r: 0.714
# 
# TFLN OPA:
#   Squeezing: -10.8 dB
#   Anti-squeezing: +12.1 dB
#   Squeezing parameter r: 1.244

Covariance Matrix Operations

Beginner

Create and manipulate Gaussian states using covariance matrix formalism.

"""
Gaussian state manipulation with covariance matrices.
"""
from cv_squeezer.quantum import CovarianceMatrix
import numpy as np

# Create different quantum states
vacuum = CovarianceMatrix.vacuum()
squeezed = CovarianceMatrix.squeezed_vacuum(r=1.0, theta=0)
thermal = CovarianceMatrix.thermal(n_bar=0.1)

print("Vacuum state covariance:")
print(vacuum.matrix)
# [[0.5, 0.0],
#  [0.0, 0.5]]

print("\nSqueezed state (r=1.0):")
print(squeezed.matrix)
# [[0.068, 0.0],
#  [0.0,  3.69]]

# Apply optical loss (50%)
squeezed_lossy = squeezed.apply_loss(efficiency=0.5)
var_x, var_p = squeezed_lossy.variances()
print(f"\nAfter 50% loss: ΔX²={var_x:.3f}, ΔP²={var_p:.3f}")

# Rotate squeezing angle by 45°
squeezed_rotated = squeezed.rotate(theta=np.pi/4)
print(f"Rotated state purity: {squeezed_rotated.purity():.4f}")

Device Design Examples

SiN Ring Resonator Optimization

Intermediate

Design and optimize a silicon nitride microring for maximum squeezing with target specifications.

"""
SiN microring resonator optimization for Kerr squeezing.
"""
from cv_squeezer.platforms import RingResonator
import numpy as np
import matplotlib.pyplot as plt

# Design specifications
TARGET_ESCAPE_EFF = 0.90
TARGET_FSR = 100e9  # 100 GHz
WAVELENGTH = 1550e-9

# Create ring with initial parameters
ring = RingResonator(
    radius=50e-6,
    width=1.2e-6,
    height=800e-9,
    gap=200e-9,
    n2=2.4e-19,
    propagation_loss=0.5  # dB/cm
)

# Get baseline properties
props = ring.calculate_properties()
print("Initial design:")
print(f"  Q_total: {props['Q_total']:.0f}")
print(f"  FSR: {props['FSR']/1e9:.1f} GHz")
print(f"  Escape efficiency: {ring.escape_efficiency():.2%}")

# Optimize coupling gap for target escape efficiency
optimal_gap = ring.optimize_coupling(TARGET_ESCAPE_EFF)
ring.gap = optimal_gap

print(f"\nOptimized gap: {optimal_gap*1e9:.0f} nm")
print(f"  New escape efficiency: {ring.escape_efficiency():.2%}")

# Calculate squeezing vs pump power
pump_powers = np.linspace(10e-3, 100e-3, 50)
squeezing_dB = []

for P in pump_powers:
    G = ring.fwm_gain(pump_power=P)
    eta = ring.escape_efficiency()
    # Simplified squeezing formula
    V_sq = 1 - eta * 4 * G / (1 + G)**2
    squeezing_dB.append(10 * np.log10(max(V_sq, 1e-6)))

# Plot results
plt.figure(figsize=(10, 6))
plt.plot(pump_powers * 1e3, squeezing_dB, 'b-', linewidth=2)
plt.xlabel('Pump Power (mW)')
plt.ylabel('Squeezing (dB)')
plt.title('SiN Microring Squeezing vs Pump Power')
plt.grid(True, alpha=0.3)
plt.savefig('sin_squeezing_optimization.png', dpi=150)

TFLN OPA Waveguide Design

Intermediate

Design a thin-film lithium niobate OPA for high-level squeezing with temperature tuning analysis.

"""
TFLN OPA waveguide design with temperature tuning.
"""
from cv_squeezer.platforms import OPAWaveguide
import numpy as np
import matplotlib.pyplot as plt

# TFLN waveguide parameters
opa = OPAWaveguide(
    length=10e-3,           # 10 mm
    width=1.5e-6,
    film_thickness=600e-9,
    poling_period=4.5e-6,   # QPM period
    d_eff=27e-12,           # d₃₃ coefficient
    propagation_loss=0.05   # dB/cm
)

# Squeezing vs waveguide length
lengths = np.linspace(1e-3, 20e-3, 50)
pump_power = 5e-3  # 5 mW

squeezing = opa.squeezing_vs_length(lengths, pump_power)

print("TFLN OPA Design Analysis:")
print(f"  Pump power: {pump_power*1e3:.0f} mW")
print(f"  Optimal length: {lengths[np.argmin(squeezing)]*1e3:.1f} mm")
print(f"  Max squeezing: {min(squeezing):.1f} dB")

# Temperature tuning curve
temperatures = np.linspace(20, 100, 100)
pm_wavelengths = opa.temperature_tuning_curve(temperatures)

print(f"\nPhase matching at 50°C: {pm_wavelengths[30]*1e9:.2f} nm")

# Gain bandwidth at different powers
for P in [1e-3, 5e-3, 10e-3]:
    gain = opa.parametric_gain(pump_power=P)
    bw = opa.bandwidth(pump_power=P)
    print(f"P={P*1e3:.0f}mW: G={gain:.1f}, BW={bw/1e9:.1f} GHz")

Analysis Examples

Complete Loss Budget Analysis

Intermediate

Track all loss sources in a PIC squeezer system and analyze their impact on detected squeezing.

"""
Comprehensive loss budget for integrated squeezer.
"""
from cv_squeezer.analysis import LossBudget
import numpy as np

# Create loss budget
budget = LossBudget()

# On-chip losses
budget.add_loss("Cavity escape efficiency", 0.88)
budget.add_loss("Waveguide propagation (2 cm)", 0.95)
budget.add_loss("On-chip filter insertion", 0.90)

# Coupling losses
budget.add_loss("Edge coupling to fiber", 0.80)

# Fiber path losses
budget.add_loss("Fiber connectors (2×)", 0.98)
budget.add_loss("External filter", 0.92)

# Detection
budget.add_loss("Beam splitter (homodyne)", 0.99)
budget.add_loss("Detector quantum efficiency", 0.95)

# Summary
print("Loss Budget Summary:")
print("=" * 50)
for name, eff in budget.losses.items():
    loss_dB = -10 * np.log10(eff)
    print(f"{name:35} {eff:.2%} ({loss_dB:.2f} dB)")

total_eff = budget.total_efficiency()
total_loss_dB = -10 * np.log10(total_eff)
print("=" * 50)
print(f"{'Total efficiency':35} {total_eff:.2%} ({total_loss_dB:.2f} dB)")

# Impact on squeezing
source_squeezing_dB = -12  # On-chip squeezing
detected = budget.detected_squeezing(source_squeezing_dB)

print(f"\nSource squeezing: {source_squeezing_dB} dB")
print(f"Detected squeezing: {detected:.1f} dB")
print(f"Squeezing degradation: {detected - source_squeezing_dB:.1f} dB")

# Sensitivity analysis
print("\nSensitivity (1% improvement in each):")
sensitivities = budget.sensitivity_analysis(source_squeezing_dB)
for name, sens in sorted(sensitivities.items(), key=lambda x: x[1], reverse=True):
    print(f"  {name:35} +{sens:.3f} dB")

Frequency-Dependent Spectral Analysis

Intermediate

Analyze the squeezing spectrum and determine optimal measurement frequencies.

"""
Squeezing spectrum analysis for different applications.
"""
from cv_squeezer.analysis import SpectralAnalyzer
import numpy as np
import matplotlib.pyplot as plt

# Create analyzer with typical parameters
analyzer = SpectralAnalyzer(
    linewidth=50e6,          # 50 MHz cavity linewidth
    gain=8.0,                # Parametric gain
    escape_efficiency=0.90,  # 90% escape efficiency
    internal_loss=5e6        # 5 MHz internal loss rate
)

# Calculate spectrum
freqs = np.linspace(0, 200e6, 1000)
sq_spectrum = analyzer.squeezing_spectrum(freqs)
antisq_spectrum = analyzer.antisqueezing_spectrum(freqs)

# Key metrics
bw_3dB = analyzer.bandwidth_3dB()
zero_freq_sq = analyzer.squeezing_at(0)

print("Spectral Analysis Results:")
print(f"  Zero-frequency squeezing: {zero_freq_sq:.1f} dB")
print(f"  3 dB bandwidth: {bw_3dB/1e6:.1f} MHz")

# Application-specific frequencies
applications = {
    "GW detection (LIGO)": 10e6,     # 10 MHz
    "CV-QKD": 25e6,                 # 25 MHz
    "Quantum computing": 100e6,     # 100 MHz
}

print("\nSqueezing at application frequencies:")
for app, freq in applications.items():
    sq = analyzer.squeezing_at(freq)
    print(f"  {app}: {sq:.1f} dB @ {freq/1e6:.0f} MHz")

# Plot spectrum
fig, ax = plt.subplots(figsize=(12, 6))
ax.plot(freqs/1e6, sq_spectrum, 'b-', label='Squeezing', lw=2)
ax.plot(freqs/1e6, antisq_spectrum, 'r-', label='Anti-squeezing', lw=2)
ax.axhline(y=0, color='gray', linestyle='--', label='Shot noise')
ax.set_xlabel('Sideband Frequency (MHz)')
ax.set_ylabel('Noise Level (dB rel. shot noise)')
ax.legend()
ax.grid(True, alpha=0.3)
plt.savefig('squeezing_spectrum.png', dpi=150)

Application Examples

Squeezed States for CV-QKD

Advanced

Calculate the key rate improvement when using squeezed states in continuous-variable QKD.

"""
CV-QKD key rate enhancement with squeezed states.
"""
from cv_squeezer import SqueezerSimulator
from cv_squeezer.quantum import CovarianceMatrix
import numpy as np

def cv_qkd_key_rate(V_A, eta_ch, excess_noise, beta=0.95):
    """
    Calculate asymptotic secret key rate for GMCS CV-QKD.

    V_A: Alice's modulation variance (in shot noise units)
    eta_ch: Channel transmittance
    excess_noise: Excess noise (shot noise units)
    beta: Reconciliation efficiency
    """
    # Bob's measured variance
    V_B = eta_ch * V_A + 1 + excess_noise

    # Mutual information I(A:B)
    I_AB = 0.5 * np.log2(1 + eta_ch * V_A / (1 + excess_noise))

    # Holevo bound χ(B:E) - simplified
    chi_BE = 0.5 * np.log2(V_B / (1 + excess_noise))

    # Secret key rate
    K = beta * I_AB - chi_BE
    return max(0, K)

# Simulation parameters
distances = np.linspace(0, 50, 100)  # km
fiber_loss = 0.2  # dB/km
excess_noise = 0.01  # shot noise units

# Standard coherent state protocol
V_mod_coherent = 4.0  # Optimal modulation for coherent

# Squeezed state protocol (6 dB squeezing)
squeezing_dB = 6
V_squeezed = 10**(-squeezing_dB/10)  # Squeezed variance
V_mod_squeezed = 4.0 / V_squeezed  # Adjusted modulation

key_rates_coherent = []
key_rates_squeezed = []

for d in distances:
    eta_ch = 10**(-fiber_loss * d / 10)

    K_coh = cv_qkd_key_rate(V_mod_coherent, eta_ch, excess_noise)
    K_sq = cv_qkd_key_rate(V_mod_squeezed, eta_ch, excess_noise * V_squeezed)

    key_rates_coherent.append(K_coh)
    key_rates_squeezed.append(K_sq)

# Find max distances
max_dist_coh = distances[np.argmax(np.array(key_rates_coherent) <= 0)]
max_dist_sq = distances[np.argmax(np.array(key_rates_squeezed) <= 0)]

print("CV-QKD Performance Comparison:")
print(f"  Coherent state max distance: {max_dist_coh:.0f} km")
print(f"  Squeezed state ({squeezing_dB} dB) max distance: {max_dist_sq:.0f} km")
print(f"  Distance improvement: {max_dist_sq - max_dist_coh:.0f} km")

Wigner Function Visualization

Advanced

Generate publication-quality Wigner function visualizations of squeezed states.

"""
Wigner function visualization for quantum states.
"""
from cv_squeezer.quantum import CovarianceMatrix
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm

def plot_wigner(sigma, title, ax, xrange=4, resolution=100):
    """Plot Wigner function with noise ellipse overlay."""

    # Generate Wigner function
    x = np.linspace(-xrange, xrange, resolution)
    p = np.linspace(-xrange, xrange, resolution)
    X, P = np.meshgrid(x, p)

    W = sigma.wigner(X, P)

    # Plot
    im = ax.contourf(X, P, W, levels=50, cmap='RdBu_r')

    # Add noise ellipse (1σ contour)
    theta = np.linspace(0, 2*np.pi, 100)
    eigenvalues, eigenvectors = np.linalg.eig(sigma.matrix)

    # Ellipse parameters
    a = np.sqrt(eigenvalues[0])
    b = np.sqrt(eigenvalues[1])
    angle = np.arctan2(eigenvectors[1,0], eigenvectors[0,0])

    x_ell = a * np.cos(theta)
    p_ell = b * np.sin(theta)
    x_rot = x_ell * np.cos(angle) - p_ell * np.sin(angle)
    p_rot = x_ell * np.sin(angle) + p_ell * np.cos(angle)

    ax.plot(x_rot, p_rot, 'k-', linewidth=2, label='1σ ellipse')

    # Vacuum reference circle
    vac_radius = np.sqrt(0.5)
    ax.plot(vac_radius*np.cos(theta), vac_radius*np.sin(theta),
            '--', color='gray', label='Vacuum')

    ax.set_xlabel('X quadrature')
    ax.set_ylabel('P quadrature')
    ax.set_title(title)
    ax.set_aspect('equal')
    ax.legend(loc='upper right')

    return im

# Create states to visualize
states = [
    (CovarianceMatrix.vacuum(), "Vacuum State"),
    (CovarianceMatrix.squeezed_vacuum(0.69, 0), "6 dB Squeezed"),
    (CovarianceMatrix.squeezed_vacuum(0.69, np.pi/4), "6 dB @ 45°"),
    (CovarianceMatrix.squeezed_vacuum(1.15, 0), "10 dB Squeezed"),
]

# Create figure
fig, axes = plt.subplots(2, 2, figsize=(12, 12))

for (sigma, title), ax in zip(states, axes.flat):
    plot_wigner(sigma, title, ax)

plt.tight_layout()
plt.savefig('wigner_functions.png', dpi=200)
print("Saved wigner_functions.png")