eispy2d.solvers package#

Subpackages#

Module contents#

Solvers module for eispy2d.

Contains forward and inverse solver implementations: - base: Abstract base classes for solvers - forward: Forward problem solvers (MoM-CG-FFT, Analytical) - inverse: Inverse problem solvers (BIM, DBIM, CSI, etc.)

class eispy2d.solvers.Analytical(contrast=None, radius=None)#

Bases: ForwardSolver

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.

name#

Name identifier for the solver (“Analytical Solution to Cylinder Scattering”).

Type:

str

contrast#

Relative permittivity contrast of the cylinder. Used for dielectric cylinder problems.

Type:

float or None

radius#

Radius of the cylinder in wavelengths. Used for both dielectric and conductor problems.

Type:

float or None

incident_field(resolution, configuration)#

Compute the incident field matrix.

solve(inputdata, noise=None, PRINT_INFO=False, COMPUTE_SCATTERED_FIELD=True,

SAVE_INTERN_FIELD=True)

Solve the analytical scattering problem.

dielectric_cylinder(inputdata, SAVE_INTERN_FIELD=True, SAVE_MAP=False)#

Solve scattering by a dielectric cylinder analytically.

conductor_cylinder(inputdata, SAVE_INTERN_FIELD=True, SAVE_MAP=False)#

Solve scattering by a perfectly conducting cylinder analytically.

save(file_name, file_path='')#

Save the analytical solver object to file.

importdata(file_name, file_path='')#

Import analytical solver data from file.

__init__(contrast=None, radius=None)#

Create the analytical solver object.

Parameters:
  • contrast (float, optional) – Relative permittivity contrast of the dielectric cylinder. Required for perfect dielectric problems.

  • radius (float, optional) – Radius of the cylinder in wavelengths. Required for both dielectric and conductor problems.

__str__()#

Return string representation of the analytical solver.

Returns:

String description including radius and contrast if available.

Return type:

str

conductor_cylinder(inputdata, SAVE_INTERN_FIELD=True, SAVE_MAP=False)#

Solve scattering by a perfectly conducting cylinder analytically.

Computes the analytical solution for electromagnetic scattering by a perfectly conducting cylinder using cylindrical wave expansions.

Parameters:
  • inputdata (InputData) – Input data object containing configuration and problem setup.

  • SAVE_INTERN_FIELD (bool, default=True) – Save the total field in the D-domain.

  • SAVE_MAP (bool, default=False) – Save the conductivity map to the inputdata object.

Raises:

MissingAttributesError – If radius attribute is None.

dielectric_cylinder(inputdata, SAVE_INTERN_FIELD=True, SAVE_MAP=False)#

Solve scattering by a dielectric cylinder analytically.

Computes the analytical solution for electromagnetic scattering by a dielectric cylinder using cylindrical wave expansions.

Parameters:
  • inputdata (InputData) – Input data object containing configuration and problem setup.

  • SAVE_INTERN_FIELD (bool, default=True) – Save the total field in the D-domain.

  • SAVE_MAP (bool, default=False) – Save the relative permittivity map to the inputdata object.

Raises:

MissingAttributesError – If radius or contrast attributes are None.

importdata(file_name, file_path='')#

Import analytical solver data from file.

Parameters:
  • file_name (str) – Name of the file to import.

  • file_path (str, default: '') – Path of the file to import.

incident_field(resolution, configuration)#

Compute the incident field matrix.

Computes the incident field matrix for plane waves from different angles based on the configuration parameters.

Parameters:
  • resolution (2-tuple) – The image size of D-domain in pixels (y, x).

  • configuration (Configuration) – Configuration object containing problem parameters.

Returns:

ei – Incident field matrix. Rows correspond to points in the image following C-order and columns correspond to sources.

Return type:

numpy.ndarray

save(file_name, file_path='')#

Save the analytical solver object to file.

Parameters:
  • file_name (str) – Name of the file to save.

  • file_path (str, default: '') – Path where to save the file.

solve(inputdata, noise=None, PRINT_INFO=False, COMPUTE_SCATTERED_FIELD=True, SAVE_INTERN_FIELD=True)#

Solve the analytical scattering problem.

Determines the problem type (dielectric or conductor) and calls the appropriate analytical solution method.

Parameters:
  • inputdata (InputData) – Input data object containing configuration and problem setup.

  • noise (float, optional) – Noise level to add to scattered field (not used in this method).

  • PRINT_INFO (bool, default: False) – Print iteration information (not used in analytical solution).

  • COMPUTE_SCATTERED_FIELD (bool, default: True) – Compute scattered field (not used in this method).

  • SAVE_INTERN_FIELD (bool, default: True) – Save the total field in the D-domain.

Raises:

WrongValueInput – If neither perfect_dielectric nor good_conductor is True.

class eispy2d.solvers.BackPropagation(forward=<eispy2d.solvers.forward.mom_cg_fft.MoM_CG_FFT object>, alias='backprop', import_filename=None, import_filepath='')#

Bases: Deterministic

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.

  • import_filename (str, optional) – Filename to import previously saved algorithm state.

  • import_filepath (str, default: '') – Path to the file containing saved algorithm state.

name#

Name of the algorithm (‘Back-Propagation’).

Type:

str

forward#

Forward solver instance used for field computations.

Type:

ForwardSolver

__init__(forward=<eispy2d.solvers.forward.mom_cg_fft.MoM_CG_FFT object>, alias='backprop', import_filename=None, import_filepath='')#

Initialize the Back-Propagation algorithm.

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.

  • import_filename (str, optional) – Filename to import previously saved algorithm state.

  • import_filepath (str, default: '') – Path to the file containing saved algorithm state.

__str__()#

Return string representation of the Back-Propagation algorithm.

Returns:

String description including algorithm name and forward solver.

Return type:

str

copy(new=None)#

Create a copy of the Back-Propagation algorithm.

Parameters:

new (BackPropagation, optional) – Existing BackPropagation object to copy attributes to. If None, creates a new instance.

Returns:

If new is None, returns a new BackPropagation instance. If new is provided, modifies it in place and returns None.

Return type:

BackPropagation or None

importdata(file_name, file_path='')#

Import Back-Propagation algorithm state from file.

Parameters:
  • file_name (str) – Name of the file containing saved algorithm state.

  • file_path (str, default: '') – Path to the file containing saved algorithm state.

save(file_path='')#

Save the Back-Propagation algorithm state to file.

Parameters:

file_path (str, default: '') – Path where to save the algorithm state file.

solve(inputdata, discretization, print_info=True, print_file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)#

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.

  • print_info (bool, default: True) – Whether to print algorithm progress information.

  • print_file (file-like object, default: sys.stdout) – File object to write progress information to.

Returns:

result – Result object containing the reconstructed contrast, fields, and error metrics.

Return type:

Result

class eispy2d.solvers.BornIterativeMethod(forward_solver, regularization, stop_criteria, alias='bim', import_filename=None, import_filepath='')#

Bases: Deterministic

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.

  • import_filename (str, optional) – Filename to import previously saved method state.

  • import_filepath (str, default: '') – Path to the file containing saved method state.

name#

Name of the method (‘Born Iterative Method’).

Type:

str

forward#

Forward solver instance for field computation.

Type:

ForwardSolver

regularization#

Regularization method for linear inverse problem.

Type:

Regularization

stop_criteria#

Convergence criteria for the iterative process.

Type:

StopCriteria

solve(inputdata, discretization, print_info=True, print_file=sys.stdout)#

Solve the nonlinear inverse scattering problem.

save(file_path='')#

Save the method state to file.

importdata(file_name, file_path='')#

Import method state from file.

copy(new=None)#

Create a copy of the method instance.

References

__init__(forward_solver, regularization, stop_criteria, alias='bim', import_filename=None, import_filepath='')#

Initialize the Born Iterative Method.

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:

  1. The incident field serves as the initial guess for total field

  2. At each iteration, the linear inverse problem is solved using the current total field estimate

  3. The forward solver computes the new total field

  4. The process continues until convergence criteria are met

