Reworked units once again

This commit is contained in:
Benoît Sierro
2021-11-04 13:58:52 +01:00
parent 514bd0a433
commit 6ba8bc2c59
14 changed files with 165 additions and 9449 deletions

0
1
View File

126
log
View File

@@ -1,126 +0,0 @@
attempt 1 to compute w_c, this time using Rule(targets={'z_targets': 1, 't': 1, 'time_window': 1, 't_num': 1, 'dt': 1, 'w_c': 1, 'w0': 1, 'w': 1, 'w_power_fact': 1, 'l': 1}, func=<function build_sim_grid_0 at 0x7f9e92cb1280>, args=['length', 'z_num', 'wavelength', 'interpolation_degree', 'time_window', 't_num'])
attempt 1 to compute time_window, this time using Rule(targets={'z_targets': 1, 't': 1, 'time_window': 1, 't_num': 1, 'dt': 1, 'w_c': 1, 'w0': 1, 'w': 1, 'w_power_fact': 1, 'l': 1}, func=<function build_sim_grid_0 at 0x7f9e92cb1280>, args=['length', 'z_num', 'wavelength', 'interpolation_degree', 'time_window', 't_num'])
error using build_sim_grid_0 : cyclic dependency detected : 'time_window' seems to depend on itself, please provide a value for at least one variable in {'w_c', 'time_window'}
attempt 2 to compute time_window, this time using Rule(targets={'z_targets': 1, 't': 1, 'time_window': 1, 't_num': 1, 'dt': 1, 'w_c': 1, 'w0': 1, 'w': 1, 'w_power_fact': 1, 'l': 1}, func=<function build_sim_grid_0 at 0x7f9e92cb11f0>, args=['length', 'z_num', 'wavelength', 'interpolation_degree', 'time_window', 'dt'])
error using build_sim_grid_0 : cyclic dependency detected : 'time_window' seems to depend on itself, please provide a value for at least one variable in {'w_c', 'time_window'}
attempt 3 to compute time_window, this time using Rule(targets={'z_targets': 1, 't': 1, 'time_window': 1, 't_num': 1, 'dt': 1, 'w_c': 1, 'w0': 1, 'w': 1, 'w_power_fact': 1, 'l': 1}, func=<function build_sim_grid_0 at 0x7f9e92cb1310>, args=['length', 'z_num', 'wavelength', 'interpolation_degree', 't_num', 'dt'])
computed z_targets=[0. 0.00043307 0.00086614 0.00129921 0.00173228 0.00216535
0.00259843 0.0030315 0.00346457 0.00389764 0.00433071 0.00476378
0.00519685 0.00562992 0.00606299 0.00649606 0.00692913 0.0073622
0.00779528 0.00822835 0.00866142 0.00909449 0.00952756 0.00996063
0.0103937 0.01082677 0.01125984 0.01169291 0.01212598 0.01255906
0.01299213 0.0134252 0.01385827 0.01429134 0.01472441 0.01515748
0.01559055 0.01602362 0.01645669 0.01688976 0.01732283 0.01775591
0.01818898 0.01862205 0.01905512 0.01948819 0.01992126 0.02035433
0.0207874 0.02122047 0.02165354 0.02208661 0.02251969 0.02295276
0.02338583 0.0238189 0.02425197 0.02468504 0.02511811 0.02555118
0.02598425 0.02641732 0.02685039 0.02728346 0.02771654 0.02814961
0.02858268 0.02901575 0.02944882 0.02988189 0.03031496 0.03074803
0.0311811 0.03161417 0.03204724 0.03248031 0.03291339 0.03334646
0.03377953 0.0342126 0.03464567 0.03507874 0.03551181 0.03594488
0.03637795 0.03681102 0.03724409 0.03767717 0.03811024 0.03854331
0.03897638 0.03940945 0.03984252 0.04027559 0.04070866 0.04114173
0.0415748 0.04200787 0.04244094 0.04287402 0.04330709 0.04374016
0.04417323 0.0446063 0.04503937 0.04547244 0.04590551 0.04633858
0.04677165 0.04720472 0.0476378 0.04807087 0.04850394 0.04893701
0.04937008 0.04980315 0.05023622 0.05066929 0.05110236 0.05153543
0.0519685 0.05240157 0.05283465 0.05326772 0.05370079 0.05413386
0.05456693 0.055 ] using build_sim_grid_0 from evaluator
computed t=[-8.1915e-12 -8.1905e-12 -8.1895e-12 ... 8.1895e-12 8.1905e-12
8.1915e-12] using build_sim_grid_0 from evaluator
computed time_window=1.6383000000000002e-11 using build_sim_grid_0 from evaluator
computed w_c=[ 0.00000000e+00 3.83495197e+11 7.66990394e+11 ... -1.15048559e+12
-7.66990391e+11 -3.83495194e+11] using build_sim_grid_0 from evaluator
computed w0=1226655097231605.2 using build_sim_grid_0 from evaluator
computed w=[1.22665510e+15 1.22703859e+15 1.22742209e+15 ... 1.22550461e+15
1.22588811e+15 1.22627160e+15] using build_sim_grid_0 from evaluator
computed w_power_fact=[[ 0.00000000e+000 7.35342831e+022 2.94137132e+023 ... 6.61808544e+023
2.94137130e+023 7.35342818e+022]
[ 0.00000000e+000 9.40001479e+033 7.52001183e+034 ... -2.53800397e+035
-7.52001174e+034 -9.40001456e+033]
[ 0.00000000e+000 9.01215131e+044 1.44194421e+046 ... 7.29984248e+046
1.44194419e+046 9.01215101e+044]
...
[ 0.00000000e+000 1.16026959e+088 2.97029015e+090 ... 7.61252860e+091
2.97029005e+090 1.16026951e+088]
[ 0.00000000e+000 4.94397571e+098 2.53131557e+101 ... -9.73122716e+102
-2.53131547e+101 -4.94397535e+098]
[ 0.00000000e+000 1.89599094e+109 1.94149472e+112 ... 1.11956366e+114
1.94149464e+112 1.89599078e+109]] using build_sim_grid_0 from evaluator
computed l=[1.53560000e-06 1.53512007e-06 1.53464044e-06 ... 1.53704160e-06
1.53656077e-06 1.53608023e-06] using build_sim_grid_0 from evaluator
computed w_c=[ 0.00000000e+00 3.83495197e+11 7.66990394e+11 ... -1.15048559e+12
-7.66990391e+11 -3.83495194e+11] using build_sim_grid_0 from evaluator
attempt 1 to compute spec_0, this time using Rule(targets={'spec_0': 3}, func=<function load_previous_spectrum at 0x7f9e8fca7ca0>, args=['prev_data_dir'])
error using load_previous_spectrum : no rule for prev_data_dir
attempt 2 to compute spec_0, this time using Rule(targets={'spec_0': 1}, func=<function fft at 0x7f9e8dd27040>, args=['field_0'])
attempt 1 to compute field_0, this time using Rule(targets={'field_0': 1}, func=<function ifft at 0x7f9e8dd27160>, args=['spec_0'])
error using ifft : cyclic dependency detected : 'spec_0' seems to depend on itself, please provide a value for at least one variable in {'field_0', 'spec_0', 'prev_data_dir'}
attempt 2 to compute field_0, this time using Rule(targets={'field_0': 1}, func=<function add_shot_noise at 0x7f9e92c9e280>, args=['pre_field_0', 'quantum_noise', 'w_c', 'w0', 'time_window', 'dt'])
attempt 1 to compute pre_field_0, this time using Rule(targets={'pre_field_0': 2, 'peak_power': 1, 'energy': 1, 'width': 1}, func=<function load_and_adjust_field_file at 0x7f9e92c9baf0>, args=['field_file', 't', 'peak_power', 'energy', 'intensity_noise', 'noise_correlation'])
attempt 1 to compute peak_power, this time using Rule(targets={'pre_field_0': 2, 'peak_power': 1, 'energy': 1, 'width': 1}, func=<function load_and_adjust_field_file at 0x7f9e92c9baf0>, args=['field_file', 't', 'peak_power', 'energy', 'intensity_noise', 'noise_correlation'])
error using load_and_adjust_field_file : cyclic dependency detected : 'peak_power' seems to depend on itself, please provide a value for at least one variable in {'peak_power', 'field_0', 'spec_0', 'prev_data_dir', 'pre_field_0'}
attempt 2 to compute peak_power, this time using Rule(targets={'peak_power': 1}, func=<function E0_to_P0 at 0x7f9e92c9bca0>, args=['energy', 't0', 'shape'])
attempt 1 to compute energy, this time using Rule(targets={'pre_field_0': 2, 'peak_power': 1, 'energy': 1, 'width': 1}, func=<function load_and_adjust_field_file at 0x7f9e92c9baf0>, args=['field_file', 't', 'peak_power', 'energy', 'intensity_noise', 'noise_correlation'])
error using load_and_adjust_field_file : cyclic dependency detected : 'peak_power' seems to depend on itself, please provide a value for at least one variable in {'peak_power', 'field_0', 'energy', 'spec_0', 'prev_data_dir', 'pre_field_0'}
attempt 2 to compute energy, this time using Rule(targets={'width': 1, 'peak_power': 1, 'energy': 1}, func=<function measure_custom_field at 0x7f9e92c9ec10>, args=['field_file', 't'])
computed width=8.827707794861245e-14 using measure_custom_field from scgenerator.physics.pulse
computed peak_power=0.0008031855671188997 using measure_custom_field from scgenerator.physics.pulse
computed energy=8.994671799886145e-17 using measure_custom_field from scgenerator.physics.pulse
attempt 1 to compute t0, this time using Rule(targets={'t0': 1}, func=<function width_to_t0 at 0x7f9e92c9b670>, args=['width', 'shape'])
computed t0=7.497564676748131e-14 using width_to_t0 from scgenerator.physics.pulse
computed peak_power=0.0009572054484404637 using E0_to_P0 from scgenerator.physics.pulse
computed pre_field_0=[0.+0.j 0.+0.j 0.+0.j ... 0.+0.j 0.+0.j 0.+0.j] using load_and_adjust_field_file from scgenerator.physics.pulse
computed field_0=[ 0.00160864+0.02127688j -0.01957086-0.0069138j -0.01820735+0.02002421j
... 0.00622707-0.01068023j 0.01055843-0.00319426j
0.00117607-0.03033724j] using add_shot_noise from scgenerator.physics.pulse
computed spec_0=[ 1.50681561-3.69877757j -5.66353753-2.05828961j -0.54462979-1.50501029j
... -1.45621111-3.03434314j 2.6362116 -3.91420005j
-2.2820021 -3.24150382j] using fft from numpy.fft
attempt 1 to compute beta2_coefficients, this time using Rule(targets={'beta2_coefficients': 1}, func=<function dispersion_coefficients at 0x7f9e9158f3a0>, args=['wl_for_disp', 'beta2_arr', 'w0', 'interpolation_range', 'interpolation_degree'])
attempt 1 to compute wl_for_disp, this time using Rule(targets={'wl_for_disp': 2, 'beta2_arr': 2, 'interpolation_range': 2}, func=<function load_custom_dispersion at 0x7f9e9158f0d0>, args=['dispersion_file'])
computed wl_for_disp=[7.0000e-07 7.0125e-07 7.0250e-07 ... 2.3960e-06 2.3970e-06 2.3980e-06] using load_custom_dispersion from scgenerator.physics.fiber
computed beta2_arr=[ 3.37108270e-26 3.37294702e-26 3.37477437e-26 ... -2.08838856e-25
-2.09213746e-25 -2.09589149e-25] using load_custom_dispersion from scgenerator.physics.fiber
computed interpolation_range=(7e-07, 2.398e-06) using load_custom_dispersion from scgenerator.physics.fiber
interpolating dispersion between 700.0nm and 2398.0nm
computed beta2_coefficients=[-2.11874551e-026 1.48178177e-040 -4.15401033e-055 2.03223853e-069
-1.65547343e-083 1.26886165e-097 -6.93559198e-112 2.31284341e-126
-3.54046694e-141] using dispersion_coefficients from scgenerator.physics.fiber
attempt 1 to compute gamma_arr, this time using Rule(targets={'gamma_arr': 1}, func=<function gamma_parameter at 0x7f9e9158caf0>, args=['n2', 'w0', 'A_eff_arr'])
attempt 1 to compute A_eff_arr, this time using Rule(targets={'A_eff_arr': 1}, func=<function A_eff_from_V at 0x7f9e9158c790>, args=['core_radius', 'V_eff_arr'])
error using A_eff_from_V : no rule for core_radius
attempt 2 to compute A_eff_arr, this time using Rule(targets={'A_eff_arr': 1}, func=<function load_custom_A_eff at 0x7f9e9158f040>, args=['A_eff_file', 'l'])
error using load_custom_A_eff : no rule for A_eff_file
attempt 3 to compute A_eff_arr, this time using Rule(targets={'A_eff_arr': -1}, func=<function constant_A_eff_arr at 0x7f9e9158cb80>, args=['l', 'A_eff'])
attempt 1 to compute A_eff, this time using Rule(targets={'A_eff': 1}, func=<function A_eff_from_V at 0x7f9e9158c790>, args=['core_radius', 'V_eff'])
error using A_eff_from_V : cyclic dependency detected : 'core_radius' seems to depend on itself, please provide a value for at least one variable in {'core_radius', 'A_eff', 'gamma_arr', 'prev_data_dir', 'A_eff_arr', 'A_eff_file'}
attempt 2 to compute A_eff, this time using Rule(targets={'A_eff': 1}, func=<function A_eff_from_diam at 0x7f9e9158cca0>, args=['effective_mode_diameter'])
computed A_eff=8.01184666481737e-11 using A_eff_from_diam from scgenerator.physics.fiber
computed A_eff_arr=[8.01184666e-11 8.01184666e-11 8.01184666e-11 ... 8.01184666e-11
8.01184666e-11 8.01184666e-11] using constant_A_eff_arr from scgenerator.physics.fiber
computed gamma_arr=[0.00112355 0.00112355 0.00112355 ... 0.00112355 0.00112355 0.00112355] using gamma_parameter from scgenerator.physics.fiber
attempt 1 to compute hr_w, this time using Rule(targets={'hr_w': 1}, func=<function delayed_raman_w at 0x7f9e9158f5e0>, args=['t', 'dt', 'raman_type'])
computed hr_w=[1.00168656+0.j 1.00197747-0.00248147j 1.00283647-0.00508742j ...
1.00422327+0.00793569j 1.00283647+0.00508742j 1.00197747+0.00248147j] using delayed_raman_w from scgenerator.physics.fiber
attempt 1 to compute adapt_step_size, this time using Rule(targets={'adapt_step_size': 1}, func=<function <lambda> at 0x7f9e92cb13a0>, args=['step_size'])
computed adapt_step_size=True using <lambda> from scgenerator.utils.parameter
attempt 1 to compute dynamic_dispersion, this time using Rule(targets={'dynamic_dispersion': 1}, func=<function <lambda> at 0x7f9e92cb1430>, args=['pressure'])
computed dynamic_dispersion=False using <lambda> from scgenerator.utils.parameter
Traceback (most recent call last):
File "/Users/benoitsierro/Nextcloud/PhD/Supercontinuum/Module/play.py", line 20, in <module>
main()
File "/Users/benoitsierro/Nextcloud/PhD/Supercontinuum/Module/play.py", line 10, in main
pa = Parameters.load(
File "/Users/benoitsierro/Nextcloud/PhD/Supercontinuum/Module/src/scgenerator/utils/parameter.py", line 507, in load
return cls(**utils.load_toml(path))
File "<string>", line 87, in __init__
File "/Users/benoitsierro/Nextcloud/PhD/Supercontinuum/Module/src/scgenerator/utils/parameter.py", line 503, in __post_init__
setattr(self, k, v)
File "/Users/benoitsierro/Nextcloud/PhD/Supercontinuum/Module/src/scgenerator/utils/parameter.py", line 245, in __set__
self.validator(self.name, value)
File "/Users/benoitsierro/Nextcloud/PhD/Supercontinuum/Module/src/scgenerator/utils/parameter.py", line 41, in _type_checker_wrapped
validator(name, n)
File "/Users/benoitsierro/Nextcloud/PhD/Supercontinuum/Module/src/scgenerator/utils/parameter.py", line 105, in int_pair
raise ValueError(f"{name!r} must be a list or a tuple of 2 int")
ValueError: 'fit_parameters' must be a list or a tuple of 2 int

26
lol.txt
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,6 +0,0 @@
import os
import numpy as np
import scgenerator as sc
import matplotlib.pyplot as plt
from pathlib import Path
from pprint import pprint

View File

@@ -3,6 +3,7 @@ from typing import Union
import numpy as np
from scipy.integrate import cumulative_trapezoid
from scipy.special import jn_zeros
import numba
from .cache import np_cache
@@ -10,9 +11,10 @@ pi = np.pi
c = 299792458.0
def inverse_integral_exponential(x: np.ndarray, y: np.ndarray) -> np.ndarray:
def inverse_integral_exponential(y: np.ndarray, dx: float) -> np.ndarray:
"""evaluates exp(-func(y)) from x=-inf to x"""
return np.exp(-cumulative_trapezoid(y, x, initial=0))
# return np.exp(-cumulative_trapezoid(y, dx=dx, initial=0))
return np.exp(-cumulative_simpson(y) * dx)
def span(*vec):
@@ -399,3 +401,28 @@ def envelope_ind(
]
return local_min, local_max
@numba.jit(nopython=True)
def cumulative_simpson(x: np.ndarray) -> np.ndarray:
out = np.zeros_like(x)
c1 = 1 / 3
c2 = 4 / 3
out[1] = (x[1] + x[0]) * 0.5
for i in range(2, len(x)):
out[i] = out[i - 2] + x[i - 2] * c1 + x[i - 1] * c2 + c1 * x[i]
return out
@numba.jit(nopython=True)
def cumulative_boole(x: np.ndarray) -> np.ndarray:
out = np.zeros_like(x)
c1 = 14 / 45
c2 = 64 / 45
c3 = 24 / 45
c = np.array([c1, c2, c3, c2, c1])
ind = np.arange(5)
out[ind] = cumulative_simpson(x[ind])
for i in range(4, len(x)):
out[i] = out[i - 4] + np.sum(c * x[i - 4 : i + 1])
return out

View File

@@ -13,6 +13,8 @@ from typing import Any, Callable, ClassVar, Iterable, Iterator, Set, Type, TypeV
import numpy as np
from scgenerator.physics import units
from . import env, legacy, utils
from .const import MANDATORY_PARAMETERS, PARAM_FN, VALID_VARIABLE, __version__
from .errors import EvaluatorError
@@ -532,7 +534,7 @@ class Configuration:
worker_num: int
parallel: bool
overwrite: bool
final_path: str
final_path: Path
all_configs: dict[tuple[tuple[int, ...], ...], "Configuration.__SimConfig"]
@dataclass(frozen=True)

View File

@@ -41,7 +41,7 @@ class PBars:
try:
self.width = os.get_terminal_size().columns
except OSError:
self.width = 80
self.width = 120
if isinstance(task, abc.Iterable):
self.iterator: Iterable[T_] = iter(task)
self.num_tot: int = len(task)

View File

@@ -1,10 +1,9 @@
from dataclasses import dataclass
import numpy as np
import scipy.special
from scipy.integrate import cumulative_trapezoid
from .units import e, hbar, me
from ..math import inverse_integral_exponential
from ..math import inverse_integral_exponential, cumulative_simpson
@dataclass
@@ -12,6 +11,8 @@ class PlasmaInfo:
electron_density: np.ndarray
dn_dt: np.ndarray
polarization: np.ndarray
loss: np.ndarray
phase_effect: np.ndarray
class IonizationRate:
@@ -39,8 +40,8 @@ class IonizationRateADK(IonizationRate):
class Plasma:
def __init__(self, t: np.ndarray, ionization_energy: float, atomic_number: int):
self.t = t
def __init__(self, dt: float, ionization_energy: float, atomic_number: int):
self.dt = dt
self.Ip = ionization_energy
self.atomic_number = atomic_number
self.rate = IonizationRateADK(self.Ip, self.atomic_number)
@@ -60,20 +61,20 @@ class Plasma:
np.ndarray
number density of free electrons as function of time
"""
# Ne = free_electron_density(self.t, field, N0, self.rate)
field_abs = np.abs(field)
delta = 1e-14 * field_abs.max()
exp_int = inverse_integral_exponential(self.t, self.rate(field_abs))
rate = self.rate(field_abs)
exp_int = inverse_integral_exponential(rate, self.dt)
electron_density = N0 * (1 - exp_int)
dn_dt = N0 * self.rate(field_abs) * exp_int
out = cumulative_trapezoid(
# np.gradient(self.density, self.t) * self.Ip / field
dn_dt = N0 * rate * exp_int
out = self.dt * cumulative_simpson(
dn_dt * self.Ip / (field + delta)
+ e ** 2 / me * cumulative_trapezoid(electron_density * field, self.t, initial=0),
self.t,
initial=0,
+ e ** 2 / me * self.dt * cumulative_simpson(electron_density * field)
)
return PlasmaInfo(electron_density, dn_dt, out)
loss = cumulative_simpson(dn_dt * self.Ip / (field + delta)) * self.dt
phase_effect = e ** 2 / me * self.dt * cumulative_simpson(electron_density * field)
phase_effect = exp_int
return PlasmaInfo(electron_density, dn_dt, out, loss, phase_effect)
def adiabadicity(w: np.ndarray, I: float, field: np.ndarray) -> np.ndarray:
@@ -81,6 +82,6 @@ def adiabadicity(w: np.ndarray, I: float, field: np.ndarray) -> np.ndarray:
def free_electron_density(
t: np.ndarray, field: np.ndarray, N0: float, rate: IonizationRate
field: np.ndarray, dt: float, N0: float, rate: IonizationRate
) -> np.ndarray:
return N0 * (1 - np.exp(-cumulative_trapezoid(rate(field), t, initial=0)))
return N0 * (1 - np.exp(-dt * cumulative_simpson(rate(field))))

View File

@@ -592,7 +592,9 @@ class RaySimulations(Simulations, priority=2):
self.num_submitted = 0
self.rolling_id = 0
self.p_actor = ray.remote(ProgressBarActor).remote(
self.configuration.final_path, self.sim_jobs_total, self.configuration.total_num_steps
self.configuration.final_path.name,
self.sim_jobs_total,
self.configuration.total_num_steps,
)
self.configuration.skip_callback = lambda num: ray.get(self.p_actor.update.remote(0, num))

View File

@@ -53,13 +53,21 @@ class UnitMap(dict):
return chained_function
units_map: dict[Union[str, tuple[str, str]], Unit] = UnitMap()
units_map: dict[Union[str, tuple[str, str]], _UT] = UnitMap()
class To:
def __init__(self, name: str):
self.name = name
def __getstate__(self):
"""make pickle happy"""
return self.name
def __setstate__(self, name):
"""make pickle happy"""
self.name = name
def __getattr__(self, key: str):
try:
return units_map[self.name, key]
@@ -83,48 +91,37 @@ def W_to_Vm(n0: float, A_eff: float) -> float:
return 1.0 / np.sqrt(A_eff * 0.5 * epsilon0 * c * n0)
class Unit:
func: _UT
inv: _UT
to: To = None
name: str = "unit"
type: str = "other"
label: str = ""
class unit:
inv = None
def __init_subclass__(cls):
def call(self, x: _T) -> _T:
return self.func(x)
def __init__(self, tpe: str, label: str):
self.type = tpe
self.label = label
call.__doc__ = f"Transform x from {cls.name!r} to {PRIMARIES.get(cls.type)!r}"
cls.__call__ = call
def __init__(self, func: _UT, inv: _UT = None):
def __call__(self, func):
self.name = func.__name__
self.func = func
if inv is None:
self.inv = func
else:
self.inv = inv
self.to = To(self.name)
units_map[self.name] = self
self.inv = func
def __call__(self, x: _T) -> _T:
"""call the original unit function"""
return self.func(x)
units_map[self.name] = self.func
func.to = To(self.name)
func.inv = func
func.inverse = self.inverse
func.type = self.type
func.label = self.label
func.name = self.name
func.__doc__ = f"Transform x from {self.name!r} to {PRIMARIES.get(self.type)!r}"
return func
def inverse(self, func: _UT):
if func.__name__ == self.name:
raise ValueError(
f"inverse function of {self.name} must be named something else than {self.name}"
)
self.inv = func
return self
def unit(tpe: str, label: str, inv: Callable = None):
def unit_maker(func) -> Unit:
nonlocal inv
name = func.__name__
unit_type = type(f"Unit_{name}", (Unit,), dict(name=name, label=label, type=tpe))
return unit_type(func, inv)
return unit_maker
self.func.inv = func
return func
@unit("WL", r"Wavelength $\lambda$ (m)")
@@ -142,33 +139,51 @@ def um(l: _T) -> _T:
return 2 * pi * c / (l * 1e-6)
@unit("FREQ", r"Frequency $f$ (Hz)", lambda w: w / (2 * pi))
@unit("FREQ", r"Frequency $f$ (Hz)")
def Hz(f: _T) -> _T:
return 2 * pi * f
@unit("FREQ", r"Frequency $f$ (THz)", lambda w: w / (1e12 * 2 * pi))
@Hz.inverse
def Hz_inv(w):
return w / (2 * pi)
@unit("FREQ", r"Frequency $f$ (THz)")
def THz(f: _T) -> _T:
return 1e12 * 2 * pi * f
@unit("FREQ", r"Frequency $f$ (PHz)", lambda w: w / (1e15 * 2 * pi))
@THz.inverse
def THz_inv(w):
return w / (1e12 * 2 * pi)
@unit("FREQ", r"Frequency $f$ (PHz)")
def PHz(f: _T) -> _T:
return 1e15 * 2 * pi * f
@PHz.inverse
def PHz_inv(w):
return w / (1e15 * 2 * pi)
@unit("AFREQ", r"Angular frequency $\omega$ ($\frac{\mathrm{rad}}{\mathrm{s}}$)")
def rad_s(w: _T) -> _T:
return w
@unit(
"AFREQ", r"Angular frequency $\omega$ ($\frac{\mathrm{Prad}}{\mathrm{s}}$)", lambda w: 1e-15 * w
)
@unit("AFREQ", r"Angular frequency $\omega$ ($\frac{\mathrm{Prad}}{\mathrm{s}}$)")
def Prad_s(w: _T) -> _T:
return w * 1e15
@Prad_s.inverse
def Prad_s_inv(w):
return w * 1e-15
@unit("TIME", r"relative time ${\tau}/{\tau_\mathrm{0, FWHM}}$")
def rel_time(t: _T) -> _T:
return t
@@ -184,51 +199,91 @@ def s(t: _T) -> _T:
return t
@unit("TIME", r"Time $t$ (us)", lambda t: t * 1e6)
@unit("TIME", r"Time $t$ (us)")
def us(t: _T) -> _T:
return t * 1e-6
@unit("TIME", r"Time $t$ (ns)", lambda t: t * 1e9)
@us.inverse
def us_inv(t):
return t * 1e6
@unit("TIME", r"Time $t$ (ns)")
def ns(t: _T) -> _T:
return t * 1e-9
@unit("TIME", r"Time $t$ (ps)", lambda t: t * 1e12)
@ns.inverse
def ns_inv(t):
return t * 1e9
@unit("TIME", r"Time $t$ (ps)")
def ps(t: _T) -> _T:
return t * 1e-12
@unit("TIME", r"Time $t$ (fs)", lambda t: t * 1e15)
@ps.inverse
def ps_inv(t):
return t * 1e12
@unit("TIME", r"Time $t$ (fs)")
def fs(t: _T) -> _T:
return t * 1e-15
@fs.inverse
def fs_inv(t):
return t * 1e15
@unit("WL", "inverse")
def inv(x: _T) -> _T:
return 1 / x
@unit("PRESSURE", "Pressure (bar)", lambda p: 1e-5 * p)
@unit("PRESSURE", "Pressure (bar)")
def bar(p: _T) -> _T:
return 1e5 * p
@unit("OTHER", r"$\beta_2$ (fs$^2$/cm)", lambda b2: 1e28 * b2)
@bar.inverse
def bar_inv(p):
return p * 1e-5
@unit("OTHER", r"$\beta_2$ (fs$^2$/cm)")
def beta2_fs_cm(b2: _T) -> _T:
return 1e-28 * b2
@unit("OTHER", r"$\beta_2$ (ps$^2$/km)", lambda b2: 1e27 * b2)
@beta2_fs_cm.inverse
def beta2_fs_cm_inv(b2):
return 1e28 * b2
@unit("OTHER", r"$\beta_2$ (ps$^2$/km)")
def beta2_ps_km(b2: _T) -> _T:
return 1e-27 * b2
@unit("OTHER", r"$D$ (ps/(nm km))", lambda D: 1e6 * D)
@beta2_ps_km.inverse
def beta2_ps_km_inv(b2):
return 1e27 * b2
@unit("OTHER", r"$D$ (ps/(nm km))")
def D_ps_nm_km(D: _T) -> _T:
return 1e-6 * D
@D_ps_nm_km.inverse
def D_ps_nm_km_inv(D):
return 1e6 * D
@unit("OTHER", r"a.u.")
def unity(x: _T) -> _T:
return x
@@ -239,11 +294,16 @@ def K(t: _T) -> _T:
return t
@unit("TEMPERATURE", r"Temperature (°C)", lambda t_K: t_K - 272.15)
@unit("TEMPERATURE", r"Temperature (°C)")
def C(t_C: _T) -> _T:
return t_C + 272.15
@C.inverse
def C_inv(t_K):
return t_K - 272.15
def get_unit(unit: Union[str, Callable]) -> Callable[[float], float]:
if isinstance(unit, str):
return units_map[unit]

View File

@@ -214,7 +214,7 @@ class SimulationSeries:
def fields(
self, z_descr: Union[float, int, None] = None, sim_ind: Optional[int] = 0
) -> Spectrum:
return np.fft.ifft(self.spectra(z_descr, sim_ind))
return self.params.ifft(self.spectra(z_descr, sim_ind))
# Plotting

File diff suppressed because it is too large Load Diff

View File

@@ -13,7 +13,7 @@ pressure = 3.2e5
length = 0.1
interpolation_range = [120e-9, 3000e-9]
full_field = true
dt = 0.05e-15
dt = 0.04e-15
t_num = 32768
z_num = 128
step_size = 10e-6

View File

@@ -1,45 +0,0 @@
from __future__ import annotations
from collections import defaultdict
class Parameter:
registered_params = defaultdict(dict)
def __init__(self, default_value, display_suffix=""):
self.value = default_value
self.display_suffix = display_suffix
def __set_name__(self, owner, name):
self.name = name
self.registered_params[owner.__name__][name] = self
def __get__(self, instance, owner):
return self.value
def __set__(self, instance, value):
self.value = value
def display(self):
return str(self.value) + " " + self.display_suffix
class A:
x = Parameter("lol")
y = Parameter(56.2)
class B:
x = Parameter(slice(None))
opt = None
def main():
print(Parameter.registered_params["A"])
print(Parameter.registered_params["B"])
a = A()
a.x = 5
print(a.x)
if __name__ == "__main__":
main()