Some more cleanups, especially tests

This commit is contained in:
Benoît Sierro
2023-07-24 14:28:41 +02:00
parent 41072ea1f2
commit be0a9b8c20
71 changed files with 142 additions and 1529 deletions

View File

@@ -1,151 +0,0 @@
from collections import defaultdict
import matplotlib.pyplot as plt
import numpy as np
import pytest
from scipy.interpolate import interp1d
import scgenerator as sc
import scgenerator.operators as op
import scgenerator.solver as so
def test_rk43_absorbtion_only():
n = 129
end = 1.0
h = 2**-3
w_c = np.linspace(-5, 5, n)
ind = np.argsort(w_c)
spec0 = np.exp(-(w_c**2))
init_state = op.SimulationState(spec0, end, h)
lin = op.envelope_linear_operator(
op.no_op_freq(n),
op.constant_array_operator(np.ones(n) * np.log(2)),
)
non_lin = op.no_op_freq(n)
judge = so.adaptive_judge(1e-6, 4)
stepper = so.ERK43(lin, non_lin)
for state in so.integrate(stepper, init_state, h, judge, max_step_size=0.125):
if state.z >= end:
break
assert np.max(state.spectrum2) == pytest.approx(0.5)
def test_rk43_soliton(plot=False):
n = 1024
b2 = sc.fiber.D_to_beta2(sc.units.D_ps_nm_km(24), 835e-9)
gamma = 0.08
t0_fwhm = 50e-15
p0 = 1.26e3
t0 = sc.pulse.width_to_t0(t0_fwhm, "sech")
print(np.sqrt(t0**2 / np.abs(b2) * gamma * p0))
disp_len = t0**2 / np.abs(b2)
end = disp_len * 0.5 * np.pi
targets = np.linspace(0, end, 32)
print(end)
h = 2**-6
t = np.linspace(-200e-15, 200e-15, n)
w_c = np.pi * 2 * np.fft.fftfreq(n, t[1] - t[0])
ind = np.argsort(w_c)
field0 = sc.pulse.sech_pulse(t, t0, p0)
init_state = op.SimulationState(np.fft.fft(field0), end, h)
no_op = op.no_op_freq(n)
lin = op.envelope_linear_operator(
op.constant_polynomial_dispersion([b2], w_c),
no_op,
# op.constant_array_operator(np.ones(n) * np.log(2)),
)
non_lin = op.envelope_nonlinear_operator(
op.constant_array_operator(np.ones(n) * gamma),
no_op,
op.envelope_spm(0),
no_op,
)
# new_state = init_state.copy()
# plt.plot(t, init_state.field2)
# new_state.set_spectrum(non_lin(init_state))
# plt.plot(t, new_state.field2)
# new_state.set_spectrum(lin(init_state))
# plt.plot(t, new_state.field2)
# print(new_state.spectrum2.max())
# plt.show()
# return
judge = so.adaptive_judge(1e-6, 4)
stepper = so.ERKIP43Stepper(lin, non_lin)
# stepper.set_state(init_state)
# state, error = stepper.take_step(init_state, 1e-3, True)
# print(error)
# plt.plot(t, stepper.fine.field2)
# plt.plot(t, stepper.coarse.field2)
# plt.show()
# return
target = 0
stats = defaultdict(list)
saved = []
zs = []
for state in so.integrate(stepper, init_state, h, judge, max_step_size=0.125):
# print(f"z = {state.z*100:.2f}")
saved.append(state.spectrum2[ind])
zs.append(state.z)
for k, v in state.stats.items():
stats[k].append(v)
if state.z > end:
break
print(len(saved))
if plot:
interp = interp1d(zs, saved, axis=0)
plt.imshow(sc.units.to_log(interp(targets)), origin="lower", aspect="auto", vmin=-40)
plt.show()
plt.plot(stats["z"][1:], np.diff(stats["z"]))
plt.show()
def test_simple_euler():
n = 129
end = 1.0
h = 2**-3
w_c = np.linspace(-5, 5, n)
ind = np.argsort(w_c)
spec0 = np.exp(-(w_c**2))
init_state = op.SimulationState(spec0, end, h)
lin = op.envelope_linear_operator(
op.no_op_freq(n),
op.constant_array_operator(np.ones(n) * np.log(2)),
)
euler = so.ConstantEuler(lin)
target = 0
end = 1.0
h = 2**-6
for state in so.integrate(euler, init_state, h):
if state.z >= target:
target += 0.125
plt.plot(w_c[ind], state.spectrum2[ind], label=f"z={state.z:.3f}")
if target > end:
print(np.max(state.spectrum2))
break
plt.title(f"{h = }")
plt.legend()
plt.show()
def benchmark():
for _ in range(50):
test_rk43_soliton()
if __name__ == "__main__":
test_rk43_soliton()
benchmark()

View File