The mathematical formulation involves solving:

\[\begin{split}\\chi^{(n+1)} = \\mathcal{L}^{-1}[E_s, E_t^{(n)}]\end{split}\]

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.

__str__()#

Return string representation of the Born Iterative Method.

Creates a comprehensive string description of the BIM instance including all its components and configuration.

Returns:

String representation including: - Base class information (name, alias, etc.) - Forward solver details - Regularization method information - Stop criteria configuration

Return type:

str

Notes

This method provides a complete overview of the BIM configuration, which is useful for debugging, logging, and understanding the method setup.

copy(new=None)#

Create a copy of the Born Iterative Method instance.

Creates a new BIM instance with the same configuration as the current one, or copies the current configuration to an existing instance.

Parameters:

new (BornIterativeMethod, optional) – Existing BIM instance to copy configuration to. If None, creates a new instance.

Returns:

If new is None, returns a new BIM instance with copied configuration. If new is provided, modifies it in place and returns None.

Return type:

BornIterativeMethod or None

Notes

The copy includes all method components: - Forward solver (reference copy) - Regularization method (reference copy) - Stop criteria (reference copy) - Base class attributes (alias, etc.)

This method is useful for creating multiple instances with the same configuration or for backup purposes before modifying parameters.

importdata(file_name, file_path='')#

Import Born Iterative Method state from file.

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.

save(file_path='')#

Save the Born Iterative Method state to file.

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(inputdata, discretization, print_info=True, print_file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)#

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.

Return type:

Result

Notes

The algorithm follows these steps:

  1. Initialization: Start with incident field as initial total field

  2. Iterative Process: For each iteration:

    1. Solve linearized inverse problem: \(\chi^{(k)} = \mathcal{R}[G_S^H (E_s - G_S E_t^{(k-1)} \chi^{(k-1)})]\)

    2. Update material properties and create auxiliary InputData

    3. Solve forward problem to get new total field: \(E_t^{(k)} = E_i + G_D \chi^{(k)} E_t^{(k)}\)

    4. Compute objective function and check convergence

  3. 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.

class eispy2d.solvers.ConjugatedGradientMethod(initial_guess, step, stop_criteria, alias='cgm', import_filename=None, import_filepath='')#

Bases: Deterministic

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:

\[\begin{split}J(\\chi) = \|\mathbf{E}^s - \mathbf{G}^s \\chi \mathbf{L}^{-1} \mathbf{E}^i\|^2\end{split}\]

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

  • stop_criteria (object) – Stopping criteria object defining convergence conditions

  • alias (str, default='cgm') – Alias name for the method

  • import_filename (str, optional) – Filename to import method parameters from

  • import_filepath (str, default='') – Path to import file

name#

Human-readable name of the method

Type:

str

initial_guess#

Initial guess strategy

Type:

str

step#

Step size computation method

Type:

str

stop_criteria#

Stopping criteria configuration

Type:

object

solve(inputdata, discretization, print_info=True, print_file=sys.stdout)#

Solve the inverse scattering problem

save(file_path='')#

Save method configuration to file

importdata(file_name, file_path='')#

Import method configuration from file

copy(new=None)#

Create a copy of the method

Notes

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:

\[\mathbf{d}^{(k+1)} = -\mathbf{g}^{(k+1)} + \beta^{(k+1)} \mathbf{d}^{(k)}\]

where \(\beta^{(k+1)} = \frac{(\mathbf{g}^{(k+1)} - \mathbf{g}^{(k)})^T \mathbf{g}^{(k+1)}}{\|\mathbf{g}^{(k)}\|^2}\)

References

Examples

>>> # Basic usage with background initial guess
>>> cgm = ConjugatedGradientMethod(initial_guess='background',
...                                step='optimum',
...                                stop_criteria=my_stop_criteria)
>>> result = cgm.solve(input_data, discretization)
>>> # Using qualitative initial guess
>>> cgm = ConjugatedGradientMethod(initial_guess='qualitative',
...                                step='fixed',
...                                stop_criteria=my_stop_criteria)
>>> result = cgm.solve(input_data, discretization)
>>> # Import from saved configuration
>>> cgm = ConjugatedGradientMethod(import_filename='cgm_config.pkl')
__init__(initial_guess, step, stop_criteria, alias='cgm', import_filename=None, import_filepath='')#

Initialize the Conjugated Gradient Method.

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')
__str__()#

Return string representation of the CGM configuration.

Creates a formatted string containing the method configuration including initial guess strategy, step size method, and stopping criteria.

Returns:

Formatted string representation of the CGM configuration

Return type:

str

Examples

>>> print(cgm)
Conjugated Gradient Method
Initial guess: background
Step: optimum
Maximum iterations: 100
Error tolerance: 1e-4
copy(new=None)#

Create a copy of the CGM instance.

Creates either a new independent instance or copies configuration to an existing instance.

Parameters:

new (ConjugatedGradientMethod or None, default=None) – If None, creates a new independent instance If provided, copies configuration to this instance

Returns:

New instance if new=None, otherwise None

Return type:

ConjugatedGradientMethod or None

Examples

>>> # Create independent copy
>>> cgm_copy = cgm.copy()
>>> # Copy configuration to existing instance
>>> cgm_new = ConjugatedGradientMethod(initial_guess='background',
...                                    step='fixed',
...                                    stop_criteria=other_criteria)
>>> cgm.copy(cgm_new)  # cgm_new now has cgm's configuration
importdata(file_name, file_path='')#

Import CGM configuration from a saved file.

Loads a previously saved CGM configuration including initial guess strategy, step size method, and stopping criteria.

Parameters:
  • file_name (str) – Name of the file to import from

  • file_path (str, default='') – Path to the file location

Examples

>>> cgm = ConjugatedGradientMethod(initial_guess='background',
...                                step='optimum',
...                                stop_criteria=my_criteria)
>>> cgm.importdata('cgm_config.pkl', '/path/to/files/')
save(file_path='')#

Save the CGM configuration to a file.

Saves the complete method configuration including initial guess strategy, step size method, and stopping criteria using pickle serialization.

Parameters:

file_path (str, default='') – Path where the configuration file will be saved

Examples

>>> cgm.save('/path/to/save/')
>>> cgm.save()  # Save in current directory
solve(inputdata, discretization, print_info=True, print_file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)#

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

Return type:

result.Result

Notes

The algorithm implements the following steps:

  1. Initialization: Set initial contrast guess based on strategy

  2. Gradient Computation: Compute gradient of objective function

  3. Conjugate Direction: Update search direction using Polak-Ribière formula

  4. Step Size: Compute optimal or fixed step size

  5. Update: Update contrast function

  6. Convergence Check: Check stopping criteria

The objective function being minimized is:

\[\begin{split}J(\\chi) = \|\mathbf{E}^s - \mathbf{G}^s \\chi (\mathbf{I} - \mathbf{G}^d \\chi)^{-1} \mathbf{E}^i\|^2\end{split}\]

where \(\\chi\) is the contrast function matrix.

Initial guess strategies: - background: Zero contrast (background medium) - backpropagation: Backpropagation-based initialization - image: Direct image reconstruction - qualitative: Orthogonality Sampling Method (OSM)

Step size methods: - fixed: \(\alpha = \frac{\mathbf{v}^H \boldsymbol{\rho}}{\|\mathbf{v}\|^2}\) - optimum: Line search optimization

Examples

>>> cgm = ConjugatedGradientMethod(initial_guess='background',
...                                step='optimum',
...                                stop_criteria=my_criteria)
>>> result = cgm.solve(input_data, discretization)
>>> print(f"Final error: {result.total_error}")
>>> print(f"Iterations: {result.number_iterations}")
>>> # Solve with custom output
>>> with open('cgm_log.txt', 'w') as f:
...     result = cgm.solve(input_data, discretization,
...                       print_file=f)
class eispy2d.solvers.ContrastSourceInversion(stop_criteria, forward_solver=<eispy2d.solvers.forward.mom_cg_fft.MoM_CG_FFT object>, alias='csi', import_filename=None, import_filepath='')#

