From a8f0379c38c064148bf08fe7310166d4ea722af3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20Sierro?= Date: Thu, 27 Jul 2023 12:12:10 +0200 Subject: [PATCH] fix docstrings --- src/scgenerator/evaluator.py | 9 +- src/scgenerator/helpers.py | 9 +- src/scgenerator/io.py | 1 + src/scgenerator/logger.py | 7 +- src/scgenerator/math.py | 34 ++-- src/scgenerator/parameter.py | 6 +- src/scgenerator/physics/__init__.py | 9 +- src/scgenerator/physics/fiber.py | 60 ++++-- src/scgenerator/physics/materials.py | 26 ++- src/scgenerator/physics/plasma.py | 3 +- src/scgenerator/physics/pulse.py | 283 +++++++++++++++------------ src/scgenerator/physics/units.py | 18 +- src/scgenerator/plotting.py | 35 ++-- src/scgenerator/spectra.py | 12 +- src/scgenerator/utils.py | 38 ++-- 15 files changed, 332 insertions(+), 218 deletions(-) diff --git a/src/scgenerator/evaluator.py b/src/scgenerator/evaluator.py index fc0c70a..a8c7d18 100644 --- a/src/scgenerator/evaluator.py +++ b/src/scgenerator/evaluator.py @@ -57,7 +57,8 @@ class Rule: args_const: list[str] = None, priorities: Union[int, list[int]] = None, ) -> list["Rule"]: - """given a function that doesn't need all its keyword arguemtn specified, will + """ + given a function that doesn't need all its keyword arguemtn specified, will return a list of Rule obj, one for each combination of n_var specified kwargs Parameters @@ -145,7 +146,8 @@ class Evaluator: self.rules[t].sort(key=lambda el: el.targets[t], reverse=True) def set(self, dico: dict[str, Any] = None, **params: Any): - """sets the internal set of parameters + """ + sets the internal set of parameters Parameters ---------- @@ -169,7 +171,8 @@ class Evaluator: self.eval_stats = defaultdict(EvalStat) def compute(self, target: str, check_only=False) -> Any: - """computes a target + """ + computes a target Parameters ---------- diff --git a/src/scgenerator/helpers.py b/src/scgenerator/helpers.py index 59d0aaa..6d91382 100644 --- a/src/scgenerator/helpers.py +++ b/src/scgenerator/helpers.py @@ -30,7 +30,8 @@ def w_from_wl(wl_min_nm: float, wl_max_nm: float, n: int) -> np.ndarray: def capillary_dispersion( wl: np.ndarray, radius: float, gas_name: str, pressure=None, temperature=None ) -> np.ndarray: - """computes the dispersion (beta2) of a capillary tube + """ + computes the dispersion (beta2) of a capillary tube Parameters ---------- @@ -67,7 +68,8 @@ def capillary_zdw( temperature=None, search_range: tuple[float, float] = (200e-9, 3000e-9), ) -> np.ndarray: - """find the zero dispersion wavelength of a capilally + """ + find the zero dispersion wavelength of a capilally Parameters ---------- @@ -104,7 +106,8 @@ def revolver_dispersion( pressure=None, temperature=None, ) -> np.ndarray: - """computes the dispersion (beta2) of a capillary tube + """ + computes the dispersion (beta2) of a capillary tube Parameters ---------- diff --git a/src/scgenerator/io.py b/src/scgenerator/io.py index 152f84a..3a2d5bc 100644 --- a/src/scgenerator/io.py +++ b/src/scgenerator/io.py @@ -6,6 +6,7 @@ import pkg_resources def data_file(path: str) -> Path: + """returns a `Path` object pointing to the desired data file included in `scgenerator`""" return Path(pkg_resources.resource_filename("scgenerator", path)) diff --git a/src/scgenerator/logger.py b/src/scgenerator/logger.py index 42eee72..b3f7974 100644 --- a/src/scgenerator/logger.py +++ b/src/scgenerator/logger.py @@ -2,7 +2,6 @@ import logging from scgenerator.env import log_file_level, log_print_level - lvl_map: dict[str, int] = dict( debug=logging.DEBUG, info=logging.INFO, @@ -13,7 +12,8 @@ lvl_map: dict[str, int] = dict( def get_logger(name=None): - """returns a logging.Logger instance. This function is there because if scgenerator + """ + returns a logging.Logger instance. This function is there because if scgenerator is used with some multiprocessing library, workers are not aware of any configuration done with the logging and so it must be reconfigured. @@ -33,7 +33,8 @@ def get_logger(name=None): def configure_logger(logger: logging.Logger): - """configures a logging.Logger obj + """ + configures a logging.Logger obj Parameters ---------- diff --git a/src/scgenerator/math.py b/src/scgenerator/math.py index 70dd6fb..4da0bf1 100644 --- a/src/scgenerator/math.py +++ b/src/scgenerator/math.py @@ -114,11 +114,14 @@ def sigmoid(x): def u_nm(n, m): - """returns the mth zero of the Bessel function of order n-1 + """ + returns the mth zero of the Bessel function of order n-1 + Parameters ---------- - n-1 : order of the Bessel function - m : order of the zero + n-1 : order of the Bessel function + m : order of the zero + Returns ---------- float @@ -139,16 +142,16 @@ def wspace(t, t_num=0): Parameters ---------- - t : float or array - float : total width of the time window - array : time array - t_num : int- - if t is a float, specifies the number of points + t : float or array + float : total width of the time window + array : time array + t_num : int- + if t is a float, specifies the number of points Returns ------- - w : array - linspace of frencies corresponding to t + w : array + linspace of frencies corresponding to t """ if isinstance(t, (np.ndarray, list, tuple)): dt = t[1] - t[0] @@ -258,7 +261,7 @@ def build_z_grid(z_num: int, length: float) -> np.ndarray: def build_t_grid( time_window: float = None, t_num: int = None, dt: float = None ) -> tuple[np.ndarray, float, float, int]: - """[summary] + """ Returns ------- @@ -308,7 +311,8 @@ def polynom_extrapolation(x: np.ndarray, y: np.ndarray, degree: int) -> np.ndarr def _polynom_extrapolation_in_place(y: np.ndarray, left_ind: int, right_ind: int, degree: float): - """extrapolates IN PLACE linearily on both side of the support + """ + extrapolates IN PLACE linearily on both side of the support Parameters ---------- @@ -415,7 +419,8 @@ def envelope_ind( def envelope_2d(x: np.ndarray, values: np.ndarray) -> np.ndarray: - """returns the envelope of a 2d propagation-like array + """ + returns the envelope of a 2d propagation-like array Parameters ---------- @@ -472,7 +477,8 @@ class LobeProps: def measure_lobe(x_in, y_in, /, lobe_pos: int = None, thr_rel: float = 1 / 50) -> LobeProps: - """given a fairly smooth signal, finds the highest lobe and returns its position as well + """ + given a fairly smooth signal, finds the highest lobe and returns its position as well as its fwhm points Parameters diff --git a/src/scgenerator/parameter.py b/src/scgenerator/parameter.py index 5abd9d0..c484022 100644 --- a/src/scgenerator/parameter.py +++ b/src/scgenerator/parameter.py @@ -213,7 +213,8 @@ class Parameter: default=None, display_info: tuple[float, str] = None, ): - """Single parameter + """ + Single parameter Parameters ---------- @@ -567,7 +568,8 @@ class Parameters: return "\n".join("{:>{l}} = {:{r}}".format(*p, l=max_left, r=max_right) for p in p_pairs) def strip_params_dict(self) -> dict[str, Any]: - """prepares a dictionary for serialization. Some keys may not be preserved + """ + prepares a dictionary for serialization. Some keys may not be preserved (dropped because they take a lot of space and can be exactly reconstructed) Parameters diff --git a/src/scgenerator/physics/__init__.py b/src/scgenerator/physics/__init__.py index 1953c67..40b99a5 100644 --- a/src/scgenerator/physics/__init__.py +++ b/src/scgenerator/physics/__init__.py @@ -26,7 +26,8 @@ def material_dispersion( pressure=None, temperature=None, ): - """returns the dispersion profile (beta_2) of a bulk material. + """ + returns the dispersion profile (beta_2) of a bulk material. Parameters ---------- @@ -59,7 +60,8 @@ def material_dispersion( def find_optimal_depth( spectrum: T, w_c: np.ndarray, w0: float, material: str, max_z: float = 1.0 ) -> tuple[T, pulse.OptimizeResult]: - """finds the optimal silica depth to compress a pulse + """ + finds the optimal silica depth to compress a pulse Parameters ---------- @@ -100,7 +102,8 @@ def find_optimal_depth( def propagate_field( t: np.ndarray, field: np.ndarray, z: float, material: str, center_wl_nm: float ) -> np.ndarray: - """propagates a field through bulk material + """ + propagates a field through bulk material Parameters ---------- diff --git a/src/scgenerator/physics/fiber.py b/src/scgenerator/physics/fiber.py index e92c190..45a3772 100644 --- a/src/scgenerator/physics/fiber.py +++ b/src/scgenerator/physics/fiber.py @@ -19,7 +19,8 @@ T = TypeVar("T") def lambda_for_envelope_dispersion( l: np.ndarray, wavelength_window: tuple[float, float] ) -> tuple[np.ndarray, np.ndarray]: - """Returns a wl vector for dispersion calculation in envelope mode + """ + Returns a wl vector for dispersion calculation in envelope mode Returns ------- @@ -50,7 +51,8 @@ def lambda_for_envelope_dispersion( def lambda_for_full_field_dispersion( l: np.ndarray, wavelength_window: tuple[float, float] ) -> tuple[np.ndarray, np.ndarray]: - """Returns a wl vector for dispersion calculation in full field mode + """ + Returns a wl vector for dispersion calculation in full field mode Returns ------- @@ -95,7 +97,8 @@ def is_dynamic_dispersion(pressure=None): def gvd_from_n_eff(n_eff: np.ndarray, wl_for_disp: np.ndarray): - """computes the dispersion parameter D from an effective index of refraction n_eff + """ + computes the dispersion parameter D from an effective index of refraction n_eff Since computing gradients/derivatives of discrete arrays is not well defined on the boundary, it is advised to chop off the two values on either end of the returned array @@ -126,7 +129,8 @@ def D_to_beta2(D, wl_for_disp): def plasma_dispersion(wl_for_disp, number_density, simple=False): - """computes dispersion (beta2) for constant plasma + """ + computes dispersion (beta2) for constant plasma Parameters ---------- @@ -151,7 +155,8 @@ def plasma_dispersion(wl_for_disp, number_density, simple=False): def n_eff_marcatili(wl_for_disp, n_gas_2, core_radius, he_mode=(1, 1)): - """computes the effective refractive index according to the Marcatili model of a capillary + """ + computes the effective refractive index according to the Marcatili model of a capillary Parameters ---------- @@ -212,7 +217,8 @@ def n_eff_marcatili_adjusted(wl_for_disp, n_gas_2, core_radius, he_mode=(1, 1), def effective_area_marcatili(core_radius: float) -> float: - """Effective mode-field area for fundamental mode hollow capillaries + """ + Effective mode-field area for fundamental mode hollow capillaries Parameters ---------- @@ -238,7 +244,8 @@ def capillary_spacing_hasan( def resonance_thickness( wl_for_disp: np.ndarray, order: int, n_gas_2: np.ndarray, core_radius: float ) -> float: - """computes at which wall thickness the specified wl is resonant + """ + computes at which wall thickness the specified wl is resonant Parameters ---------- @@ -361,7 +368,8 @@ def n_eff_hasan( def effective_area_hasan(core_radius, capillary_num, capillary_spacing): - """computed the effective mode area + """ + computed the effective mode area Parameters ---------- @@ -413,7 +421,8 @@ def V_eff_step_index( def V_parameter_koshiba(l: np.ndarray, pcf_pitch: float, pcf_pitch_ratio: float) -> float: - """returns the V parameter according to Koshiba2004 + """ + returns the V parameter according to Koshiba2004 Parameters @@ -447,7 +456,8 @@ def V_parameter_koshiba(l: np.ndarray, pcf_pitch: float, pcf_pitch_ratio: float) def effective_area_from_V(core_radius: float, V_eff: T) -> T: - """According to Marcuse1978 + """ + According to Marcuse1978 Parameters ---------- @@ -508,7 +518,8 @@ def HCPCF_dispersion( temperature=None, **model_params, ): - """returns the dispersion profile (beta_2) of a hollow-core photonic crystal fiber. + """ + returns the dispersion profile (beta_2) of a hollow-core photonic crystal fiber. Parameters ---------- @@ -643,7 +654,8 @@ def saitoh_paramters(pcf_pitch_ratio: float) -> tuple[float, float]: def load_custom_effective_area(effective_area_file: str, l: np.ndarray) -> np.ndarray: - """loads custom effective area file + """ + loads custom effective area file Parameters ---------- @@ -673,7 +685,8 @@ def load_custom_dispersion(dispersion_file: str) -> tuple[np.ndarray, np.ndarray def load_custom_loss(l: np.ndarray, loss_file: str) -> np.ndarray: - """loads a npz loss file that contains a wavelength and a loss entry + """ + loads a npz loss file that contains a wavelength and a loss entry Parameters ---------- @@ -699,7 +712,8 @@ def dispersion_coefficients( w0: float, interpolation_degree: int, ): - """Computes the taylor expansion of beta2 to be used in dispersion_op + """ + Computes the taylor expansion of beta2 to be used in dispersion_op Parameters ---------- @@ -735,7 +749,8 @@ def dispersion_coefficients( def dispersion_from_coefficients( w_c: np.ndarray, beta2_coefficients: Iterable[float] ) -> np.ndarray: - """computes the dispersion profile (beta2) from the beta coefficients + """ + computes the dispersion profile (beta2) from the beta coefficients Parameters ---------- @@ -810,8 +825,10 @@ def delayed_raman_t(t: np.ndarray, raman_type: str) -> np.ndarray: def delayed_raman_w(t: np.ndarray, raman_type: str) -> tuple[np.ndarray, float]: - """returns the delayed raman response function as function of w - see delayed_raman_t for detailes as well as the raman fraction""" + """ + returns the delayed raman response function as function of w + see delayed_raman_t for detailes as well as the raman fraction + """ hr_w = fft(delayed_raman_t(t, raman_type)) * (t[1] - t[0]) return hr_w, raman_fraction(raman_type) @@ -851,7 +868,8 @@ def _fast_disp_loop(dispersion: np.ndarray, beta_arr, power_fact_arr): def direct_dispersion(w: np.ndarray, w0: float, n_eff: np.ndarray) -> np.ndarray: - """returns the dispersive operator in direct form (without polynomial interpolation) + """ + returns the dispersive operator in direct form (without polynomial interpolation) i.e. -1j * (beta(w) - beta1 * (w - w0) - beta0) Parameters @@ -879,7 +897,8 @@ def fast_direct_dispersion(w: np.ndarray, w0: float, n_eff: np.ndarray, w0_ind: def effective_core_radius(wl_for_disp, core_radius, s=0.08, h=200e-9): - """return the variable core radius according to Eq. S2.2 from Köttig2017 + """ + return the variable core radius according to Eq. S2.2 from Köttig2017 Parameters ---------- @@ -910,7 +929,8 @@ def scalar_loss(alpha: float, w_num: int) -> np.ndarray: def capillary_loss(wl: np.ndarray, he_mode: tuple[int, int], core_radius: float) -> np.ndarray: - """computes the wavelenth dependent capillary loss according to Marcatili + """ + computes the wavelenth dependent capillary loss according to Marcatili Parameters ---------- diff --git a/src/scgenerator/physics/materials.py b/src/scgenerator/physics/materials.py index fb943f1..588b0e8 100644 --- a/src/scgenerator/physics/materials.py +++ b/src/scgenerator/physics/materials.py @@ -142,7 +142,8 @@ class Gas: return self.sellmeier.temperature_ref / temperature * density * self.sellmeier.pressure_ref def density_factor(self, temperature: float, pressure: float, ideal_gas: bool) -> float: - """returns the number density relative to reference values + """ + returns the number density relative to reference values Parameters ---------- @@ -176,7 +177,8 @@ class Gas: def number_density( self, temperature: float = None, pressure: float = None, ideal_gas: bool = False ) -> float: - """returns the number density in 1/m^3 using van der Waals equation + """ + returns the number density in 1/m^3 using van der Waals equation Parameters ---------- @@ -198,7 +200,8 @@ class Gas: return self.number_density_van_der_waals(pressure, temperature) def number_density_van_der_waals(self, pressure: float = None, temperature: float = None): - """returns the number density of a gas + """ + returns the number density of a gas Parameters ---------- @@ -324,28 +327,34 @@ def n_gas_2(wl_for_disp: np.ndarray, gas_name: str, pressure: float, temperature def pressure_from_gradient(ratio: float, p0: float, p1: float) -> float: - """returns the pressure as function of distance with eq. 20 in Markos et al. (2017) + """ + returns the pressure as function of distance with eq. 20 in Markos et al. (2017) + Parameters ---------- ratio : relative position in the fiber (0 = start, 1 = end) p0 : pressure at the start p1 : pressure at the end + Returns - ---------- + ------- the pressure (float) """ return np.sqrt(p0**2 - ratio * (p0**2 - p1**2)) def delta_gas(w: np.ndarray, gas: Gas) -> np.ndarray: - """returns the value delta_t (eq. 24 in Markos(2017)) + """ + returns the value delta_t (eq. 24 in Markos(2017)) + Parameters ---------- w : np.ndarray angular frequency array gas : Gas + Returns - ---------- + ------- delta_t since 2 gradients are computed, it is recommended to exclude the 2 extremum values """ @@ -377,7 +386,8 @@ def gas_n2(gas_name: str, pressure: float, temperature: float) -> float: def gas_chi3(gas_name: str, wavelength: float, pressure: float, temperature: float) -> float: - """returns the chi3 of a particular material + """ + returns the chi3 of a particular material Parameters ---------- diff --git a/src/scgenerator/physics/plasma.py b/src/scgenerator/physics/plasma.py index ec14f9c..62f46ed 100644 --- a/src/scgenerator/physics/plasma.py +++ b/src/scgenerator/physics/plasma.py @@ -85,7 +85,8 @@ class Plasma: self.rate = create_ion_rate_func(self.ionization_energy) def __call__(self, field: np.ndarray, N0: float) -> PlasmaInfo: - """returns the number density of free electrons as function of time + """ + returns the number density of free electrons as function of time Parameters ---------- diff --git a/src/scgenerator/physics/pulse.py b/src/scgenerator/physics/pulse.py index 277162c..07c785e 100644 --- a/src/scgenerator/physics/pulse.py +++ b/src/scgenerator/physics/pulse.py @@ -106,7 +106,8 @@ def initial_full_field( w0: float, n0: float, ) -> np.ndarray: - """initial field in full field simulations + """ + initial field in full field simulations Parameters ---------- @@ -136,7 +137,8 @@ def initial_full_field( def initial_field_envelope(t: np.ndarray, shape: str, t0: float, peak_power: float) -> np.ndarray: - """returns the initial field + """ + returns the initial field Parameters ---------- @@ -176,7 +178,8 @@ def modify_field_ratio( intensity_noise: float = None, noise_correlation: float = 0, ) -> float: - """multiply a field by this number to get the desired specifications + """ + multiply a field by this number to get the desired specifications Parameters ---------- @@ -204,7 +207,8 @@ def modify_field_ratio( def convert_field_units(envelope: np.ndarray, n: np.ndarray, effective_area: float) -> np.ndarray: - """[summary] + """ + [summary] Parameters ---------- @@ -249,7 +253,8 @@ def conform_pulse_params( gamma: float = None, beta2: float = None, ): - """makes sure all parameters of the pulse are set and consistent + """ + makes sure all parameters of the pulse are set and consistent Parameters ---------- @@ -464,14 +469,15 @@ def technical_noise(rms_noise, noise_correlation=-0.4): Parameters ---------- - rms_noise : float - RMS amplitude noise of the laser - relative factor : float - magnitude of the anticorrelation between peak_power and pulse width noise + rms_noise : float + RMS amplitude noise of the laser + relative factor : float + magnitude of the anticorrelation between peak_power and pulse width noise + Returns ---------- - delta_int : float - delta_T0 : float + delta_int : float + delta_T0 : float """ psy = np.random.normal(1, rms_noise) return psy, 1 + noise_correlation * (psy - 1) @@ -482,19 +488,19 @@ def shot_noise(w: np.ndarray, T: float, dt: float, additional_noise_factor=1.0): Parameters ---------- - w_c : array, shape (n,) - angular frequencies centered around 0 - T : float - length of the time windows - dt : float - resolution of time grid - additional_noise_factor : float - resulting noise spectrum is multiplied by this number + w_c : array, shape (n,) + angular frequencies centered around 0 + T : float + length of the time windows + dt : float + resolution of time grid + additional_noise_factor : float + resulting noise spectrum is multiplied by this number Returns ------- - out : array, shape (n,) - noise field to be added on top of initial field in time domain + out : array, shape (n,) + noise field to be added on top of initial field in time domain """ rand_phase = np.random.rand(len(w)) * 2 * pi A_oppm = np.sqrt(hbar * (np.abs(w)) * T) * np.exp(-1j * rand_phase) @@ -531,21 +537,25 @@ def C_to_A(C: np.ndarray, effective_area_arr: np.ndarray) -> np.ndarray: def mean_phase(spectra): - """computes the mean phase of spectra - Parameter + """ + computes the mean phase of spectra + + Parameters ---------- - spectra : 2D array - The mean is taken on the 0th axis. This means the array has to be of shape (n, nt) + spectra : 2D array + The mean is taken on the 0th axis. This means the array has to be of shape (n, nt) + Returns ---------- - mean_phase : 1D array of shape (len(spectra[0])) - array of complex numbers of unit length representing the mean phase + mean_phase : 1D array of shape (len(spectra[0])) + array of complex numbers of unit length representing the mean phase + Example ---------- - >>> x = np.array([[1 + 1j, 0 + 2j, -3 - 1j], - [1 + 0j, 2 + 3j, -3 + 1j]]) - >>> mean_phase(x) - array([ 0.92387953+0.38268343j, 0.28978415+0.95709203j, -1. +0.j ]) + >>> x = np.array([[1 + 1j, 0 + 2j, -3 - 1j], + [1 + 0j, 2 + 3j, -3 + 1j]]) + >>> mean_phase(x) + array([ 0.92387953+0.38268343j, 0.28978415+0.95709203j, -1. +0.j ]) """ @@ -564,12 +574,12 @@ def flatten_phase(spectra): Parameters ---------- - spectra : 2D array of shape (n, nt) - spectra arranged in the same fashion as in `scgenerator.physics.pulse.mean_phase` + spectra : 2D array of shape (n, nt) + spectra arranged in the same fashion as in `scgenerator.physics.pulse.mean_phase` Returns ---------- - output : array of same dimensions and amplitude, but with a flattened phase + output : array of same dimensions and amplitude, but with a flattened phase """ mean_theta = mean_phase(spectra) tiled = np.tile(mean_theta, (len(spectra), 1)) @@ -578,19 +588,20 @@ def flatten_phase(spectra): def compress_pulse(spectra): - """given some complex spectrum, returns the compressed pulse in the time domain + """ + given some complex spectrum, returns the compressed pulse in the time domain Parameters ---------- - spectra : ND array - spectra to compress. The shape must be at least 2D. Compression occurs along - the -2th axis. This means spectra have to be of shape ([what, ever,] n, nt) where n - is the number of spectra brought together for one compression operation and nt the - resolution of the grid. + spectra : ND array + spectra to compress. The shape must be at least 2D. Compression occurs along + the -2th axis. This means spectra have to be of shape ([what, ever,] n, nt) where n + is the number of spectra brought together for one compression operation and nt the + resolution of the grid. Returns ---------- - out : array of shape ([what, ever,] nt) - compressed inverse Fourier-transformed pulse + out : array of shape ([what, ever,] nt) + compressed inverse Fourier-transformed pulse """ if spectra.ndim > 2: return np.array([compress_pulse(spec) for spec in spectra]) @@ -599,14 +610,16 @@ def compress_pulse(spectra): def ideal_compressed_pulse(spectra): - """returns the ideal compressed pulse assuming flat phase + """ + returns the ideal compressed pulse assuming flat phase Parameters ---------- - spectra : 2D array, sc-ordering + spectra : 2D array, sc-ordering + Returns ---------- - compressed : 1D array - time envelope of the compressed field + compressed : 1D array + time envelope of the compressed field """ return math.abs2(fftshift(ifft(np.sqrt(np.mean(math.abs2(spectra), axis=0))))) @@ -622,18 +635,18 @@ def spectrogram( Parameters ---------- - time : np.ndarray, shape (nt,) - time in the co-moving frame of reference - delays : np.ndarray, shape (nd,) - delays overs which to compute the spectrogram - signal : np.ndarray, shape (nt,) - signal array that matches the time array - old_w : np.ndarray, shape (nt,) - angular frequency array corresponding to the fourier space of the `time` array - new_w : np.ndarray, shape (nw,) - angural frequency grid of the spectrogram - gate_width : float, optional - full width at half maximum of the gaussian gate pulse + time : np.ndarray, shape (nt,) + time in the co-moving frame of reference + delays : np.ndarray, shape (nd,) + delays overs which to compute the spectrogram + signal : np.ndarray, shape (nt,) + signal array that matches the time array + old_w : np.ndarray, shape (nt,) + angular frequency array corresponding to the fourier space of the `time` array + new_w : np.ndarray, shape (nw,) + angural frequency grid of the spectrogram + gate_width : float, optional + full width at half maximum of the gaussian gate pulse Returns ---------- @@ -656,9 +669,11 @@ def g12(values): Parameters ---------- - values : 2D array - complex values following sc-ordering - return: + values : 2D array + complex values following sc-ordering + + Returns + ------- g12_arr : coherence function as a n-D array """ @@ -677,11 +692,11 @@ def g12(values): def avg_g12(values): """ - comptutes the average of the coherence function weighted by amplitude of spectrum + computes the average of the coherence function weighted by amplitude of spectrum Parameters ---------- - values : (m, n)-D array containing m complex values + values : np.ndarray, shape (nd, nt) Returns ---------- @@ -697,17 +712,20 @@ def avg_g12(values): def fwhm_ind(values, mam=None): - """returns the indices where values is bigger than half its maximum + """ + returns the indices where values is bigger than half its maximum + Parameters ---------- - values : array - real values with ideally only one smooth peak - mam : tupple (float, int) - (maximum value, index of the maximum value) + values : array + real values with ideally only one smooth peak + mam : tupple (float, int) + (maximum value, index of the maximum value) + Returns - ---------- - left_ind, right_ind : int - indices of the the left and right spots where values drops below 1/2 the maximum + ------- + left_ind, right_ind : int + indices of the the left and right spots where values drops below 1/2 the maximum """ if mam is None: @@ -722,18 +740,20 @@ def fwhm_ind(values, mam=None): def peak_ind(values, mam=None): - """returns the indices that encapsulate the entire peak + """ + returns the indices that encapsulate the entire peak Parameters ---------- - values : array - real values with ideally only one smooth peak - mam : tupple (float, int) - (maximum value, index of the maximum value) + values : array + real values with ideally only one smooth peak + mam : tupple (float, int) + (maximum value, index of the maximum value) + Returns - ---------- - left_ind, right_ind : int - indices of the the left and right spots where values starts rising again, - with a margin of 3 + ------- + left_ind, right_ind : int + indices of the the left and right spots where values starts rising again, + with a margin of 3 """ if mam is None: @@ -761,33 +781,36 @@ def peak_ind(values, mam=None): def setup_splines(x_axis, values, mam=None): - """sets up spline interpolation to better measure a peak. Different splines with different + """ + sets up spline interpolation to better measure a peak. Different splines with different orders are necessary because derivatives and second derivatives are computed to find extremea and inflection points + Parameters ---------- - x_axis : 1D array - domain of values - values : 1D array - real values that ideally contain only one smooth peak to measure - mam : tupple (float, int) - (maximum value, index of the maximum value) + x_axis : 1D array + domain of values + values : 1D array + real values that ideally contain only one smooth peak to measure + mam : tupple (float, int) + (maximum value, index of the maximum value) + Returns - ---------- - small_spline : scipy.interpolate.UnivariateSpline - order 3 spline that interpolates `values - m/2` around the peak - spline_4 : scipy.interpolate.UnivariateSpline - order 4 spline that interpolate values around the peak - spline 5 : scipy.interpolate.UnivariateSpline - order 5 spline that interpolates values around the peak - d_spline : scipy.interpolate.UnivariateSpline - order 3 spline that interpolates the derivative of values around the peak - d_roots : list - roots of d_spline - dd_roots : list - inflection points of spline_5 - l_ind, r_ind : int - return values of peak_ind + ------- + small_spline : scipy.interpolate.UnivariateSpline + order 3 spline that interpolates `values - m/2` around the peak + spline_4 : scipy.interpolate.UnivariateSpline + order 4 spline that interpolate values around the peak + spline 5 : scipy.interpolate.UnivariateSpline + order 5 spline that interpolates values around the peak + d_spline : scipy.interpolate.UnivariateSpline + order 3 spline that interpolates the derivative of values around the peak + d_roots : list + roots of d_spline + dd_roots : list + inflection points of spline_5 + l_ind, r_ind : int + return values of peak_ind """ # Isolate part thats roughly above max/2 @@ -814,31 +837,32 @@ def setup_splines(x_axis, values, mam=None): def find_lobe_limits(x_axis, values, debug="", already_sorted=True): - """find the limits of the centra lobe given 2 derivatives of the values and + """ + find the limits of the centra lobe given 2 derivatives of the values and the position of the FWHM Parameters ---------- - x_axis : 1D array - domain of values - values : 1D array - real values that present a peak whose properties we want to meausure - debug : str - if the peak is not distinct, a plot is made to assess the measurement - providing a debug label can help identify which plot correspond to which function call - sorted : bool - faster computation if arrays are already sorted + x_axis : 1D array + domain of values + values : 1D array + real values that present a peak whose properties we want to meausure + debug : str + if the peak is not distinct, a plot is made to assess the measurement + providing a debug label can help identify which plot correspond to which function call + sorted : bool + faster computation if arrays are already sorted Returns - ---------- - peak_lim : 1D array (left_lim, right_lim, peak_pos) - values that delimit the left, right and maximum of the peak in units of x_axis - fwhm_pos : 1D array (left_pos, right_pos) - values corresponding to fwhm positions in units of x_axis - good_roots : 1D array - all candidate values that could delimit the peak position - spline_4 : scipy.interpolate.UnivariateSpline - order 4 spline that interpolate values around the peak + ------- + peak_lim : 1D array (left_lim, right_lim, peak_pos) + values that delimit the left, right and maximum of the peak in units of x_axis + fwhm_pos : 1D array (left_pos, right_pos) + values corresponding to fwhm positions in units of x_axis + good_roots : 1D array + all candidate values that could delimit the peak position + spline_4 : scipy.interpolate.UnivariateSpline + order 4 spline that interpolate values around the peak """ if not already_sorted: @@ -910,7 +934,8 @@ def find_lobe_limits(x_axis, values, debug="", already_sorted=True): def _select_roots(d_spline, d_roots, dd_roots, fwhm_pos): - """selects the limits of a lobe + """ + selects the limits of a lobe Parameters ---------- @@ -1036,7 +1061,8 @@ def _detailed_find_lobe_limits( def measure_properties(spectra, t, compress=True, return_limits=False, debug="") -> PulseProperties: - """measure the quality factor, the fwhm variation, the peak power variation, + """ + measure the quality factor, the fwhm variation, the peak power variation, Parameters ---------- @@ -1052,7 +1078,7 @@ def measure_properties(spectra, t, compress=True, return_limits=False, debug="") return the time values of the limits Returns - ---------- + ------- PulseProperties object: quality : float quality factor of the pulse ensemble @@ -1123,7 +1149,8 @@ def measure_properties(spectra, t, compress=True, return_limits=False, debug="") def rin_curve(spectra: np.ndarray) -> np.ndarray: - """computes the rin curve, i.e. the rin at every single point + """ + computes the rin curve, i.e. the rin at every single point Parameters ---------- @@ -1159,7 +1186,8 @@ def measure_field(t: np.ndarray, field: np.ndarray) -> Tuple[float, float, float def remove_2nd_order_dispersion( spectrum: T, w_c: np.ndarray, beta2: float, max_z: float = -100.0 ) -> tuple[T, OptimizeResult]: - """attempts to remove 2nd order dispersion from a complex spectrum + """ + attempts to remove 2nd order dispersion from a complex spectrum Parameters ---------- @@ -1189,7 +1217,8 @@ def remove_2nd_order_dispersion( def remove_2nd_order_dispersion2( spectrum: T, w_c: np.ndarray, max_gdd: float = 1000e-30 ) -> tuple[T, OptimizeResult]: - """attempts to remove 2nd order dispersion from a complex spectrum + """ + attempts to remove 2nd order dispersion from a complex spectrum Parameters ---------- diff --git a/src/scgenerator/physics/units.py b/src/scgenerator/physics/units.py index a52da7b..7a13bb8 100644 --- a/src/scgenerator/physics/units.py +++ b/src/scgenerator/physics/units.py @@ -341,7 +341,8 @@ def beta2_coef(beta2_coefficients): def to_WL(spectrum: np.ndarray, lambda_: np.ndarray) -> np.ndarray: - """rescales the spectrum because of uneven binning when going from freq to wl + """ + rescales the spectrum because of uneven binning when going from freq to wl Parameters ---------- @@ -360,12 +361,15 @@ def to_WL(spectrum: np.ndarray, lambda_: np.ndarray) -> np.ndarray: def to_log(arr, ref=None): - """takes the log of each 1D array relative to the max of said array. Useful + """ + takes the log of each 1D array relative to the max of said array. Useful to plot spectrum evolution, but use to_log2D for spectrograms + Parameters ---------- arr : 1D array of real numbers. >1D array : operation is applied on axis=0 ref : reference value corresponding to 0dB (default : max(arr)) + Returns ---------- arr array in dB @@ -381,11 +385,14 @@ def to_log(arr, ref=None): def to_log2D(arr, ref=None): - """computes the log of a 2D array + """ + computes the log of a 2D array + Parameters ---------- arr : 2D array of real numbers ref : reference value corresponding to 0dB + Returns ---------- arr array in dB @@ -431,8 +438,9 @@ def sort_axis( Parameters ---------- - axis : 1D array containing the original axis (usual the w or t array) - plt_range : tupple (min, max, conversion_function) used to crop the axis + axis : 1D array + containing the original axis (usual the w or t array) + plt_range : tupple (min, max, conversion_function) used to crop the axis Returns ------- diff --git a/src/scgenerator/plotting.py b/src/scgenerator/plotting.py index 01f4447..be800c1 100644 --- a/src/scgenerator/plotting.py +++ b/src/scgenerator/plotting.py @@ -278,7 +278,8 @@ def propagation_plot( cbar_label: Optional[str] = "normalized intensity (dB)", cmap: str = None, ) -> tuple[Figure, Axes, plt.Line2D, np.ndarray, np.ndarray]: - """transforms and plots a 2D propagation + """ + transforms and plots a 2D propagation Parameters ---------- @@ -343,7 +344,8 @@ def plot_2D( cmap: str = None, cbar_label: str = "", ) -> Union[tuple[Axes, Axes], Axes]: - """plots given 2D values in a standard + """ + plots given 2D values in a standard Parameters ---------- @@ -436,7 +438,8 @@ def transform_2D_propagation( skip: int = 1, params: Parameters = None, ) -> tuple[np.ndarray, np.ndarray, np.ndarray]: - """transforms raws values into plottable values + """ + transforms raws values into plottable values Parameters ---------- @@ -640,7 +643,8 @@ def plot_mean( mean_style: dict[str, Any] = None, individual_style: dict[str, Any] = None, ) -> tuple[plt.Line2D, list[plt.Line2D]]: - """plots already transformed 1D values + """ + plots already transformed 1D values Parameters ---------- @@ -737,7 +741,8 @@ def plot_1D( transpose: bool = False, **line_kwargs, ) -> plt.Line2D: - """plots already transformed 1D values + """ + plots already transformed 1D values Parameters ---------- @@ -788,7 +793,8 @@ def transform_1D_values( log: Union[int, float, bool] = False, spacing: Union[int, float] = 1, ) -> tuple[np.ndarray, np.ndarray]: - """transforms raw values to be plotted + """ + transforms raw values to be plotted Parameters ---------- @@ -852,7 +858,9 @@ def plot_spectrogram( cmap: str = None, ax: Union[Axes, tuple[Axes, Axes]] = None, ): - """Plots a spectrogram given a complex field in the time domain + """ + Plots a spectrogram given a complex field in the time domain + Parameters ---------- values : 2D array @@ -881,7 +889,6 @@ def plot_spectrogram( ax : matplotlib.axes._subplots.AxesSubplot object or tupple of 2 axis objects, optional axis on which to draw the plot if only one is given, a new one will be created to draw the colorbar - """ if values.ndim != 1: print("plot_spectrogram can only plot 1D arrays") @@ -951,7 +958,8 @@ def uniform_axis( values: np.ndarray, new_axis_spec: Union[PlotRange, RangeType, str], ) -> tuple[np.ndarray, np.ndarray]: - """given some values(axis), creates a new uniformly spaced axis and interpolates + """ + given some values(axis), creates a new uniformly spaced axis and interpolates the values over it. Parameters @@ -1001,7 +1009,8 @@ def uniform_axis( def apply_log(values: np.ndarray, log: Union[str, bool, float, int]) -> np.ndarray: - """apply log transform + """ + apply log transform Parameters ---------- @@ -1062,7 +1071,8 @@ def white_bottom_cmap(name, start=0, end=1, new_name="white_background", c_back= def default_marker_style(k): - """returns a style dictionary + """ + returns a style dictionary Parameters ---------- @@ -1100,7 +1110,8 @@ def measure_and_annotate_fwhm( arrow_length_pts: float = 20.0, arrow_props: dict[str, Any] = None, ) -> float: - """measured the FWHM of a pulse and plots it + """ + measured the FWHM of a pulse and plots it Parameters ---------- diff --git a/src/scgenerator/spectra.py b/src/scgenerator/spectra.py index 22bf054..acd9e51 100644 --- a/src/scgenerator/spectra.py +++ b/src/scgenerator/spectra.py @@ -138,7 +138,8 @@ class SimulationSeries: fiber_positions: list[tuple[str, float]] def __init__(self, path: os.PathLike): - """Create a SimulationSeries + """ + Create a SimulationSeries Parameters ---------- @@ -249,7 +250,8 @@ class SimulationSeries: sim_ind: int = 0, **kwargs, ) -> tuple[np.ndarray, np.ndarray]: - """gives the desired values already tranformes according to the give range + """ + gives the desired values already tranformes according to the give range Parameters ---------- @@ -299,7 +301,8 @@ class SimulationSeries: def rin_propagation( self, left: float, right: float, unit: str ) -> tuple[np.ndarray, np.ndarray, np.ndarray]: - """returns the RIN as function of unit and z + """ + returns the RIN as function of unit and z Parameters ---------- @@ -387,7 +390,8 @@ class SimulatedFiber: raise ValueError(f"cannot match z={pos} with max length of {self.params.length}") def _load_1(self, z_ind: int, sim_ind=0) -> np.ndarray: - """loads a spectrum file + """ + loads a spectrum file Parameters ---------- diff --git a/src/scgenerator/utils.py b/src/scgenerator/utils.py index 860684f..44490c9 100644 --- a/src/scgenerator/utils.py +++ b/src/scgenerator/utils.py @@ -8,6 +8,7 @@ from __future__ import annotations import datetime import inspect import itertools +import json import os import re from collections import defaultdict @@ -71,9 +72,11 @@ def open_single_config(path: os.PathLike) -> dict[str, Any]: def _open_config(path: os.PathLike): - """returns a dictionary parsed from the specified toml file + """ + returns a dictionary parsed from the specified toml file This also handle having a 'INCLUDE' argument that will fill - otherwise unspecified keys with what's in the INCLUDE file(s)""" + otherwise unspecified keys with what's in the INCLUDE file(s) + """ path = conform_toml_path(path) dico = resolve_loadfile_arg(load_toml(path)) @@ -150,20 +153,24 @@ def save_toml(path: os.PathLike, dico): @cache def load_material_dico(name: str) -> dict[str, Any]: - """loads a material dictionary + """ + loads a material dictionary + Parameters ---------- - name : str - name of the material + name : str + name of the material + Returns - ---------- - material_dico : dict + ------- + material_dico : dict """ return json.loads(io.data_file("materials.json").read_text())[name] def save_data(data: Union[np.ndarray, MutableMapping], data_dir: Path, file_name: str): - """saves numpy array to disk + """ + saves numpy array to disk Parameters ---------- @@ -186,7 +193,8 @@ def save_data(data: Union[np.ndarray, MutableMapping], data_dir: Path, file_name def ensure_folder(path: Path, prevent_overwrite: bool = True, mkdir=True) -> Path: - """ensure a folder exists and doesn't overwrite anything if required + """ + ensure a folder exists and doesn't overwrite anything if required Parameters ---------- @@ -276,7 +284,8 @@ def to_62(i: int) -> str: def get_arg_names(func: Callable) -> list[str]: - """returns the positional argument names of func. + """ + returns the positional argument names of func. Parameters ---------- @@ -338,7 +347,8 @@ def fft_functions( def combine_simulations(path: Path, dest: Path = None): - """combines raw simulations into one folder per branch + """ + combines raw simulations into one folder per branch Parameters ---------- @@ -393,7 +403,8 @@ def update_params(new_path: Path, file: Path): def save_parameters( params: dict[str, Any], destination_dir: Path, file_name: str = PARAM_FN ) -> Path: - """saves a parameter dictionary. Note that is does remove some entries, particularly + """ + saves a parameter dictionary. Note that is does remove some entries, particularly those that take a lot of space ("t", "w", ...) Parameters @@ -427,7 +438,8 @@ def fiber_folder(i: int, sim_name: str, fiber_name: str) -> str: def simulations_list(path: os.PathLike) -> list[Path]: - """finds simulations folders contained in a parent directory + """ + finds simulations folders contained in a parent directory Parameters ----------