iddefix package
Submodules
iddefix.framework module
Created on Mon Mar 23 13:20:11 2020
@author: sjoly @modified by: MaltheRaschke, edelafue
- class iddefix.framework.EvolutionaryAlgorithm(x_data: Union[_Buffer, _SupportsArray[dtype[Any]], _NestedSequence[_SupportsArray[dtype[Any]]], complex, bytes, str, _NestedSequence[complex | bytes | str]], y_data: Union[_Buffer, _SupportsArray[dtype[Any]], _NestedSequence[_SupportsArray[dtype[Any]]], complex, bytes, str, _NestedSequence[complex | bytes | str]], N_resonators: int, parameterBounds: list[tuple[float, float]], plane: str = 'longitudinal', fitFunction: str = 'impedance', objectiveFunction: Optional[Union[Callable[[...], float], str]] = None, wake_length: float | None = None, sigma: float | None = None, uncertainty_warning: float = 0.2)[source]
Bases:
object- check_y_data() None[source]
Small function to avoid 0 frequency leading to zero division when using resonators.
- display_resonator_parameters(params: Optional[Union[_Buffer, _SupportsArray[dtype[Any]], _NestedSequence[_SupportsArray[dtype[Any]]], complex, bytes, str, _NestedSequence[complex | bytes | str]]] = None, to_markdown: bool = False, uncertainties: Optional[Union[_Buffer, _SupportsArray[dtype[Any]], _NestedSequence[_SupportsArray[dtype[Any]]], complex, bytes, str, _NestedSequence[complex | bytes | str]]] = None, display_uncertainties: bool = True) None[source]
Displays resonance parameters in a formatted table using ASCII characters.
- Parameters
solution – A NumPy array of resonator parameters, typically shaped
(n_resonators –
3). –
- generate_Initial_Parameters(parameterBounds: list[tuple[float, float]], objectiveFunction: Callable[[...], float], fitFunction: Callable[[...], ndarray], x_values_data: Union[_Buffer, _SupportsArray[dtype[Any]], _NestedSequence[_SupportsArray[dtype[Any]]], complex, bytes, str, _NestedSequence[complex | bytes | str]], y_values_data: Union[_Buffer, _SupportsArray[dtype[Any]], _NestedSequence[_SupportsArray[dtype[Any]]], complex, bytes, str, _NestedSequence[complex | bytes | str]], maxiter: int = 2000, popsize: int = 150, mutation: tuple[float, float] = (0.1, 0.5), crossover_rate: float = 0.8, tol: float = 0.01, solver: str = 'scipy') tuple[numpy.ndarray, str][source]
Generates initial parameter estimates using a Differential Evolution (DE) solver.
This function applies a DE optimization method to identify suitable initial parameters for resonance fitting. These parameters can be further refined using local minimization.
- Parameters
parameterBounds (list of tuple) – A list of (min, max) bounds for each parameter.
objectiveFunction (callable) – The objective function to minimize. It should accept parameters, a fitting function, x-data, and y-data.
fitFunction (callable) – The fitting function that models the impedance response.
x_values_data (numpy.ndarray) – Array containing x-values of the data (frequency points).
y_values_data (numpy.ndarray) – Array containing y-values of the data (impedance magnitudes).
maxiter (int, optional) – Maximum number of iterations for the DE solver. Default is 2000.
popsize (int, optional) – Population size for the DE algorithm. Default is 150.
mutation (tuple of float, optional) – Range of mutation factors that control parameter variation. Default is (0.1, 0.5).
crossover_rate (float, optional) – Probability of recombining individuals in the DE algorithm. Default is 0.8.
tol (float, optional) – Convergence tolerance for stopping criteria. Default is 0.01.
solver (str, optional) – The solver to use for differential evolution. Available options: - “scipy”: Uses SciPy’s built-in DE solver. - “pyfde”: Uses pyfde, an alternative DE implementation. - “pyfde_jade”: Uses JADE, a self-adaptive DE variant (automatically adjusts mutation and crossover_rate). Default is “scipy”.
- Returns
- solutionnumpy.ndarray
Optimized parameter estimates found by the DE solver.
- messagestr
Solver status message.
- Return type
tuple
Notes
Calls the appropriate solver function based on the solver argument.
If solver=’pyfde_jade’, mutation and crossover rates are automatically adjusted.
The result can be used as an initial guess for further optimization.
- get_extrapolated_wake(new_end_time: float | None = None, dt: float | None = None, time_data: Optional[Union[_Buffer, _SupportsArray[dtype[Any]], _NestedSequence[_SupportsArray[dtype[Any]]], complex, bytes, str, _NestedSequence[complex | bytes | str]]] = None, use_minimization: bool = True) tuple[numpy.ndarray, numpy.ndarray][source]
- get_impedance(frequency_data: Optional[Union[_Buffer, _SupportsArray[dtype[Any]], _NestedSequence[_SupportsArray[dtype[Any]]], complex, bytes, str, _NestedSequence[complex | bytes | str]]] = None, use_minimization: bool = True, wakelength: float | None = None) ndarray[source]
- get_impedance_from_fft(time_data: Optional[Union[_Buffer, _SupportsArray[dtype[Any]], _NestedSequence[_SupportsArray[dtype[Any]]], complex, bytes, str, _NestedSequence[complex | bytes | str]]] = None, wake_data: Optional[Union[_Buffer, _SupportsArray[dtype[Any]], _NestedSequence[_SupportsArray[dtype[Any]]], complex, bytes, str, _NestedSequence[complex | bytes | str]]] = None, fmax: float = 3e9, samples: int = 1001) tuple[numpy.ndarray, numpy.ndarray][source]
- get_impedance_from_fitFunction(frequency_data: Optional[Union[_Buffer, _SupportsArray[dtype[Any]], _NestedSequence[_SupportsArray[dtype[Any]]], complex, bytes, str, _NestedSequence[complex | bytes | str]]] = None, use_minimization: bool = True) ndarray[source]
- get_wake(time_data: Optional[Union[_Buffer, _SupportsArray[dtype[Any]], _NestedSequence[_SupportsArray[dtype[Any]]], complex, bytes, str, _NestedSequence[complex | bytes | str]]] = None, use_minimization: bool = True) ndarray[source]
- get_wake_potential(time_data: Optional[Union[_Buffer, _SupportsArray[dtype[Any]], _NestedSequence[_SupportsArray[dtype[Any]]], complex, bytes, str, _NestedSequence[complex | bytes | str]]] = None, sigma: float | None = None, use_minimization: bool = True) ndarray[source]
- read_txt(txt: str, skiprows: int = 2, delimiter: str | None = None, usecols: Optional[Sequence[int]] = None, as_dict: bool = False) dict[Any, numpy.ndarray] | tuple[numpy.ndarray, numpy.ndarray][source]
Reads data from an ASCII text file and returns it as a dictionary or tuple.
This function reads a structured text file containing numerical data, where the first line is expected to contain column headers. It attempts to parse the headers and assign them as dictionary keys. If headers are not properly formatted, integer indices are used instead.
- Parameters
txt (str) – Path to the text file to read.
skiprows (int, optional) – Number of initial rows to skip before reading the data. Default is 2.
delimiter (str, optional) – Character used to separate values in the file. If None, whitespace is used.
usecols (list of int, optional) – Indices of columns to read from the file. If None, all columns are read.
as_dict (bool, optional) – If True, returns a dictionary where keys are the column headers (if available) or integers (if headers are missing). If False, returns x_data and `y_data`as separate arrays. Default is False.
- Returns
If as_dict=True, returns a dictionary {header: column_data}.
If as_dict=False, returns (x_data, y_data), where:
x_data is the first column of data.
y_data is the second column of data.
- Return type
dict or tuple
Notes
If an error occurs while reading the file, the function attempts to reload
the data assuming complex numbers (dtype=complex). - If column headers are missing or unreadable, integer indices [0, 1, …] are assigned as dictionary keys. - The first line of the file is expected to contain column headers.
Examples
Read a file and return as a dictionary:
>>> data = read_txt("data.txt", as_dict=True) >>> print(data.keys()) # Example output: {'Time[s]': array([...]), 'Amplitude': array([...])}
Read a file and return x and y data separately:
>>> x, y = read_txt("data.txt") >>> print(x.shape, y.shape)
Example of an expected file format:
` # Time[s] Amplitude ------------------------ 0.00 0.00 2.50 0.59 5.00 -0.99 `
- run_cmaes(maxiter: int = 1000, popsize: int = 50, sigma: float = 0.6, verbose: bool = False, **kwargs: Any) Any[source]
Runs the CMA-ES (Covariance Matrix Adaptation Evolution Strategy) algorithm from pymoo to optimize resonance parameters.
This function applies the CMA-ES global optimization method to minimize the objective function based on the given impedance data and parameter bounds. The resulting optimized parameters are stored for further analysis or refinement.
- Parameters
maxiter (int, optional) – Maximum number of iterations for the CMA-ES solver. Default is 1000.
popsize (int, optional) – Population size for the CMA-ES algorithm. Default is 50.
sigma (float, optional) – Initial standard deviation for the sampling distribution. Default is 0.1.
**kwargs (dict, optional) – Additional arguments passed to the pymoo.CMAES solver.
- Returns
res – The optimization result object containing the solution and metadata.
- Return type
pymoo.optimize.Result
Notes
Uses Solvers.run_pymoo_cmaes_solver() to execute the optimization.
The optimized parameters are stored in self.evolutionParameters.
Calls self.display_resonator_parameters() to present the results.
- run_differential_evolution(maxiter: int = 2000, popsize: int = 15, mutation: tuple[float, float] = (0.1, 0.5), crossover_rate: float = 0.8, tol: float = 0.01, solver: str = 'scipy') None[source]
Runs the differential evolution (DE) algorithm to estimate optimal resonance parameters.
This function applies a global optimization technique using a DE solver to determine the best-fitting parameters for the given impedance data. The results can later be refined using a local minimization algorithm.
- Parameters
maxiter (int, optional) – Maximum number of iterations for the DE solver. Default is 2000.
popsize (int, optional) – Population size for the DE algorithm. Default is 15.
mutation (tuple of float, optional) – Range of mutation factors controlling parameter variation. Default is (0.1, 0.5).
crossover_rate (float, optional) – Probability of recombining individuals in the DE algorithm. Default is 0.8.
tol (float, optional) – Convergence tolerance for stopping criteria. Default is 0.01.
solver (str, optional) – Specifies the DE solver to use. Valid options are: - “scipy”: Uses SciPy’s built-in DE solver. - “pyfde”: Uses pyfde, an alternative DE implementation. - “pyfde_jade”: Uses JADE, a self-adaptive DE variant. Default is “scipy”.
Notes
Uses generate_Initial_Parameters() to perform the differential evolution process.
The optimized parameters are stored in self.evolutionParameters.
Calls self.display_resonator_parameters() to present the estimated parameters.
- Returns
The optimized parameters are stored in self.evolutionParameters.
- Return type
None
- run_minimization_algorithm(margin: Union[float, Sequence[float]] = [0.1, 0.1, 0.1], method: str = 'Nelder-Mead') None[source]
Runs a minimization algorithm to refine resonance parameters.
This function refines the parameters obtained from the Differential Evolution (DE) algorithm by using a local optimization method. If the DE algorithm has not been run, it directly minimizes the objective function using initial parameter bounds.
Each parameter is allowed to vary within a specified margin, where: - Rs values use margin[0] - Q values use margin[1] - fres values use margin[2]
- Parameters
margin (float or list of float, optional) – A list of three values specifying the relative margins for Rs, Q, and fres. Each parameter is allowed to vary by ±(margin * value). Default is [0.1, 0.1, 0.1].
method (str, optional) – Optimization method for scipy.optimize.minimize. Default is ‘Nelder-Mead’.
Notes
The optimization is constrained within minimizationBounds, which
are computed using margin and the current evolutionParameters. - If the DE algorithm has not been run, the function initializes parameters using self.parameterBounds and minimizes the objective function. - The minimization results are stored in self.minimizationParameters. - Calls self.display_resonator_parameters() to display the refined parameters.
- Returns
The refined parameters are stored in self.minimizationParameters.
- Return type
None
- save_txt(f_name: str, x_data: Optional[Union[_Buffer, _SupportsArray[dtype[Any]], _NestedSequence[_SupportsArray[dtype[Any]]], complex, bytes, str, _NestedSequence[complex | bytes | str]]] = None, y_data: Optional[Union[_Buffer, _SupportsArray[dtype[Any]], _NestedSequence[_SupportsArray[dtype[Any]]], complex, bytes, str, _NestedSequence[complex | bytes | str]]] = None, x_name: str = 'X [-]', y_name: str = 'Y [-]') None[source]
Saves x and y data to a text file in a two-column format.
This function exports the provided x_data and y_data to a .txt file, formatting the output with a header that includes custom column names.
- Parameters
f_name (str) – Name of the output file (with or without the .txt extension).
x_data (numpy.ndarray, optional) – Array containing x-axis data. If None, the file is not saved.
y_data (numpy.ndarray, optional) – Array containing y-axis data. If None, the file is not saved.
x_name (str, optional) – Label for the x-axis column in the output file. Default is “X [-]”.
y_name (str, optional) – Label for the y-axis column in the output file. Default is “Y [-]”.
Notes
The data is saved in a two-column format where x_data and y_data
are combined column-wise. - If x_data or y_data is missing, the function prints a warning and does not save a file.
Examples
Save two NumPy arrays to data.txt:
>>> x = np.linspace(0, 10, 5) >>> y = np.sin(x) >>> save_txt("data", x, y, x_name="Time [s]", y_name="Amplitude [a.u.]")
The saved file will look like:
0.00 0.00 2.50 0.59 5.00 -0.99 7.50 0.94 10.00 -0.54
iddefix.objectiveFunctions module
Created on Sat Dec 5 16:34:10 2020 Modified Tue 23 Sep @edelafue
@author: sjoly
- class iddefix.objectiveFunctions.ObjectiveFunctions[source]
Bases:
object- logsumOfSquaredError(fitFunction: Callable[[Union[_Buffer, _SupportsArray[dtype[Any]], _NestedSequence[_SupportsArray[dtype[Any]]], complex, bytes, str, _NestedSequence[complex | bytes | str]], dict[int, Union[numpy._typing._array_like._Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], complex, bytes, str, numpy._typing._nested_sequence._NestedSequence[complex | bytes | str]]]], Union[_Buffer, _SupportsArray[dtype[Any]], _NestedSequence[_SupportsArray[dtype[Any]]], complex, bytes, str, _NestedSequence[complex | bytes | str]]], x: Union[_Buffer, _SupportsArray[dtype[Any]], _NestedSequence[_SupportsArray[dtype[Any]]], complex, bytes, str, _NestedSequence[complex | bytes | str]], y: Union[_Buffer, _SupportsArray[dtype[Any]], _NestedSequence[_SupportsArray[dtype[Any]]], complex, bytes, str, _NestedSequence[complex | bytes | str]]) float[source]
Calculates the sum of log squared errors for a fit function.
This function computes the log squared errors between the predicted values from a fit function and the actual data points. It works with both real and imaginary components of the data.
- Parameters
parameters – Array of parameters used by the fit_function.
fitFunction – Function that takes parameters and x values as input and returns predicted y values (including real and imaginary parts).
x – Array of x values for the data.
y – Array of y values for the data (including real and imaginary parts).
- Returns
The sum of log squared errors.
- logsumOfSquaredErrorAbs(fitFunction: Callable[[Union[_Buffer, _SupportsArray[dtype[Any]], _NestedSequence[_SupportsArray[dtype[Any]]], complex, bytes, str, _NestedSequence[complex | bytes | str]], dict[int, Union[numpy._typing._array_like._Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], complex, bytes, str, numpy._typing._nested_sequence._NestedSequence[complex | bytes | str]]]], Union[_Buffer, _SupportsArray[dtype[Any]], _NestedSequence[_SupportsArray[dtype[Any]]], complex, bytes, str, _NestedSequence[complex | bytes | str]]], x: Union[_Buffer, _SupportsArray[dtype[Any]], _NestedSequence[_SupportsArray[dtype[Any]]], complex, bytes, str, _NestedSequence[complex | bytes | str]], y: Union[_Buffer, _SupportsArray[dtype[Any]], _NestedSequence[_SupportsArray[dtype[Any]]], complex, bytes, str, _NestedSequence[complex | bytes | str]], eps: float = 1e-12) float[source]
Calculates the magnitude-based sum of log squared errors.
This function computes the log of squared errors between the magnitudes of the predicted values from a fit function and the magnitudes of the actual data points. A small epsilon is added inside the log to avoid issues with
log(0).- Parameters
parameters – Array of parameters used by the fitFunction.
fitFunction – Function that takes parameters and x values as input and returns predicted y values.
x – Array of x values for the data.
y – Array of y values for the data.
eps – Small positive constant to prevent log(0).
- Returns
The magnitude-based sum of log squared errors.
- logsumOfSquaredErrorReal(fitFunction: Callable[[Union[_Buffer, _SupportsArray[dtype[Any]], _NestedSequence[_SupportsArray[dtype[Any]]], complex, bytes, str, _NestedSequence[complex | bytes | str]], dict[int, Union[numpy._typing._array_like._Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], complex, bytes, str, numpy._typing._nested_sequence._NestedSequence[complex | bytes | str]]]], Union[_Buffer, _SupportsArray[dtype[Any]], _NestedSequence[_SupportsArray[dtype[Any]]], complex, bytes, str, _NestedSequence[complex | bytes | str]]], x: Union[_Buffer, _SupportsArray[dtype[Any]], _NestedSequence[_SupportsArray[dtype[Any]]], complex, bytes, str, _NestedSequence[complex | bytes | str]], y: Union[_Buffer, _SupportsArray[dtype[Any]], _NestedSequence[_SupportsArray[dtype[Any]]], complex, bytes, str, _NestedSequence[complex | bytes | str]]) float[source]
Calculates the real sum of log squared errors for a given fit function.
This function computes the real log squared errors between the predicted values from a fit function and the actual data points. It works only with the real component of the data.
- Parameters
parameters – Array of parameters used by the fit_function.
fitFunction – Function that takes parameters and x values as input and returns predicted y values (including only the real part).
x – Array of x values for the data.
y – Array of y values for the data (including only the real part).
- Returns
The real sum of log squared errors.
- sumOfSquaredError(fitFunction: Callable[[Union[_Buffer, _SupportsArray[dtype[Any]], _NestedSequence[_SupportsArray[dtype[Any]]], complex, bytes, str, _NestedSequence[complex | bytes | str]], dict[int, Union[numpy._typing._array_like._Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], complex, bytes, str, numpy._typing._nested_sequence._NestedSequence[complex | bytes | str]]]], Union[_Buffer, _SupportsArray[dtype[Any]], _NestedSequence[_SupportsArray[dtype[Any]]], complex, bytes, str, _NestedSequence[complex | bytes | str]]], x: Union[_Buffer, _SupportsArray[dtype[Any]], _NestedSequence[_SupportsArray[dtype[Any]]], complex, bytes, str, _NestedSequence[complex | bytes | str]], y: Union[_Buffer, _SupportsArray[dtype[Any]], _NestedSequence[_SupportsArray[dtype[Any]]], complex, bytes, str, _NestedSequence[complex | bytes | str]]) float[source]
Calculates the sum of squared errors (SSE) for a given fit function.
This function computes the SSE between the predicted values from a fit function and the actual data points. It works with both real and imaginary components of the data.
- Parameters
parameters – Array of parameters used by the fit_function.
fitFunction – Function that takes parameters and x values as input and returns predicted y values (including real and imaginary parts).
x – Array of x values for the data.
y – Array of y values for the data (including real and imaginary parts).
- Returns
The sum of squared errors (SSE).
- sumOfSquaredErrorAbs(fitFunction: Callable[[Union[_Buffer, _SupportsArray[dtype[Any]], _NestedSequence[_SupportsArray[dtype[Any]]], complex, bytes, str, _NestedSequence[complex | bytes | str]], dict[int, Union[numpy._typing._array_like._Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], complex, bytes, str, numpy._typing._nested_sequence._NestedSequence[complex | bytes | str]]]], Union[_Buffer, _SupportsArray[dtype[Any]], _NestedSequence[_SupportsArray[dtype[Any]]], complex, bytes, str, _NestedSequence[complex | bytes | str]]], x: Union[_Buffer, _SupportsArray[dtype[Any]], _NestedSequence[_SupportsArray[dtype[Any]]], complex, bytes, str, _NestedSequence[complex | bytes | str]], y: Union[_Buffer, _SupportsArray[dtype[Any]], _NestedSequence[_SupportsArray[dtype[Any]]], complex, bytes, str, _NestedSequence[complex | bytes | str]]) float[source]
Calculates the magnitude-based sum of squared errors (SSE).
This function computes the SSE between the magnitudes of the predicted values from a fit function and the magnitudes of the actual data points.
- Parameters
parameters – Array of parameters used by the fitFunction.
fitFunction – Function that takes parameters and x values as input and returns predicted y values.
x – Array of x values for the data.
y – Array of y values for the data.
- Returns
The magnitude-based sum of squared errors (SSE).
- sumOfSquaredErrorReal(fitFunction: Callable[[Union[_Buffer, _SupportsArray[dtype[Any]], _NestedSequence[_SupportsArray[dtype[Any]]], complex, bytes, str, _NestedSequence[complex | bytes | str]], dict[int, Union[numpy._typing._array_like._Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], complex, bytes, str, numpy._typing._nested_sequence._NestedSequence[complex | bytes | str]]]], Union[_Buffer, _SupportsArray[dtype[Any]], _NestedSequence[_SupportsArray[dtype[Any]]], complex, bytes, str, _NestedSequence[complex | bytes | str]]], x: Union[_Buffer, _SupportsArray[dtype[Any]], _NestedSequence[_SupportsArray[dtype[Any]]], complex, bytes, str, _NestedSequence[complex | bytes | str]], y: Union[_Buffer, _SupportsArray[dtype[Any]], _NestedSequence[_SupportsArray[dtype[Any]]], complex, bytes, str, _NestedSequence[complex | bytes | str]]) float[source]
Calculates the real sum of squared errors (SSE) for a given fit function.
This function computes the SSE between the predicted values from a fit function and the actual data points. It works only with the real component of the data.
- Parameters
parameters – Array of parameters used by the fit_function.
fitFunction – Function that takes parameters and x values as input and returns predicted y values (including only the real part).
x – Array of x values for the data.
y – Array of y values for the data (including only the real part).
- Returns
The real sum of squared errors (SSE).
iddefix.resonatorFormulas module
Created on Mon Mar 23 13:20:11 2020
@author: sjoly
- class iddefix.resonatorFormulas.Impedances[source]
Bases:
object- Resonator_longitudinal_imp(Rs: float, Q: float, resonant_frequency: float, wake_length: float | None = None) ndarray[source]
Calculates the longitudinal impedance of a resonator.
This function calculates the longitudinal impedance of a resonator with shunt impedance Rs, quality factor Q, and resonant frequency resonant_frequency at different frequencies frequencies.
- Parameters
frequencies (np.ndarray) – Array of frequencies values in Hz.
Rs (float) – Shunt impedance of the resonator in Ohm.
Q (float) – Quality factor of the resonator.
resonant_frequency (float) – Resonant frequency of the resonator in Hz.
wake_length (float, optional) – Additional parameter for the calculation
wake. (of the impedance of a partially decayed) – Defaults to None for the original (fully decayed wake) behavior.
- Returns
Array of longitudinal impedance values [Ohm] at the corresponding frequencies.
- Return type
np.ndarray
Notes
The fully decayed formula uses the generalized impedance formula (https://cds.cern.ch/record/192684/files/198812060.pdf) and can be used for any real positive value of Q.
The partially decayed formula uses the formula derived in (Joly, S. thesis not published yet!)
Moreover, it sets the impedance value to zero for zero frequencies in both cases.
- Units for this formula are:
Rs: Ohm/m Q: dimensionless resonant_frequency: Hz wake_length: m
Examples
>>> frequencies = np.linspace(0, 2.5e9, 1000) >>> Rs = 1e6 >>> Q = 0.6 >>> resonant_frequency = 1e9 >>> impedance = Resonator_longitudinal_imp(frequencies, Rs, Q, resonant_frequency) >>> plt.plot(frequencies, impedance) >>> plt.xlabel("Frequency [Hz]") >>> plt.ylabel("Longitudinal Impedance [Ohm]") >>> plt.show()
- Resonator_transverse_imp(Rs: float, Q: float, resonant_frequency: float, wake_length: float | None = None) ndarray[source]
Calculates the transverse impedance of a resonator.
This function calculates the transverse impedance of a resonator with shunt impedance Rs, quality factor Q, and resonant frequency resonant_frequency at different frequencies frequencies. The wake_length argument allows computing the impedance of a partially decayed wake over wake_length.
- Parameters
frequencies (np.ndarray) – Array of frequencies values in Hz.
Rs (float) – Shunt impedance of the resonator in Ohm/m.
Q (float) – Quality factor of the resonator.
resonant_frequency (float) – Resonant frequency of the resonator in Hz.
wake_length (float, optional) – Additional parameter for the calculation
wake. (of the impedance of a partially decayed) – Defaults to None for the original (fully decayed wake) behavior.
- Returns
Array of transverse impedance values [Ohm/m] at the corresponding frequencies.
- Return type
np.ndarray
Notes
The fully decayed formula uses the generalized impedance formula (https://cds.cern.ch/record/192684/files/198812060.pdf) and can be used for any real positive value of Q.
The partially decayed formula uses the formula derived in (Joly, S. thesis not published yet!)
Moreover, it sets the impedance value to zero for zero frequencies in both cases.
- Units for this formula are:
Rs: Ohm/m Q: dimensionless resonant_frequency: Hz wake_length: m
- n_Resonator_longitudinal_imp(pars: Union[dict[int, Sequence[float]], _Buffer, _SupportsArray[dtype[Any]], _NestedSequence[_SupportsArray[dtype[Any]]], complex, bytes, str, _NestedSequence[complex | bytes | str]], wake_length: float | None = None) ndarray[source]
Calculates the combined longitudinal impedance of multiple resonators.
This function calculates the total longitudinal impedance of a system consisting of multiple resonators at different frequencies frequencies. Each resonator is defined by its parameters provided in a dictionary dict_params.
- Parameters
frequencies (np.ndarray) – Array of frequencies values in Hz.
dict_params (dict or ndarray) –
Dictionary containing resonator parameters. Keys are unique identifiers for each resonator, and values are lists containing the parameters in the following order:
Rs (float): Shunt impedance of the resonator in Ohm.
Q (float): Quality factor of the resonator.
resonant_frequency (float): Resonant frequency of the resonator in Hz.
wake_length (float, optional) – Additional parameter for the calculation
wake. (of the impedance of a partially decayed) –
original (Defaults to None for the) –
- Returns
- Array of combined longitudinal impedance values [Ohm] at
the corresponding frequencies.
- Return type
np.ndarray
Examples
>>> frequencies = np.linspace(0, 2.5e9, 1000) >>> pars = { ... 1: [1e6, 1, 1e9], ... 2: [2e6, 1, 5e8], ... } >>> # Or, use directly the result from the DE solver >>> pars = DE_model.evolutionParameters >>> impedance = n_Resonator_longitudinal_imp(frequencies, pars) >>> plt.plot(frequencies, impedance) >>> plt.xlabel("Frequency [Hz]") >>> plt.ylabel("Longitudinal Impedance [Ohm]") >>> plt.show()
Notes
- This function assumes all resonators have the same type of longitudinal
impedance formula implemented in Resonator_longitudinal_imp.
- The combined impedance is calculated by summing the individual
impedance contributions from each resonator at each frequency.
Resonator parameters should be positive values (except for the shunt impedance).
Behavior for invalid values is not defined and may lead to errors.
- n_Resonator_transverse_imp(pars: Union[dict[int, Sequence[float]], _Buffer, _SupportsArray[dtype[Any]], _NestedSequence[_SupportsArray[dtype[Any]]], complex, bytes, str, _NestedSequence[complex | bytes | str]], wake_length: float | None = None) ndarray[source]
Calculates the combined transverse impedance of multiple resonators.
This function calculates the total transverse impedance of a system consisting of multiple resonators at different frequencies frequencies. Each resonator is defined by its parameters provided in a dictionary dict_params.
- Parameters
frequencies (np.ndarray) – Array of frequencies values in Hz.
dict_params (dict or ndaray) –
Dictionary containing resonator parameters. Keys are unique identifiers for each resonator, and values are lists containing the parameters in the following order:
Rs (float): Shunt impedance of the resonator in Ohm/m.
Q (float): Quality factor of the resonator.
resonant_frequency (float): Resonant frequency of the resonator in Hz.
wake_length (float, optional) – Additional parameter for the calculation
wake. (of the impedance of a partially decayed) –
original (Defaults to None for the) –
- Returns
- Array of combined transverse impedance values [Ohm/m] at
the corresponding frequencies.
- Return type
np.ndarray
Examples
>>> frequencies = np.linspace(0, 2.5e9, 1000) >>> pars = { ... 1: [1e6, 1, 1e9], ... 2: [2e6, 1, 5e8], ... } >>> # Or, use directly the result from the DE solver >>> pars = DE_model.evolutionParameters >>> impedance = n_Resonator_transverse_imp(frequencies, pars) >>> plt.plot(frequencies, impedance) >>> plt.xlabel("Frequency [Hz]") >>> plt.ylabel("Transverse Impedance [Ohm/m]") >>> plt.show()
Notes
- This function assumes all resonators have the same type of transverse
impedance formula implemented in Resonator_transverse_imp.
- The combined impedance is calculated by summing the individual
impedance contributions from each resonator at each frequency.
Resonator parameters should be positive values (except for the shunt impedance).
Behavior for invalid values is not defined and may lead to errors.
- class iddefix.resonatorFormulas.Wakes[source]
Bases:
object- Resonator_longitudinal_wake(Rs: float, Q: float, resonant_frequency: float) ndarray[source]
Calculates the longitudinal wake function of a resonator.
This function calculates the longitudinal wake function of a resonator with shunt impedance Rs, quality factor Q, and resonant frequency resonant_frequency at different times times.
- Parameters
times (np.ndarray) – Array of time values in seconds.
Rs (float) – Shunt impedance of the resonator in Ohm.
Q (float) – Quality factor of the resonator.
resonant_frequency (float) – Resonant frequency of the resonator in Hz.
- Returns
Array of longitudinal wake function values [V/C] at the corresponding times.
- Return type
np.ndarray
Notes
This formula uses the generalized wake function formula and can be used for any real positive value of Q. https://cds.cern.ch/record/192684/files/198812060.pdf
- Units for this formula are:
Rs: Ohm Q: dimensionless resonant_frequency: Hz
Examples
>>> times = np.linspace(0, 1e-9, 1000) >>> Rs = 1e6 >>> Q = 0.6 >>> resonant_frequency = 1e9 >>> wake_function = Resonator_longitudinal_wake(times, Rs, Q, resonant_frequency) >>> plt.plot(times, wake_function) >>> plt.xlabel("Time [s]") >>> plt.ylabel("Longitudinal Wake Function [V/C]") >>> plt.show()
- Resonator_longitudinal_wake_potential(Rs: float, Q: float, resonant_frequency: float, sigma: float = 1e-10, use_mpmath: bool = False) ndarray[source]
Single resonator wake potential (longitudinal) for a Gaussian bunch of line density.
- Parameters
Rs (float or list) – Shunt impedance (Ohm).
resonant_frequency (float or list) – Resonant frequency (Hz).
Q (float or list) – Quality factor.
sigma (float) – RMS bunch length (s)
times (array-like) – Times (s) where wake is computed (times > 0 behind the source).
use_mpmath (bool, optional) – Use mpmath for calculations. Defaults to False.
- Returns
Wake potential at times times.
- Return type
np.ndarray
Notes
The formula is from Chao’s Handbook (p. 237, sec 3.2), partly re-derived by N. Mounet. Equivalent formula in https://cds.cern.ch/record/192684/files/198812060.pdf Q must be different from 0.5! Rs, resonant_frequency, and Q must be scalar.
- Resonator_transverse_wake(Rs: float, Q: float, resonant_frequency: float) ndarray[source]
Calculates the longitudinal wake function of a resonator.
This function calculates the transverse wake function of a resonator with shunt impedance Rs, quality factor Q, and resonant frequency resonant_frequency at different times times.
- Parameters
times (np.ndarray) – Array of time values in seconds.
Rs (float) – Shunt impedance of the resonator in Ohm/m.
Q (float) – Quality factor of the resonator.
resonant_frequency (float) – Resonant frequency of the resonator in Hz.
- Returns
Array of longitudinal wake function values [V/C/m] at the corresponding times.
- Return type
np.ndarray
Notes
This formula uses the generalized wake function formula and can be used for any real positive value of Q. https://cds.cern.ch/record/192684/files/198812060.pdf
- Units for this formula are:
Rs: Ohm/m Q: dimensionless resonant_frequency: Hz
Examples
>>> times = np.linspace(0, 1e-9, 1000) >>> Rs = 1e6 >>> Q = 0.6 >>> resonant_frequency = 1e9 >>> wake_function = Resonator_transverse_wake(times, Rs, Q, resonant_frequency) >>> plt.plot(times, wake_function) >>> plt.xlabel("Time [s]") >>> plt.ylabel("Transverse Wake Function [V/C]") >>> plt.show()
- Resonator_transverse_wake_potential(Rs: float, Q: float, resonant_frequency: float, sigma: float = 1e-10, use_mpmath: bool = False) ndarray[source]
Single resonator wake potential (transverse) for a Gaussian bunch of line density.
- Parameters
Rs (float or list) – Shunt impedance (Ohm).
resonant_frequency (float or list) – Resonant frequency (Hz).
Q (float or list) – Quality factor.
sigma (float) – RMS bunch length (s)
times (array-like) – Times (s) where wake is computed (times > 0 behind the source).
use_mpmath (bool, optional) – Use mpmath for calculations. Defaults to False.
- Returns
Wake potential at times times.
- Return type
np.ndarray
Notes
The formula is from Chao’s Handbook (p. 237, sec 3.2), partly re-derived by N. Mounet. Equivalent formula in https://cds.cern.ch/record/192684/files/198812060.pdf Q must be different from 0.5! Rs, resonant_frequency, and Q must be scalar.
- n_Resonator_longitudinal_wake(pars: Union[dict[int, Sequence[float]], _Buffer, _SupportsArray[dtype[Any]], _NestedSequence[_SupportsArray[dtype[Any]]], complex, bytes, str, _NestedSequence[complex | bytes | str]]) ndarray[source]
Calculates the combined longitudinal wake function of multiple resonators.
This function calculates the total longitudinal wake function induced by a system consisting of multiple resonators at different times times. Each resonator is defined by its parameters provided in a dictionary dict_params.
- Parameters
times (np.ndarray) – Array of time values in seconds.
dict_params (dict or ndarray) – Dictionary containing resonator parameters.
dict (If) –
resonator (Keys are unique identifiers for each) –
are (and values) –
order (lists containing the parameters in the following) –
Rs (float): Shunt impedance of the resonator in Ohm.
Q (float): Quality factor of the resonator.
resonant_frequency (float): Resonant frequency of the resonator in Hz.
- Returns
- Array of combined transverse wake function values [V/C] at
the corresponding times.
- Return type
np.ndarray
Examples
>>> times = np.linspace(0, 1e-9, 1000) >>> pars = { ... 1: [1e6, 1, 1e9], ... 2: [2e6, 1, 5e8], ... } >>> # Or, use directly the result from the DE solver >>> pars = DE_model.evolutionParameters >>> wake_function = n_Resonator_longitudinal_wake(times, pars) >>> plt.plot(times, wake_function) >>> plt.xlabel("Time [s]") >>> plt.ylabel("Longitudinal Wake Function [V/C]") >>> plt.show()
Notes
- This function assumes all resonators have the same type of longitudinal
wake function formula implemented in Resonator_longitudinal_wake.
- The combined wake function is calculated by summing the individual
wake function contributions from each resonator at each time step.
Resonator parameters should be positive values (except for the shunt impedance).
Behavior for invalid values is not defined and may lead to errors.
- n_Resonator_longitudinal_wake_potential(pars: Union[dict[int, Sequence[float]], _Buffer, _SupportsArray[dtype[Any]], _NestedSequence[_SupportsArray[dtype[Any]]], complex, bytes, str, _NestedSequence[complex | bytes | str]], sigma: float = 1e-10) ndarray[source]
- n_Resonator_transverse_wake(pars: Union[dict[int, Sequence[float]], _Buffer, _SupportsArray[dtype[Any]], _NestedSequence[_SupportsArray[dtype[Any]]], complex, bytes, str, _NestedSequence[complex | bytes | str]]) ndarray[source]
Calculates the combined transverse wake function of multiple resonators.
This function calculates the total transverse wake function induced by a system consisting of multiple resonators at different times times. Each resonator is defined by its parameters provided in a dictionary dict_params.
- Parameters
times (np.ndarray) – Array of time values in seconds.
dict_params (dict or ndarray) –
Dictionary containing resonator parameters. Keys are unique identifiers for each resonator, and values are lists containing the parameters in the following order:
Rs (float): Shunt impedance of the resonator in Ohm/m.
Q (float): Quality factor of the resonator.
resonant_frequency (float): Resonant frequency of the resonator in Hz.
- Returns
- Array of combined transverse wake function values [V/C/m] at
the corresponding times.
- Return type
np.ndarray
Examples
>>> times = np.linspace(0, 1e-9, 1000) >>> pars = { ... 1: [1e6, 1, 1e9], ... 2: [2e6, 1, 5e8], ... } >>> # Or, use directly the result from the DE solver >>> pars = DE_model.evolutionParameters >>> wake_function = n_Resonator_transverse_wake(times, pars) >>> plt.plot(times, wake_function) >>> plt.xlabel("Time [s]") >>> plt.ylabel("Transverse Wake Function [V/C/m]") >>> plt.show()
Notes
- This function assumes all resonators have the same type of transverse
wake function formula implemented in Resonator_transverse_wake.
- The combined wake function is calculated by summing the individual
wake function contributions from each resonator at each time step.
Resonator parameters should be positive values (except for the shunt impedance).
Behavior for invalid values is not defined and may lead to errors.
iddefix.smartBoundDetermination module
Created on Sat Dec 5 16:34:10 2020
@author: MaltheRaschke
- class iddefix.smartBoundDetermination.SmartBoundDetermination(frequency_data: Union[_Buffer, _SupportsArray[dtype[Any]], _NestedSequence[_SupportsArray[dtype[Any]]], complex, bytes, str, _NestedSequence[complex | bytes | str]], impedance_data: Union[_Buffer, _SupportsArray[dtype[Any]], _NestedSequence[_SupportsArray[dtype[Any]]], complex, bytes, str, _NestedSequence[complex | bytes | str]], minimum_peak_height: float = 1.0, threshold: float | None = None, distance: float | None = None, prominence: float | None = None, Rs_bounds: list[float] = [0.8, 10], Q_bounds: list[float] = [0.5, 5], fres_bounds: list[float] = [- 0.01e9, + 0.01e9])[source]
Bases:
object- find(frequency_data: Optional[Union[_Buffer, _SupportsArray[dtype[Any]], _NestedSequence[_SupportsArray[dtype[Any]]], complex, bytes, str, _NestedSequence[complex | bytes | str]]] = None, impedance_data: Optional[Union[_Buffer, _SupportsArray[dtype[Any]], _NestedSequence[_SupportsArray[dtype[Any]]], complex, bytes, str, _NestedSequence[complex | bytes | str]]] = None, minimum_peak_height: float | None = None, threshold: float | None = None, distance: float | None = None, prominence: float | None = None) list[tuple[float, float]][source]
Identifies peaks in the impedance data and determines the bounds for fitting parameters based on the detected peaks.
This function uses scipy.signal.find_peaks to locate peaks in the impedance data and then calculates bounds for fitting parameters, including resistance (Rs), quality factor (Q), and resonant frequency.
- Parameters
frequency_data (numpy.ndarray, optional) – Array containing the frequency data in Hz. If None, the instance attribute self.frequency_data is used.
impedance_data (numpy.ndarray, optional) – Array containing the impedance data in Ohms. If None, the instance attribute self.impedance_data is used.
minimum_peak_height (float or numpy.ndarray or 2-item list, optional) – Minimum peak height for the peak-finding algorithm. * If numpy.ndarray, it should have the same length as impedance_data * If 2-item list, specifies the [min, max] of peak heights
threshold (float, optional) – Required vertical distance between a peak and its neighboring values to be considered a peak. Passed to scipy.signal.find_peaks. Default is None.
distance (float, optional) – Required minimum horizontal distance (in indices) between peaks. Passed to scipy.signal.find_peaks. Default is None.
prominence (float, optional) – Required prominence of peaks. The prominence measures how much a peak stands out compared to its surrounding values. Passed to scipy.signal.find_peaks. Default is None.
- Returns
parameterBounds – A list of parameter bounds for fitting. Each resonance contributes three sets of bounds: - (Rs_min, Rs_max): Bounds for resistance Rs. - (Q_min, Q_max): Bounds for quality factor Q. - (freq_min, freq_max): Bounds for the resonant frequency.
- Return type
list of tuples
Notes
The peak-finding algorithm is implemented using scipy.signal.find_peaks.
See the official documentation for more details: https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.find_peaks.html - The 3dB bandwidth method is used to estimate initial Q factors and define frequency bounds. - The detected peaks and their heights are stored in instance attributes self.peaks and self.peaks_height, respectively. - The number of detected resonances is stored in self.Nres.
- to_table(parameterBounds: list[tuple[float, float]] | None = None, to_markdown: bool = False) None[source]
Displays resonance parameters in a formatted ASCII table.
- Parameters
params – A list of tuples containing resonator parameters in the order: (Rs_min, Rs_max), (Q_min, Q_max), (fres_min, fres_max).
to_markdown – If True, prints the table in Markdown format.
1 | 31.12 to 311.12 | 88.20 to 180.47 | 4.16e+08 to 6.82e+08 2 | 85.61 to 864.12 | 120.55 to 200.23| 5.30e+08 to 7.23e+08 ————————————————————
iddefix.solvers module
Created on Sat Dec 5 16:33:41 2020
@author: sjoly @contributor: edelafue, babreufig
- class iddefix.solvers.ProgressBarCallback(max_generations: int, desc: str = 'Optimization')[source]
Bases:
object
- class iddefix.solvers.Solvers[source]
Bases:
object- run_pyfde_jade_solver(minimization_function: Callable[[ndarray], float], maxiter: int = 2000, popsize: int = 150, tol: float = 0.01, **kwargs) tuple[numpy.ndarray, str][source]
Runs the pyfde JADE solver to minimize a given function.
- Parameters
parameterBounds – A list of tuples representing the bounds for each parameter.
minimization_function – The function to be minimized.
maxiter – The maximum number of iterations to run the solver for.
popsize – The population size for the differential evolution algorithm.
tol – The tolerance for convergence.
- Returns
The solution found by the solver.
A message indicating the solver’s status.
- Return type
A tuple containing
- run_pyfde_solver(minimization_function: Callable[[ndarray], float], maxiter: int = 2000, popsize: int = 150, mutation: float = 0.45, crossover_rate: float = 0.8, tol: float = 0.01, **kwargs) tuple[numpy.ndarray, str][source]
Runs the pyfde ClassicDE solver to minimize a given function.
- Parameters
parameterBounds – A list of tuples representing the bounds for each parameter.
minimization_function – The function to be minimized.
maxiter – The maximum number of iterations to run the solver for.
popsize – The population size for the differential evolution algorithm.
mutation – A tuple of two floats representing the mutation factors.
crossover_rate – The crossover rate for the differential evolution algorithm.
tol – The tolerance for convergence.
- Returns
The solution found by the solver.
A message indicating the solver’s status.
- Return type
A tuple containing
- run_pymoo_cmaes_solver(minimization_function: Callable[[ndarray], float], sigma: float = 0.1, maxiter: int | None = None, popsize: int | None = None, verbose: bool = False, **kwargs) tuple[numpy.ndarray, str, Any][source]
Runs the pymoo CMAES solver to minimize a given function.
- Parameters
parameterBounds – A list of tuples representing the bounds for each parameter.
minimization_function – The function to be minimized.
sigma – The initial standard deviation for the CMA-ES algorithm.
maxiter – The maximum number of iterations to run the solver for.
popsize – The population size for the differential evolution algorithm.
tol – The tolerance for convergence.
- Returns
The solution found by the solver.
A message indicating the solver’s status.
- Return type
A tuple containing
- run_scipy_solver(minimization_function: Callable[[ndarray], float], maxiter: int = 2000, popsize: int = 150, mutation: tuple[float, float] = (0.1, 0.5), crossover_rate: float = 0.8, tol: float = 0.01, **kwargs) tuple[numpy.ndarray, str][source]
Run SciPy’s
differential_evolutionto minimize a function.All arguments are detailed in the SciPy documentation: https://docs.scipy.org/doc/scipy/reference/generated/ scipy.optimize.differential_evolution.html. Setting
workers=-1uses all available CPUs. Default parameters for the DE algorithm are taken from https://www.mdpi.com/2227-7390/9/4/427.- Parameters
parameterBounds – List of
(min, max)bounds for each parameter.minimization_function – Function to be minimized.
maxiter – Maximum number of iterations to run the solver.
popsize – Population size for the differential evolution algorithm.
mutation – Tuple of two floats representing mutation factors.
crossover_rate – Crossover rate for the differential evolution algorithm.
tol – Tolerance for convergence.
- Returns
Tuple
(solution, message)with the best solution and a status message.
- iddefix.solvers.stop_criterion(solver: Any) float[source]
Stopping criterion used in SciPy’s differential evolution.
Based on the criterion used in
scipy.optimize.differential_evolution: it checks the ratio of the spread of the population fitness compared to its average. If most individuals converge to the same solution, an optimal solution is considered found.