Bases: Deterministic

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:

\[F = F_S + F_D = \frac{\|\mathbf{E}^s - \mathbf{G}^s \mathbf{J}\|^2}{\|\mathbf{E}^s\|^2} + \frac{\|\chi \mathbf{E} - \mathbf{J}\|^2}{\|\chi \mathbf{E}^i\|^2}\]

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

Parameters:
  • stop_criteria (StopCriteria) – Stopping criteria object defining convergence conditions.

  • forward_solver (ForwardSolver, default=mom.MoM_CG_FFT()) – Forward solver implementation for computing electromagnetic fields.

  • alias (str, default='csi') – Alias name for the method.

  • import_filename (str, optional) – Filename to import method parameters from.

  • import_filepath (str, default='') – Path to import file.

References

Examples

>>> # Basic usage with default forward solver
>>> csi = ContrastSourceInversion(stop_criteria=my_stop_criteria)
>>> result = csi.solve(input_data, discretization)
>>> # Using custom forward solver
>>> csi = ContrastSourceInversion(stop_criteria=my_stop_criteria,
...                               forward_solver=my_forward_solver)
>>> result = csi.solve(input_data, discretization)
>>> # Import from saved configuration
>>> csi = ContrastSourceInversion(stop_criteria=my_stop_criteria,
...                               import_filename='csi_config.pkl')
__init__(stop_criteria, forward_solver=<eispy2d.solvers.forward.mom_cg_fft.MoM_CG_FFT object>, alias='csi', import_filename=None, import_filepath='')#

Initialize the Contrast Source Inversion method.

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')
__str__()#

String representation of the CSI algorithm.

Returns:

Human-readable string representation including forward solver and stopping criteria information

Return type:

str

copy(new=None)#

Create a copy of the CSI algorithm instance.

This method creates a deep copy of the CSI algorithm with the same configuration parameters.

Parameters:

new (ContrastSourceInversion, optional) – Existing instance to copy configuration into

Returns:

New algorithm instance if new is None, otherwise None

Return type:

ContrastSourceInversion or None

importdata(file_name, file_path='')#

Import CSI algorithm state from file.

This method loads the complete algorithm state including forward solver configuration and stopping criteria from a saved file.

Parameters:
  • file_name (str) – Name of the file containing algorithm state

  • file_path (str, optional) – Path to the directory containing the state file

Returns:

Dictionary containing imported algorithm state data

Return type:

dict

save(file_path='')#

Save CSI algorithm state to file.

This method saves the complete algorithm state including forward solver configuration, stopping criteria, and inherited solver data.

Parameters:

file_path (str, optional) – Base path for saving algorithm state files

Returns:

Dictionary containing algorithm state data

Return type:

dict

solve(inputdata, discretization, print_info=True, print_file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>, initial_guess=None)#

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

Return type:

result.Result

Notes

The CSI algorithm performs the following steps:

  1. Initialization: Compute initial contrast and current using backpropagation or provided initial guess

  2. Data Error: Compute \(\boldsymbol{\rho} = \mathbf{E}^s - \mathbf{G}^s \mathbf{J}\)

  3. Object Error: Compute \(\mathbf{r} = \chi \mathbf{E} - \mathbf{J}\)

  4. Objective Function: Evaluate \(F = F_S + F_D\)

  5. Gradient: Compute gradient with respect to current \(\mathbf{J}\)

  6. Conjugate Direction: Update search direction using Polak-Ribière

  7. Step Size: Compute optimal step size minimizing cost function

  8. Update: Update current, total field, and contrast

  9. Convergence: Check stopping criteria and repeat if needed

The method uses FFT-based products for efficient computation of domain interactions and automatic normalization for numerical stability.

Algorithm features: - Simultaneous reconstruction: Both contrast and sources updated - Robust convergence: Conjugate gradient with automatic step size - Efficient computation: FFT-based operations for large problems - Flexible initialization: Backpropagation or custom initial guess

Examples

>>> # Basic usage with automatic initialization
>>> csi = ContrastSourceInversion(stop_criteria=my_criteria)
>>> result = csi.solve(input_data, discretization)
>>> print(f"Final error: {result.total_error}")
>>> # Using custom initial guess
>>> initial_contrast = np.random.random(discretization.elements)
>>> result = csi.solve(input_data, discretization,
...                   initial_guess=initial_contrast)
>>> # Solve with custom output file
>>> with open('csi_log.txt', 'w') as f:
...     result = csi.solve(input_data, discretization,
...                       print_file=f)
class eispy2d.solvers.Deterministic(alias='', parallelization=False)#

Bases: InverseSolver

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.

alias#

Solver identifier string

Type:

str

parallelization#

Parallelization flag

Type:

bool

name#

Human-readable name of the solver (inherited from InverseSolver)

Type:

str

solve(inputdata, discretization, print_info=True, print_file=sys.stdout)#

Solve the inverse scattering problem

save(file_path='')#

Save solver state to file

importdata(file_name, file_path='')#

Load solver state from file

copy(new=None)#

Create copy of solver instance

Notes

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
>>> class MyDeterministicMethod(Deterministic):
...     def __init__(self, my_param, **kwargs):
...         super().__init__(**kwargs)
...         self.my_param = my_param
...         self.name = 'My Deterministic Method'
...
...     def solve(self, inputdata, discretization, **kwargs):
...         result = super().solve(inputdata, discretization, **kwargs)
...         # Add algorithm-specific processing
...         return result

See also

inverse.InverseSolver

Parent class providing basic solver interface

__init__(alias='', parallelization=False)#

Initialize the deterministic inverse solver.

Parameters:
  • 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.

Examples

>>> # Basic initialization
>>> solver = Deterministic(alias='test_solver')
>>> print(solver.alias)
'test_solver'
>>> # With parallelization enabled
>>> solver = Deterministic(alias='parallel_solver', parallelization=True)
>>> print(solver.parallelization)
True
copy(new=None)#

Create a copy of the solver instance.

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.

Return type:

Deterministic or None

Notes

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:

```python def copy(self, new=None):

if new is None:
return MyDeterministicSolver(

my_param=self.my_param, alias=self.alias, parallelization=self.parallelization

)

else:

super().copy(new) new.my_param = self.my_param

```

Examples

>>> # Create independent copy
>>> solver_copy = solver.copy()
>>> print(f"Original: {solver.alias}, Copy: {solver_copy.alias}")
>>> # 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 _ in range(5)]
>>> # Modify each copy independently for different parameters

See also

__init__

Initialize new solver instance

importdata(file_name, file_path='')#

Load solver state from previously saved file.

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:

```python def importdata(self, file_name, file_path=’’):

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

See also

save

Save solver state to file

save(file_path='')#

Save solver state to file for later restoration.

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:

```python def save(self, file_path=’’):

data = super().save(file_path=file_path) data[‘my_specific_param’] = self.my_specific_param # Save additional algorithm-specific data return data

```

The method uses the solver’s alias to construct the filename, ensuring each solver instance can be saved independently.

Examples

>>> # Save to current directory
>>> data = solver.save()
>>> print(f"Saved solver data with {len(data)} parameters")
>>> # Save to specific directory
>>> data = solver.save(file_path='/path/to/save/directory/')
>>> print(f"Solver state saved to {file_path + solver.alias}")

See also

importdata

Load solver state from file

solve(inputdata, discretization, print_info=True, print_file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)#

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

Return type:

Result

Notes

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:

```python def solve(self, inputdata, discretization, **kwargs):

result = super().solve(inputdata, discretization, **kwargs) # Algorithm-specific implementation return result

