Analytical Solution for Electromagnetic Scattering by Cylinders.
This class implements analytical solutions for electromagnetic scattering
by dielectric and perfectly conducting cylinders using cylindrical wave
expansions. It provides exact solutions that can be used for validation
of numerical methods and benchmarking purposes.
Back-Propagation Algorithm for Electromagnetic Inverse Scattering.
This class implements the Back-Propagation algorithm, a non-iterative method
for solving electromagnetic inverse scattering problems. The algorithm
reconstructs the contrast function directly from scattered field measurements
using Green’s function relationships.
The method provides a fast approximation to the inverse problem by computing
the contrast in a single step, making it suitable for real-time applications
or as an initial guess for iterative methods.
Parameters:
forward (ForwardSolver, default: mom.MoM_CG_FFT()) – Forward solver object used to compute incident fields and Green’s functions.
alias (str, default: 'backprop') – Alias name for the algorithm instance.
Solve the inverse scattering problem using Back-Propagation.
This method implements the Back-Propagation algorithm to reconstruct
the contrast function from scattered field measurements. The algorithm
computes the solution in a single step using Green’s function relationships.
Parameters:
inputdata (InputData) – Input data object containing scattered field measurements and
configuration parameters.
discretization (Discretization) – Discretization object containing domain information and Green’s
function matrix.
Benchmark Class for Performance Evaluation of Inverse Scattering Algorithms.
This class provides a comprehensive framework for systematic performance
evaluation of electromagnetic inverse scattering algorithms. It extends
the Experiment class to handle multiple test sets and provides various
analysis and visualization tools.
The Benchmark class supports different parallelization strategies to
efficiently run large-scale performance evaluations and provides statistical
analysis capabilities for comparing algorithm performance.
Parameters:
name (str, default: '') – Name identifier for the benchmark instance.
method (InverseMethod or list of InverseMethod, optional) – Single method or list of methods to be benchmarked.
discretization (Discretization or list of Discretization, optional) – Single discretization or list of discretizations to be used.
testset (TestSet or list of TestSet, optional) – Single test set or list of test sets for evaluation.
Creates box plots showing the distribution of algorithm performance
across test instances. Useful for comparing algorithm variability
and identifying outliers.
Parameters:
indicator (str or list of str) – Performance indicator(s) to plot. Must be valid result indicators.
axis (matplotlib.axes.Axes or numpy.ndarray of Axes, optional) – Matplotlib axes to plot on. If None, new figure is created.
testset (int or str or list, optional) – Test set(s) to include in plot. Can be indices, names, or list.
method (int or str or list, optional) – Method(s) to include in plot. Can be indices, names, or list.
yscale ({'linear', 'log'}, optional) – Y-axis scale for the plot.
show (bool, default: False) – Whether to display the plot.
file_name (str, optional) – Name for saving the plot file (without extension).
file_path (str, default: '') – Path where to save the plot file.
file_format (str, default: 'eps') – File format for saving the plot.
title (str or bool or list of str, optional) – Title(s) for the plot(s). Can be string, boolean, or list.
fontsize (int, default: 10) – Font size for plot text.
color (str, default: 'b') – Color for the box plots.
Perform statistical comparison of algorithm performance.
Conducts statistical tests to compare the performance of different
algorithms, providing p-values and significance tests for determining
if performance differences are statistically significant.
Parameters:
indicator (str) – Performance indicator to compare.
method (int or str or list, optional) – Method(s) to include in comparison.
testset (int or str or list, optional) – Test set(s) to include in comparison.
reference (int or str, optional) – Reference method for comparison.
all2all (bool, default: False) – Whether to perform all-to-all comparison.
all2one (int or str, optional) – Method to use as reference for all-to-one comparison.
samples ({'methods', 'testsets'}, default: 'methods') – Whether to compare across methods or test sets.
Returns:
Dictionary containing statistical comparison results including
p-values and test statistics.
Compute and visualize confidence intervals for performance indicators.
Calculates confidence intervals for algorithm performance metrics
and creates visualizations to show the statistical uncertainty
in the performance estimates.
Parameters:
indicator (str) – Performance indicator to compute confidence intervals for.
method (int or str or list, optional) – Method(s) to include in analysis.
testset (int or str or list, optional) – Test set(s) to include in analysis.
Plot evolution of performance indicators across test sets or methods.
Creates plots showing how algorithm performance evolves across
different test sets or methods, useful for analyzing trends and
comparing algorithm behavior.
Parameters:
indicator (str) – Performance indicator to plot.
axis (matplotlib.axes.Axes, optional) – Matplotlib axes to plot on. If None, new figure is created.
method (int or str or list, optional) – Method(s) to include in plot.
testset (int or str or list, optional) – Test set(s) to include in plot.
labels (list of str, optional) – Custom labels for the plot lines.
xlabel (str, optional) – Label for the x-axis.
title (str, optional) – Title for the plot.
fontsize (int, default: 10) – Font size for plot text.
yscale ({'linear', 'log'}, optional) – Y-axis scale for the plot.
Loads a previously saved benchmark configuration from file.
Parameters:
file_name (str) – Name of the file containing saved benchmark state.
file_path (str, default: '') – Path to the file containing saved benchmark state.
Notes
This method restores the benchmark configuration including methods,
discretizations, and test set references. If test set data was not
saved with the benchmark, the test sets need to be imported separately.
Test and visualize normality of performance indicators.
Performs statistical normality tests and creates Q-Q plots to
assess whether the performance indicators follow a normal distribution.
This is useful for determining appropriate statistical tests.
Parameters:
indicator (str) – Performance indicator to test for normality.
axis (matplotlib.axes.Axes, optional) – Matplotlib axes to plot on. If None, new figure is created.
method (int or str or list, optional) – Method(s) to include in analysis.
testset (int or str or list, optional) – Test set(s) to include in analysis.
fontsize (int, optional) – Font size for plot text.
title (str, optional) – Title for the plot.
show (bool, default: False) – Whether to display the plot.
file_name (str, optional) – Name for saving the plot file.
file_path (str, default: '') – Path where to save the plot file.
file_format (str, default: 'eps') – File format for saving the plot.
WrongValueInput – If parallelization parameter has invalid value.
Notes
The method automatically sets stochastic algorithms to AVERAGE_CASE
mode for consistent benchmarking. Results are stored in the results
attribute as a numpy array.
Saves the benchmark configuration and optionally the test set data
to a file for later retrieval.
Parameters:
file_path (str, default: '') – Path where to save the benchmark file.
save_testset (bool, default: False) – Whether to save the full test set data or just references.
If False, only test set names are saved.
Notes
The file is saved with the benchmark’s name as filename using pickle
serialization. Test set data can be large, so save_testset=False is
recommended for most use cases.
Creates violin plots showing the probability density of algorithm
performance across test instances. Combines aspects of box plots
and kernel density estimation to show distribution shape.
Parameters:
indicator (str or list of str) – Performance indicator(s) to plot. Must be valid result indicators.
axis (matplotlib.axes.Axes or numpy.ndarray of Axes, optional) – Matplotlib axes to plot on. If None, new figure is created.
testset (int or str or list, optional) – Test set(s) to include in plot. Can be indices, names, or list.
method (int or str or list, optional) – Method(s) to include in plot. Can be indices, names, or list.
yscale ({'linear', 'log'}, optional) – Y-axis scale for the plot.
show (bool, default: False) – Whether to display the plot.
file_name (str, optional) – Name for saving the plot file (without extension).
file_path (str, default: '') – Path where to save the plot file.
file_format (str, default: 'eps') – File format for saving the plot.
title (str or bool or list of str, optional) – Title(s) for the plot(s). Can be string, boolean, or list.
fontsize (int, default: 10) – Font size for plot text.
color (str, default: 'b') – Color for the violin plots.
Creates offspring by mixing variables from two parents based on
a crossover rate. Commonly used in Differential Evolution.
Parameters:
crossover_rate (float) – Probability of taking variable from the second parent.
Notes
Binomial crossover is the standard crossover operator in DE.
Each variable has crossover_rate probability of coming from the
second parent, otherwise from the first.
Initializes population using the Born approximation to estimate
initial fields. Requires DiscretizationElementBased representation.
Notes
This initialization uses the first-order Born approximation to
initialize the total field, providing a better starting point than
random initialization for electromagnetic inverse scattering problems.
Born Iterative Method for Nonlinear Electromagnetic Inverse Scattering.
This class implements the Born Iterative Method (BIM), a classical iterative
approach for solving nonlinear electromagnetic inverse scattering problems.
The method couples forward and inverse solvers in an iterative process to
reconstruct material properties from scattered field measurements.
The algorithm works by:
1. Starting with the incident field as initial guess
2. Solving the linearized inverse problem using the current total field
3. Updating the total field using the forward solver
4. Repeating until convergence criteria are met
Parameters:
forward_solver (ForwardSolver) – Forward solver implementation for computing total electric field.
regularization (Regularization) – Regularization method for the linear inverse problem.
stop_criteria (StopCriteria) – Convergence criteria for the iterative process.
alias (str, default: 'bim') – Alias name for the method instance.
Creates a new BIM instance with the specified forward solver,
regularization method, and convergence criteria.
Parameters:
forward_solver (ForwardSolver) – Forward solver implementation for computing the total electric field
in the scattering domain. Must implement the ForwardSolver interface.
regularization (Regularization) – Regularization method for solving the linearized inverse problem.
Used to handle ill-conditioning in the linear system.
stop_criteria (StopCriteria) – Convergence criteria object that determines when to stop the
iterative process. Typically based on relative change in solution
or maximum number of iterations.
alias (str, default: 'bim') – Alias name for this method instance, used for identification
and file naming.
import_filename (str, optional) – Filename to import previously saved method state. If provided,
other parameters are ignored and state is loaded from file.
import_filepath (str, default: '') – Path to the file containing saved method state.
Notes
The method uses the standard Born iterative approach where:
The incident field serves as the initial guess for total field
At each iteration, the linear inverse problem is solved using
the current total field estimate
The forward solver computes the new total field
The process continues until convergence criteria are met
where \(\\chi\) is the contrast, \(E_s\) is the scattered field,
\(E_t^{(n)}\) is the total field at iteration n, and \(\\mathcal{L}^{-1}\)
is the linearized inverse operator.
Loads a previously saved BIM configuration from file, restoring
all method parameters and settings.
Parameters:
file_name (str) – Name of the file containing saved method state.
file_path (str, default: '') – Path to the file containing saved method state.
Notes
This method restores the complete BIM configuration including:
- Forward solver with all its parameters
- Regularization method configuration
- Stop criteria settings
- Base class attributes
The loaded configuration can be used to recreate the exact same
method instance as was saved.
Saves the complete method configuration including forward solver,
regularization method, and stop criteria to a file for later retrieval.
Parameters:
file_path (str, default: '') – Path where to save the method state file. The file will be
saved with the method’s alias as the filename.
Notes
The method saves all necessary information to recreate the BIM
instance, including:
- Forward solver configuration
- Regularization method parameters
- Stop criteria settings
- Base class attributes (alias, etc.)
The file is saved using pickle serialization format.
Solve the nonlinear inverse scattering problem using BIM.
Implements the Born Iterative Method to reconstruct material properties
from scattered field measurements. The method iteratively refines the
solution by coupling forward and inverse solvers.
Parameters:
inputdata (InputData) – Input data object containing scattered field measurements,
configuration parameters, and other problem-specific information.
discretization (Discretization) – Discretization object containing domain information, Green’s
function matrices, and methods for field computation.
print_info (bool, default: True) – Whether to print iteration progress information to output.
print_file (file-like object, default: sys.stdout) – File object to write progress information to.
Returns:
result – Result object containing the reconstructed material properties,
fields, error metrics, and algorithm performance information.
Update material properties and create auxiliary InputData
Solve forward problem to get new total field:
\(E_t^{(k)} = E_i + G_D \chi^{(k)} E_t^{(k)}\)
Compute objective function and check convergence
Termination: Stop when convergence criteria are satisfied
The method handles both dielectric and conducting materials, automatically
converting between contrast and physical parameters (permittivity,
conductivity) as needed.
Convergence Criteria: The algorithm stops when the stop criteria
object determines convergence based on iteration count, objective
function value, or relative change in solution.
Error Tracking: The method computes and tracks various error metrics
including relative permittivity error, objective function value, and
field reconstruction errors.
Abstract base class for boundary conditions in evolutionary algorithms.
Boundary conditions handle how variables that go outside the allowed range
are treated during evolution. This class defines the interface for all
boundary handling strategies.
Comprehensive case study framework for electromagnetic inverse scattering.
This class extends the Experiment class to provide a complete framework
for conducting case studies in electromagnetic inverse scattering problems.
It supports both deterministic and stochastic methods, parallel execution,
and comprehensive result analysis including statistical comparisons and
visualizations.
A case study includes:
- Test data (ground truth) for validation
- One or more inverse scattering methods
- Discretization parameters
- Stochastic execution configuration
- Result analysis and visualization tools
Parameters:
name (str, optional) – Name identifier for the case study
method (object or list of objects, optional) – Inverse scattering method(s) to be evaluated
discretization (object or list of objects, optional) – Discretization parameters for the methods
test (InputData or str, optional) – Test data for validation or filename if string
stochastic_runs (int, default=30) – Number of stochastic executions for statistical analysis
save_stochastic_runs (bool, default=False) – Whether to save individual stochastic execution results
import_filename (str, optional) – Filename to import case study configuration from
import_filepath (str, default='') – Path to import file
>>> # Single method case study>>> case=CaseStudy(name='bim_test',method=bim_method,... discretization=disc,test=test_data)>>> case.run(parallelization=True)>>> case.reconstruction(show=True)
Creates a formatted string containing comprehensive information about
the case study configuration, including inherited experiment details,
test data status, and stochastic execution parameters.
Returns:
Formatted string representation of the case study
Return type:
str
Examples
>>> print(case)CASE STUDYName: my_caseMethod: Born Iterative MethodTest: test_scenario_1Save stochastic runs? yesNumber of stochastic runs: 50
Create boxplot visualization for stochastic method results.
Generates boxplot visualizations of performance indicators for
stochastic methods to show statistical distributions of results
across multiple executions.
Parameters:
indicator (str or list of str) – Performance indicator(s) to plot (e.g., ‘total_error’, ‘data_error’)
axis (matplotlib.axes.Axes or ndarray, optional) – Axes for plotting. If None, new figure is created
method (int, str, or list, optional) – Method indices or names to plot. If None, all stochastic methods are used
file_name (str, optional) – Name for saving the figure
file_path (str, default='') – Path for saving the figure
file_format (str, default='eps') – Format for saving the figure
show (bool, default=False) – Whether to display the figure
fontsize (int, default=10) – Font size for labels and titles
title (str, bool, list, or None, optional) – Figure title(s). If None, automatic titles are used
mean (bool, default=False) – Whether to show mean indicators (unused parameter)
Conducts statistical tests to compare performance indicators between
different methods. Supports pairwise comparisons and multiple comparison
procedures for stochastic methods.
Parameters:
indicator (str or list of str) – Performance indicator(s) to compare (e.g., ‘total_error’, ‘data_error’)
method (int, str, or list, optional) – Method indices or names to compare. If None, all methods are used
all2all (bool, default=False) – Whether to perform all-to-all comparisons in multiple comparison
all2one (int, optional) – Index of reference method for all-to-one comparisons
error.Error – If case study configuration is invalid for comparison
Notes
The method automatically selects appropriate statistical tests:
- Two-sample tests for stochastic vs. stochastic comparisons
- One-sample tests for stochastic vs. deterministic comparisons
- Multiple comparison procedures for more than two methods
Only stochastic methods with saved runs can be compared statistically.
Deterministic methods are included as reference points.
Examples
>>> # Compare two methods>>> case.compare('total_error',method=[0,1])
Calculate and visualize confidence intervals for performance indicators.
Computes confidence intervals for performance indicators from stochastic
method executions and creates visualization plots with optional
statistical information output.
Parameters:
indicator (str or list of str) – Performance indicator(s) to analyze (e.g., ‘total_error’, ‘data_error’)
method (int, str, or list, optional) – Method indices or names to analyze. If None, all methods are used
axis (matplotlib.axes.Axes or ndarray, optional) – Axes for plotting. If None, new figure is created
file_name (str, optional) – Name for saving the figure
file_path (str, default='') – Path for saving the figure
file_format (str, default='eps') – Format for saving the figure
show (bool, default=False) – Whether to display the figure
fontsize (int, default=10) – Font size for labels and titles
title (str, bool, list, or None, optional) – Figure title(s). If None, automatic titles are used
print_info (bool, default=True) – Whether to print statistical information
print_obj (file-like object, default=sys.stdout) – Object to print statistical information to
Confidence intervals are calculated using appropriate statistical methods
based on the distribution of the performance indicator values. The method
requires stochastic methods with saved executions.
Plot convergence analysis for performance indicators.
Visualizes the convergence behavior of specified performance indicators
throughout the iterative process. Supports both deterministic and
stochastic methods with options for mean curves and boxplots.
Parameters:
indicator (str or list of str) – Performance indicator(s) to plot (e.g., ‘total_error’, ‘data_error’)
axis (matplotlib.axes.Axes or ndarray, optional) – Axes for plotting. If None, new figure is created
method (int, str, or list, optional) – Method indices or names to plot. If None, all methods are used
file_name (str, optional) – Name for saving the figure
file_path (str, default='') – Path for saving the figure
file_format (str, default='eps') – Format for saving the figure
show (bool, default=False) – Whether to display the figure
fontsize (int, default=10) – Font size for labels and titles
title (str, bool, list, or None, optional) – Figure title(s). If None, automatic titles are used
mean (bool, default=False) – Whether to show mean curves for stochastic methods
Visualize reconstruction results from the case study.
Creates visualization plots of the reconstructed electromagnetic
properties, with options to include ground truth, compare multiple
methods, and handle stochastic results.
Parameters:
image (str, default='contrast') – Property to visualize:
- ‘epsilon_r’: Relative permittivity
- ‘sigma’: Conductivity
- ‘both’: Both properties
- ‘contrast’: Contrast function
axis (matplotlib.axes.Axes or ndarray, optional) – Axes for plotting. If None, new figure is created
method (int, str, or list, optional) – Method indices or names to plot. If None, all methods are used
file_name (str, optional) – Name for saving the figure
file_path (str, default='') – Path for saving the figure
file_format (str, default='eps') – Format for saving the figure
show (bool, default=False) – Whether to display the figure
fontsize (int, default=10) – Font size for labels and titles
title (str, bool, or None, optional) – Figure title. If None, automatic titles are used
indicator (str, optional) – Performance indicator for selecting best execution
include_true (bool, default=False) – Whether to include ground truth in the visualization
mode (str, default='all') – Mode for stochastic results:
- ‘all’: Show all executions
- ‘best’: Show only best execution
Execute the case study with the configured methods.
Runs the inverse scattering method(s) on the test data with specified
parallelization strategy. Supports both deterministic and stochastic
methods with different parallelization approaches.
Parameters:
parallelization (bool, str, or None, default=None) – Parallelization strategy:
- None or True: Enable parallelization (default strategy)
- False: Disable parallelization
- ‘method’: Parallelize across methods
- ‘executions’: Parallelize across executions
save_stochastic_executions (bool, default=False) – Whether to save individual stochastic execution results
(parameter name kept for backward compatibility)
Saves the complete case study configuration including test data,
stochastic execution parameters, and all inherited experiment settings
using pickle serialization.
Parameters:
file_path (str, default='') – Path where the file will be saved
save_test (bool, default=False) – Whether to save the complete test data object or just the name
Collocation method for electromagnetic inverse scattering discretization.
This class implements the collocation method for discretizing electromagnetic
inverse scattering problems. The method uses trial functions and collocation
points to approximate the solution of integral equations, providing an
efficient framework for electromagnetic reconstruction algorithms.
The collocation method is particularly well-suited for problems where the
Green’s function can be computed analytically or semi-analytically, making
it computationally efficient for iterative reconstruction methods.
Parameters:
configuration (configuration.Configuration, optional) – Problem configuration object containing geometry and material properties
trial (str, optional) – Type of trial function to use (e.g., ‘pulse’, ‘linear’, ‘cubic’)
elements (int or tuple of int, optional) – Number of discretization elements. If int, creates square grid (N×N).
If tuple, creates rectangular grid (NY×NX)
name (str, optional) – Custom name for the discretization method
alias (str, default='clc') – Short alias for the method used in file operations
import_filename (str, optional) – Filename to import configuration from
import_filepath (str, default='') – Path to import file
The collocation method discretizes the electromagnetic integral equation
by choosing specific collocation points where the equation is enforced
exactly. This approach transforms the continuous integral equation into
a system of linear equations that can be solved numerically.
Trial functions commonly used include:
- pulse: Piecewise constant functions
- linear: Piecewise linear functions
- cubic: Piecewise cubic functions
You may either give the parameters or import information from a
save object. In addition, you must give either the frequency of
operation or the wavelength.
Parameters:
name (string) – A string naming the problem configuration.
number_measurements (int, default: 10) – Receivers in S-domain.
number_sources (int, default: 10) – Sources in S-domain
observation_radius (float, default: 1.1*sqrt(2)*max([Lx,Ly])) – Radius for circular array of sources and receivers at
S-domain [m]
frequency (float) – Linear frequency of operation [Hz]
image_size (2-tuple of int, default: (1., 1.)) – Side length of the image domain (D-domain). It may be
given in meters or in wavelengths.
wavelength_unit (boolean, default: True) – If True, the variable image_size will be interpreted
as given in wavelegnths. Otherwise, it will be
interpreted in meters.
magnitude (float, default: 1.0) – Magnitude of the incident field.
perfect_dielectric (boolean, default: False) – If True, it indicates the assumption of only perfect
dielectric objects. Then, only the relative permittivity
map will be recovered.
good_conductor (boolean, default: False) – If True, it indicates the assumption of only good
conductors objects. Then, only the conductivity map will
be recovered.
import_filename (string, default: None) – A string with the name of the pickle file containing the
information of a previous Configuration object.
import_filepath (string, default: '') – A string containing the path to the object to be
imported.
Save the problem configuration within a pickle file.
It will only be saved the attribute variables, not the object
itself. If you want to load these variables, you may use the
constant string variables for a more friendly usage.
Conjugated Gradient Method for nonlinear inverse scattering.
This class implements the Conjugated Gradient Method (CGM) for solving
nonlinear electromagnetic inverse scattering problems. The method uses
gradient-based optimization with conjugate gradient updates to iteratively
reconstruct the electromagnetic properties of unknown scatterers from
scattered field measurements.
The algorithm minimizes the following objective function:
where \(\\chi\) is the contrast function, \(\mathbf{E}^s\) is the
scattered field, \(\mathbf{G}^s\) is the Green’s function matrix,
and \(\mathbf{L}^{-1}\) is the inverse of the Lippmann-Schwinger
operator.
Parameters:
initial_guess (str) – Strategy for initial guess:
- ‘background’: Start with background medium
- ‘backpropagation’: Use backpropagation algorithm
- ‘image’: Use direct image reconstruction
- ‘qualitative’: Use qualitative method (OSM)
step (str) – Step size computation method:
- ‘fixed’: Fixed step size based on gradient
- ‘optimum’: Optimal step size via line search
The conjugate gradient method is particularly effective for problems where
the gradient computation is efficient. The method uses the Polak-Ribière
formula for computing conjugate directions:
Creates a new instance of the CGM with specified initialization
strategy, step size method, and stopping criteria.
Parameters:
initial_guess (str) – Strategy for initial guess:
- ‘background’: Start with background medium (zero contrast)
- ‘backpropagation’: Use backpropagation algorithm for initialization
- ‘image’: Use direct image reconstruction as initial guess
- ‘qualitative’: Use qualitative method (OSM) for initialization
step (str) – Step size computation method:
- ‘fixed’: Fixed step size based on gradient and residual
- ‘optimum’: Optimal step size via line search optimization
stop_criteria (object) – Stopping criteria object that defines convergence conditions
(e.g., maximum iterations, error tolerance)
alias (str, default='cgm') – Alias name for the method used in saving/loading
import_filename (str, optional) – If provided, import method parameters from this file
import_filepath (str, default='') – Path to the import file
Examples
>>> # Create CGM with background initial guess and optimal step>>> cgm=ConjugatedGradientMethod(initial_guess='background',... step='optimum',... stop_criteria=my_criteria)
>>> # Create CGM with qualitative initial guess and fixed step>>> cgm=ConjugatedGradientMethod(initial_guess='qualitative',... step='fixed',... stop_criteria=my_criteria)
>>> # Import from saved configuration>>> cgm=ConjugatedGradientMethod(initial_guess='background',... step='optimum',... stop_criteria=my_criteria,... import_filename='cgm_config.pkl')
Solve the nonlinear inverse scattering problem using CGM.
Applies the conjugated gradient method to iteratively reconstruct
the electromagnetic properties of unknown scatterers from scattered
field measurements. The method minimizes the data misfit using
gradient-based optimization with conjugate gradient updates.
Parameters:
inputdata (inputdata.InputData) – Input data object containing:
- scattered_field: Measured scattered electric field
- configuration: Problem configuration (frequency, geometry, etc.)
- resolution: Target resolution for reconstruction
- indicators: List of performance indicators to compute
discretization (object) – Discretization object containing:
- elements: Grid dimensions (NY, NX)
- GS: Green’s function matrix for scattered field
- GD: Green’s function matrix for domain interaction
print_info (bool, default=True) – Whether to print iteration information during solving
print_file (file-like object, default=sys.stdout) – File object for printing iteration information
Returns:
Result object containing:
- rel_permittivity: Reconstructed relative permittivity
- conductivity: Reconstructed conductivity (if applicable)
- total_error: Final data misfit error
- data_error: Data error evolution
- execution_time: Total execution time
- number_iterations: Number of iterations performed
- number_evaluations: Number of function evaluations
Contrast Source Inversion method for nonlinear electromagnetic inverse scattering.
This class implements the Contrast Source Inversion (CSI) method, which
simultaneously reconstructs both the contrast function and the contrast
sources (induced currents) in electromagnetic inverse scattering problems.
The method uses an iterative conjugate gradient optimization approach to
minimize a cost functional with both data and object error terms.
The CSI method solves the nonlinear inverse problem by minimizing:
where:
- (F_S) is the data error term (scattered field misfit)
- (F_D) is the object error term (current-contrast consistency)
- (mathbf{J}) is the contrast source (induced current)
- (chi) is the contrast function
- (mathbf{E}) is the total electric field
- (mathbf{E}^s) is the scattered field
- (mathbf{E}^i) is the incident field
- (mathbf{G}^s) is the scattered field Green’s function
Creates a new CSI instance with specified stopping criteria and
forward solver for electromagnetic field computation.
Parameters:
stop_criteria (object) – Stopping criteria object that defines convergence conditions
such as maximum iterations, error tolerance, or divergence limits
forward_solver (object, default=mom.MoM_CG_FFT()) – Forward solver implementation for computing electromagnetic fields.
Must implement the incident_field() method and support the
required discretization formats
alias (str, default='csi') – Alias name for the method used in file operations and identification
import_filename (str, optional) – If provided, import method parameters from this file instead
of using the provided parameters
import_filepath (str, default='') – Path to the import file
Examples
>>> # Create CSI with default forward solver>>> csi=ContrastSourceInversion(stop_criteria=my_criteria)
>>> # Create CSI with custom forward solver>>> csi=ContrastSourceInversion(stop_criteria=my_criteria,... forward_solver=my_forward_solver)
>>> # Import from saved configuration>>> csi=ContrastSourceInversion(stop_criteria=my_criteria,... import_filename='csi_config.pkl')
Solve the nonlinear inverse scattering problem using CSI.
Applies the Contrast Source Inversion method to reconstruct the
electromagnetic properties of unknown scatterers. The method
simultaneously updates both the contrast function and contrast
sources using conjugate gradient optimization.
Parameters:
inputdata (inputdata.InputData) – Input data object containing:
- scattered_field: Measured scattered electric field
- configuration: Problem configuration (frequency, geometry, etc.)
- resolution: Target resolution for reconstruction
- indicators: List of performance indicators to compute
discretization (object) – Discretization object containing:
- elements: Grid dimensions (NY, NX)
- GS: Green’s function matrix for scattered field
- contrast_image: Method for contrast imaging
- total_image: Method for total field imaging
- solve: Method for solving linear systems
print_info (bool, default=True) – Whether to print iteration information during solving
print_file (file-like object, default=sys.stdout) – File object for printing iteration information
initial_guess (numpy.ndarray, optional) – Initial guess for the contrast function. If None, uses
backpropagation method for initialization
Returns:
Result object containing:
- rel_permittivity: Reconstructed relative permittivity
- conductivity: Reconstructed conductivity (if applicable)
- scattered_field: Reconstructed scattered field
- total_field: Reconstructed total field
- total_error: Final objective function value
- data_error: Data error evolution
- execution_time: Total execution time
- number_iterations: Number of iterations performed
- number_evaluations: Number of function evaluations
Base class for deterministic inverse scattering solvers.
This class provides the foundation for all deterministic inverse scattering
methods in the eispy2d library. It inherits from InverseSolver and
implements the common interface required by all deterministic algorithms.
Deterministic solvers are characterized by their reproducible behavior -
given the same input data and parameters, they will always produce the
same output. This is in contrast to stochastic methods that may produce
different results on different runs due to random components.
The class serves as an abstract base that defines the standard workflow
for deterministic inverse solvers:
1. Initialize solver with configuration parameters
2. Solve the inverse problem using deterministic algorithm
3. Save/load solver state for persistence
4. Copy solver instances for parallel or comparative studies
Parameters:
alias (str, default='') – Unique identifier for the solver instance. Used for file naming
when saving/loading solver state and for identification in
multi-solver comparisons.
parallelization (bool, default=False) – Whether to enable parallel processing capabilities. When True,
the solver may utilize multiple CPU cores or parallel algorithms
where available.
This class is designed to be inherited by specific deterministic
algorithms. The base implementation provides standard functionality
while derived classes implement algorithm-specific behavior.
All methods in this class call the parent InverseSolver methods,
ensuring consistent behavior across the solver hierarchy. Derived
classes should override these methods to add algorithm-specific
functionality while maintaining the standard interface.
Examples
This class is not used directly, but serves as base for specific solvers:
>>> # Example derived class structure>>> classMyDeterministicMethod(Deterministic):... def__init__(self,my_param,**kwargs):... super().__init__(**kwargs)... self.my_param=my_param... self.name='My Deterministic Method'...... defsolve(self,inputdata,discretization,**kwargs):... result=super().solve(inputdata,discretization,**kwargs)... # Add algorithm-specific processing... returnresult
alias (str, default='') – Unique identifier for the solver instance. This string is used
for file naming when saving/loading solver state and for
identification in multi-solver studies. Should be descriptive
and unique within the application context.
parallelization (bool, default=False) – Flag to enable parallel processing capabilities. When True,
the solver may utilize multiple CPU cores or parallel algorithms
where available in the specific implementation.
Notes
This method calls the parent InverseSolver initialization to
establish the basic solver framework. Derived classes should
call this method via super() and then add their specific
initialization requirements.
The parallelization flag is stored for use by derived classes
but does not activate any parallel processing by itself. Each
specific algorithm implementation decides how to utilize this flag.
This method creates a deep copy of the current solver instance,
including all configuration parameters and settings. The copy
can be used independently without affecting the original solver.
Parameters:
new (Deterministic, optional) – If provided, the current solver’s configuration will be
copied into this existing instance. If None, a new instance
will be created and returned.
Returns:
If new is None, returns a new Deterministic instance with
the same configuration. If new is provided, returns None
and the configuration is copied into the new instance.
This method creates independent copies that can be used for
parallel processing, parameter studies, or comparative analysis
without interference between instances.
The base implementation copies common solver attributes. Derived
classes should override this method to handle algorithm-specific
parameters:
>>> # Copy configuration into existing instance>>> target_solver=Deterministic()>>> solver.copy(target_solver)>>> print(f"Target now has alias: {target_solver.alias}")
>>> # Use for parameter studies>>> solvers=[solver.copy()for_inrange(5)]>>> # Modify each copy independently for different parameters
This method deserializes solver state from a file that was
previously created using the save method. It restores all
configuration parameters, algorithm settings, and internal state
to recreate the exact solver configuration.
Parameters:
file_name (str) – Name of the file containing the saved solver state. This
should match the filename created by the save method.
file_path (str, default='') – Directory path where the save file is located. If empty,
looks in the current directory.
Returns:
Dictionary containing the loaded solver state data. This
provides access to all restored parameters and settings.
Return type:
dict
Notes
The base implementation loads common solver attributes. Derived
classes should override this method to restore algorithm-specific
state information:
data = super().importdata(file_name, file_path=file_path)
self.my_specific_param = data[‘my_specific_param’]
# Restore additional algorithm-specific data
return data
The method completely replaces the current solver state with
the loaded configuration, so any existing settings will be lost.
Examples
>>> # Load from current directory>>> data=solver.importdata('solver_state.pkl')>>> print(f"Loaded {len(data)} parameters")
>>> # Load from specific directory>>> data=solver.importdata('state.pkl',file_path='/path/to/files/')>>> print(f"Restored solver configuration from {file_path}")
Raises:
FileNotFoundError – If the specified file does not exist
pickle.UnpicklingError – If the file is corrupted or incompatible
This method serializes the current solver state including all
configuration parameters, algorithm settings, and internal state
to a file. The saved state can later be restored using the
importdata method.
Parameters:
file_path (str, default='') – Base path for saving the solver state. The actual filename
will be constructed by appending the solver’s alias to this
base path. If empty, saves to current directory.
Returns:
Dictionary containing the serialized solver state data.
This includes all necessary information to fully restore
the solver configuration and state.
Return type:
dict
Notes
The base implementation saves common solver attributes. Derived
classes should override this method to include algorithm-specific
state information:
Solve the electromagnetic inverse scattering problem.
This method provides the standard interface for solving inverse
scattering problems using deterministic methods. The base implementation
calls the parent InverseSolver method to handle common setup and
validation tasks.
Parameters:
inputdata (InputData) – Input data object containing:
- scattered_field: Measured scattered field data
- configuration: Problem configuration (frequency, background, etc.)
- resolution: Desired reconstruction resolution
- indicators: Performance metrics to compute
discretization (Discretization) – Discretization object containing:
- elements: Spatial discretization grid
- GS: Scattered field Green’s function matrix
- GD: Domain Green’s function matrix (if needed)
- Methods for field interpolation and imaging
print_info (bool, default=True) – Whether to print algorithm progress and iteration information
during the solving process. Useful for monitoring convergence
and debugging.
print_file (file-like object, default=sys.stdout) – Output stream for printing information. Can be redirected to
files or other output streams as needed.
Returns:
Result object containing reconstruction results and performance
metrics. The specific contents depend on the algorithm
implementation but typically include:
- Reconstructed electromagnetic properties
- Convergence history
- Performance metrics
- Algorithm-specific information
This base implementation performs common setup tasks and validation
that are required by all deterministic solvers. Derived classes
should override this method to implement their specific algorithm
while calling the parent method for initialization:
Abstract base class for spatial discretization methods.
This class defines the interface that all discretization methods must
implement for electromagnetic inverse scattering problems. It provides
the foundation for converting continuous field problems into discrete
algebraic systems that can be solved numerically.
The discretization handles the spatial aspect of the inverse scattering
problem, defining how continuous electromagnetic fields are represented
on discrete grids and how the governing equations are discretized.
Key responsibilities include:
- Spatial grid generation and management
- Field representation using basis functions
- Residual computation for data and state equations
- Linear system solution for field reconstruction
- Resolution conversion and field interpolation
- Green’s function matrix computation and storage
Parameters:
configuration (Configuration, optional) – Problem configuration object containing electromagnetic parameters,
geometry definitions, and solver settings. If None, must be set
before solving.
name (str, optional) – Human-readable name for the discretization method
alias (str, default='') – Short identifier for the discretization, used in file naming
and method identification
import_filename (str, optional) – If provided, loads discretization state from this file
import_filepath (str, default='') – Directory path for import file
This is an abstract base class - all methods marked with @abstractmethod
must be implemented by derived classes. The class provides parameter
validation and error checking for the abstract methods.
Different discretization methods will implement these abstract methods
according to their specific mathematical formulations:
- Method of Moments uses basis functions and testing functions
- Finite Differences use grid-based approximations
- Finite Elements use element-based basis functions
- Collocation uses point-wise matching
Examples
This class cannot be instantiated directly. Use derived classes:
>>> # Example derived class usage>>> fromcollocationimportCollocation>>> discretization=Collocation(configuration,name='Pulse Collocation')>>>>>> # Solve linear inverse problem>>> contrast=discretization.solve(... scattered_field=measured_data,... incident_field=incident_data,... linear_solver=regularization_method... )>>>>>> # Convert to image format>>> image=discretization.contrast_image(contrast,resolution)
configuration (Configuration, optional) – Problem configuration object containing electromagnetic parameters,
geometry, frequency, and other problem-specific settings. If None,
must be set before solving any problems.
name (str, optional) – Human-readable name for the discretization method. Used for
identification and display purposes.
alias (str, default='') – Short identifier string for the discretization method. Used in
file naming and method identification within algorithms.
import_filename (str, optional) – If provided, loads the discretization state from this file
instead of initializing with the other parameters.
import_filepath (str, default='') – Directory path where the import file is located.
Notes
If import_filename is provided, the method loads its state from
the specified file and ignores other initialization parameters.
Otherwise, it initializes with the provided parameters.
The configuration object is copied to avoid unintended modifications
to the original configuration during discretization operations.
Return string representation of the discretization.
This method provides a string representation of the discretization
method for display and debugging purposes. The base implementation
provides a generic identifier.
Returns:
String representation of the discretization method
Return type:
str
Notes
Derived classes should override this method to provide more
specific information about the discretization:
This method converts the discrete contrast function coefficients
from the discretization basis to a regular image grid at the
specified resolution. This is useful for visualization and
analysis of reconstruction results.
Parameters:
coefficients (array_like) – Contrast function coefficients at discretization points,
typically obtained from solving the inverse problem
resolution (array_like or tuple) – Desired image resolution as (nx, ny) where nx and ny are
the number of pixels in x and y directions respectively
Returns:
2D array representing the contrast function image with
shape matching the specified resolution
Return type:
array_like
Notes
The conversion process typically involves:
1. Interpolation from discretization points to image grid
2. Proper handling of boundary conditions
3. Scaling and normalization if needed
The image format allows for easy visualization and comparison
with reference solutions or other reconstruction methods.
Examples
>>> # Convert to 64x64 image>>> image=discretization.contrast_image(... coefficients=solution_coeffs,... resolution=(64,64)... )>>>>>> # Display the reconstruction>>> importmatplotlib.pyplotasplt>>> plt.imshow(image.real,cmap='jet')>>> plt.title('Reconstructed Contrast Function')
This method creates a copy of the current discretization instance
with the same configuration and settings. Since this is an abstract
base class, the method cannot create a new instance directly.
Parameters:
new (Discretization, optional) – If provided, the current discretization’s configuration will be
copied into this existing instance. If None, raises an error
since abstract classes cannot be instantiated.
Returns:
This method only supports copying into an existing instance
due to the abstract nature of the base class.
Return type:
None
Raises:
TypeError – If new is None, since abstract classes cannot be instantiated
Notes
This method is designed to be overridden by derived classes to
provide proper copying functionality:
This method loads discretization configuration and state from a
previously saved file. The base implementation handles common
parameters, but derived classes should extend this to restore
method-specific data.
Parameters:
file_name (str) – Name of the file containing the saved discretization state
file_path (str, default='') – Directory path where the save file is located
Returns:
Dictionary containing the loaded discretization state data
Return type:
dict
Notes
Derived classes should override this method to restore additional
method-specific data:
This method computes the residual (error) between measured scattered
field data and the scattered field predicted by the current estimate
of the scatterer properties. The residual is used in optimization
algorithms to minimize the data misfit.
The data equation relates the scattered field to the scatterer
properties and internal fields:
\[E^s = G^s J\]
where \(E^s\) is the scattered field, \(G^s\) is the scattered
field Green’s function, and \(J\) is the contrast source.
Parameters:
scattered_field (array_like) – Measured scattered field data at receiver locations.
contrast (array_like, optional) – Contrast function values at discretization points. Required
if total_field is provided.
total_field (array_like, optional) – Total electric field at discretization points. Required
if contrast is provided.
current (array_like, optional) – Contrast source (current) at discretization points. If provided,
contrast and total_field are ignored.
Returns:
Data residual vector representing the difference between
measured and computed scattered field.
Return type:
array_like
Raises:
MissingInputError – If required parameter combinations are not provided.
Error – If no valid parameter combination is given.
Notes
The method requires either:
- Both contrast and total_field parameters, or
- The current parameter alone.
The residual is computed as:
residual = measured_scattered_field - predicted_scattered_field
A small residual indicates good agreement between the model and data.
Examples
>>> # Using contrast and total field>>> residual=discretization.residual_data(... scattered_field=measured_data,... contrast=current_contrast,... total_field=current_total_field... )
>>> # Using current directly>>> residual=discretization.residual_data(... scattered_field=measured_data,... current=current_source... )
This method computes the residual (error) in the state equation,
which relates the total field, contrast function, and current source.
The state equation ensures consistency between the electromagnetic
field quantities within the scattering domain.
The state equation can be written as:
\[J = \chi E^t\]
where \(J\) is the contrast source, \(\chi\) is the contrast
function, and \(E^t\) is the total electric field.
Parameters:
incident_field (array_like) – Incident electric field at discretization points.
contrast (array_like, optional) – Contrast function values at discretization points. Required
if total_field or current is provided.
total_field (array_like, optional) – Total electric field at discretization points. Used with
contrast to compute current source.
current (array_like, optional) – Contrast source (current) at discretization points. Used with
contrast to validate state equation.
Returns:
State residual vector representing the inconsistency in the
state equation.
Return type:
array_like
Raises:
MissingInputError – If required parameter combinations are not provided.
Error – If no valid parameter combination is given.
Notes
The method requires:
- contrast parameter along with either total_field or current.
The residual measures how well the state equation is satisfied:
- If using total_field: residual = contrast * total_field - current
- If using current: residual = contrast * (incident + scattered) - current
A small residual indicates good consistency between field quantities.
Examples
>>> # Using contrast and total field>>> residual=discretization.residual_state(... incident_field=incident_data,... contrast=current_contrast,... total_field=current_total_field... )
>>> # Using contrast and current>>> residual=discretization.residual_state(... incident_field=incident_data,... contrast=current_contrast,... current=current_source... )
This method saves the discretization configuration and state to a
file for later restoration. The base implementation provides the
common data structure, but derived classes should extend this to
include method-specific parameters.
Parameters:
file_path (str, default='') – Base path for saving the discretization state. The specific
filename will be determined by the derived class implementation.
Returns:
Dictionary containing the discretization state data including:
- name: Discretization method name
- alias: Method identifier
- configuration: Problem configuration object
Return type:
dict
Notes
Derived classes should override this method to include additional
method-specific data:
Compute scattered field from scatterer properties.
This method computes the scattered electric field at receiver locations
given the scatterer properties (contrast function, total field, or
current source). This is the forward scattering operation.
The scattered field is computed using:
.. math:
E^s=G^sJ
where \(G^s\) is the scattered field Green’s function matrix and
\(J\) is the contrast source.
Parameters:
contrast (array_like, optional) – Contrast function values at discretization points. Required
if total_field is provided.
total_field (array_like, optional) – Total electric field at discretization points. Required
if contrast is provided.
current (array_like, optional) – Contrast source (current) at discretization points. Alternative
to providing contrast and total_field separately.
Returns:
Scattered electric field at receiver locations
Return type:
array_like
Raises:
MissingInputError – If required parameter combinations are not provided
Notes
The method requires either:
- Both contrast and total_field parameters, or
- The current parameter alone
If contrast and total_field are provided, the current source is
computed as J = chi E^t, then used to calculate the scattered field.
Examples
>>> # Using contrast and total field>>> scattered=discretization.scattered_field(... contrast=contrast_values,... total_field=total_field_values... )
>>> # Using current directly>>> scattered=discretization.scattered_field(... current=current_source... )
This method solves the discretized linear inverse scattering problem
to reconstruct the contrast function from measured scattered field data.
The solution involves solving a linear system that may be ill-conditioned,
requiring regularization techniques.
The linear problem typically has the form:
\[G \chi = E^s\]
where \(G\) is the system matrix, \(\chi\) is the contrast
function to be reconstructed, and \(E^s\) is the scattered field data.
Parameters:
scattered_field (array_like, optional) – Measured scattered field data at receiver locations.
incident_field (array_like, optional) – Incident electric field at discretization points.
contrast (array_like, optional) – Initial or known contrast function values.
total_field (array_like, optional) – Total electric field at discretization points.
current (array_like, optional) – Contrast source (current) at discretization points.
linear_solver (Regularization, optional) – Regularization/linear solver method to use for solving the
potentially ill-conditioned linear system.
Returns:
Reconstructed contrast function coefficients at discretization points.
Return type:
array_like
Notes
The specific parameters required depend on the discretization method
and the formulation of the linear system. Common approaches include:
- Born approximation: uses incident field as total field
- Moment method: requires Green’s function matrices
- Finite differences: uses grid-based operators
The linear solver handles regularization to deal with ill-conditioning
that is common in inverse scattering problems.
>>> # Advanced solution with known total field>>> contrast=discretization.solve(... scattered_field=measured_data,... total_field=computed_total_field,... linear_solver=truncated_svd_solver... )
This method converts the discrete total field coefficients
from the discretization basis to a regular image grid at the
specified resolution. This is useful for visualization and
analysis of field distributions.
Parameters:
coefficients (array_like) – Total field coefficients at discretization points,
typically obtained from solving the forward problem
resolution (array_like or tuple) – Desired image resolution as (nx, ny) where nx and ny are
the number of pixels in x and y directions respectively
Returns:
2D array representing the total field image with
shape matching the specified resolution
Return type:
array_like
Notes
The conversion process typically involves:
1. Interpolation from discretization points to image grid
2. Proper handling of boundary conditions
3. Phase and amplitude representation
4. Scaling and normalization if needed
The image format allows for visualization of field patterns
and understanding of scattering behavior.
Examples
>>> # Convert to 128x128 image>>> field_image=discretization.total_image(... coefficients=field_coeffs,... resolution=(128,128)... )>>>>>> # Display field magnitude>>> importmatplotlib.pyplotasplt>>> plt.imshow(np.abs(field_image),cmap='viridis')>>> plt.title('Total Field Magnitude')
Distorted Born Iterative Method for electromagnetic inverse scattering.
This class implements the Distorted Born Iterative Method (DBIM) [1]_, a
nonlinear iterative algorithm for solving electromagnetic inverse scattering
problems. The method couples forward and inverse solvers iteratively,
updating the Green’s function at each iteration to account for the
estimated contrast function.
The DBIM algorithm works by:
1. Starting with Born approximation (incident field as total field)
2. Solving linear inverse problem to get initial contrast estimate
3. Updating Green’s function using current contrast estimate
4. Solving forward problem with updated Green’s function
5. Computing residual scattered field
6. Solving linear inverse problem for contrast update
7. Repeating until convergence or maximum iterations
The method provides improved convergence compared to standard BIM,
particularly for high-contrast scatterers, by using distorted incident
fields that better approximate the true total field.
Parameters:
forward_solver (Forward) – Forward solver implementation for computing total electric field
and scattered field from given contrast distribution
regularization (Regularization) – Regularization method for solving the linear inverse problem
(e.g., Tikhonov regularization, truncated SVD)
stop_criteria (StopCriteria) – Stopping criteria object defining when to terminate iterations
(e.g., maximum iterations, relative error threshold)
alias (str, default='dbim') – Alias name for the algorithm instance
import_filename (str, optional) – Filename to import previously saved algorithm state
import_filepath (str, default='') – Path to directory containing import file
Initialize the Distorted Born Iterative Method solver.
Parameters:
forward_solver (Forward) – Forward solver implementation for computing electromagnetic fields.
Must implement methods for computing incident field and solving
the forward scattering problem.
regularization (Regularization) – Regularization method for solving the linear inverse problem.
Common choices include Tikhonov regularization, truncated SVD,
or other regularization schemes.
stop_criteria (StopCriteria) – Stopping criteria object that determines when to terminate
the iterative process. Can be based on maximum iterations,
relative error, objective function value, etc.
alias (str, default='dbim') – Alias name for the algorithm instance, used for identification
and file naming when saving/loading algorithm state.
import_filename (str, optional) – If provided, imports algorithm state from this file instead
of initializing with provided parameters.
import_filepath (str, default='') – Directory path where the import file is located.
Notes
If import_filename is provided, the algorithm state is loaded
from file and other parameters are ignored. Otherwise, a new
instance is created with the provided solver components.
Solve electromagnetic inverse scattering problem using DBIM.
This method implements the complete DBIM algorithm, iteratively
updating the contrast function and Green’s function until
convergence or maximum iterations are reached.
Algorithm Steps:
1. Initialize with Born approximation (incident field as total field)
2. Solve linear inverse problem for initial contrast estimate
3. Enter iterative loop:
Update Green’s function using current contrast
Solve forward problem with updated Green’s function
Compute residual scattered field
Solve linear inverse problem for contrast update
Check stopping criteria
Return final reconstruction results
Parameters:
inputdata (InputData) – Input data object containing:
- scattered_field: Measured scattered field data
- configuration: Problem configuration (frequency, background, etc.)
- resolution: Desired output resolution
- indicators: Performance metrics to compute
discretization (Discretization) – Discretization object containing:
- elements: Discretization grid points
- GS: Scattered field Green’s function matrix
- GD: Domain Green’s function matrix
- Methods for field interpolation and contrast imaging
print_info (bool, default=True) – Whether to print iteration information during solving
print_file (file-like object, default=sys.stdout) – Output stream for printing iteration information
initial_guess (array_like, optional) – Initial guess for contrast function. If None, uses Born
approximation with incident field as total field.
Returns:
Result object containing:
- rel_permittivity: Reconstructed relative permittivity
- conductivity: Reconstructed conductivity (if applicable)
- scattered_field: Final computed scattered field
- total_field: Final computed total field
- execution_time: Algorithm execution time
- number_iterations: Number of iterations performed
- number_evaluations: Number of function evaluations
- error_history: Convergence history
The algorithm automatically handles both good conductor and
perfect dielectric cases based on the configuration. For
good conductors, only conductivity is reconstructed. For
perfect dielectrics, only permittivity is reconstructed.
The Green’s function update is the key difference from standard
BIM, providing better convergence for high-contrast scatterers
by using distorted incident fields.
Examples
>>> # Solve with default settings>>> result=solver.solve(input_data,discretization)>>> print(f"Converged in {result.number_iterations} iterations")
>>> # Solve with initial guess and custom output>>> withopen('output.txt','w')asf:... result=solver.solve(input_data,discretization,... initial_guess=my_guess,... print_file=f)
Evolutionary Algorithm for electromagnetic inverse scattering.
This class implements a general evolutionary algorithm framework for solving
electromagnetic inverse scattering problems. It supports various evolutionary
mechanisms including Differential Evolution, Particle Swarm Optimization,
and Genetic Algorithms.
Parameters:
population_size (int) – Size of the population.
initialization (Initialization) – Population initialization strategy.
objective_function (ObjectiveFunction) – Objective function to evaluate solution quality.
This class implements the Extended Contrast Source Inversion (ECSI) algorithm,
an advanced iterative nonlinear solver for electromagnetic inverse scattering
problems. ECSI extends the classical Contrast Source Inversion (CSI) approach
by incorporating enhanced optimization techniques and conjugate gradient methods.
The method alternately updates the contrast function (representing material
properties) and current density distribution within the scattering domain.
It employs a cost function minimization approach with conjugate gradient
optimization for efficient convergence.
where:
- \(\\chi\) is the contrast function
- \(\\mathbf{J}\) is the current density
- \(\\mathbf{E}^s\) is the scattered electric field
- \(\\mathbf{E}^{tot}\) is the total electric field
- \(\\mathbf{G}^s\) is the scattered field Green’s function
Initialize the Extended Contrast Source Inversion solver.
Creates an ECSI solver instance with specified stopping criteria and
forward solver. The solver can be initialized from scratch or loaded
from a previously saved state.
Parameters:
stop_criteria (stopcriteria.StopCriteria) – Object defining the stopping criteria for the iterative algorithm.
This includes maximum iterations, convergence thresholds, and
other termination conditions.
forward_solver (forward.Forward, optional) – Forward solver implementation for computing the total electric field.
Default is mom_cg_fft.MoM_CG_FFT.
alias (str, optional) – Short identifier for this solver instance. Used in result naming
and file operations. Default is ‘ecsi’.
import_filename (str, optional) – Name of file containing previously saved solver state. If provided,
the solver will be initialized from this saved state. Default is None.
import_filepath (str, optional) – Directory path containing the import file. Only used if import_filename
is provided. Default is empty string (current directory).
Raises:
FileNotFoundError – If import_filename is specified but the file cannot be found.
ValueError – If the loaded file contains invalid or corrupted solver state.
Creates a new solver instance with the same configuration or copies
configuration from another solver instance.
Parameters:
new (ExtendedContrastSourceInversion, optional) – Another solver instance to copy configuration from. If None,
creates a new instance with current configuration.
Solve the electromagnetic inverse scattering problem using ECSI.
Performs iterative reconstruction of the contrast function and current
density distribution using the Extended Contrast Source Inversion algorithm.
The method alternates between updating the current density (J) and the
contrast function (\chi) using conjugate gradient optimization.
Parameters:
inputdata (inputdata.InputData) – Object containing the measured scattered field data and problem
configuration including frequency, measurement points, and incident
field parameters.
discretization (discretization.Discretization) – Discretization scheme defining the computational grid, Green’s
functions, and spatial sampling of the investigation domain.
print_info (bool, optional) – Whether to print iteration progress information. Default is True.
print_file (file-like object, optional) – File object for printing output. Default is sys.stdout.
initial_guess (numpy.ndarray, optional) – Initial guess for the contrast function. If None, backpropagation
method is used to generate initial guess. Default is None.
Returns:
result – Object containing the reconstructed contrast function, relative
permittivity, conductivity, total field, and convergence information.
Return type:
result.Result
Raises:
ValueError – If input data or discretization are invalid.
RuntimeError – If the algorithm fails to converge within specified criteria.
Notes
The algorithm implements the following iterative procedure:
Initialization: Generate initial guess using backpropagation if not provided
Current Update: Minimize data and object error functionals with respect to J
Contrast Update: Minimize object error functional with respect to \chi
Convergence Check: Evaluate stopping criteria and continue if necessary
First-Order Born Approximation for Electromagnetic Inverse Scattering.
This class implements the First-Order Born Approximation (FOBA), a
linearization technique for solving electromagnetic inverse scattering
problems. The method assumes that the total field inside the scattering
object is approximately equal to the incident field, making it suitable
for weak scatterers.
The Born approximation converts the nonlinear inverse scattering problem
into a linear one by replacing the unknown total field with the known
incident field in the scattering integral equation. This results in a
single linear system that can be solved directly.
Mathematical Formulation:
The method solves the linearized equation:
E_s = G_S * chi * E_i
where:
- E_s: scattered field (measured data)
- G_S: scattering Green’s function matrix
- chi: contrast function (unknown to be reconstructed)
- E_i: incident field (known)
Parameters:
regularization (Regularization) – Regularization method for solving the linear inverse problem.
Required to handle the ill-conditioned nature of the inverse problem.
forward (ForwardSolver, default: mom.MoM_CG_FFT()) – Forward solver for computing incident fields and Green’s functions.
alias (str, default: 'ba') – Alias name for the method instance.
Validity Range: The Born approximation is valid when:
- The contrast is small (|\chi| << 1)
- The scatterer is electrically small
- The refractive index variation is gradual
Advantages:
- Fast computation (single linear solve)
- No iteration required
- Good initial guess for iterative methods
- Stable and well-understood
Limitations:
- Limited to weak scatterers
- Poor performance for high-contrast objects
- No nonlinear coupling effects
Initialize the First-Order Born Approximation method.
Creates a new FOBA instance with the specified regularization method
and forward solver configuration.
Parameters:
regularization (Regularization) – Regularization method for solving the ill-conditioned linear
inverse problem. Common choices include Tikhonov regularization,
truncated SVD, or iterative methods like CGLS.
forward (ForwardSolver, default: mom.MoM_CG_FFT()) – Forward solver implementation for computing incident fields and
Green’s function matrices. Must implement the ForwardSolver interface.
alias (str, default: 'ba') – Short alias name for this method instance, used for identification
and file naming purposes.
import_filename (str, optional) – Filename to import previously saved method state. If provided,
other parameters are ignored and the state is loaded from file.
import_filepath (str, default: '') – Path to the file containing saved method state.
Notes
The regularization parameter is crucial for the Born approximation
because the inverse scattering problem is inherently ill-conditioned.
The choice of regularization method and its parameters significantly
affects the reconstruction quality.
The forward solver is used to compute the incident field, which serves
as the approximation for the total field in the Born approximation.
Different forward solvers may be used depending on the problem geometry
and computational requirements.
Return string representation of the First-Order Born Approximation.
Creates a comprehensive string description of the FOBA instance
including all its components and configuration.
Returns:
String representation including:
- Base class information (name, alias, etc.)
- Regularization method details
- Forward solver configuration
Return type:
str
Notes
This method provides a complete overview of the FOBA configuration,
which is useful for debugging, logging, and understanding the
method setup. The string includes detailed information about
the regularization method and forward solver parameters.
Examples
>>> print(born)First-Order Born Approximation (ba)Regularization: Tikhonov (λ=1e-3)Forward Solver: MoM-CG-FFT...
The copy includes all method components:
- Regularization method (reference copy)
- Forward solver (reference copy)
- Base class attributes (alias, etc.)
This method is useful for creating multiple instances with the same
configuration, parameter studies, or backup purposes before
modifying parameters.
Examples
>>> # Create a copy>>> born_copy=born.copy()>>>>>> # Copy to existing instance>>> new_born=FirstOrderBornApproximation(some_regularization)>>> born.copy(new_born)# copies configuration to new_born
Import First-Order Born Approximation method state from file.
Loads a previously saved FOBA configuration from file, restoring
all method parameters and settings.
Parameters:
file_name (str) – Name of the file containing saved method state.
file_path (str, default: '') – Path to the file containing saved method state.
Notes
This method restores the complete FOBA configuration including:
- Regularization method with all its parameters
- Forward solver configuration and settings
- Base class attributes and state
The loaded configuration can be used to recreate the exact same
method instance as was saved, ensuring reproducibility of results.
Examples
>>> # Import from current directory>>> born=FirstOrderBornApproximation(None)# dummy init>>> born.importdata('ba')# load from file>>>>>> # Import from specific path>>> born.importdata('my_method','/path/to/files/')
Save the First-Order Born Approximation method state to file.
Saves the complete method configuration including regularization
method and forward solver settings to a file for later retrieval.
Parameters:
file_path (str, default: '') – Path where to save the method state file. The file will be
saved with the method’s alias as the filename.
Notes
The method saves all necessary information to recreate the FOBA
instance, including:
- Regularization method and its parameters
- Forward solver configuration
- Base class attributes (alias, etc.)
The file is saved using pickle serialization format, which preserves
the complete object state including any custom parameters or
configurations.
Examples
>>> # Save method to current directory>>> born.save()>>>>>> # Save to specific path>>> born.save('/path/to/save/')
Solve the inverse scattering problem using First-Order Born Approximation.
Implements the Born approximation to reconstruct material properties
from scattered field measurements. The method solves a single linearized
system by approximating the total field with the incident field.
Parameters:
inputdata (InputData) – Input data object containing scattered field measurements,
configuration parameters, and problem setup information.
discretization (Discretization) – Discretization object containing domain information, Green’s
function matrices, and numerical methods for field computation.
print_info (bool, default: True) – Whether to print algorithm progress and results information.
print_file (file-like object, default: sys.stdout) – File object to write progress information to.
Returns:
result – Result object containing the reconstructed material properties,
fields, error metrics, and algorithm performance information.
Incident Field Computation: Calculate the incident field E_i
in the discretization domain using the forward solver.
Linear System Solution: Solve the linearized equation:
\[\chi = \mathcal{R}[G_S^H E_s]\]
where \(\mathcal{R}\) is the regularization operator,
\(G_S^H\) is the adjoint scattering Green’s function,
and \(E_s\) is the scattered field.
Field Reconstruction: Compute the reconstructed scattered field
using the estimated contrast:
\[E_s^{rec} = G_S \chi E_i\]
Parameter Conversion: Convert the contrast function to physical
parameters (relative permittivity, conductivity) based on the
problem configuration.
Error Computation: Calculate various error metrics and
performance indicators.
Computational Complexity: O(N²) where N is the number of
discretization points, dominated by the linear system solution.
Memory Requirements: Depends on the regularization method and
Green’s function matrix storage.
The method automatically handles both dielectric and conducting
materials, converting between contrast and physical parameters
as needed based on the problem configuration.
Linear Sampling Method for qualitative inverse scattering.
This class implements the Linear Sampling Method (LSM), a qualitative
technique for shape reconstruction of scatterers. The method identifies
the support of the scatterer without reconstructing material properties.
Parameters:
alias (str, default='') – Alias name for the algorithm.
regularization (Regularization, optional) – Regularization method for solving linear systems.
This method creates a deep copy of the current solver instance,
including all configuration parameters and settings. The copy
can be used independently without affecting the original solver.
Parameters:
new (Deterministic, optional) – If provided, the current solver’s configuration will be
copied into this existing instance. If None, a new instance
will be created and returned.
Returns:
If new is None, returns a new Deterministic instance with
the same configuration. If new is provided, returns None
and the configuration is copied into the new instance.
This method creates independent copies that can be used for
parallel processing, parameter studies, or comparative analysis
without interference between instances.
The base implementation copies common solver attributes. Derived
classes should override this method to handle algorithm-specific
parameters:
>>> # Copy configuration into existing instance>>> target_solver=Deterministic()>>> solver.copy(target_solver)>>> print(f"Target now has alias: {target_solver.alias}")
>>> # Use for parameter studies>>> solvers=[solver.copy()for_inrange(5)]>>> # Modify each copy independently for different parameters
This method deserializes solver state from a file that was
previously created using the save method. It restores all
configuration parameters, algorithm settings, and internal state
to recreate the exact solver configuration.
Parameters:
file_name (str) – Name of the file containing the saved solver state. This
should match the filename created by the save method.
file_path (str, default='') – Directory path where the save file is located. If empty,
looks in the current directory.
Returns:
Dictionary containing the loaded solver state data. This
provides access to all restored parameters and settings.
Return type:
dict
Notes
The base implementation loads common solver attributes. Derived
classes should override this method to restore algorithm-specific
state information:
data = super().importdata(file_name, file_path=file_path)
self.my_specific_param = data[‘my_specific_param’]
# Restore additional algorithm-specific data
return data
The method completely replaces the current solver state with
the loaded configuration, so any existing settings will be lost.
Examples
>>> # Load from current directory>>> data=solver.importdata('solver_state.pkl')>>> print(f"Loaded {len(data)} parameters")
>>> # Load from specific directory>>> data=solver.importdata('state.pkl',file_path='/path/to/files/')>>> print(f"Restored solver configuration from {file_path}")
Raises:
FileNotFoundError – If the specified file does not exist
pickle.UnpicklingError – If the file is corrupted or incompatible
This method serializes the current solver state including all
configuration parameters, algorithm settings, and internal state
to a file. The saved state can later be restored using the
importdata method.
Parameters:
file_path (str, default='') – Base path for saving the solver state. The actual filename
will be constructed by appending the solver’s alias to this
base path. If empty, saves to current directory.
Returns:
Dictionary containing the serialized solver state data.
This includes all necessary information to fully restore
the solver configuration and state.
Return type:
dict
Notes
The base implementation saves common solver attributes. Derived
classes should override this method to include algorithm-specific
state information:
Solve the electromagnetic inverse scattering problem.
This method provides the standard interface for solving inverse
scattering problems using deterministic methods. The base implementation
calls the parent InverseSolver method to handle common setup and
validation tasks.
Parameters:
inputdata (InputData) – Input data object containing:
- scattered_field: Measured scattered field data
- configuration: Problem configuration (frequency, background, etc.)
- resolution: Desired reconstruction resolution
- indicators: Performance metrics to compute
discretization (Discretization) – Discretization object containing:
- elements: Spatial discretization grid
- GS: Scattered field Green’s function matrix
- GD: Domain Green’s function matrix (if needed)
- Methods for field interpolation and imaging
print_info (bool, default=True) – Whether to print algorithm progress and iteration information
during the solving process. Useful for monitoring convergence
and debugging.
print_file (file-like object, default=sys.stdout) – Output stream for printing information. Can be redirected to
files or other output streams as needed.
Returns:
Result object containing reconstruction results and performance
metrics. The specific contents depend on the algorithm
implementation but typically include:
- Reconstructed electromagnetic properties
- Convergence history
- Performance metrics
- Algorithm-specific information
This base implementation performs common setup tasks and validation
that are required by all deterministic solvers. Derived classes
should override this method to implement their specific algorithm
while calling the parent method for initialization:
This class implements a classical nonlinear inverse solver [1]_. The
method is based on coupling forward and inverse solvers in an
iterative process. Therefore, it depends on the definition of a
forward solver implementation and an linear inverse one.
Stop criterion for the algorithm. The algorithm will stop
when the amount of variation from the current iteration in
respect to the last one is below some threshold percentage:
Number of iterations in which it will be accepted a
divergence occurrence, i.e., the new solution has a larger
evaluation than the previous considering the stop criterion
measure.
configuration (configuration.Configuration) – It may be either an object of problem configuration or
a string to a pre-saved file or a 2-tuple with the file
name and path, respectively.
version (str) – A string naming the version of this method. It may be
useful when using different implementation of forward
and inverse solvers.
forward_solver (forward.Forward) – An implementation of the abstract class Forward which
defines a method for computing the total intern field.
inverse_solver (inverse.Inverse) – An implementation of the abstract class Inverse which
defines a method for solving the linear inverse problem.
maximum_iterations (int, default: 10) – Maximum number of iterations.
stopcriterion_measure (float, default: 1e-3) –
Define the measure for stop criterion. The algorithm
will stop when the amount of variation from the current
iteration in respect to the last one is below some
threshold percentage:
This method creates a deep copy of the current solver instance,
including all configuration parameters and settings. The copy
can be used independently without affecting the original solver.
Parameters:
new (Deterministic, optional) – If provided, the current solver’s configuration will be
copied into this existing instance. If None, a new instance
will be created and returned.
Returns:
If new is None, returns a new Deterministic instance with
the same configuration. If new is provided, returns None
and the configuration is copied into the new instance.
This method creates independent copies that can be used for
parallel processing, parameter studies, or comparative analysis
without interference between instances.
The base implementation copies common solver attributes. Derived
classes should override this method to handle algorithm-specific
parameters:
>>> # Copy configuration into existing instance>>> target_solver=Deterministic()>>> solver.copy(target_solver)>>> print(f"Target now has alias: {target_solver.alias}")
>>> # Use for parameter studies>>> solvers=[solver.copy()for_inrange(5)]>>> # Modify each copy independently for different parameters
This method deserializes solver state from a file that was
previously created using the save method. It restores all
configuration parameters, algorithm settings, and internal state
to recreate the exact solver configuration.
Parameters:
file_name (str) – Name of the file containing the saved solver state. This
should match the filename created by the save method.
file_path (str, default='') – Directory path where the save file is located. If empty,
looks in the current directory.
Returns:
Dictionary containing the loaded solver state data. This
provides access to all restored parameters and settings.
Return type:
dict
Notes
The base implementation loads common solver attributes. Derived
classes should override this method to restore algorithm-specific
state information:
data = super().importdata(file_name, file_path=file_path)
self.my_specific_param = data[‘my_specific_param’]
# Restore additional algorithm-specific data
return data
The method completely replaces the current solver state with
the loaded configuration, so any existing settings will be lost.
Examples
>>> # Load from current directory>>> data=solver.importdata('solver_state.pkl')>>> print(f"Loaded {len(data)} parameters")
>>> # Load from specific directory>>> data=solver.importdata('state.pkl',file_path='/path/to/files/')>>> print(f"Restored solver configuration from {file_path}")
Raises:
FileNotFoundError – If the specified file does not exist
pickle.UnpicklingError – If the file is corrupted or incompatible
This method serializes the current solver state including all
configuration parameters, algorithm settings, and internal state
to a file. The saved state can later be restored using the
importdata method.
Parameters:
file_path (str, default='') – Base path for saving the solver state. The actual filename
will be constructed by appending the solver’s alias to this
base path. If empty, saves to current directory.
Returns:
Dictionary containing the serialized solver state data.
This includes all necessary information to fully restore
the solver configuration and state.
Return type:
dict
Notes
The base implementation saves common solver attributes. Derived
classes should override this method to include algorithm-specific
state information:
This method creates a deep copy of the current solver instance,
including all configuration parameters and settings. The copy
can be used independently without affecting the original solver.
Parameters:
new (Deterministic, optional) – If provided, the current solver’s configuration will be
copied into this existing instance. If None, a new instance
will be created and returned.
Returns:
If new is None, returns a new Deterministic instance with
the same configuration. If new is provided, returns None
and the configuration is copied into the new instance.
This method creates independent copies that can be used for
parallel processing, parameter studies, or comparative analysis
without interference between instances.
The base implementation copies common solver attributes. Derived
classes should override this method to handle algorithm-specific
parameters:
>>> # Copy configuration into existing instance>>> target_solver=Deterministic()>>> solver.copy(target_solver)>>> print(f"Target now has alias: {target_solver.alias}")
>>> # Use for parameter studies>>> solvers=[solver.copy()for_inrange(5)]>>> # Modify each copy independently for different parameters
This method deserializes solver state from a file that was
previously created using the save method. It restores all
configuration parameters, algorithm settings, and internal state
to recreate the exact solver configuration.
Parameters:
file_name (str) – Name of the file containing the saved solver state. This
should match the filename created by the save method.
file_path (str, default='') – Directory path where the save file is located. If empty,
looks in the current directory.
Returns:
Dictionary containing the loaded solver state data. This
provides access to all restored parameters and settings.
Return type:
dict
Notes
The base implementation loads common solver attributes. Derived
classes should override this method to restore algorithm-specific
state information:
data = super().importdata(file_name, file_path=file_path)
self.my_specific_param = data[‘my_specific_param’]
# Restore additional algorithm-specific data
return data
The method completely replaces the current solver state with
the loaded configuration, so any existing settings will be lost.
Examples
>>> # Load from current directory>>> data=solver.importdata('solver_state.pkl')>>> print(f"Loaded {len(data)} parameters")
>>> # Load from specific directory>>> data=solver.importdata('state.pkl',file_path='/path/to/files/')>>> print(f"Restored solver configuration from {file_path}")
Raises:
FileNotFoundError – If the specified file does not exist
pickle.UnpicklingError – If the file is corrupted or incompatible
This method serializes the current solver state including all
configuration parameters, algorithm settings, and internal state
to a file. The saved state can later be restored using the
importdata method.
Parameters:
file_path (str, default='') – Base path for saving the solver state. The actual filename
will be constructed by appending the solver’s alias to this
base path. If empty, saves to current directory.
Returns:
Dictionary containing the serialized solver state data.
This includes all necessary information to fully restore
the solver configuration and state.
Return type:
dict
Notes
The base implementation saves common solver attributes. Derived
classes should override this method to include algorithm-specific
state information:
Solve the electromagnetic inverse scattering problem.
This method provides the standard interface for solving inverse
scattering problems using deterministic methods. The base implementation
calls the parent InverseSolver method to handle common setup and
validation tasks.
Parameters:
inputdata (InputData) – Input data object containing:
- scattered_field: Measured scattered field data
- configuration: Problem configuration (frequency, background, etc.)
- resolution: Desired reconstruction resolution
- indicators: Performance metrics to compute
discretization (Discretization) – Discretization object containing:
- elements: Spatial discretization grid
- GS: Scattered field Green’s function matrix
- GD: Domain Green’s function matrix (if needed)
- Methods for field interpolation and imaging
print_info (bool, default=True) – Whether to print algorithm progress and iteration information
during the solving process. Useful for monitoring convergence
and debugging.
print_file (file-like object, default=sys.stdout) – Output stream for printing information. Can be redirected to
files or other output streams as needed.
Returns:
Result object containing reconstruction results and performance
metrics. The specific contents depend on the algorithm
implementation but typically include:
- Reconstructed electromagnetic properties
- Convergence history
- Performance metrics
- Algorithm-specific information
This base implementation performs common setup tasks and validation
that are required by all deterministic solvers. Derived classes
should override this method to implement their specific algorithm
while calling the parent method for initialization:
configuration (string or Configuration:Configuration) – Either a configuration object or a string with the name
of file in which the configuration is saved. In this
case, the file path may also be provided.
configuration_filepath (string, optional) – A string with the path to the configuration file (when
the file name is provided).
Given the configuration information stored in the object, it
computes the incident field matrix considering plane waves in
different from different angles.
Parameters:
resolution (2-tuple) – The image size of D-domain in pixels (y and x).
Returns:
einumpy.ndarray
Incident field matrix. The rows correspond to the points
in the image following C-order and the columns
corresponds to the sources.
Orthogonality Sampling Method for qualitative inverse scattering.
This class implements the Orthogonality Sampling Method (OSM), a qualitative
technique for shape reconstruction based on orthogonality properties of
the scattered field.
Parameters:
alias (str, default='osm') – Alias name for the algorithm.
threshold (float, optional) – Threshold for indicator function.
far_field (bool, optional) – Whether to use far-field approximation.
import_filename (str, optional) – Filename to import algorithm state from.
import_filepath (str, default='') – Path to import file.
This method creates a deep copy of the current solver instance,
including all configuration parameters and settings. The copy
can be used independently without affecting the original solver.
Parameters:
new (Deterministic, optional) – If provided, the current solver’s configuration will be
copied into this existing instance. If None, a new instance
will be created and returned.
Returns:
If new is None, returns a new Deterministic instance with
the same configuration. If new is provided, returns None
and the configuration is copied into the new instance.
This method creates independent copies that can be used for
parallel processing, parameter studies, or comparative analysis
without interference between instances.
The base implementation copies common solver attributes. Derived
classes should override this method to handle algorithm-specific
parameters:
>>> # Copy configuration into existing instance>>> target_solver=Deterministic()>>> solver.copy(target_solver)>>> print(f"Target now has alias: {target_solver.alias}")
>>> # Use for parameter studies>>> solvers=[solver.copy()for_inrange(5)]>>> # Modify each copy independently for different parameters
This method deserializes solver state from a file that was
previously created using the save method. It restores all
configuration parameters, algorithm settings, and internal state
to recreate the exact solver configuration.
Parameters:
file_name (str) – Name of the file containing the saved solver state. This
should match the filename created by the save method.
file_path (str, default='') – Directory path where the save file is located. If empty,
looks in the current directory.
Returns:
Dictionary containing the loaded solver state data. This
provides access to all restored parameters and settings.
Return type:
dict
Notes
The base implementation loads common solver attributes. Derived
classes should override this method to restore algorithm-specific
state information:
data = super().importdata(file_name, file_path=file_path)
self.my_specific_param = data[‘my_specific_param’]
# Restore additional algorithm-specific data
return data
The method completely replaces the current solver state with
the loaded configuration, so any existing settings will be lost.
Examples
>>> # Load from current directory>>> data=solver.importdata('solver_state.pkl')>>> print(f"Loaded {len(data)} parameters")
>>> # Load from specific directory>>> data=solver.importdata('state.pkl',file_path='/path/to/files/')>>> print(f"Restored solver configuration from {file_path}")
Raises:
FileNotFoundError – If the specified file does not exist
pickle.UnpicklingError – If the file is corrupted or incompatible
This method serializes the current solver state including all
configuration parameters, algorithm settings, and internal state
to a file. The saved state can later be restored using the
importdata method.
Parameters:
file_path (str, default='') – Base path for saving the solver state. The actual filename
will be constructed by appending the solver’s alias to this
base path. If empty, saves to current directory.
Returns:
Dictionary containing the serialized solver state data.
This includes all necessary information to fully restore
the solver configuration and state.
Return type:
dict
Notes
The base implementation saves common solver attributes. Derived
classes should override this method to include algorithm-specific
state information:
Solve the electromagnetic inverse scattering problem.
This method provides the standard interface for solving inverse
scattering problems using deterministic methods. The base implementation
calls the parent InverseSolver method to handle common setup and
validation tasks.
Parameters:
inputdata (InputData) – Input data object containing:
- scattered_field: Measured scattered field data
- configuration: Problem configuration (frequency, background, etc.)
- resolution: Desired reconstruction resolution
- indicators: Performance metrics to compute
discretization (Discretization) – Discretization object containing:
- elements: Spatial discretization grid
- GS: Scattered field Green’s function matrix
- GD: Domain Green’s function matrix (if needed)
- Methods for field interpolation and imaging
print_info (bool, default=True) – Whether to print algorithm progress and iteration information
during the solving process. Useful for monitoring convergence
and debugging.
print_file (file-like object, default=sys.stdout) – Output stream for printing information. Can be redirected to
files or other output streams as needed.
Returns:
Result object containing reconstruction results and performance
metrics. The specific contents depend on the algorithm
implementation but typically include:
- Reconstructed electromagnetic properties
- Convergence history
- Performance metrics
- Algorithm-specific information
This base implementation performs common setup tasks and validation
that are required by all deterministic solvers. Derived classes
should override this method to implement their specific algorithm
while calling the parent method for initialization:
Processing strategy for stochastic method results.
Defines how multiple execution results are combined into a single
output result.
Parameters:
rule ({'each', 'best', 'worst', 'average'}) – Processing rule:
- ‘each’: Return all individual results
- ‘best’: Return the result with best reference indicator
- ‘worst’: Return the result with worst reference indicator
- ‘average’: Return averaged results using reference indicator
reference (str, optional) – Indicator name used for best/worst/average selection (required
unless rule=’each’).
sample_rate (float, default=5) – Sampling rate for averaging (0-100%).
Reflects values that fall outside [0, 1] back into the range using
a reflection strategy. Values are reflected multiple times if needed.
Notes
This boundary handling strategy preserves the interval [0, 1] by
reflecting out-of-bounds values back into the valid range using
a mirroring technique.
Storage and analysis class for electromagnetic inverse scattering results.
This class provides comprehensive storage and analysis capabilities for results
from electromagnetic inverse scattering algorithms. It stores reconstructed
fields, material properties, and various error metrics, while providing
sophisticated plotting and analysis tools.
The class supports multiple error indicators for quantitative evaluation of
reconstruction quality, including residual norm errors, percentage average
deviation (PAD) errors, and shape/position analysis. It also provides
extensive plotting capabilities for visualizing reconstructed images and
convergence behavior.
>>> importresultasrst>>> importnumpyasnp>>>>>> # Create result object>>> result=rst.Result(name='csi_reconstruction')>>>>>> # Store reconstruction data>>> result.rel_permittivity=np.random.rand(64,64)*2+1>>> result.conductivity=np.random.rand(64,64)*0.1>>>>>> # Update with error metrics>>> result.zeta_rn.append(1e-3)>>> result.zeta_epad.append(15.5)>>>>>> # Plot results>>> result.plot_map(image=rst.BOTH_PROPERTIES,show=True)>>> result.plot_convergence(show=True)>>>>>> # Save results>>> result.save(file_path='/path/to/results/')
Notes
The class automatically computes various error metrics when the
update_error() method is called with appropriate input data
and ground truth information. Error metrics are stored as lists
to track evolution during iterative reconstruction processes.
Initialize a Result object for storing reconstruction results.
Creates a new Result object to store electromagnetic inverse scattering
reconstruction results. The object can be initialized with reconstruction
data directly or loaded from a previously saved file.
Parameters:
name (str, optional) – Unique identifier for this result. Required if not loading from file.
Typically combines method name, input data, and configuration info.
method_name (str, optional) – Name of the reconstruction method that generated this result.
Examples: ‘CSI’, ‘DBIM’, ‘Born’, ‘Gauss-Newton’.
configuration (configuration.Configuration, optional) – Problem configuration object containing frequency, geometry, and
material parameters used in the reconstruction.
scattered_field (numpy.ndarray, optional) – Computed scattered field at measurement points.
Shape: (N_measurements, N_sources). Units: [V/m].
total_field (numpy.ndarray, optional) – Reconstructed total field in the investigation domain.
Shape: (N_pixels, N_sources). Units: [V/m].
FileNotFoundError – If import_filename is specified but file cannot be found.
Examples
>>> # Create new result object>>> result=Result(name='csi_test',method_name='CSI')>>>>>> # Create with reconstruction data>>> result=Result(... name='dbim_reconstruction',... method_name='DBIM',... rel_permittivity=epsilon_r_map,... conductivity=sigma_map,... execution_time=45.2... )>>>>>> # Load from saved file>>> result=Result(import_filename='saved_result.pkl')
Notes
If import_filename is provided, the object is initialized from the
saved file and all other parameters are ignored. Otherwise, a new
object is created with the provided parameters.
All error metric lists (zeta_*) are initialized as empty lists
and can be populated using the update_error() method.
Return a comprehensive string representation of the Result object.
Generates a detailed text summary of the Result object including all
reconstruction data, error metrics, and algorithm performance statistics.
This method provides a human-readable overview of the complete result.
Returns:
Multi-line string containing:
- Result name and configuration
- Field data dimensions and resolution
- Material property map resolutions
- Execution time and performance metrics
- Complete error metric histories with formatting
- Algorithm iteration and evaluation counts
Create a deep copy of the Result object or copy data from another Result.
Creates a complete deep copy of the current Result object with all
reconstruction data and error metrics, or copies data from another
Result object into the current one. This method is useful for creating
backups or comparing different reconstruction results.
Parameters:
new (Result, optional) – If provided, copies data from this Result object into the current
object, overwriting existing data. If None, creates a new Result
object as a copy of the current one.
Returns:
If new is None, returns a new Result object containing a deep copy
of all data. If new is provided, returns None and modifies the
current object in-place.
Get the final (most recent) value of a specific error indicator.
Retrieves the last computed value from the specified error indicator’s
history. This method is useful for accessing the final reconstruction
quality metrics after algorithm completion.
Parameters:
indicator (str) – Name of the error indicator to retrieve. Must be a valid indicator
constant such as ‘zeta_rn’, ‘zeta_epad’, ‘zeta_sad’, etc.
Use valid_indicators() to see available indicators.
Returns:
The final (most recent) value of the specified indicator.
For list-type indicators, returns the last element.
For scalar indicators, returns the scalar value.
>>> result=Result(name='test')>>> result.zeta_rn=[1e-2,5e-3,1e-3]>>> result.zeta_epad=[25.0,15.0,8.5]>>>>>> # Get final residual norm error>>> final_rn=result.final_value('zeta_rn')>>> print(f"Final residual norm: {final_rn:.3e}")Final residual norm: 1.000e-03>>>>>> # Get final permittivity error>>> final_epad=result.final_value('zeta_epad')>>> print(f"Final permittivity PAD: {final_epad:.1f}%")Final permittivity PAD: 8.5%>>>>>> # Error handling>>> try:... result.final_value('invalid_indicator')... excepterror.WrongValueInputase:... print(f"Error: {e}")
Notes
This method assumes that the indicator has been computed and contains
at least one value. If the indicator list is empty, IndexError will
be raised when trying to access the last element.
Restores a previously saved Result object by loading all reconstruction
data, error metrics, and configuration information from a pickle file.
Parameters:
file_name (str) – Name of the pickle file containing the saved Result object.
file_path (str, optional) – Directory path containing the file. Default is current directory.
Raises:
FileNotFoundError – If the specified file cannot be found.
pickle.UnpicklingError – If the file cannot be unpickled or contains invalid data.
Examples
>>> result=Result(name='empty')>>> result.importdata('saved_result.pkl','/path/to/results/')>>> print(result.name)# Will show the name from saved file>>> print(result.rel_permittivity.shape)# Access loaded data
Notes
This method completely overwrites the current object state with
data from the saved file. Any existing data in the object is lost.
Generate a formatted summary of the latest error metrics.
Creates a comprehensive text summary of the most recent error indicator
values for display or logging purposes. This method is typically used
to provide concise status updates during iterative reconstruction processes.
Parameters:
pre_message (str, optional) – Custom prefix message to prepend to the error summary.
If None, uses default prefix “Indicators:”.
Returns:
Formatted string containing the latest values of all available
error indicators. Format: “Indicators: Residual norm: 1.23e-4,
Residual PAD: 12.34%, Rel. Per. PAD: 8.56%, …”
Return type:
str
Notes
Only error indicators that have been computed (non-empty lists) are
included in the summary. The formatting is optimized for readability
with appropriate precision for each metric type:
Residual norm errors: scientific notation with 3 decimal places
Percentage errors: fixed point with 2 decimal places + % symbol
Regularization metrics: fixed point with 2 decimal places
Plot convergence curves for error indicators over iterations.
Creates line plots showing the evolution of error metrics during the
iterative reconstruction process. Supports multiple indicators in
separate subplots with customizable styling and formatting.
Parameters:
axis (matplotlib.axes.Axes or numpy.ndarray, optional) – Pre-existing axes for plotting. If None, new figure is created.
For multiple indicators, provide array of axes objects.
indicators (str, list of str, or None, optional) – Error indicators to plot. If None, plots all valid indicators.
If string, plots single indicator. If list, plots multiple indicators.
Valid indicators are returned by valid_indicators().
show (bool, optional) – If True, display the plot window. Default is False.
file_name (str, optional) – Filename for saving the figure (without extension). If None,
figure is not saved. Default is None.
file_path (str, optional) – Directory path for saving the figure. Default is current directory.
file_format (str, optional) – File format for saving (‘eps’, ‘png’, ‘pdf’, etc.). Default is ‘eps’.
fontsize (int, optional) – Font size for labels and titles. Default is 10.
title (str, list of str, or None, optional) – Plot title(s). If None, uses standard titles. If string, uses
same title for all plots. If list, uses separate titles for each plot.
style (str, optional) – Line style for plots (matplotlib format). Default is ‘–*’.
yscale (str, list of str, or None, optional) – Y-axis scale (‘linear’, ‘log’, ‘symlog’, etc.). If None, uses
linear scale. If string, uses same scale for all plots. If list,
uses separate scales for each plot.
markersize (float, optional) – Size of markers in the plot. Default is None (matplotlib default).
Returns:
fig (matplotlib.figure.Figure) – Figure object (only if axis is None and show=False and file_name=None).
ax (numpy.ndarray) – Array of axes objects (only if axis is None and show=False and file_name=None).
Raises:
error.WrongValueInput – If provided axis array size doesn’t match number of indicators.
Examples
>>> # Plot all available indicators>>> result.plot_convergence(show=True)>>>>>> # Plot specific indicators with logarithmic scale>>> result.plot_convergence(... indicators=['zeta_rn','zeta_epad'],... yscale='log',... show=True... )>>>>>> # Save convergence plot>>> result.plot_convergence(... file_name='convergence_plot',... file_path='/path/to/figures/',... file_format='png'... )>>>>>> # Custom styling>>> result.plot_convergence(... style='-o',... markersize=6,... fontsize=12,... title='Algorithm Convergence',... show=True... )
Notes
X-axis represents iteration numbers starting from 1
Each indicator is plotted in a separate subplot
Grid is enabled for all plots to improve readability
Automatic titles are generated based on indicator types
Supports both linear and logarithmic y-axis scaling
Creates visualizations of reconstructed material properties and field
distributions with optional ground truth comparison. Supports various
image types including permittivity, conductivity, contrast, and total field.
Parameters:
axis (matplotlib.axes.Axes or numpy.ndarray, optional) – Pre-existing axes for plotting. If None, new figure is created.
For multiple plots, provide array of axes objects.
image (str, optional) – Type of image to plot. Options: ‘contrast’, ‘epsilon_r’, ‘sigma’,
‘both’, ‘total field’. Default is ‘contrast’.
groundtruth (inputdata.InputData, optional) – Ground truth data for comparison plotting. If provided, both
ground truth and reconstructed images are displayed.
title (str, list, or bool, optional) – Plot title(s). If list, separate titles for each subplot.
If False, no titles are shown. Default is None (automatic titles).
show (bool, optional) – If True, display the plot window. Default is False.
save (bool, optional) – If True, save the figure to file. Default is False.
file_path (str, optional) – Directory path for saving the figure. Default is current directory.
file_format (str, optional) – File format for saving (‘eps’, ‘png’, ‘pdf’, etc.). Default is ‘eps’.
fontsize (int, optional) – Font size for labels and titles. Default is 10.
file_name (str, optional) – Custom filename for saving. If None, uses object name. Default is None.
source (int, list, or None, optional) – Source indices for total field plotting. If None, plots all sources.
For int, plots single source. For list, plots multiple sources.
interpolation (str, optional) – Interpolation method for imshow (‘nearest’, ‘bilinear’, etc.).
Default is None (matplotlib default).
Returns:
fig (matplotlib.figure.Figure) – Figure object (only if show=False and save=False).
ax (numpy.ndarray) – Array of axes objects (only if show=False and save=False).
>>> # Plot contrast map>>> result.plot_map(image='contrast',show=True)>>>>>> # Plot both properties with ground truth>>> result.plot_map(image='both',groundtruth=input_data,... title=['Ground Truth','Reconstructed'],show=True)>>>>>> # Plot total field for specific source>>> result.plot_map(image='total field',source=0,show=True)>>>>>> # Save high-resolution figure>>> result.plot_map(image='epsilon_r',save=True,file_format='png',... file_path='/path/to/figures/',fontsize=14)
Notes
Spatial coordinates are normalized by background wavelength λ_b
Color bars are automatically added with appropriate units
Ground truth comparison creates side-by-side plots
Total field plotting supports multiple sources
Images are displayed with ‘lower’ origin (bottom-left corner)
Serializes the complete Result object including all reconstruction data
and error metrics to a pickle file for later loading and analysis.
Parameters:
file_path (str, optional) – Directory path where the file will be saved. The file is saved
with the object’s name as the filename. Default is current directory.
Notes
The saved file contains all reconstruction results, error metrics,
and configuration information. The file can be loaded later using
the importdata() method or by initializing a new Result object
with the import_filename parameter.
Compute and update error metrics for reconstruction quality assessment.
Calculates various error indicators based on the specified input data
indicators and updates the corresponding error metric lists. This method
is typically called during iterative reconstruction to track convergence
and quality metrics.
Parameters:
inputdata (inputdata.InputData) – Input data object containing ground truth information and indicator
specifications. The indicators attribute determines which error
metrics will be computed.
scattered_field (numpy.ndarray, optional) – Computed scattered field for comparison with measured data.
Shape: (N_measurements, N_sources). Units: [V/m].
Required for residual norm and PAD error calculations.
total_field (numpy.ndarray, optional) – Reconstructed total field distribution.
Shape: (N_pixels, N_sources). Units: [V/m].
Required for total field error calculations.
contrast (numpy.ndarray, optional) – Reconstructed contrast function.
Shape: (N_x, N_y). Complex-valued.
Alternative to providing separate permittivity and conductivity.
objective_function (float, optional) – Current objective function value for tracking convergence.
Permittivity Errors:
- REL_PERMITTIVITY_PAD_ERROR: Percentage average deviation of permittivity
- REL_PERMITTIVITY_BACKGROUND_ERROR: Background region permittivity error
- REL_PERMITTIVITY_OBJECT_ERROR: Object region permittivity error
- SSIM_ERROR: Structural Similarity Index Measure between true and reconstructed permittivity
Conductivity Errors:
- CONDUCTIVITY_AD_ERROR: Average deviation of conductivity
- CONDUCTIVITY_BACKGROUND_ERROR: Background region conductivity error
- CONDUCTIVITY_OBJECT_ERROR: Object region conductivity error
Shape and Position Errors:
- SHAPE_ERROR: Percentage difference in reconstructed object shape
- POSITION_ERROR: Percentage difference in reconstructed object position
Regularization Metrics:
- TOTAL_VARIATION: Total variation of the reconstructed contrast
Total Field Errors:
- TOTALFIELD_MAGNITUDE_PAD: Magnitude percentage average deviation
- TOTALFIELD_PHASE_AD: Phase average deviation
Identify which error indicators have been computed and contain data.
Examines all error metric attributes to determine which indicators have
been calculated and contain valid data. This method is used internally
for plotting and analysis functions to determine which metrics are
available for display.
Returns:
List of indicator names (constants) that have been computed and
contain at least one data point. Possible indicators include:
RESIDUAL_NORM_ERROR: Residual norm error
RESIDUAL_PAD_ERROR: Residual percentage average deviation
REL_PERMITTIVITY_PAD_ERROR: Permittivity PAD error
TOTAL_VARIATION: Total variation regularization metric
TOTALFIELD_MAGNITUDE_PAD: Total field magnitude PAD
TOTALFIELD_PHASE_AD: Total field phase average deviation
OBJECTIVE_FUNCTION: Objective function values
Return type:
list of str
Notes
This method checks both that the attribute exists (is not None) and
that it contains data (length > 0). Empty lists are considered invalid
indicators and are excluded from the results.
Examples
>>> result=Result(name='test')>>> result.zeta_rn=[1e-3,5e-4]>>> result.zeta_epad=[20.5,15.2]>>> result.zeta_sad=[]# Empty list>>>>>> indicators=result.valid_indicators()>>> print(indicators)['zeta_rpad', 'zeta_epad'] # Only non-empty indicators>>>>>> # Use with plotting>>> result.plot_convergence(indicators=result.valid_indicators())
Richmond discretization method for electromagnetic inverse scattering.
Implements the Richmond discretization method, which is a specific case of
the collocation method using pulse basis functions. This method is widely
used in electromagnetic inverse scattering for its simplicity and numerical
stability, particularly when dealing with the singularities in the Green’s
function integrals.
The Richmond method approximates the scattered field using:
- Pulse basis functions for the contrast function
- Collocation points at the center of each discretization cell
- Analytical treatment of the Green’s function singularity
Parameters:
configuration (Configuration) – Problem configuration object.
elements (int or tuple of int) – Number of discretization elements. If int, creates square grid (N×N).
If tuple, creates rectangular grid (NY×NX).
state (bool, default: True) – If True, computes the state-space Green’s function matrix (GD).
alias (str, default: 'ric') – Short alias for the method.
import_filename (str, optional) – Filename to import configuration from.
import_filepath (str, default='') – Path to import file.
The Green’s function matrices are computed using the analytical formulas
from Richmond’s method, which handles the singularity at the origin
by using the small-argument approximation of the Hankel function.
This method converts the discrete contrast function coefficients
from the discretization basis to a regular image grid at the
specified resolution. This is useful for visualization and
analysis of reconstruction results.
Parameters:
coefficients (array_like) – Contrast function coefficients at discretization points,
typically obtained from solving the inverse problem
resolution (array_like or tuple) – Desired image resolution as (nx, ny) where nx and ny are
the number of pixels in x and y directions respectively
Returns:
2D array representing the contrast function image with
shape matching the specified resolution
Return type:
array_like
Notes
The conversion process typically involves:
1. Interpolation from discretization points to image grid
2. Proper handling of boundary conditions
3. Scaling and normalization if needed
The image format allows for easy visualization and comparison
with reference solutions or other reconstruction methods.
Examples
>>> # Convert to 64x64 image>>> image=discretization.contrast_image(... coefficients=solution_coeffs,... resolution=(64,64)... )>>>>>> # Display the reconstruction>>> importmatplotlib.pyplotasplt>>> plt.imshow(image.real,cmap='jet')>>> plt.title('Reconstructed Contrast Function')
Compute residual for the state equation using Richmond discretization.
Parameters:
incident_field (array_like) – Incident electric field.
contrast (array_like, optional) – Contrast function values.
total_field (array_like, optional) – Total electric field.
current (array_like, optional) – Contrast source (current).
Returns:
Residual vector.
Return type:
array_like
Notes
The residual depends on the parameters provided:
- If current is None: \(\text{res} = E^t - E^i - G^D \chi E^t\)
- If current is provided: \(\text{res} = J - \chi E^i - \chi G^D J\)
Compute scattered field from scatterer properties.
This method computes the scattered electric field at receiver locations
given the scatterer properties (contrast function, total field, or
current source). This is the forward scattering operation.
The scattered field is computed using:
.. math:
E^s=G^sJ
where \(G^s\) is the scattered field Green’s function matrix and
\(J\) is the contrast source.
Parameters:
contrast (array_like, optional) – Contrast function values at discretization points. Required
if total_field is provided.
total_field (array_like, optional) – Total electric field at discretization points. Required
if contrast is provided.
current (array_like, optional) – Contrast source (current) at discretization points. Alternative
to providing contrast and total_field separately.
Returns:
Scattered electric field at receiver locations
Return type:
array_like
Raises:
MissingInputError – If required parameter combinations are not provided
Notes
The method requires either:
- Both contrast and total_field parameters, or
- The current parameter alone
If contrast and total_field are provided, the current source is
computed as J = chi E^t, then used to calculate the scattered field.
Examples
>>> # Using contrast and total field>>> scattered=discretization.scattered_field(... contrast=contrast_values,... total_field=total_field_values... )
>>> # Using current directly>>> scattered=discretization.scattered_field(... current=current_source... )
Solve the linear inverse scattering problem using Richmond discretization.
Parameters:
scattered_field (array_like, optional) – Measured scattered field data.
incident_field (array_like, optional) – Incident electric field.
contrast (array_like, optional) – Contrast function values.
total_field (array_like, optional) – Total electric field.
current (array_like, optional) – Contrast source.
linear_solver (Regularization, optional) – Regularization method for solving the linear system.
Returns:
Reconstructed contrast function or field coefficients.
Return type:
array_like
Notes
The method can solve for:
- Contrast function X: requires scattered_field and total_field
- Total field E: requires scattered_field and contrast
- Current source J: requires scattered_field
- Other combinations for state-space problems.
This method converts the discrete total field coefficients
from the discretization basis to a regular image grid at the
specified resolution. This is useful for visualization and
analysis of field distributions.
Parameters:
coefficients (array_like) – Total field coefficients at discretization points,
typically obtained from solving the forward problem
resolution (array_like or tuple) – Desired image resolution as (nx, ny) where nx and ny are
the number of pixels in x and y directions respectively
Returns:
2D array representing the total field image with
shape matching the specified resolution
Return type:
array_like
Notes
The conversion process typically involves:
1. Interpolation from discretization points to image grid
2. Proper handling of boundary conditions
3. Phase and amplitude representation
4. Scaling and normalization if needed
The image format allows for visualization of field patterns
and understanding of scattering behavior.
Examples
>>> # Convert to 128x128 image>>> field_image=discretization.total_image(... coefficients=field_coeffs,... resolution=(128,128)... )>>>>>> # Display field magnitude>>> importmatplotlib.pyplotasplt>>> plt.imshow(np.abs(field_image),cmap='viridis')>>> plt.title('Total Field Magnitude')
Creates offspring by simulating the behavior of binary crossover
in real-valued spaces. The distribution index eta controls the
spread of offspring around parents.
Parameters:
eta (float) – Distribution index. Higher values produce offspring closer to parents.
Notes
SBX is commonly used in real-coded genetic algorithms and produces
offspring with a probability distribution that mimics binary crossover.
Base class for stochastic inverse scattering solvers.
This class provides the foundation for stochastic inverse scattering
methods in the eispy2d library. Stochastic solvers use random processes
during execution and may produce different results on different runs
even with identical inputs.
Initialize stopping criteria for iterative algorithms.
Parameters:
max_evaluations (int, optional) – Maximum number of objective function evaluations.
max_iterations (int, optional) – Maximum number of iterations.
max_evals_woimp (int, optional) – Maximum number of evaluations without improvement.
max_iter_woimp (int, optional) – Maximum number of iterations without improvement.
cost_function_threshold (float, optional) – Threshold for the objective function value.
improvement_threshold (float, optional) – Minimum relative improvement (percentage) to be considered as
improvement. Required if max_evals_woimp or max_iter_woimp is set.
Raises:
Error – If no stopping criterion is provided, or if improvement_threshold
is missing when using improvement-based criteria.
MissingInputError – If improvement_threshold is missing when required.
This class implements a classical nonlinear inverse solver [1]_. The
method is based on coupling forward and inverse solvers in an
iterative process. Therefore, it depends on the definition of a
forward solver implementation and an linear inverse one.
Stop criterion for the algorithm. The algorithm will stop
when the amount of variation from the current iteration in
respect to the last one is below some threshold percentage:
Number of iterations in which it will be accepted a
divergence occurrence, i.e., the new solution has a larger
evaluation than the previous considering the stop criterion
measure.
configuration (configuration.Configuration) – It may be either an object of problem configuration or
a string to a pre-saved file or a 2-tuple with the file
name and path, respectively.
version (str) – A string naming the version of this method. It may be
useful when using different implementation of forward
and inverse solvers.
forward_solver (forward.Forward) – An implementation of the abstract class Forward which
defines a method for computing the total intern field.
inverse_solver (inverse.Inverse) – An implementation of the abstract class Inverse which
defines a method for solving the linear inverse problem.
maximum_iterations (int, default: 10) – Maximum number of iterations.
stopcriterion_measure (float, default: 1e-3) –
Define the measure for stop criterion. The algorithm
will stop when the amount of variation from the current
iteration in respect to the last one is below some
threshold percentage:
This method creates a deep copy of the current solver instance,
including all configuration parameters and settings. The copy
can be used independently without affecting the original solver.
Parameters:
new (Deterministic, optional) – If provided, the current solver’s configuration will be
copied into this existing instance. If None, a new instance
will be created and returned.
Returns:
If new is None, returns a new Deterministic instance with
the same configuration. If new is provided, returns None
and the configuration is copied into the new instance.
This method creates independent copies that can be used for
parallel processing, parameter studies, or comparative analysis
without interference between instances.
The base implementation copies common solver attributes. Derived
classes should override this method to handle algorithm-specific
parameters:
>>> # Copy configuration into existing instance>>> target_solver=Deterministic()>>> solver.copy(target_solver)>>> print(f"Target now has alias: {target_solver.alias}")
>>> # Use for parameter studies>>> solvers=[solver.copy()for_inrange(5)]>>> # Modify each copy independently for different parameters
This method deserializes solver state from a file that was
previously created using the save method. It restores all
configuration parameters, algorithm settings, and internal state
to recreate the exact solver configuration.
Parameters:
file_name (str) – Name of the file containing the saved solver state. This
should match the filename created by the save method.
file_path (str, default='') – Directory path where the save file is located. If empty,
looks in the current directory.
Returns:
Dictionary containing the loaded solver state data. This
provides access to all restored parameters and settings.
Return type:
dict
Notes
The base implementation loads common solver attributes. Derived
classes should override this method to restore algorithm-specific
state information:
data = super().importdata(file_name, file_path=file_path)
self.my_specific_param = data[‘my_specific_param’]
# Restore additional algorithm-specific data
return data
The method completely replaces the current solver state with
the loaded configuration, so any existing settings will be lost.
Examples
>>> # Load from current directory>>> data=solver.importdata('solver_state.pkl')>>> print(f"Loaded {len(data)} parameters")
>>> # Load from specific directory>>> data=solver.importdata('state.pkl',file_path='/path/to/files/')>>> print(f"Restored solver configuration from {file_path}")
Raises:
FileNotFoundError – If the specified file does not exist
pickle.UnpicklingError – If the file is corrupted or incompatible
This method serializes the current solver state including all
configuration parameters, algorithm settings, and internal state
to a file. The saved state can later be restored using the
importdata method.
Parameters:
file_path (str, default='') – Base path for saving the solver state. The actual filename
will be constructed by appending the solver’s alias to this
base path. If empty, saves to current directory.
Returns:
Dictionary containing the serialized solver state data.
This includes all necessary information to fully restore
the solver configuration and state.
Return type:
dict
Notes
The base implementation saves common solver attributes. Derived
classes should override this method to include algorithm-specific
state information:
Save the problem configuration within a pickle file.
It will only be saved the attribute variables, not the object
itself. If you want to load these variables, you may use the
constant string variables for a more friendly usage.
choice (int, float, or {'fixed', 'mozorov', 'lcurve'}) – Regularization parameter selection strategy:
- If int or float: fixed regularization parameter value.
- ‘fixed’: use a fixed parameter value (must provide parameter).
- ‘mozorov’: use Morozov’s discrepancy principle.
- ‘lcurve’: use L-curve criterion.
parameter (float, optional) – Fixed regularization parameter value (required if choice=’fixed’).
Solve the linear system using Tikhonov regularization.
Parameters:
K (numpy.ndarray) – Coefficient matrix (kernel) with shape (M, N).
y (numpy.ndarray) – Right-hand side vector or matrix with shape (M,) or (M, P).
Returns:
Solution vector or matrix with shape (N,) or (N, P).
Return type:
numpy.ndarray
Notes
The solution is computed as:
- For fixed parameter: \(x = (K^*K + \alpha I)^{-1}K^*y\)
- For Morozov: automatically selects \(\alpha\) using discrepancy principle
- For L-curve: automatically selects \(\alpha\) using L-curve criterion
axis_length_x (float, default: 2.0) – Length of the size of the image.
axis_length_y (float, default: 2.0) – Length of the size of the image.
resolution (2-tuple) – Image resolution, in y and x directions, i.e., (NY, NX).
Either this argument or rel_permittivity or
conductivity must be given!
background_rel_permittivity (float, default: 1.0)
background_conductivity (float, default: 0.0)
object_rel_permittivity (float, default: 1.0)
object_conductivity (float, default: 0.0)
center (list, default: [0.0, 0.0]) – Center of the object in the image. The center of the image
corresponds to the origin of the coordinates.
rel_permittivity (numpy.ndarray, default:None) – A predefined image in which the object will be drawn.
conductivity (numpy.ndarray, default:None) – A predefined image in which the object will be drawn.
This routine plots a figure comparing the confidence interval of
means among samples. The confidence intervals are computed at a
0.95 confidence level. This routine does not show any plot. It only
draws the graphic.
Parameters:
data (either numpy.ndarray or list) – A 2-d array with the samples in which each column is a
single sample or a list of 1-d arrays.
axes (matplotlib.Axes.axes, default: None) – A specified axes for plotting the graphics. If none is
provided, then one will be created and returned.
title (str, default: None) – A possible title to the plot.
xlabel (str, default: None) – The label of the x-axis which represent the unit of the
data.
ylabel (list of str, default: None) – A list with the name of the samples.
axis_length_x (float, default: 2.0) – Length of the size of the image.
axis_length_y (float, default: 2.0) – Length of the size of the image.
resolution (2-tuple) – Image resolution, in y and x directions, i.e., (NY, NX).
Either this argument or rel_permittivity or
conductivity must be given!
background_rel_permittivity (float, default: 1.0)
background_conductivity (float, default: 0.0)
object_rel_permittivity (float, default: 1.0)
object_conductivity (float, default: 0.0)
center (list, default: [0.0, 0.0]) – Center of the object in the image. The center of the image
corresponds to the origin of the coordinates.
rel_permittivity (numpy.ndarray, default:None) – A predefined image in which the object will be drawn.
conductivity (numpy.ndarray, default:None) – A predefined image in which the object will be drawn.
rotate (float, default: 0.0 degrees) – Rotation of the object around its center. In degrees.
Perform all-to-one comparisons through Dunnett’s test.
The Dunnett’s test is a procedure for comparing a set of \(a-1\)
treatments against a single one called the control group [1]_. The
test is a modification of the usual t-test where, in each
comparison, the null hypothesis is the equality of means. The
significance level is fixed in 0.05.
Parameters:
y0 (numpy.ndarray) – Control sample (1-d array).
y (list or numpy.ndarray) – \(a-1\) treatments to be compared. The argument must be
either a list of Numpy arrays or a matrix with shape
(a-1, n).
Returns:
null_hypothesislist of bool
List of boolean values indicating the result of the null
hypothesis. If True, it means that the test has failed in
rejecting the null hypothesis. If False, then the null
hypothesis of equality of means for the respective
comparison has been reject at a 0.05 significance level.
axis_length_x (float, default: 2.0) – Length of the size of the image.
axis_length_y (float, default: 2.0) – Length of the size of the image.
resolution (2-tuple) – Image resolution, in y and x directions, i.e., (NY, NX).
Either this argument or rel_permittivity or
conductivity must be given!
background_rel_permittivity (float, default: 1.0)
background_conductivity (float, default: 0.0)
object_rel_permittivity (float, default: 1.0)
object_conductivity (float, default: 0.0)
center (list, default: [0.0, 0.0]) – Center of the object in the image. The center of the image
corresponds to the origin of the coordinates.
rel_permittivity (numpy.ndarray, default:None) – A predefined image in which the object will be drawn.
conductivity (numpy.ndarray, default:None) – A predefined image in which the object will be drawn.
rotate (float, default: 0.0 degrees) – Rotation of the object around its center. In degrees.
Given a data set with some amount of factors and levels, the method
performs the factorial analysis in order to find evidences for
impact of single factors (main effects) and combination among them
(interaction effects) [1]_.
In this current version, it only supports two or three factors and
balanced data.
Parameters:
data (numpy.ndarray) – The data set in array format in which each dimension
represents a factor and the number of elements represents
the number of levels of respective factor. The shape must be
either (a, b, n), for two-factors, or (a, b, c, n), for
three factors. Obs.: the last dimension is the number of
samples for each combination of factors-levels.
group_names (list, default: None) – Factor names for plot purposes.
ylabel (str) – Y-axis label for plot purposes (meaning of the data).
Returns:
null_hypothesislist
The list with the results of the null hypothesis of the
statistic tests. If True, means that the test failed to
reject the null hypothesis; if False, means the null
hypothesis was rejected. For two-factor anaylsis, the each
element represents the test on the following factors
[A, B, AB]. For three-factor,
[A, B, C, AB, AC, BC, ABC].
pvalueslist
The list with the p-values of each test. The order follows
the same defined for null_hypothesis.
shapiro_pvalue: float
The p-value of the Shapiro-Wilk’s test for normality of
residuals assumption. A p-value less than 0.05 means the
rejection of the assumption.
fligner_pvalue: float
The p-value of the Fligner-Killen’s test for homoscedascity
(variance equality) of samples. A p-value less than 0.05
means the rejection of the assumption.
figmatplotlib.figure.Figure
A plot showing the normality and homoscedascity assumption.
The graphic way to anaylise the assumptions.
transformationNone or str
If None, no transformation was applied on the data in
order to fix it for following the assumption. Otherwise,
it is a string saying the type of transformation.
Graphic investigation of homoscedasticity assumption.
This routine plots a figure comparing variance of samples for the
purpose of investigating the assumption of homoscedasticity
(samples with equal variance). Each samples is positioned in the
x-axis in the correspondent value of its own mean. This routine does
not show any plot. It only draws the graphic.
Parameters:
data (either numpy.ndarray or list) – A 2-d array with the samples in which each row is a single
sample or a list of 1-d arrays.
axes (matplotlib.Axes.axes, default: None) – A specified axes for plotting the graphics. If none is
provided, then one will be created and returned.
title (str, default: None) – A possible title to the plot.
ylabel (str, default: None) – The label of the y-axis which represent the unit of the
data.
names (list of str, default: None) – A list with the name of the samples for legend purpose.
axis_length_x (float, default: 2.0) – Length of the size of the image.
axis_length_y (float, default: 2.0) – Length of the size of the image.
resolution (2-tuple) – Image resolution, in y and x directions, i.e., (NY, NX).
Either this argument or rel_permittivity or
conductivity must be given!
background_rel_permittivity (float, default: 1.0)
background_conductivity (float, default: 0.0)
object_rel_permittivity (float, default: 1.0)
object_conductivity (float, default: 0.0)
center (list, default: [0.0, 0.0]) – Center of the object in the image. The center of the image
corresponds to the origin of the coordinates.
rel_permittivity (numpy.ndarray, default:None) – A predefined image in which the object will be drawn.
conductivity (numpy.ndarray, default:None) – A predefined image in which the object will be drawn.
rotate (float, default: 0.0 degrees) – Rotation of the object around its center. In degrees.
This routine plots a figure comparing a sample to a standard normal
distribution for the purpose of investigating the assumption of
normality. This routine does not show any plot. It only draws the
graphic.
Parameters:
data (numpy.ndarray) – An 1-d array representing the sample.
axes (matplotlib.Axes.axes, default: None) – A specified axes for plotting the graphics. If none is
provided, then one will be created and returned.
title (str, default: None) – A possible title to the plot.
axis_length_x (float, default: 2.0) – Length of the size of the image.
axis_length_y (float, default: 2.0) – Length of the size of the image.
resolution (2-tuple) – Image resolution, in y and x directions, i.e., (NY, NX).
Either this argument or rel_permittivity or
conductivity must be given!
background_rel_permittivity (float, default: 1.0)
background_conductivity (float, default: 0.0)
object_rel_permittivity (float, default: 1.0)
object_conductivity (float, default: 0.0)
center (list, default: [0.0, 0.0]) – Center of the object in the image. The center of the image
corresponds to the origin of the coordinates.
rel_permittivity (numpy.ndarray, default:None) – A predefined image in which the object will be drawn.
conductivity (numpy.ndarray, default: None) – A predefined image in which the object will be drawn.
rotate (float, default: 0.0 degrees) – Rotation of the object around its center. In degrees.
radius (float) – Radius from the center to each vertex.
axis_length_x (float, default: 2.0) – Length of the size of the image.
axis_length_y (float, default: 2.0) – Length of the size of the image.
resolution (2-tuple) – Image resolution, in y and x directions, i.e., (NY, NX).
Either this argument or rel_permittivity or
conductivity must be given!
background_rel_permittivity (float, default: 1.0)
background_conductivity (float, default: 0.0)
object_rel_permittivity (float, default: 1.0)
object_conductivity (float, default: 0.0)
center (list, default: [0.0, 0.0]) – Center of the object in the image. The center of the image
corresponds to the origin of the coordinates.
rel_permittivity (numpy.ndarray, default:None) – A predefined image in which the object will be drawn.
conductivity (numpy.ndarray, default:None) – A predefined image in which the object will be drawn.
rotate (float, default: 0.0 degrees) – Rotation of the object around its center. In degrees.
number_sides (int) – Number of sides of the polygon.
maximum_radius (float) – Maximum radius from the origin to each vertex.
axis_length_x (float, default: 2.0) – Length of the size of the image.
axis_length_y (float, default: 2.0) – Length of the size of the image.
resolution (2-tuple) – Image resolution, in y and x directions, i.e., (NY, NX).
Either this argument or rel_permittivity or
conductivity must be given!
background_rel_permittivity (float, default: 1.0)
background_conductivity (float, default: 0.0)
object_rel_permittivity (float, default: 1.0)
object_conductivity (float, default: 0.0)
center (list, default: [0.0, 0.0]) – Center of the object in the image. The center of the image
corresponds to the origin of the coordinates.
rel_permittivity (numpy.ndarray, default:None) – A predefined image in which the object will be drawn.
conductivity (numpy.ndarray, default:None) – A predefined image in which the object will be drawn.
rotate (float, default: 0.0 degrees) – Rotation of the object around its center. In degrees.
axis_length_x (float, default: 2.0) – Length of the size of the image.
axis_length_y (float, default: 2.0) – Length of the size of the image.
resolution (2-tuple) – Image resolution, in y and x directions, i.e., (NY, NX).
Either this argument or rel_permittivity or
conductivity must be given!
background_rel_permittivity (float, default: 1.0)
background_conductivity (float, default: 0.0)
object_rel_permittivity (float, default: 1.0)
object_conductivity (float, default: 0.0)
center (list, default: [0.0, 0.0]) – Center of the object in the image. The center of the image
corresponds to the origin of the coordinates.
rel_permittivity (numpy.ndarray, default:None) – A predefined image in which the object will be drawn.
conductivity (numpy.ndarray, default: None) – A predefined image in which the object will be drawn.
rotate (float, default: 0.0 degrees) – Rotation of the object around its center. In degrees.
inner_radius (float) – Inner and outer radii of the ring.
outer_radius (float) – Inner and outer radii of the ring.
axis_length_x (float, default: 2.0) – Length of the size of the image.
axis_length_y (float, default: 2.0) – Length of the size of the image.
resolution (2-tuple) – Image resolution, in y and x directions, i.e., (NY, NX).
Either this argument or rel_permittivity or
conductivity must be given!
background_rel_permittivity (float, default: 1.0)
background_conductivity (float, default: 0.0)
object_rel_permittivity (float, default: 1.0)
object_conductivity (float, default: 0.0)
center (list, default: [0.0, 0.0]) – Center of the object in the image. The center of the image
corresponds to the origin of the coordinates.
rel_permittivity (numpy.ndarray, default:None) – A predefined image in which the object will be drawn.
conductivity (numpy.ndarray, default:None) – A predefined image in which the object will be drawn.
Draw a square with specified electromagnetic properties.
This function creates a square object with customizable electromagnetic
properties, positioning, and rotation on a 2D grid. The square can be
drawn on a new image or overlaid on existing permittivity and conductivity
arrays.
Parameters:
side_length (float) – Length of the square’s side in the same units as axis_length_x/y.
axis_length_x (float, default=2.0) – Physical length of the image in the x-direction.
axis_length_y (float, default=2.0) – Physical length of the image in the y-direction.
resolution (tuple of int, optional) – Image resolution as (NY, NX). Required if rel_permittivity and
conductivity are not provided.
background_rel_permittivity (float, default=1.0) – Relative permittivity of the background medium.
background_conductivity (float, default=0.0) – Conductivity of the background medium in S/m.
object_rel_permittivity (float, default=1.0) – Relative permittivity of the square object.
object_conductivity (float, default=0.0) – Conductivity of the square object in S/m.
center (list of float, default=[0.0, 0.0]) – Center position of the square as [x, y] coordinates.
rotate (float, default=0.0) – Rotation angle in degrees (counterclockwise).
rel_permittivity (numpy.ndarray, optional) – Existing relative permittivity array to overlay on.
conductivity (numpy.ndarray, optional) – Existing conductivity array to overlay on.
radius (float) – Radius of the vertex from the center of the star.
axis_length_x (float, default: 2.0) – Length of the size of the image.
axis_length_y (float, default: 2.0) – Length of the size of the image.
resolution (2-tuple) – Image resolution, in y and x directions, i.e., (NY, NX).
Either this argument or rel_permittivity or
conductivity must be given!
background_rel_permittivity (float, default: 1.0)
background_conductivity (float, default: 0.0)
object_rel_permittivity (float, default: 1.0)
object_conductivity (float, default: 0.0)
center (list, default: [0.0, 0.0]) – Center of the object in the image. The center of the image
corresponds to the origin of the coordinates.
rel_permittivity (numpy.ndarray, default:None) – A predefined image in which the object will be drawn.
conductivity (numpy.ndarray, default: None) – A predefined image in which the object will be drawn.
rotate (float, default: 0.0 degrees) – Rotation of the object around its center. In degrees.
radius (int) – Length from the center of the star to the main vertices.
maximum_radius (float) – Maximum radius from the origin to each vertex.
axis_length_x (float, default: 2.0) – Length of the size of the image.
axis_length_y (float, default: 2.0) – Length of the size of the image.
resolution (2-tuple) – Image resolution, in y and x directions, i.e., (NY, NX).
Either this argument or rel_permittivity or
conductivity must be given!
background_rel_permittivity (float, default: 1.0)
background_conductivity (float, default: 0.0)
object_rel_permittivity (float, default: 1.0)
object_conductivity (float, default: 0.0)
center (list, default: [0.0, 0.0]) – Center of the object in the image. The center of the image
corresponds to the origin of the coordinates.
rel_permittivity (numpy.ndarray, default:None) – A predefined image in which the object will be drawn.
conductivity (numpy.ndarray, default:None) – A predefined image in which the object will be drawn.
rotate (float, default: 0.0 degrees) – Rotation of the object around its center. In degrees.
radius (float) – Length from the center to the maximum edge.
axis_length_x (float, default: 2.0) – Length of the size of the image.
axis_length_y (float, default: 2.0) – Length of the size of the image.
resolution (2-tuple) – Image resolution, in y and x directions, i.e., (NY, NX).
Either this argument or rel_permittivity or
conductivity must be given!
background_rel_permittivity (float, default: 1.0)
background_conductivity (float, default: 0.0)
object_rel_permittivity (float, default: 1.0)
object_conductivity (float, default: 0.0)
center (list, default: [0.0, 0.0]) – Center of the object in the image. The center of the image
corresponds to the origin of the coordinates.
rel_permittivity (numpy.ndarray, default:None) – A predefined image in which the object will be drawn.
conductivity (numpy.ndarray, default:None) – A predefined image in which the object will be drawn.
rotate (float, default: 0.0 degrees) – Rotation of the object around its center. In degrees.
axis_length_x (float, default: 2.0) – Length of the size of the image.
axis_length_y (float, default: 2.0) – Length of the size of the image.
resolution (2-tuple) – Image resolution, in y and x directions, i.e., (NY, NX).
Either this argument or rel_permittivity or
conductivity must be given!
background_rel_permittivity (float, default: 1.0)
background_conductivity (float, default: 0.0)
object_rel_permittivity (float, default: 1.0)
object_conductivity (float, default: 0.0)
center (list, default: [0.0, 0.0]) – Center of the object in the image. The center of the image
corresponds to the origin of the coordinates.
rel_permittivity (numpy.ndarray, default:None) – A predefined image in which the object will be drawn.
conductivity (numpy.ndarray, default: None) – A predefined image in which the object will be drawn.
rotate (float, default: 0.0 degrees) – Rotation of the object around its center. In degrees.