@@ -1,14 +1,18 @@
from __future__ import annotations from __future__ import annotations
import json
import os
import warnings import warnings
import zipfile
from collections import defaultdict from collections import defaultdict
from pathlib import Path
from typing import Any, Iterator, Sequence from typing import Any, Iterator, Sequence
import numba import numba
import numpy as np import numpy as np
from scgenerator.math import abs2 from scgenerator.math import abs2
from scgenerator.operators import SpecOperator from scgenerator.operators import SpecOperator, VariableQuantity
from scgenerator.utils import TimedMessage from scgenerator.utils import TimedMessage
@@ -18,8 +22,15 @@ class SimulationResult:
stats: dict[str, list[Any]] stats: dict[str, list[Any]]
z: np.ndarray z: np.ndarray
def __init__(self, spectra: Sequence[np.ndarray], stats: dict[str, list[Any]]): def __init__(
if "z" in stats: self,
spectra: Sequence[np.ndarray],
stats: dict[str, list[Any]],
z: np.ndarray | None = None,
):
if z is not None:
self.z = z
elif "z" in stats:
self.z = np.array(stats["z"]) self.z = np.array(stats["z"])
else: else:
self.z = np.arange(len(spectra), dtype=float) self.z = np.arange(len(spectra), dtype=float)
@@ -30,6 +41,29 @@ class SimulationResult:
def stat(self, stat_name: str) -> np.ndarray: def stat(self, stat_name: str) -> np.ndarray:
return np.array(self.stats[stat_name]) return np.array(self.stats[stat_name])
def save(self, path: os.PathLike):
path = Path(path)
if not path.name.endswith(".zip"):
path = path.parent / (path.name + ".zip")
with zipfile.ZipFile(path, "w") as zf:
with zf.open("spectra.npy", "w") as file:
np.save(file, self.spectra)
with zf.open("z.npy", "w") as file:
np.save(file, self.z)
with zf.open("stats.json", "w") as file:
file.write(json.dumps(self.stats).encode())
@classmethod
def load(cls, path: os.PathLike):
with zipfile.ZipFile(path, "r") as zf:
with zf.open("spectra.npy", "r") as file:
spectra = np.load(file)
with zf.open("z.npy", "r") as file:
z = np.load(file)
with zf.open("stats.json", "r") as file:
stats = json.loads(file.read().decode())
return cls(spectra, stats, z)
@numba.jit(nopython=True) @numba.jit(nopython=True)
def compute_diff(coarse_spec: np.ndarray, fine_spec: np.ndarray) -> float: def compute_diff(coarse_spec: np.ndarray, fine_spec: np.ndarray) -> float:
@@ -82,7 +116,7 @@ def pi_step_factor(error: float, last_error: float, order: int, eps: float = 0.8
def solve43( def solve43(
spec: np.ndarray, spec: np.ndarray,
linear: SpecOperator, linear: VariableQuantity,
nonlinear: SpecOperator, nonlinear: SpecOperator,
z_max: float, z_max: float,
atol: float, atol: float,

View File

@@ -1,18 +0,0 @@
name = "/Users/benoitsierro/tests/test_sc/Chang2011Fig2"
wavelength = 800e-9
shape = "gaussian"
energy = 2.5e-7
width = 30e-15
core_radius = 10e-6
model = "marcatili"
gas_name = "argon"
pressure = 3.2e5
length = 0.1
full_field = true
photoionization = false
dt = 0.04e-15
t_num = 32768
z_num = 128

View File

@@ -1,26 +0,0 @@
name = "test config"
# fiber
# gamma = 0.018
length = 1
model = "pcf"
pitch = 1.5e-6
pitch_ratio = 0.37
# pulse
intensity_noise = 0.05e-2
peak_power = 100e3
quantum_noise = true
shape = "gaussian"
wavelength = 1050e-9
width = 50e-15
# simulation
behaviors = ["spm", "raman", "ss"]
parallel = false
raman_type = "agrawal"
repeat = 4
t_num = 16384
time_window = 37e-12
tolerated_error = 1e-11
z_num = 128

View File

@@ -1,24 +0,0 @@
# fiber
core_radius = 50e-6
length = 50e-2
model = "marcatili"
# pulse
peak_power = 100e3
wavelength = 800e-9
# simulation
parallel = true
repeat = 4
t_num = 16384
time_window = 37e-12
tolerated_error = 1e-11
z_num = 128
[variable]
# gas.variable
gas_name = ["air", "helium"]
# pulse.variable
width = [250e-15, 240e-15, 230e-15, 220e-15, 210e-15]
# simulation.variable
behaviors = [["spm", "raman", "ss"], ["spm", "raman"], ["spm"]]

View File

@@ -1,21 +0,0 @@
# fiber
core_radius = 50e-6
length = 50e-2
model = "marcatili"
# gas
gas_name = "air"
# pulse
peak_power = 100e3
wavelength = 800e-9
width = 250e-15
# simulation
behaviors = ["spm", "raman", "ss"]
parallel = true
repeat = 1
t_num = 16384
time_window = 37e-12
tolerated_error = 1e-11
z_num = 128

View File

@@ -1,22 +0,0 @@
# fiber
core_radius = 50e-6
length = 50e-2
model = "marcatili"
# gas
gas_name = "air"
# pulse
peak_power = 100e3
wavelength = 800e-9
# simulation
behaviors = ["spm", "raman", "ss"]
parallel = true
repeat = 1
t_num = 16384
time_window = 37e-12
tolerated_error = 1e-11
z_num = 128
[variable]
width = [250e-15]

View File

@@ -1,21 +0,0 @@
# fiber
core_radius = 50e-6
length = 50e-2
model = "marcatili"
# gas
gas_name = "air"
# pulse
peak_power = 100e3
wavelength = 800e-9
width = 250e-15
# simulation
behaviors = ["spm", "raman", "ss"]
parallel = true
repeat = 2
t_num = 16384
time_window = 37e-12
tolerated_error = 1e-11
z_num = 128

View File

@@ -1,24 +0,0 @@
# fiber
core_radius = 50e-6
length = 50e-2
model = "marcatili"
# gas
gas_name = "air"
# pulse
soliton_num = 5
wavelength = 800e-9
width = 250e-15
# simulation
behaviors = ["spm", "raman", "ss"]
parallel = true
repeat = 1
t_num = 16384
time_window = 37e-12
tolerated_error = 1e-11
z_num = 128
[variable]
shape = ["gaussian", "sech"]

View File

@@ -1,8 +0,0 @@
dt = 1e-15
field_file = "testing/configs/custom_field/init_field.npz"
length = 1
mean_power = 220e-3
repetition_rate = 40e6
t_num = 2048
wavelength = 1000e-9
z_num = 32

View File

@@ -1,6 +0,0 @@
dt = 1e-15
field_file = "testing/configs/custom_field/init_field.npz"
length = 1
t_num = 2048
wavelength = 1000e-9
z_num = 32

View File

@@ -1,7 +0,0 @@
dt = 1e-15
field_file = "testing/configs/custom_field/init_field.npz"
length = 1
peak_power = 20000
t_num = 2048
wavelength = 1593e-9
z_num = 32

View File

@@ -1,7 +0,0 @@
dt = 1e-15
input_transmission = 1
length = 1
prev_data_dir = "testing/configs/custom_field/recover_data"
t_num = 2048
wavelength = 1000e-9
z_num = 32

View File

@@ -1,7 +0,0 @@
dt = 1e-15
input_transmission = 0.9
length = 1
prev_data_dir = "testing/configs/custom_field/recover_data"
t_num = 2048
wavelength = 1000e-9
z_num = 32

View File

@@ -1,20 +0,0 @@
name = "test config"
# fiber
length = 1
model = "pcf"
pitch = 1.5e-6
pitch_ratio = 0.37
# pulse
field_file = "testing/configs/custom_field/init_field.npz"
quantum_noise = false
wavelength = 1050e-9
# simulation
behaviors = ["spm", "raman", "ss"]
raman_type = "agrawal"
t_num = 16384
time_window = 37e-12
tolerated_error = 1e-11
z_num = 128

View File

@@ -1,24 +0,0 @@
name = "test config"
# fiber
length = 1
model = "pcf"
pitch = 1.5e-6
pitch_ratio = 0.37
# pulse
field_file = "testing/configs/custom_field/init_field.npz"
quantum_noise = false
# simulation
behaviors = ["spm", "raman", "ss"]
interpolation_range = [300e-9, 1900e-9]
raman_type = "agrawal"
t_num = 16384
time_window = 37e-12
tolerated_error = 1e-11
z_num = 128
[variable]
# pulse.variable
wavelength = [1050e-9, 1321e-9, 1593e-9]

View File

@@ -1,30 +0,0 @@
#t0 or width missing
name = "test config"
# fiber
gamma = 0.018
length = 1
model = "pcf"
pitch = 1.5e-6
pitch_ratio = 0.37
# pulse
peak_power = 100e3
quantum_noise = true
shape = "gaussian"
wavelength = 1050e-9
# simulation
behaviors = ["spm", "raman", "ss"]
parallel = true
raman_type = "agrawal"
repeat = 4
t_num = 16384
time_window = 37e-12
tolerated_error = 1e-11
z_num = 128
[variable]
# pulse.variable
intensity_noise = [0.05e-2, 0.1e-2]

View File

@@ -1,30 +0,0 @@
#t0, width, peak_power or energy missing
name = "test config"
# fiber
gamma = 0.018
length = 1
model = "pcf"
pitch = 1.5e-6
pitch_ratio = 0.37
# pulse
quantum_noise = true
shape = "gaussian"
wavelength = 1050e-9
# simulation
behaviors = ["spm", "raman", "ss"]
parallel = true
raman_type = "agrawal"
repeat = 4
t_num = 16384
time_window = 37e-12
tolerated_error = 1e-11
z_num = 128
[variable]
# pulse.variable
intensity_noise = [0.05e-2, 0.1e-2]
soliton_num = [1, 2, 3, 4]

View File

@@ -1,30 +0,0 @@
# window size or dt missing
name = "test config"
# fiber
gamma = 0.018
length = 1
model = "pcf"
pitch = 1.5e-6
pitch_ratio = 0.37
# pulse
peak_power = 100e3
quantum_noise = true
shape = "gaussian"
wavelength = 1050e-9
# simulation
behaviors = ["spm", "raman", "ss"]
parallel = true
raman_type = "agrawal"
repeat = 4
t_num = 16384
tolerated_error = 1e-11
z_num = 128
[variable]
# pulse.variable
intensity_noise = [0.05e-2, 0.1e-2]
width = [50e-15, 100e-15, 200e-15]

View File

@@ -1,32 +0,0 @@
#multiple width parameters
name = "test config"
# fiber
gamma = 0.018
length = 1
model = "pcf"
pitch = 1.5e-6
pitch_ratio = 0.37
# pulse
peak_power = 100e3
quantum_noise = true
shape = "gaussian"
wavelength = 1050e-9
width = 120e-15
# simulation
behaviors = ["spm", "raman", "ss"]
parallel = true
raman_type = "agrawal"
repeat = 4
t_num = 16384
time_window = 37e-12
tolerated_error = 1e-11
z_num = 128
[variable]
# pulse.variable
intensity_noise = [0.05e-2, 0.1e-2]
width = [50e-15, 100e-15, 200e-15]

View File

@@ -1,33 +0,0 @@
# missing capillary_thickness
name = "test config"
# fiber
capillary_num = 6
capillary_outer_d = 2e-6
capillary_spacing = 4e-6
core_radius = 50e-6
gamma = 0.018
length = 1
model = "hasan"
# pulse
peak_power = 100e3
quantum_noise = true
shape = "gaussian"
wavelength = 1050e-9
# simulation
behaviors = ["spm", "raman", "ss"]
parallel = true
raman_type = "agrawal"
repeat = 4
t_num = 16384
time_window = 37e-12
tolerated_error = 1e-11
z_num = 128
[variable]
# pulse.variable
intensity_noise = [0.05e-2, 0.1e-2]
width = [50e-15, 100e-15, 200e-15]

View File

@@ -1,32 +0,0 @@
# missing capillary_outer_d and capillary_spacing
name = "test config"
# fiber
capillary_num = 6
capillary_thickness = 4e-6
core_radius = 50e-6
gamma = 0.018
length = 1
model = "hasan"
# pulse
peak_power = 100e3
quantum_noise = true
shape = "gaussian"
wavelength = 1050e-9
# simulation
behaviors = ["spm", "raman", "ss"]
parallel = true
raman_type = "agrawal"
repeat = 4
t_num = 16384
time_window = 37e-12
tolerated_error = 1e-11
z_num = 128
[variable]
# pulse.variable
intensity_noise = [0.05e-2, 0.1e-2]
width = [50e-15, 100e-15, 200e-15]

View File

@@ -1,31 +0,0 @@
# model 'pcf' should be added and no gas dico
name = "test config"
# fiber
gamma = 0.018
length = 1
model = "pcf"
pitch = 1.5e-6
pitch_ratio = 0.37
# pulse
peak_power = 100e3
quantum_noise = true
shape = "gaussian"
wavelength = 1050e-9
# simulation
behaviors = ["spm", "raman", "ss"]
parallel = true
raman_type = "agrawal"
repeat = 4
t_num = 16384
time_window = 37e-12
tolerated_error = 1e-11
z_num = 128
[variable]
# pulse.variable
intensity_noise = [0.05e-2, 0.1e-2]
width = [50e-15, 100e-15, 200e-15]

View File

@@ -1,30 +0,0 @@
# raman_type should be added
name = "test config"
# fiber
gamma = 0.018
length = 1
model = "pcf"
pitch = 1.5e-6
pitch_ratio = 0.37
# pulse
peak_power = 100e3
quantum_noise = true
shape = "gaussian"
wavelength = 1050e-9
# simulation
behaviors = ["spm", "raman", "ss"]
parallel = true
repeat = 4
t_num = 16384
time_window = 37e-12
tolerated_error = 1e-11
z_num = 128
[variable]
# pulse.variable
intensity_noise = [0.05e-2, 0.1e-2]
width = [50e-15, 100e-15, 200e-15]

View File

@@ -1,29 +0,0 @@
# name should be added
# fiber
gamma = 0.018
length = 1
model = "pcf"
pitch = 1.5e-6
pitch_ratio = 0.37
# pulse
peak_power = 100e3
quantum_noise = true
shape = "gaussian"
wavelength = 1050e-9
# simulation
behaviors = ["spm", "raman", "ss"]
parallel = true
raman_type = "agrawal"
repeat = 4
t_num = 16384
time_window = 37e-12
tolerated_error = 1e-11
z_num = 128
[variable]
# pulse.variable
intensity_noise = [0.05e-2, 0.1e-2]
width = [50e-15, 100e-15, 200e-15]

View File

@@ -1,38 +0,0 @@
# should add capillary_nested and capillary_resonance_strengths
name = "test config"
# fiber
capillary_num = 6
capillary_outer_d = 2e-6
capillary_spacing = 4e-6
capillary_thickness = 1e-7
core_radius = 50e-6
length = 1
model = "hasan"
# gas
gas_name = "helium"
# pulse
peak_power = 100e3
quantum_noise = true
shape = "gaussian"
wavelength = 1050e-9
# simulation
behaviors = ["spm", "raman", "ss"]
parallel = true
raman_type = "agrawal"
repeat = 4
t_num = 16384
time_window = 37e-12
tolerated_error = 1e-11
z_num = 128
[variable]
# gas.variable
temperature = [300, 350, 400]
# pulse.variable
intensity_noise = [0.05e-2, 0.1e-2]
width = [50e-15, 100e-15, 200e-15]

View File

@@ -1,30 +0,0 @@
# should add he_mode and gas
name = "test config"
# fiber
core_radius = 50e-6
gamma = 0.018
length = 1
model = "marcatili"
# pulse
peak_power = 100e3
quantum_noise = true
shape = "gaussian"
wavelength = 1050e-9
# simulation
behaviors = ["spm", "raman", "ss"]
parallel = true
raman_type = "agrawal"
repeat = 4
t_num = 16384
time_window = 37e-12
tolerated_error = 1e-11
z_num = 128
[variable]
# pulse.variable
intensity_noise = [0.05e-2, 0.1e-2]
width = [50e-15, 100e-15, 200e-15]

View File

@@ -1,32 +0,0 @@
# should not touch simulation parameters
# should add wavelength ranges
name = "test config"
# fiber
gamma = 0.018
length = 1
model = "pcf"
pitch = 1.5e-6
pitch_ratio = 0.37
# pulse
peak_power = 100e3
quantum_noise = true
shape = "gaussian"
wavelength = 1050e-9
# simulation
behaviors = ["spm", "raman", "ss"]
parallel = true
raman_type = "agrawal"
repeat = 4
t_num = 16384
time_window = 37e-12
tolerated_error = 1e-11
z_num = 128
[variable]
# pulse.variable
intensity_noise = [0.05e-2, 0.1e-2]
width = [50e-15, 100e-15, 200e-15]

View File

@@ -1,23 +0,0 @@
name = "fiber 2"
# fiber
beta2_coefficients = [
-1.183e-26,
8.1038e-41,
-9.5205e-56,
2.0737e-70,
-5.3943e-85,
1.3486e-99,
-2.5495e-114,
3.0524e-129,
-1.714e-144,
]
gamma = 0.13
length = 0.05
model = "custom"
# simulation
z_num = 16
[variable]
# fiber.variable
input_transmission = [0.9, 0.95]

View File

@@ -1,42 +0,0 @@
name = "full anomalous"
# fiber
beta2_coefficients = [
-1.183e-26,
8.1038e-41,
-9.5205e-56,
2.0737e-70,
-5.3943e-85,
1.3486e-99,
-2.5495e-114,
3.0524e-129,
-1.714e-144,
]
gamma = 0.11
input_transmission = 1.0
length = 0.02
model = "custom"
# pulse
intensity_noise = 0
peak_power = 10000
quantum_noise = false
shape = "gaussian"
t0 = 2.84e-14
# simulation
behaviors = ["spm", "ss"]
dt = 1e-15
frep = 80000000.0
ideal_gas = false
interpolation_range = [3e-7, 1.9e-6]
parallel = true
raman_type = "measured"
repeat = 3
t_num = 16384
tolerated_error = 1e-9
z_num = 64
[variable]
# pulse.variable
wavelength = [8.35e-7, 8.3375e-7]

View File

@@ -1,30 +0,0 @@
# raman_type should be added
name = "test config"
# fiber
gamma = 0.018
length = 1
model = "pcf"
pitch = 1.5e-6
pitch_ratio = 0.37
# pulse
peak_power = 100e3
quantum_noise = true
shape = "gaussian"
wavelength = 1050e-9
width = 50e-15
# simulation
behaviors = ["spm", "raman", "ss"]
parallel = true
repeat = 4
t_num = 16384
time_window = 37e-12
tolerated_error = 1e-11
z_num = 128
[variable]
# pulse.variable
intensity_noise = [0.10000000005e-2, 0.1e-2]

View File

@@ -1,30 +0,0 @@
# raman_type should be added
name = "test config"
# fiber
gamma = 0.018
length = 1
model = "pcf"
pitch = 1.5e-6
pitch_ratio = 0.37
# pulse
peak_power = 100e3
quantum_noise = true
shape = "gaussian"
wavelength = 1050e-9
width = 50e-15
# simulation
behaviors = ["spm", "raman", "ss"]
parallel = true
repeat = 4
t_num = 16384
time_window = 37e-12
tolerated_error = 1e-11
z_num = 128
[variable]
# pulse.variable
intensity_noise = [0.1e-2, 0.001]

View File

@@ -1,27 +0,0 @@
# raman_type should be added
name = "test config"
# fiber
gamma = 0.018
length = 1
model = "pcf"
pitch = 1.5e-6
pitch_ratio = 0.37
# pulse
intensity_noise = 0.1e-2
peak_power = 100e3
quantum_noise = true
shape = "gaussian"
wavelength = 1050e-9
width = 50e-15
# simulation
behaviors = ["spm", "raman", "ss"]
parallel = true
repeat = 4
t_num = 16384
time_window = 37e-12
tolerated_error = 1e-11
z_num = 128

View File

@@ -1,33 +0,0 @@
nam)e = "full anomalous"
# fiber
beta2_coefficients = [
-1.183e-26,
8.1038e-41,
-9.5205e-56,
2.0737e-70,
-5.3943e-85,
1.3486e-99,
-2.5495e-114,
3.0524e-129,
-1.714e-144,
]
gamma = 0.11
length = 0.02
# pulse
peak_power = 10000
t0 = 2.84e-14
# simulation
dt = 1e-15
parallel = true
raman_type = "measured"
repeat = 4
t_num = 16384
tolerated_error = 1e-10
z_num = 64
[variable]
# pulse.variable
wavelength = [835e-9, 830e-9]

View File

@@ -1,31 +0,0 @@
# pitch in wrong section
name = "test config"
# fiber
gamma = 0.018
length = 1
model = "pcf"
pitch_ratio = 0.37
# pulse
peak_power = 100e3
pitch = 1.5e-6
quantum_noise = true
shape = "gaussian"
wavelength = 1050e-9
# simulation
behaviors = ["spm", "raman", "ss"]
parallel = true
raman_type = "agrawal"
repeat = 4
t_num = 16384
time_window = 37e-12
tolerated_error = 1e-11
z_num = 128
[variable]
# pulse.variable
intensity_noise = [0.05e-2, 0.1e-2]
width = [50e-15, 100e-15, 200e-15]

View File

@@ -1,31 +0,0 @@
# wrong value in behaviors
name = "test config"
# fiber
gamma = 0.018
length = 1
model = "pcf"
pitch = 1.5e-6
pitch_ratio = 0.37
# pulse
peak_power = 100e3
quantum_noise = true
shape = "gaussian"
wavelength = 1050e-9
# simulation
behaviors = ["spm", "raman", "ss", "q_noise"]
parallel = true
raman_type = "agrawal"
repeat = 4
t_num = 16384
time_window = 37e-12
tolerated_error = 1e-11
z_num = 128
[variable]
# pulse.variable
intensity_noise = [0.05e-2, 0.1e-2]
width = [50e-15, 100e-15, 200e-15]

View File

@@ -1,31 +0,0 @@
# wrong type in width
name = "test config"
# fiber
gamma = 0.018
length = 1
model = "pcf"
pitch = 1.5e-6
pitch_ratio = 0.37
# pulse
peak_power = 100e3
quantum_noise = true
shape = "gaussian"
wavelength = 1050e-9
# simulation
behaviors = ["spm", "raman", "ss"]
parallel = true
raman_type = "agrawal"
repeat = 4
t_num = 16384
time_window = 37e-12
tolerated_error = 1e-11
z_num = 128
[variable]
# pulse.variable
intensity_noise = [0.05e-2, 0.1e-2]
width = ["gaussian", "sech"]

View File

@@ -1,32 +0,0 @@
# parallel should not be variable
name = "test config"
# fiber
gamma = 0.018
length = 1
model = "pcf"
pitch = 1.5e-6
pitch_ratio = 0.37
# pulse
peak_power = 100e3
quantum_noise = true
shape = "gaussian"
wavelength = 1050e-9
# simulation
behaviors = ["spm", "raman", "ss"]
raman_type = "agrawal"
repeat = 4
t_num = 16384
time_window = 37e-12
tolerated_error = 1e-11
z_num = 1
[variable]
# pulse.variable
intensity_noise = [0.05e-2, 0.1e-2]
width = [50e-15, 100e-15, 200e-15]
# simulation.variable
parallel = [true, false]

View File

@@ -1,31 +0,0 @@
#variable parameters should be lists
name = "test config"
# fiber
gamma = 0.018
length = 1
model = "pcf"
pitch = 1.5e-6
pitch_ratio = 0.37
# pulse
peak_power = 100e3
quantum_noise = true
shape = "gaussian"
wavelength = 1050e-9
# simulation
behaviors = ["spm", "raman", "ss"]
parallel = true
raman_type = "agrawal"
repeat = 4
t_num = 16384
time_window = 37e-12
tolerated_error = 1e-11
z_num = 128
[variable]
# pulse.variable
intensity_noise = 0.05e-2
width = [50e-15, 100e-15, 200e-15]

View File

@@ -1,31 +0,0 @@
#repeat should not be 0
name = "test config"
# fiber
gamma = 0.018
length = 1
model = "pcf"
pitch = 1.5e-6
pitch_ratio = 0.37
# pulse
intensity_noise = 0.05e-2
peak_power = 100e3
quantum_noise = true
shape = "gaussian"
wavelength = 1050e-9
# simulation
behaviors = ["spm", "raman", "ss"]
parallel = true
raman_type = "agrawal"
repeat = 0
t_num = 16384
time_window = 37e-12
tolerated_error = 1e-11
z_num = 128
[variable]
# pulse.variable
width = [50e-15, 100e-15, 200e-15]

View File

@@ -1,29 +0,0 @@
# gamma missing
name = "test config"
# fiber
beta2_coefficients = [1, 2, 3]
gamma = 0.018
length = 1
# pulse
peak_power = 100e3
quantum_noise = true
shape = "gaussian"
wavelength = 1050e-9
# simulation
behaviors = ["spm", "raman", "ss"]
parallel = true
raman_type = "agrawal"
repeat = 4
t_num = 16384
time_window = 37e-12
tolerated_error = 1e-11
z_num = 128
[variable]
# pulse.variable
intensity_noise = []
width = [50e-15, 100e-15, 200e-15]

View File

@@ -1,29 +0,0 @@
name = "test config"
# fiber
gamma = 0.018
length = 1
model = "pcf"
pitch = 1.5e-6
pitch_ratio = 0.37
# pulse
peak_power = 100e3
quantum_noise = true
shape = "gaussian"
wavelength = 1050e-9
# simulation
behaviors = ["spm", "raman", "ss"]
parallel = true
raman_type = "agrawal"
repeat = 4
t_num = 16384
time_window = 37e-12
tolerated_error = 1e-11
z_num = 128
[variable]
# pulse.variable
intensity_noise = [0.05e-2, 0.1e-2]
width = [50e-15, 100e-15, 200e-15]

View File

@@ -1,16 +0,0 @@
from scgenerator.math import all_zeros
import matplotlib.pyplot as plt
import numpy as np
def main():
x = np.linspace(-10, 10, 30)
y = np.sin(x)
z = all_zeros(x, y)
plt.plot(x, y)
plt.plot(z, z * 0, ls="", marker="o")
plt.show()
if __name__ == "__main__":
main()

View File

View File

View File

@@ -1,55 +0,0 @@
import scgenerator as sc
from customfunc.app import PlotApp
from tqdm import tqdm
# warnings.filterwarnings("error")
def get_specs(params: dict):
p = sc.Parameters(**params)
sim = sc.RK4IP(p)
return [s.actual_spectrum for _, s in tqdm(sim.irun(), total=p.z_num)], p.dump_dict()
def main():
params = sc.Parameters.load("testing/configs/Chang2011Fig2.toml")
specs, params = get_specs(params.dump_dict(add_metadata=False))
params = sc.Parameters(**params)
rs = sc.PlotRange(100, 1500, "nm")
rt = sc.PlotRange(-500, 500, "fs")
x, o, ext = rs.sort_axis(params.w)
vmin = -50
with PlotApp(i=range(params.z_num)) as app:
spec_ax = app[0]
spec_ax.set_xlabel(rs.unit.label)
field_ax = app[1]
field_ax.set_xlabel(rt.unit.label)
@app.update
def draw(i):
spec, *fields = compute(i)
spec_ax.set_line_data("spec", *spec, label=f"z = {params.z_targets[i]*1e2:.0f}cm")
for label, x, y in fields:
field_ax.set_line_data(label, x, y)
print(params)
@app.cache
def compute(i):
xt, field = sc.transform_1D_values(params.ifft(specs[i]), rt, params=params)
x, spec = sc.transform_1D_values(sc.abs2(specs[i]), rs, params=params, log=True)
# spec = np.where(spec > vmin, spec, vmin)
field2 = sc.abs2(field)
bot, top = sc.math.envelope_ind(field2)
return (x, spec), ("field^2", xt, field2), ("envelope", xt[top], field2[top])
# bot, top = sc.math.envelope_ind(field)
# bot = interp1d(xt[bot], field[bot], "cubic", bounds_error=False, fill_value=0)(xt)
# top = interp1d(xt[top], field[top], "cubic", bounds_error=False, fill_value=0)(xt)
# return ((x, spec), ("upper", xt, top), ("field", xt, field), ("lower", xt, bot))
if __name__ == "__main__":
main()

View File

View File

View File

@@ -1,134 +0,0 @@
from math import factorial
import numpy as np
import pytest
import scgenerator.math as m
def test__power_fact_array():
x = np.random.rand(5)
for i in range(5):
assert m._power_fact_array(x, i) == pytest.approx(x**i / factorial(i))
def test__power_fact_single():
pass
def test_abs2():
x = np.random.rand(5)
assert m.abs2(5) == 25
assert m.abs2(2 - 2j) == 8
assert all(m.abs2(x) == abs(x) ** 2)
def test_all_zeros():
x = np.geomspace(0.1, 1, 100)
y = np.sin(1 / x)
target = [1 / (3 * np.pi), 1 / (2 * np.pi), 1 / np.pi]
assert m.all_zeros(x, y) == pytest.approx(target, abs=1e-4)
x = np.array([0, 1])
y = np.array([-1, 1])
assert all(m.all_zeros(x, y) == np.array([0.5]))
x = np.array([0, 1])
y = np.array([1, 1])
assert len(m.all_zeros(x, y)) == 0
def test_argclosest():
pass
def test_build_sim_grid():
pass
def test_indft():
pass
def test_indft_matrix():
pass
def test_jn_zeros():
pass
def test_length():
pass
def test_ndft():
pass
def test_ndft_matrix():
pass
def test_np_cache():
pass
def test_power_fact():
pass
def test_sigmoid():
pass
def test_span():
pass
def test_tspace():
pass
def test_u_nm():
pass
def test_update_frequency_domain():
pass
def test_wspace():
pass
def test_differentiate():
x = np.linspace(-10, 10, 256)
y = np.exp(-((x / 3) ** 2)) * (1 + 0.2 * np.sin(x * 5))
y[100] = 1e4
# true = np.exp(-(x/3)**2) * (x*(-0.4/9 * np.sin(5*x) - 2/9) + np.cos(5*x))
true = np.exp(-((x / 3) ** 2)) * (
x**2 * (0.00987654321 * np.sin(5 * x) + 0.0493827)
- 5.044444 * np.sin(5 * x)
- 0.44444 * x * np.cos(5 * x)
- 0.2222222
)
import matplotlib.pyplot as plt
h = x[1] - x[0]
grad = np.gradient(np.gradient(y)) / h**2
fine = m.differentiate_arr(y, 2, 6) / h**2
plt.plot(x, y)
plt.plot(x, grad, label="gradient")
plt.plot(x, fine, label="fine")
plt.plot(x, true, label="ture", ls=":")
plt.legend()
plt.show()
if __name__ == "__main__":
test_differentiate()

View File

View File

@@ -1,21 +0,0 @@
import numpy as np
import scgenerator as sc
import matplotlib.pyplot as plt
def main():
capillary_thickness = 1.4e-6
wl = np.linspace(200e-9, 2000e-9, 500)
n_gas_2 = sc.materials.n_gas_2(wl, "air", 3e5, 300)
resonances = []
for i in range(5):
t = sc.fiber.resonance_thickness(wl, i, n_gas_2, 40e-6)
resonances += list(1e9 * sc.math.all_zeros(wl, t - capillary_thickness))
plt.plot(1e9 * wl, 1e6 * t)
plt.xlabel("nm")
plt.ylabel("μm")
plt.show()
if __name__ == "__main__":
main()

View File

View File

@@ -1,54 +0,0 @@
from pydantic import main
import scgenerator as sc
def test_descriptor():
# Same branch
var1 = sc.VariationDescriptor(
raw_descr=[[("num", 1), ("a", False)], [("b", 0)]], index=[[1, 0], [0]]
)
var2 = sc.VariationDescriptor(
raw_descr=[[("num", 2), ("a", False)], [("b", 0)]], index=[[1, 0], [0]]
)
assert var1.branch.identifier == "b_0"
assert var1.identifier != var1.branch.identifier
assert var1.identifier != var2.identifier
assert var1.branch.identifier == var2.branch.identifier
# different branch
var3 = sc.VariationDescriptor(
raw_descr=[[("num", 2), ("a", True)], [("b", 0)]], index=[[1, 0], [0]]
)
assert var1.branch.identifier != var3.branch.identifier
assert var1.formatted_descriptor() != var2.formatted_descriptor()
assert var1.formatted_descriptor() != var3.formatted_descriptor()
def test_variationer():
var = sc.Variationer(
[
dict(a=[1, 2], num=[0, 1, 2]),
[dict(b=["000", "111"], c=["a", "-1"])],
dict(),
dict(),
[dict(aaa=[True, False], bb=[1, 3])],
]
)
assert var.var_num(0) == 6
assert var.var_num(1) == 12
assert var.var_num() == 24
cfg = dict(bb=None)
branches = set()
for descr in var.iterate():
assert descr.update_config(cfg).items() >= set(descr.raw_descr[-1])
branches.add(descr.branch.identifier)
assert len(branches) == 8
def main():
test_descriptor()
if __name__ == "__main__":
main()

View File

@@ -1,21 +0,0 @@
import matplotlib.pyplot as plt
import numpy as np
import scgenerator as sc
wl = np.linspace(200e-9, 2e-6, 2048)
w = sc.units.m(wl)
wl0 = 800e-9
gas = sc.materials.Gas("argon")
ng2 = gas.sellmeier.n_gas_2(wl, pressure=1e5)
n = sc.fiber.n_eff_vincetti(wl, wl0, ng2, 1e-6, 20e-6, 5e-6, 7)
b2 = sc.fiber.beta2(w, n)
bcap = sc.capillary_dispersion(
wl, sc.fiber.core_radius_from_capillaries(20e-6, 5e-6, 7), "argon", pressure=1e5
)
plt.plot(wl, b2)
plt.plot(wl, bcap)
plt.show()

View File

@@ -1,31 +0,0 @@
import numpy as np
import pytest
from scgenerator.operators import SimulationState
def test_creation():
x = np.linspace(0, 1, 128, dtype=complex)
cs = SimulationState(1.0, 0, 0.1, x, 1.0)
assert cs.converter is np.fft.ifft
assert cs.stats == {}
assert np.allclose(cs.field2, np.abs(np.fft.ifft(x)) ** 2)
with pytest.raises(ValueError):
cs = SimulationState(1.0, 0, 0.0, x, 1.0, spectrum2=np.abs(x) ** 3)
cs = SimulationState(1.0, 0, 0.1, x, 1.0, spectrum2=x.copy(), field=x.copy(), field2=x.copy())
assert np.allclose(cs.spectrum2, cs.spectrum)
assert np.allclose(cs.spectrum, cs.field)
assert np.allclose(cs.field, cs.field2)
def test_copy():
x = np.linspace(0, 1, 128, dtype=complex)
start = SimulationState(1.0, 0, 0.1, x, 1.0)
end = start.copy()
assert start.spectrum is not end.spectrum
assert np.all(start.field2 == end.field2)

87
tests/test_integrator.py Normal file
View File

@@ -0,0 +1,87 @@
import matplotlib.pyplot as plt
import numpy as np
import pytest
import scgenerator as sc
import scgenerator.operators as op
def test_rk43_absorbtion_only():
n = 129
w_c = np.linspace(-5, 5, n)
spec0 = np.exp(-(w_c**2))
lin = op.envelope_linear_operator(
op.constant_quantity(np.zeros(n)),
op.constant_quantity(np.ones(n) * np.log(2)),
)
non_lin = op.no_op_freq(n)
res = sc.integrate(spec0, 1.0, lin, non_lin, targets=[1.0])
assert np.max(sc.abs2(res.spectra[-1])) == pytest.approx(0.5)
def test_rk43_soliton(plot=False):
"""
create a N=3 soliton and test that the spectrum at after one oscillation goes back to the same
maximum value
"""
n = 1024
l0 = 835e-9
w0 = sc.units.m(l0)
b2 = sc.fiber.D_to_beta2(sc.units.D_ps_nm_km(24), l0)
gamma = 0.08
t0_fwhm = 50e-15
p0 = 1.26e3
t0 = sc.pulse.width_to_t0(t0_fwhm, "sech")
soliton_num = 3
p0 = soliton_num**2 * np.abs(b2) / (gamma * t0**2)
disp_len = t0**2 / np.abs(b2)
end = disp_len * 0.5 * np.pi
targets = np.linspace(0, end, 64)
t = np.linspace(-200e-15, 200e-15, n)
w_c = np.pi * 2 * np.fft.fftfreq(n, t[1] - t[0])
field0 = sc.pulse.sech_pulse(t, t0, p0)
spec0 = np.fft.fft(field0)
no_op = op.no_op_freq(n)
lin = op.envelope_linear_operator(
op.constant_polynomial_dispersion([b2], w_c),
op.constant_quantity(np.zeros(n)),
)
non_lin = op.envelope_nonlinear_operator(
op.constant_quantity(np.ones(n) * gamma),
op.constant_quantity(np.zeros(n)),
op.envelope_spm(0),
no_op,
)
res = sc.integrate(spec0, end, lin, non_lin, targets=targets, atol=1e-10, rtol=1e-9)
if plot:
x, y, z = sc.plotting.transform_2D_propagation(
res.spectra,
sc.PlotRange(500, 1300, "nm"),
w_c + w0,
targets,
)
plt.imshow(z, extent=sc.plotting.get_extent(x, y), origin="lower", aspect="auto", vmin=-40)
plt.show()
plt.plot(sc.abs2(spec0))
plt.plot(sc.abs2(res.spectra[-1]))
plt.yscale("log")
plt.show()
assert sc.abs2(spec0).max() == pytest.approx(sc.abs2(res.spectra[-1]).max(), rel=0.01)
def benchmark():
for _ in range(50):
test_rk43_soliton()
if __name__ == "__main__":
test_rk43_soliton()
benchmark()

View File

@@ -0,0 +1,17 @@
from pathlib import Path
import numpy as np
from scgenerator.solver import SimulationResult
def test_load_save(tmp_path: Path):
sim = SimulationResult(
np.random.randint(0, 20, (5, 5)), dict(a=[], b=[1, 2, 3], z=list(range(32)))
)
sim.save(tmp_path / "mysim")
sim2 = SimulationResult.load(tmp_path / "mysim.zip")
assert np.all(sim2.spectra == sim.spectra)
assert np.all(sim2.z == sim.z)
for k, v in sim.stats.items():
assert sim2.stats[k] == v