```

The method ensures consistent behavior across all deterministic solvers in terms of input validation, result formatting, and error handling.

Examples

>>> # Basic usage (in derived class)
>>> result = solver.solve(input_data, discretization)
>>> print(f"Reconstruction completed: {result.success}")
>>> # With custom output stream
>>> with open('solver_log.txt', 'w') as f:
...     result = solver.solve(input_data, discretization, print_file=f)
>>> # Silent execution
>>> result = solver.solve(input_data, discretization, print_info=False)
class eispy2d.solvers.DistortedBornIterativeMethod(forward_solver, regularization, stop_criteria, alias='dbim', import_filename=None, import_filepath='')#

Bases: Deterministic

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

name#

Algorithm name (‘Distorted Born Iterative Method’)

Type:

str

forward#

Forward solver instance

Type:

Forward

regularization#

Regularization method instance

Type:

Regularization

stop_criteria#

Stopping criteria instance

Type:

StopCriteria

alias#

Algorithm alias for identification and file naming

Type:

str

solve(inputdata, discretization, print_info=True, print_file=sys.stdout, initial_guess=None)#

Solve electromagnetic inverse scattering problem using DBIM

save(file_path='')#

Save algorithm state to file

importdata(file_name, file_path='')#

Import algorithm state from file

copy(new=None)#

Create copy of algorithm instance

Examples

>>> # Create DBIM solver with components
>>> forward_solver = MomentMethod()
>>> regularization = TikhonovRegularization(alpha=1e-3)
>>> stop_criteria = MaxIterations(max_iterations=20)
>>> solver = DistortedBornIterativeMethod(
...     forward_solver=forward_solver,
...     regularization=regularization,
...     stop_criteria=stop_criteria
... )
>>> # Solve inverse problem
>>> result = solver.solve(input_data, discretization)
>>> print(f"Converged in {result.number_iterations} iterations")

References

__init__(forward_solver, regularization, stop_criteria, alias='dbim', import_filename=None, import_filepath='')#

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.

__str__()#

Return string representation of the DBIM algorithm.

Returns:

String representation including algorithm details and configuration of forward solver, regularization method, and stopping criteria.

Return type:

str

copy(new=None)#

Create a copy of the DBIM algorithm instance.

This method creates a deep copy of the algorithm with the same configuration parameters, allowing independent use of multiple solver instances.

Parameters:

new (DistortedBornIterativeMethod, optional) – Existing instance to copy configuration into. If None, creates and returns a new instance.

Returns:

New algorithm instance if new is None, otherwise None (configuration is copied into new parameter)

Return type:

DistortedBornIterativeMethod or None

Notes

When new is None, returns a completely independent new instance. When new is provided, copies configuration into that instance.

importdata(file_name, file_path='')#

Import DBIM algorithm state from file.

This method loads the complete algorithm state including forward solver, regularization method, and stopping criteria from a previously saved file.

Parameters:
  • file_name (str) – Name of the file containing algorithm state data

  • file_path (str, default='') – Path to the directory containing the state file

Returns:

Dictionary containing imported algorithm state data

Return type:

dict

Notes

This method restores the complete algorithm configuration, allowing resumption of work with previously saved settings.

save(file_path='')#

Save DBIM algorithm state to file.

This method saves the complete algorithm state including forward solver, regularization method, and stopping criteria to a file for later restoration.

Parameters:

file_path (str, default='') – Base path for saving algorithm state files. The algorithm alias will be appended to create the full filename.

Returns:

Dictionary containing algorithm state data

Return type:

dict

Notes

The saved file can be loaded later using the importdata method or by specifying import_filename during initialization.

solve(inputdata, discretization, print_info=True, print_file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>, initial_guess=None)#

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:

  1. Update Green’s function using current contrast

  2. Solve forward problem with updated Green’s function

  3. Compute residual scattered field

  4. Solve linear inverse problem for contrast update

  5. Check stopping criteria

  1. 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

Return type:

Result

Notes

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
>>> with open('output.txt', 'w') as f:
...     result = solver.solve(input_data, discretization,
...                          initial_guess=my_guess,
...                          print_file=f)
class eispy2d.solvers.EvolutionaryAlgorithm(population_size, initialization, objective_function, representation, mechanism, stop_criteria, outputmode, alias='ea', parallelization=False, number_executions=1, forward_solver=None, import_filename=None, import_filepath='')#

Bases: Stochastic

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.

  • representation (Representation) – Solution representation scheme.

  • mechanism (Mechanism) – Evolutionary mechanism (DE, PSO, GA, etc.).

  • stop_criteria (StopCriteria) – Stopping criteria for the algorithm.

  • outputmode (OutputMode) – Output processing mode for stochastic results.

  • alias (str, default='ea') – Alias name for the algorithm.

  • parallelization (bool, default=False) – Whether to enable parallel processing.

  • number_executions (int, default=1) – Number of executions to perform.

  • forward_solver (ForwardSolver, optional) – Forward solver for field computations.

  • import_filename (str, optional) – Filename to import algorithm state from.

  • import_filepath (str, default='') – Path to import file.

copy(new=None)#

Create a copy of the solver instance.

Parameters:

new (InverseSolver, optional) – If provided, copies configuration into this instance. If None, creates a new instance.

Returns:

New instance if new=None, otherwise None.

Return type:

InverseSolver or None

run_algorithm(inputdata, run_name, incident_field, print_info=True, print_file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)#

Run a single execution of the evolutionary algorithm.

Parameters:
  • inputdata (InputData) – Input data object containing problem configuration.

  • run_name (str) – Name for this execution.

  • incident_field (numpy.ndarray) – Incident field data.

  • print_info (bool, default=True) – Whether to print progress information.

  • print_file (file-like object, default=sys.stdout) – Output stream for printing.

Returns:

Result object for this execution.

Return type:

Result

save(file_path)#

Save solver configuration to file.

Parameters:

file_path (str, default='') – Base path for saving the configuration.

Returns:

Dictionary containing the serialized solver data.

Return type:

dict

solve(inputdata, discretization=None, print_info=True, print_file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)#

Solve the inverse scattering problem.

This is the main routine for any method implementation. The input may include additional arguments, but the output must always be a Result object.

Parameters:
  • inputdata (InputData) – Input data object defining the problem instance.

  • discretization (Discretization) – Discretization scheme to use.

  • print_info (bool, default=True) – Whether to display progress information.

  • print_file (file-like object, default=sys.stdout) – Output stream for printed information.

Returns:

Result object containing the reconstruction results.

Return type:

Result

class eispy2d.solvers.ExtendedContrastSourceInversion(stop_criteria, forward_solver=<eispy2d.solvers.forward.mom_cg_fft.MoM_CG_FFT object>, alias='ecsi', import_filename=None, import_filepath='')#

Bases: Deterministic

Extended Contrast Source Inversion (ECSI) Method.

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.

Mathematical Foundation#

The ECSI method minimizes the cost function:

\[\begin{split}F(\\chi, \\mathbf{J}) = \\frac{||\\mathbf{E}^s - \\mathbf{G}^s \\mathbf{J}||^2}{||\\mathbf{E}^s||^2} + \\frac{||\\mathbf{J} - \\chi \\mathbf{E}^{tot}||^2}{||\\chi \\mathbf{E}^{inc}||^2}\end{split}\]

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

forward#

An implementation of the abstract forward solver class which computes the total electric field for a given contrast distribution.

Type:

forward.Forward

stop_criteria#

Object defining the stopping criteria for the iterative algorithm, including maximum iterations and convergence thresholds.

Type:

stopcriteria.StopCriteria

name#

Human-readable name of the algorithm (‘Extended Contrast Source Inversion’).

Type:

str

type stop_criteria:

stopcriteria.StopCriteria

param stop_criteria:

Stopping criteria configuration for the iterative algorithm.

type stop_criteria:

stopcriteria.StopCriteria

type forward_solver:

forward.Forward, optional

param forward_solver:

Forward solver implementation. Default is MoM_CG_FFT().

type forward_solver:

forward.Forward, optional

type alias:

str, optional

param alias:

Short identifier for the algorithm. Default is ‘ecsi’.

type alias:

str, optional

type import_filename:

str, optional

param import_filename:

Name of file to import saved algorithm state from. Default is None.

type import_filename:

str, optional

type import_filepath:

str, optional

param import_filepath:

Path to directory containing import file. Default is empty string.

type import_filepath:

str, optional

Examples

>>> import stopcriteria as sc
>>> import mom_cg_fft as mom
>>>
>>> # Create stopping criteria
>>> stop_crit = sc.MaxIterations(max_iterations=50)
>>>
>>> # Create ECSI solver
>>> solver = ExtendedContrastSourceInversion(
...     stop_criteria=stop_crit,
...     forward_solver=mom.MoM_CG_FFT()
... )
>>>
>>> # Solve inverse problem
>>> result = solver.solve(input_data, discretization)

Notes

  • The algorithm supports both perfect dielectric and good conductor approximations

  • Uses Numba JIT compilation for performance-critical computations

  • Employs conjugate gradient techniques for efficient convergence

  • Can handle complex-valued contrast functions for lossy media

References

__init__(stop_criteria, forward_solver=<eispy2d.solvers.forward.mom_cg_fft.MoM_CG_FFT object>, alias='ecsi', import_filename=None, import_filepath='')#

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.

Examples

>>> import stopcriteria as sc
>>> import mom_cg_fft as mom
>>>
>>> # Initialize with stopping criteria
>>> stop_crit = sc.MaxIterations(max_iterations=100)
>>> solver = ExtendedContrastSourceInversion(
...     stop_criteria=stop_crit,
...     forward_solver=mom.MoM_CG_FFT()
... )
>>>
>>> # Initialize from saved file
>>> solver = ExtendedContrastSourceInversion(
...     stop_criteria=stop_crit,
...     import_filename='saved_ecsi.pkl',
...     import_filepath='/path/to/saved/files/'
... )

Notes

If both import_filename and other parameters are provided, the solver will be initialized from the saved file and other parameters will be ignored.

__str__()#

Return string representation of the solver.

Returns:

String description including solver name, forward solver, and stopping criteria.

Return type:

str

copy(new=None)#

Create a copy of the solver.

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.

Returns:

New solver instance with copied configuration.

Return type:

ExtendedContrastSourceInversion

importdata(file_name, file_path='')#

Load solver state from file.

Restores the solver configuration from a previously saved pickle file.

Parameters:
  • file_name (str) – Name of the file containing saved solver state.

  • file_path (str, optional) – Directory path containing the file. Default is current directory.

Raises:

FileNotFoundError – If the specified file cannot be found.

save(file_path='')#

Save solver state to file.

Saves the current solver configuration including forward solver and stopping criteria to a pickle file for later restoration.

Parameters:

file_path (str, optional) – Directory path where the file will be saved. Default is current directory.

Notes

The file is saved with the name specified by the solver’s alias attribute.

solve(inputdata, discretization, print_info=True, print_file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>, initial_guess=None)#

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:

  1. Initialization: Generate initial guess using backpropagation if not provided

  2. Current Update: Minimize data and object error functionals with respect to J

  3. Contrast Update: Minimize object error functional with respect to \chi

  4. Convergence Check: Evaluate stopping criteria and continue if necessary

The cost function minimized is:

\[\begin{split}F(\\chi, \\mathbf{J}) = \\frac{||\\mathbf{E}^s - \\mathbf{G}^s \\mathbf{J}||^2}{||\\mathbf{E}^s||^2} + \\frac{||\\mathbf{J} - \\chi \\mathbf{E}^{tot}||^2}{||\\chi \\mathbf{E}^{inc}||^2}\end{split}\]

Examples

>>> import inputdata as ipt
>>> import discretization as dsc
>>> import stopcriteria as sc
>>>
>>> # Create problem setup
>>> data = ipt.InputData(frequency=1e9, ...)
>>> disc = dsc.Discretization(grid_size=(64, 64), ...)
>>> stop_crit = sc.MaxIterations(max_iterations=100)
>>>
>>> # Create and run solver
>>> solver = ExtendedContrastSourceInversion(stop_criteria=stop_crit)
>>> result = solver.solve(data, disc, print_info=True)
>>>
>>> # Access results
>>> contrast = result.contrast
>>> permittivity = result.rel_permittivity
>>> convergence_info = result.number_iterations
class eispy2d.solvers.FFTProduct(discretization=None, adjoint=False, conjugate=False)#

Bases: object

Fast Fourier Transform-based convolution product for Green’s function.

This class computes the matrix-vector product using FFT-based convolution for efficient implementation of the Method of Moments.

discretization#

Discretization object containing the Green’s function matrix.

Type:

Discretization

G#

Extended Green’s function matrix for FFT convolution.

Type:

numpy.ndarray

adjoint#

Whether to use the adjoint operator.

Type:

bool

conjugate#

Whether to use the conjugate operator.

Type:

bool

compute(J)#

Compute the convolution product.

compute(J)#

Compute the convolution product.

Parameters:

J (numpy.ndarray) – Current density matrix with shape (N, NS) where N is the number of discretization elements and NS is the number of sources.

Returns:

Result of the convolution product.

Return type:

numpy.ndarray

property discretization#
class eispy2d.solvers.FirstOrderBornApproximation(regularization, forward=<eispy2d.solvers.forward.mom_cg_fft.MoM_CG_FFT object>, alias='ba', import_filename=None, import_filepath='')#

Bases: Deterministic

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.

  • import_filename (str, optional) – Filename to import previously saved method state.

  • import_filepath (str, default: '') – Path to the file containing saved method state.

name#

Name of the method (‘First-Order Born Approximation’).

Type:

str

regularization#

Regularization method for the linear inverse problem.

Type:

Regularization

forward#

Forward solver instance for field computation.

Type:

ForwardSolver

solve(inputdata, discretization, print_info=True, print_file=sys.stdout)#

Solve the linearized inverse scattering problem.

save(file_path='')#

Save the method state to file.

importdata(file_name, file_path='')#

Import method state from file.

copy(new=None)#

Create a copy of the method instance.

Notes

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

References

__init__(regularization, forward=<eispy2d.solvers.forward.mom_cg_fft.MoM_CG_FFT object>, alias='ba', import_filename=None, import_filepath='')#

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.

Examples

>>> import regularization as reg
>>> import mom_cg_fft as mom
>>>
>>> # Create regularization method
>>> tikhonov = reg.Tikhonov(regularization_parameter=1e-3)
>>>
>>> # Create forward solver
>>> forward_solver = mom.MoM_CG_FFT()
>>>
>>> # Initialize Born approximation
>>> born = FirstOrderBornApproximation(tikhonov, forward_solver)
__str__()#

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
...
copy(new=None)#

Create a copy of the First-Order Born Approximation instance.

Creates a new FOBA instance with the same configuration as the current one, or copies the current configuration to an existing instance.

Parameters:

new (FirstOrderBornApproximation, optional) – Existing FOBA instance to copy configuration to. If None, creates a new instance.

Returns:

If new is None, returns a new FOBA instance with copied configuration. If new is provided, modifies it in place and returns None.

Return type:

FirstOrderBornApproximation or None

Notes

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
importdata(file_name, file_path='')#

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(file_path='')#

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(inputdata, discretization, print_info=True, print_file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)#

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.

Return type:

Result

Notes

Algorithm Steps:

  1. Incident Field Computation: Calculate the incident field E_i in the discretization domain using the forward solver.

  2. 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.

  3. Field Reconstruction: Compute the reconstructed scattered field using the estimated contrast:

    \[E_s^{rec} = G_S \chi E_i\]
  4. Parameter Conversion: Convert the contrast function to physical parameters (relative permittivity, conductivity) based on the problem configuration.

  5. 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.

Examples

>>> # Solve inverse problem
>>> result = born.solve(input_data, discretization)
>>>
>>> # Access reconstructed properties
>>> rel_permittivity = result.rel_permittivity
>>> conductivity = result.conductivity
>>>
>>> # Check reconstruction quality
>>> rel_error = result.rel_permittivity_error
class eispy2d.solvers.ForwardSolver(parallelization=False)#

Bases: ABC

Abstract base class for forward solvers.

This class provides the expected attributes and methods of any implementation of a forward solver for electromagnetic scattering.

name#

The name of the method. Should be defined within the implementation.

Type:

str

parallelization#

Whether parallel processing is enabled.

Type:

bool

et#

Total field information. Rows are points in D-domain (C order), columns are sources.

Type:

numpy.ndarray

ei#

Incident field information. Rows are points in D-domain (C order), columns are sources.

Type:

numpy.ndarray

es#

Scattered field information. Rows correspond to measurement points, columns correspond to sources.

Type:

numpy.ndarray

epsilon_r#

Relative permittivity map (rows: y-coordinates, columns: x-coordinates).

Type:

numpy.ndarray

sigma#

Conductivity map in S/m (rows: y-coordinates, columns: x-coordinates).

Type:

numpy.ndarray

configuration#

Problem configuration object.

Type:

Configuration

solve(inputdata, noise=None, PRINT_INFO=False, SAVE_INTERN_FIELD=True)#

Execute the forward solver given a problem input.

incident_field(resolution, configuration)#

Return the incident field for a given resolution.

save(file_name, file_path='')#

Save simulation data.

importdata(file_name, file_path='')#

Import solver data from file.

__init__(parallelization=False)#

Create a forward solver object.

Parameters:

None

abstractmethod __str__()#

Print information of the method object.

abstractmethod importdata(file_name, file_path='')#
abstractmethod incident_field(resolution, configuration)#

Return the incident field for a given resolution.

Parameters:
  • resolution (tuple of int) – Image resolution (NY, NX).

  • configuration (Configuration) – Problem configuration object.

Returns:

Incident field matrix with shape (NY*NX, NS) where NS is the number of sources.

Return type:

numpy.ndarray

abstractmethod save(file_name, file_path='')#

Save simulation data.

abstractmethod solve(inputdata, noise=None, PRINT_INFO=False, SAVE_INTERN_FIELD=True)#

Execute the forward solver given a problem input.

Parameters:
  • inputdata (InputData) – Input data object containing the problem configuration and either relative permittivity or conductivity maps.

  • noise (float, optional) – Noise level to add to the computed scattered field (percentage).

  • PRINT_INFO (bool, default=False) – Whether to print progress information.

  • SAVE_INTERN_FIELD (bool, default=True) – Whether to save the internal total field.

Returns:

(epsilon_r, sigma) arrays with the computed dielectric properties. Derived classes may return additional fields.

Return type:

tuple

class eispy2d.solvers.InverseSolver(alias='', parallelization=False, import_filename=None, import_filepath='')#

Bases: ABC

Abstract base class for inverse scattering solvers.

This class defines the basic interface for any implementation of an inverse solver for electromagnetic scattering problems.

name#

The name of the solver.

Type:

str

alias#

Short identifier for the solver.

Type:

str

parallelization#

Whether parallel processing is enabled.

Type:

bool

execution_time#

Execution time for a single run of the method (set by derived classes).

Type:

float

solve(inputdata, discretization, print_info=True, print_file=sys.stdout)#

Solve the inverse scattering problem.

save(file_path='')#

Save solver state to file.

importdata(file_name, file_path='')#

Load solver state from file.

copy(new=None)#

Create a copy of the solver instance.

__init__(alias='', parallelization=False, import_filename=None, import_filepath='')#

Create an inverse solver object.

Parameters:
  • alias (str, default='') – Short identifier for the solver.

  • parallelization (bool, default=False) – Whether to enable parallel processing.

  • import_filename (str, optional) – If provided, imports solver configuration from this file.

  • import_filepath (str, default='') – Path to the import file.

copy(new=None)#

Create a copy of the solver instance.

Parameters:

new (InverseSolver, optional) – If provided, copies configuration into this instance. If None, creates a new instance.

Returns:

New instance if new=None, otherwise None.

Return type:

InverseSolver or None

abstractmethod importdata(file_name, file_path='')#

Import solver configuration from file.

Parameters:
  • file_name (str) – Name of the file to import from.

  • file_path (str, default='') – Path to the import file.

Returns:

Dictionary containing the imported data.

Return type:

dict

abstractmethod save(file_path='')#

Save solver configuration to file.

Parameters:

file_path (str, default='') – Base path for saving the configuration.

Returns:

Dictionary containing the serialized solver data.

Return type:

dict

abstractmethod solve(inputdata, discretization, print_info=True, print_file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)#

Solve the inverse scattering problem.

This is the main routine for any method implementation. The input may include additional arguments, but the output must always be a Result object.

Parameters:
  • inputdata (InputData) – Input data object defining the problem instance.

  • discretization (Discretization) – Discretization scheme to use.

  • print_info (bool, default=True) – Whether to display progress information.

  • print_file (file-like object, default=sys.stdout) – Output stream for printed information.

Returns:

Result object containing the reconstruction results.

Return type:

Result

class eispy2d.solvers.LinearSamplingMethod(alias='', regularization=None, tikhonov=None, sv_cutoff=None, threshold=None, far_field=None, indicator_function=<function standard>, import_filename=None, import_filepath='')#

Bases: Deterministic

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.

  • tikhonov (float, optional) – Tikhonov regularization parameter.

  • sv_cutoff (float, optional) – Singular value cutoff threshold.

  • threshold (float, optional) – Threshold for indicator function.

  • far_field (bool, optional) – Whether to use far-field approximation.

  • indicator_function (callable, default=standard) – Function to compute indicator values.

  • import_filename (str, optional) – Filename to import algorithm state from.

  • import_filepath (str, default='') – Path to import file.

copy(new=None)#

Create a copy of the solver instance.

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.

Return type:

Deterministic or None

Notes

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:

```python def copy(self, new=None):

if new is None:
return MyDeterministicSolver(

my_param=self.my_param, alias=self.alias, parallelization=self.parallelization

)

else:

super().copy(new) new.my_param = self.my_param

```

Examples

>>> # Create independent copy
>>> solver_copy = solver.copy()
>>> print(f"Original: {solver.alias}, Copy: {solver_copy.alias}")
>>> # 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 _ in range(5)]
>>> # Modify each copy independently for different parameters

See also

__init__

Initialize new solver instance

importdata(file_name, file_path='')#

Load solver state from previously saved file.

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:

```python def importdata(self, file_name, file_path=’’):

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

See also

save

Save solver state to file

save(file_path='')#

Save solver state to file for later restoration.

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:

```python def save(self, file_path=’’):

data = super().save(file_path=file_path) data[‘my_specific_param’] = self.my_specific_param # Save additional algorithm-specific data return data

```

The method uses the solver’s alias to construct the filename, ensuring each solver instance can be saved independently.

Examples

>>> # Save to current directory
>>> data = solver.save()
>>> print(f"Saved solver data with {len(data)} parameters")
>>> # Save to specific directory
>>> data = solver.save(file_path='/path/to/save/directory/')
>>> print(f"Solver state saved to {file_path + solver.alias}")

See also

importdata

Load solver state from file

solve(inputdata, discretization=None, print_info=True, print_file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)#

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

Return type:

Result

Notes

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:

```python def solve(self, inputdata, discretization, **kwargs):

result = super().solve(inputdata, discretization, **kwargs) # Algorithm-specific implementation return result

```

The method ensures consistent behavior across all deterministic solvers in terms of input validation, result formatting, and error handling.

Examples

>>> # Basic usage (in derived class)
>>> result = solver.solve(input_data, discretization)
>>> print(f"Reconstruction completed: {result.success}")
>>> # With custom output stream
>>> with open('solver_log.txt', 'w') as f:
...     result = solver.solve(input_data, discretization, print_file=f)
>>> # Silent execution
>>> result = solver.solve(input_data, discretization, print_info=False)
class eispy2d.solvers.MRContrastSourceInversion(stop_criteria, exponent=1.0, forward_solver=<eispy2d.solvers.forward.mom_cg_fft.MoM_CG_FFT object>, alias='mrcsi', import_filename=None, import_filepath='')#

Bases: Deterministic

The Born Interative Method (BIM).

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.

forward#

An implementation of the abstract class which defines a forward method which solves the total electric field.

Type:

forward.Forward:

inverse#

An implementation of the abstract class which defines method for solving the linear inverse scattering problem.

Type:

inverse.Inverse:

MAX_IT#

The number of iterations.

Type:

int

sc_measure#

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:

\[\frac{|\zeta^i-\zeta^{i-1}|}{\zeta^{i-1}}*100 \leq \eta\]
Type:

str

stopcriterion_measure#

Threshold criterion for stop the algorithm.

Type:

float

divergence_tolerance#

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.

Type:

int, default: 5

References

__init__(stop_criteria, exponent=1.0, forward_solver=<eispy2d.solvers.forward.mom_cg_fft.MoM_CG_FFT object>, alias='mrcsi', import_filename=None, import_filepath='')#

Create the object.

Parameters:
  • 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:

    \[\frac{|\zeta^i-\zeta^{i-1}|}{\zeta^{i-1}}*100 \leq \eta\]

  • stopcriterion_measure – Threshold criterion for stop the algorithm.

copy(new=None)#

Create a copy of the solver instance.

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.

Return type:

Deterministic or None

Notes

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:

```python def copy(self, new=None):

if new is None:
return MyDeterministicSolver(

my_param=self.my_param, alias=self.alias, parallelization=self.parallelization

)

else:

super().copy(new) new.my_param = self.my_param

```

Examples

>>> # Create independent copy
>>> solver_copy = solver.copy()
>>> print(f"Original: {solver.alias}, Copy: {solver_copy.alias}")
>>> # 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 _ in range(5)]
>>> # Modify each copy independently for different parameters

See also

__init__

Initialize new solver instance

importdata(file_name, file_path='')#

Load solver state from previously saved file.

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:

```python def importdata(self, file_name, file_path=’’):

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

See also

save

Save solver state to file

save(file_path='')#

Save solver state to file for later restoration.

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:

```python def save(self, file_path=’’):

data = super().save(file_path=file_path) data[‘my_specific_param’] = self.my_specific_param # Save additional algorithm-specific data return data

```

The method uses the solver’s alias to construct the filename, ensuring each solver instance can be saved independently.

Examples

>>> # Save to current directory
>>> data = solver.save()
>>> print(f"Saved solver data with {len(data)} parameters")
>>> # Save to specific directory
>>> data = solver.save(file_path='/path/to/save/directory/')
>>> print(f"Solver state saved to {file_path + solver.alias}")

See also

importdata

Load solver state from file

solve(inputdata, discretization, print_info=True, print_file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>, initial_guess=None)#

Solve a nonlinear inverse problem.

Parameters:
  • instance (inputdata.InputData) – An object which defines a case problem with scattered field and some others information.

  • print_info (bool) – Print or not the iteration information.

class eispy2d.solvers.MUSIC(alias='', sv_cutoff=None, threshold=None, import_filename=None, import_filepath='')#

Bases: Deterministic

Multiple Signal Classification imaging method.

This class implements the MUSIC algorithm for qualitative imaging, which uses singular value decomposition to identify scatterer locations.

Parameters:
  • alias (str, default='') – Alias name for the algorithm.

  • sv_cutoff (int or float, optional) – Singular value cutoff (int: number of values, float: threshold).

  • threshold (float, optional) – Threshold for indicator function.

  • import_filename (str, optional) – Filename to import algorithm state from.

  • import_filepath (str, default='') – Path to import file.

copy(new=None)#

Create a copy of the solver instance.

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.

Return type:

Deterministic or None

Notes

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:

```python def copy(self, new=None):

if new is None:
return MyDeterministicSolver(

my_param=self.my_param, alias=self.alias, parallelization=self.parallelization

)

else:

super().copy(new) new.my_param = self.my_param

```

Examples

>>> # Create independent copy
>>> solver_copy = solver.copy()
>>> print(f"Original: {solver.alias}, Copy: {solver_copy.alias}")
>>> # 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 _ in range(5)]
>>> # Modify each copy independently for different parameters

See also

__init__

Initialize new solver instance

importdata(file_name, file_path='')#

Load solver state from previously saved file.

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:

```python def importdata(self, file_name, file_path=’’):

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

See also

save

Save solver state to file

save(file_path='')#

Save solver state to file for later restoration.

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:

```python def save(self, file_path=’’):

data = super().save(file_path=file_path) data[‘my_specific_param’] = self.my_specific_param # Save additional algorithm-specific data return data

```

The method uses the solver’s alias to construct the filename, ensuring each solver instance can be saved independently.

Examples

>>> # Save to current directory
>>> data = solver.save()
>>> print(f"Saved solver data with {len(data)} parameters")
>>> # Save to specific directory
>>> data = solver.save(file_path='/path/to/save/directory/')
>>> print(f"Solver state saved to {file_path + solver.alias}")

See also

importdata

Load solver state from file

solve(inputdata, discretization=None, print_info=True, print_file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)#

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

Return type:

Result

Notes

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:

```python def solve(self, inputdata, discretization, **kwargs):

result = super().solve(inputdata, discretization, **kwargs) # Algorithm-specific implementation return result

```

The method ensures consistent behavior across all deterministic solvers in terms of input validation, result formatting, and error handling.

Examples

>>> # Basic usage (in derived class)
>>> result = solver.solve(input_data, discretization)
>>> print(f"Reconstruction completed: {result.success}")
>>> # With custom output stream
>>> with open('solver_log.txt', 'w') as f:
...     result = solver.solve(input_data, discretization, print_file=f)
>>> # Silent execution
>>> result = solver.solve(input_data, discretization, print_info=False)
class eispy2d.solvers.MoM_CG_FFT(tolerance=0.001, maximum_iterations=5000, parallelization=True)#

Bases: ForwardSolver

Method of Moments with Conjugated-Gradient FFT method.

This class implements the Method of Moments following the Conjugated-Gradient FFT formulation for solving electromagnetic scattering problems.

TOL#

Tolerance level for convergence.

Type:

float

MAX_IT#

Maximum number of iterations.

Type:

int

name#

Solver name (“Method of Moments - CG-FFT”).

Type:

str

incident_field(resolution, configuration)#

Compute the incident field matrix.

solve(inputdata, noise=None, PRINT_INFO=False,

COMPUTE_SCATTERED_FIELD=True, SAVE_INTERN_FIELD=True)

Solve the forward problem.

save(file_name, file_path='')#

Save solver state to file.

importdata(file_name, file_path='')#

Import solver state from file.

CG_FFT(G, b, NX, NY, NS, Xr, MAX_IT, TOL, PRINT_CONVERGENCE)#

Apply the Conjugated-Gradient Method to the forward problem.

Parameters:
  • G (numpy.ndarray) – Extended matrix, (2NX-1)x(2NY-1)

  • b (numpy.ndarray) – Excitation source, (NX.NY)xNi

  • NX (int) – Contrast map in x-axis.

  • NY (int) – Contrast map in x-axis.

  • NS (int) – Number of incidences.

  • Xr (numpy.ndarray) – Contrast map, NX x NY

  • MAX_IT (int) – Maximum number of iterations

  • TOL (float) – Error tolerance

  • PRINT_CONVERGENCE (boolean) – Print error information per iteration.

Returns:

Jnumpy:ndarray

Current density, (NX.NY)xNS

__init__(tolerance=0.001, maximum_iterations=5000, parallelization=True)#

Create the object.

Parameters:
  • 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).

  • tolerance (float, default: 1e-6) – Minimum error tolerance.

  • maximum_iteration (int, default: 10000) – Maximum number of iterations.

__str__()#

Print method parametrization.

importdata(file_name, file_path='')#
incident_field(resolution, configuration)#

Compute the incident field matrix.

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.

save(file_name, file_path='')#

Save simulation data.

solve(inputdata, noise=None, PRINT_INFO=False, COMPUTE_SCATTERED_FIELD=True, SAVE_INTERN_FIELD=True)#

Solve the forward problem.

Parameters:
  • inputdata (inputdata:InputData) – An object describing the dielectric property map.

  • PRINT_INFO (boolean, default: False) – Print iteration information.

  • COMPUTE_INTERN_FIELD (boolean, default: True) – Compute the total field in D-domain.

Returns:

es, et, einumpy:ndarray

Matrices with the scattered, total and incident field information.

Examples

>>> solver = MoM_CG_FFT(configuration)
>>> es, et, ei = solver.solve(inputdata)
>>> es, ei = solver.solve(inputdata, COMPUTE_INTERN_FIELD=False)
class eispy2d.solvers.OrthogonalitySamplingMethod(alias='osm', threshold=None, far_field=None, import_filename=None, import_filepath='')#

Bases: Deterministic

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.

copy(new=None)#

Create a copy of the solver instance.

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.

Return type:

Deterministic or None

Notes

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:

```python def copy(self, new=None):

if new is None:
return MyDeterministicSolver(

my_param=self.my_param, alias=self.alias, parallelization=self.parallelization

)

else:

super().copy(new) new.my_param = self.my_param

```

Examples

>>> # Create independent copy
>>> solver_copy = solver.copy()
>>> print(f"Original: {solver.alias}, Copy: {solver_copy.alias}")
>>> # 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 _ in range(5)]
>>> # Modify each copy independently for different parameters

See also

__init__

Initialize new solver instance

importdata(file_name, file_path='')#

Load solver state from previously saved file.

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:

```python def importdata(self, file_name, file_path=’’):

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

See also

save

Save solver state to file

save(file_path='')#

Save solver state to file for later restoration.

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:

```python def save(self, file_path=’’):

data = super().save(file_path=file_path) data[‘my_specific_param’] = self.my_specific_param # Save additional algorithm-specific data return data

```

The method uses the solver’s alias to construct the filename, ensuring each solver instance can be saved independently.

Examples

>>> # Save to current directory
>>> data = solver.save()
>>> print(f"Saved solver data with {len(data)} parameters")
>>> # Save to specific directory
>>> data = solver.save(file_path='/path/to/save/directory/')
>>> print(f"Solver state saved to {file_path + solver.alias}")

See also

importdata

Load solver state from file

solve(inputdata, discretization=None, print_info=True, print_file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)#

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

Return type:

Result

Notes

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:

```python def solve(self, inputdata, discretization, **kwargs):

result = super().solve(inputdata, discretization, **kwargs) # Algorithm-specific implementation return result

```

The method ensures consistent behavior across all deterministic solvers in terms of input validation, result formatting, and error handling.

Examples

>>> # Basic usage (in derived class)
>>> result = solver.solve(input_data, discretization)
>>> print(f"Reconstruction completed: {result.success}")
>>> # With custom output stream
>>> with open('solver_log.txt', 'w') as f:
...     result = solver.solve(input_data, discretization, print_file=f)
>>> # Silent execution
>>> result = solver.solve(input_data, discretization, print_info=False)
class eispy2d.solvers.OutputMode(rule, reference=None, sample_rate=5)#

Bases: object

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%).

make(name, method_name, results)#

Process results according to the specified rule.

copy(new=None)#

Create a copy of the OutputMode object.

copy(new=None)#
make(name, method_name, results)#

Process results according to the specified rule.

Parameters:
  • name (str) – Name for the result object.

  • method_name (str) – Name of the method that generated the results.

  • results (list of Result or Result) – Results to process.

Returns:

Processed result(s) according to the rule.

Return type:

Result or list of Result

class eispy2d.solvers.Stochastic(outputmode, alias=None, parallelization=False, number_executions=1)#

Bases: InverseSolver

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.

nexec#

Number of executions to perform.

Type:

int

outputmode#

Strategy for processing multiple execution results.

Type:

OutputMode

_single_execution#

Whether only one execution is required.

Type:

bool

copy(new=None)#

Create a copy of the solver instance.

Parameters:

new (InverseSolver, optional) – If provided, copies configuration into this instance. If None, creates a new instance.

Returns:

New instance if new=None, otherwise None.

Return type:

InverseSolver or None

importdata(file_name, file_path='')#

Import solver configuration from file.

Parameters:
  • file_name (str) – Name of the file to import from.

  • file_path (str, default='') – Path to the import file.

Returns:

Dictionary containing the imported data.

Return type:

dict

property nexec#

Set the number of executions.

Parameters:

new (int or None) – Number of executions. If None, defaults to 1. Must be >= 1.

Raises:
abstractmethod save(file_path='')#

Save solver configuration to file.

Parameters:

file_path (str, default='') – Base path for saving the configuration.

Returns:

Dictionary containing the serialized solver data.

Return type:

dict

solve(inputdata, discretization, print_info=True, print_file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)#

Solve the inverse scattering problem.

This is the main routine for any method implementation. The input may include additional arguments, but the output must always be a Result object.

Parameters:
  • inputdata (InputData) – Input data object defining the problem instance.

  • discretization (Discretization) – Discretization scheme to use.

  • print_info (bool, default=True) – Whether to display progress information.

  • print_file (file-like object, default=sys.stdout) – Output stream for printed information.

Returns:

Result object containing the reconstruction results.

Return type:

Result

class eispy2d.solvers.SubspaceBasedOptimizationMethod(stop_criteria, cutoff_index=5, forward_solver=<eispy2d.solvers.forward.mom_cg_fft.MoM_CG_FFT object>, alias='som', import_filename=None, import_filepath='')#

Bases: Deterministic

The Born Interative Method (BIM).

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.

forward#

An implementation of the abstract class which defines a forward method which solves the total electric field.

Type:

forward.Forward:

inverse#

An implementation of the abstract class which defines method for solving the linear inverse scattering problem.

Type:

inverse.Inverse:

MAX_IT#

The number of iterations.

Type:

int

sc_measure#

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:

\[\frac{|\zeta^i-\zeta^{i-1}|}{\zeta^{i-1}}*100 \leq \eta\]
Type:

str

stopcriterion_measure#

Threshold criterion for stop the algorithm.

Type:

float

divergence_tolerance#

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.

Type:

int, default: 5

References

__init__(stop_criteria, cutoff_index=5, forward_solver=<eispy2d.solvers.forward.mom_cg_fft.MoM_CG_FFT object>, alias='som', import_filename=None, import_filepath='')#

Create the object.

Parameters:
  • 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:

    \[\frac{|\zeta^i-\zeta^{i-1}|}{\zeta^{i-1}}*100 \leq \eta\]

  • stopcriterion_measure – Threshold criterion for stop the algorithm.

copy(new=None)#

Create a copy of the solver instance.

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.

Return type:

Deterministic or None

Notes

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:

```python def copy(self, new=None):

if new is None:
return MyDeterministicSolver(

my_param=self.my_param, alias=self.alias, parallelization=self.parallelization

)

else:

super().copy(new) new.my_param = self.my_param

```

Examples

>>> # Create independent copy
>>> solver_copy = solver.copy()
>>> print(f"Original: {solver.alias}, Copy: {solver_copy.alias}")
>>> # 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 _ in range(5)]
>>> # Modify each copy independently for different parameters

See also

__init__

Initialize new solver instance

importdata(file_name, file_path='')#

Load solver state from previously saved file.

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:

```python def importdata(self, file_name, file_path=’’):

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

See also

save

Save solver state to file

save(file_path='')#

Save solver state to file for later restoration.

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:

```python def save(self, file_path=’’):

data = super().save(file_path=file_path) data[‘my_specific_param’] = self.my_specific_param # Save additional algorithm-specific data return data

```

The method uses the solver’s alias to construct the filename, ensuring each solver instance can be saved independently.

Examples

>>> # Save to current directory
>>> data = solver.save()
>>> print(f"Saved solver data with {len(data)} parameters")
>>> # Save to specific directory
>>> data = solver.save(file_path='/path/to/save/directory/')
>>> print(f"Solver state saved to {file_path + solver.alias}")

See also

importdata

Load solver state from file

solve(inputdata, discretization, print_info=True, print_file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>, initial_guess=None)#

Solve a nonlinear inverse problem.

Parameters:
  • instance (inputdata.InputData) – An object which defines a case problem with scattered field and some others information.

  • print_info (bool) – Print or not the iteration information.