eispy2d.solvers.inverse package#

Submodules#

eispy2d.solvers.inverse.backprop module#

Back-Propagation Algorithm for Electromagnetic Inverse Scattering.

This module implements the Back-Propagation algorithm for solving two-dimensional electromagnetic inverse scattering problems. The algorithm uses scattered field measurements to reconstruct the contrast function of the scattering object.

The Back-Propagation method is a non-iterative technique that provides a fast approximation to the inverse scattering problem by computing the contrast directly from the scattered field measurements using Green’s function relationships.

References

class eispy2d.solvers.inverse.backprop.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

eispy2d.solvers.inverse.backprop.compute_contrast(E, J, NX, NY)#

Compute contrast function from total field and current density.

Computes the contrast function (relative permittivity or conductivity contrast) using the relationship between total field and current density in the scattering domain.

Parameters:
  • E (numpy.ndarray) – Total field matrix with shape (ND, NS) where ND is the number of domain points and NS is the number of sources.

  • J (numpy.ndarray) – Current density matrix with shape (ND, NS).

  • NX (int) – Number of pixels in the x-direction.

  • NY (int) – Number of pixels in the y-direction.

Returns:

Contrast function matrix with shape (NY, NX).

Return type:

numpy.ndarray

eispy2d.solvers.inverse.backprop.compute_current(Es, GS, gamma)#

Compute current density from scattered field measurements.

Computes the current density in the scattering domain using the Back-Propagation algorithm. The current density is estimated using the adjoint of the Green’s function matrix scaled by the gamma parameter.

Parameters:
  • Es (numpy.ndarray) – Scattered field measurements matrix. Shape (NM, NS) where NM is the number of measurement points and NS is the number of sources.

  • GS (numpy.ndarray) – Green’s function matrix from sources to measurement points. Shape (NM, ND) where ND is the number of domain points.

  • gamma (numpy.ndarray) – Gamma scaling parameter array with shape (NS,).

Returns:

Current density matrix with shape (ND, NS).

Return type:

numpy.ndarray

eispy2d.solvers.inverse.backprop.compute_gamma(Es, GS)#

Compute gamma parameter for Back-Propagation algorithm.

Computes the gamma parameter used in the Back-Propagation algorithm, which represents the optimal scaling factor for the current density estimation.

Parameters:
  • Es (numpy.ndarray) – Scattered field measurements matrix. Shape (NM, NS) where NM is the number of measurement points and NS is the number of sources.

  • GS (numpy.ndarray) – Green’s function matrix from sources to measurement points. Shape (NM, ND) where ND is the number of domain points.

Returns:

Gamma parameter array with shape (NS,).

Return type:

numpy.ndarray

eispy2d.solvers.inverse.bim module#

Born Iterative Method for Electromagnetic Inverse Scattering.

This module implements the Born Iterative Method (BIM) for solving nonlinear electromagnetic inverse scattering problems. The BIM is a classical iterative approach that couples forward and inverse solvers to reconstruct the material properties of scattering objects.

The method works by iteratively improving the solution using the Born approximation, where each iteration involves solving a linearized inverse problem and updating the total field using a forward solver.

The implementation follows the Deterministic solver abstract class and provides a complete framework for nonlinear inverse scattering reconstruction.

Classes#

BornIterativeMethoddtm.Deterministic

Main class implementing the Born Iterative Method.

Constants#

FORWARDstr

Key for forward solver in serialization.

REGULARIZATIONstr

Key for regularization method in serialization.

STOP_CRITERIAstr

Key for stop criteria in serialization.

References

class eispy2d.solvers.inverse.bim.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.

eispy2d.solvers.inverse.bornapprox module#

First-Order Born Approximation for Electromagnetic Inverse Scattering.

This module implements the First-Order Born Approximation (FOBA) method for solving electromagnetic inverse scattering problems. The Born approximation is a linearization technique that assumes the total field inside the scattering object is approximately equal to the incident field.

This is a non-iterative method that provides a fast solution to the inverse scattering problem by solving a single linear system. While it’s limited to weak scatterers, it serves as an excellent starting point for more complex iterative methods and provides good results for low-contrast objects.

The method solves the linearized scattering equation:

E_s = G_S * chi * E_i

where E_s is the scattered field, G_S is the scattering Green’s function, chi is the contrast function, and E_i is the incident field.

Classes#

FirstOrderBornApproximationdtm.Deterministic

Main class implementing the First-Order Born Approximation method.

Constants#

REGULARIZATIONstr

Key for regularization method in serialization.

FORWARDstr

Key for forward solver in serialization.

References

class eispy2d.solvers.inverse.bornapprox.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

eispy2d.solvers.inverse.cgm module#

Conjugated Gradient Method for Electromagnetic Inverse Scattering

This module implements the Conjugated Gradient Method (CGM) for solving nonlinear electromagnetic inverse scattering problems. The method is based on gradient-based optimization techniques and uses the conjugate gradient algorithm to iteratively reconstruct the electromagnetic properties of scatterers from scattered field measurements.

The implementation includes various initialization strategies, step size optimization methods, and stopping criteria for robust convergence.

Classes#

ConjugatedGradientMethodExtends deterministic.Deterministic

Main implementation of the conjugated gradient method

Constants#

INITIAL_GUESSstr

Dictionary key for initial guess strategy

BACKGROUNDstr

Background initial guess strategy

BACKPROPAGATIONstr

Backpropagation initial guess strategy

IMAGEstr

Image-based initial guess strategy

QUALITATIVEstr

Qualitative initial guess strategy

STEPstr

Dictionary key for step size method

FIXEDstr

Fixed step size method

OPTIMUMstr

Optimum step size method

STOP_CRITERIAstr

Dictionary key for stopping criteria

References

Examples

>>> # Create CGM with background initial guess
>>> cgm = ConjugatedGradientMethod(initial_guess='background',
...                                step='optimum',
...                                stop_criteria=my_criteria)
>>> result = cgm.solve(input_data, discretization)
>>> # Create CGM with qualitative initial guess
>>> cgm = ConjugatedGradientMethod(initial_guess='qualitative',
...                                step='fixed',
...                                stop_criteria=my_criteria)
>>> result = cgm.solve(input_data, discretization)
class eispy2d.solvers.inverse.cgm.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)

eispy2d.solvers.inverse.csi module#

Contrast Source Inversion Method for Electromagnetic Inverse Scattering

This module implements the Contrast Source Inversion (CSI) method for solving nonlinear electromagnetic inverse scattering problems. The CSI method is an iterative algorithm that simultaneously reconstructs both the contrast function and the contrast sources (induced currents) in the investigation domain.

The method is based on minimizing a cost functional that includes both data error (difference between measured and computed scattered fields) and object error (consistency between contrast and current distributions). The algorithm uses conjugate gradient optimization to efficiently solve the nonlinear inverse problem.

Classes#

ContrastSourceInversion : Class implementing the CSI method for nonlinear inverse scattering.

Functions#

Optimized computational functions (JIT-compiled with Numba): get_data_error(Es, GS, J) : Compute data error term get_object_error(chi, E, J) : Compute object error term get_normalization_s(Es) : Compute scattered field normalization get_normalization_d(chi, Ei) : Compute domain normalization get_gradient(GS, rho, eta_s, r, GDaXr, eta_d) : Compute gradient get_gamma(g, glast) : Compute conjugate gradient coefficient update_direction(g, gamma, v) : Update search direction compute_constant(rho, GSv, eta_s, r, v_XGDv, eta_d) : Compute step size update_current(J, alpha, v) : Update current distribution update_total_field(E, alpha, GDv) : Update total field compute_contrast(J, E) : Compute contrast from current and field evaluate_objective_function(rho, eta_s, r, eta_d) : Evaluate cost function

Constants#

FORWARDstr

Dictionary key for forward solver

STOP_CRITERIAstr

Dictionary key for stopping criteria

Notes

The CSI method minimizes the following cost functional:

\[\begin{split}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}\end{split}\]

where \(F_S\) is the data error term, \(F_D\) is the object error term, \(\mathbf{J}\) is the contrast source, \(\\chi\) is the contrast function, and \(\mathbf{E}\) is the total electric field.

The method uses conjugate gradient optimization with Polak-Ribière updates for efficient convergence to the solution.

References

Examples

>>> # Create CSI method with MoM forward solver
>>> csi = ContrastSourceInversion(stop_criteria=my_criteria)
>>> result = csi.solve(input_data, discretization)
>>> # Create CSI with custom forward solver
>>> csi = ContrastSourceInversion(stop_criteria=my_criteria,
...                               forward_solver=my_forward_solver)
>>> result = csi.solve(input_data, discretization)
class eispy2d.solvers.inverse.csi.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)
eispy2d.solvers.inverse.csi.compute_constant(rho, GSv, eta_s, r, v_XGDv, eta_d)#

Compute optimal step size for CSI update.

This function computes the optimal step size that minimizes the CSI objective function along the search direction.

Parameters:
  • rho (numpy.ndarray) – Data residual

  • GSv (numpy.ndarray) – Scattered field Green’s function times direction

  • eta_s (float) – Scattered field normalization factor

  • r (numpy.ndarray) – Object residual

  • v_XGDv (numpy.ndarray) – Direction minus contrast convolution result

  • eta_d (float) – Domain normalization factor

Returns:

Optimal step size

Return type:

numpy.ndarray

eispy2d.solvers.inverse.csi.compute_contrast(J, E)#

Compute contrast function from contrast source and total field.

This function computes the contrast function by solving the least squares problem for the relationship J = chi E.

Parameters:
  • J (numpy.ndarray) – Contrast source

  • E (numpy.ndarray) – Total electric field

Returns:

Complex contrast function

Return type:

numpy.ndarray

eispy2d.solvers.inverse.csi.evaluate_objective_function(rho, eta_s, r, eta_d)#

Evaluate the CSI objective function.

This function computes the total cost function as the sum of normalized data fidelity and object constraint terms.

Parameters:
  • rho (numpy.ndarray) – Data residual term

  • eta_s (float) – Scattered field normalization factor

  • r (numpy.ndarray) – Object residual term

  • eta_d (float) – Domain normalization factor

Returns:

Total objective function value

Return type:

float

eispy2d.solvers.inverse.csi.get_data_error(Es, GS, J)#

Compute data error term for CSI algorithm.

This function computes the data error as the difference between the measured scattered field and the forward model prediction.

Parameters:
  • Es (numpy.ndarray) – Measured scattered electric field

  • GS (numpy.ndarray) – Scattered field Green’s function matrix

  • J (numpy.ndarray) – Current contrast source

Returns:

Data error term

Return type:

numpy.ndarray

eispy2d.solvers.inverse.csi.get_gamma(g, glast)#

Compute Polak-Ribiere conjugate gradient parameter.

This function computes the beta parameter for the Polak-Ribiere conjugate gradient method.

Parameters:
  • g (numpy.ndarray) – Current gradient

  • glast (numpy.ndarray) – Previous gradient

Returns:

Beta parameter for direction update

Return type:

numpy.ndarray

eispy2d.solvers.inverse.csi.get_gradient(GS, rho, eta_s, r, GDaXr, eta_d)#

Compute gradient for CSI optimization.

This function computes the gradient of the CSI objective function with respect to the contrast source.

Parameters:
  • GS (numpy.ndarray) – Scattered field Green’s function matrix

  • rho (numpy.ndarray) – Data residual

  • eta_s (float) – Scattered field normalization factor

  • r (numpy.ndarray) – Object residual

  • GDaXr (numpy.ndarray) – Green’s function convolution result

  • eta_d (float) – Domain normalization factor

Returns:

Gradient vector

Return type:

numpy.ndarray

eispy2d.solvers.inverse.csi.get_normalization_d(chi, Ei)#

Compute domain normalization factor.

This function computes the normalization factor for the domain as the sum of squared magnitudes of the contrast times incident field.

Parameters:
  • chi (numpy.ndarray) – Contrast function diagonal matrix

  • Ei (numpy.ndarray) – Incident electric field

Returns:

Domain normalization factor

Return type:

float

eispy2d.solvers.inverse.csi.get_normalization_s(Es)#

Compute scattered field normalization factor.

This function computes the normalization factor for the scattered field as the sum of squared magnitudes.

Parameters:

Es (numpy.ndarray) – Scattered electric field

Returns:

Scattered field normalization factor

Return type:

float

eispy2d.solvers.inverse.csi.get_object_error(chi, E, J)#

Compute object error term for CSI algorithm.

This function computes the object error as the difference between the contrast times the total field and the contrast source.

Parameters:
  • chi (numpy.ndarray) – Contrast function diagonal matrix

  • E (numpy.ndarray) – Total electric field

  • J (numpy.ndarray) – Current contrast source

Returns:

Object error term

Return type:

numpy.ndarray

eispy2d.solvers.inverse.csi.update_current(J, alpha, v)#

Update contrast source with optimal step size.

This function updates the contrast source by taking an optimal step along the search direction.

Parameters:
  • J (numpy.ndarray) – Current contrast source

  • alpha (numpy.ndarray) – Optimal step size

  • v (numpy.ndarray) – Search direction

Returns:

Updated contrast source

Return type:

numpy.ndarray

eispy2d.solvers.inverse.csi.update_direction(g, gamma, v)#

Update search direction using conjugate gradient.

This function updates the search direction using the current gradient and the conjugate gradient parameter.

Parameters:
  • g (numpy.ndarray) – Current gradient

  • gamma (numpy.ndarray) – Conjugate gradient parameter

  • v (numpy.ndarray) – Previous search direction

Returns:

Updated search direction

Return type:

numpy.ndarray

eispy2d.solvers.inverse.csi.update_total_field(E, alpha, GDv)#

Update total electric field with optimal step size.

This function updates the total electric field by taking an optimal step along the direction of the Green’s function convolution.

Parameters:
  • E (numpy.ndarray) – Current total electric field

  • alpha (numpy.ndarray) – Optimal step size

  • GDv (numpy.ndarray) – Green’s function convolution of search direction

Returns:

Updated total electric field

Return type:

numpy.ndarray

eispy2d.solvers.inverse.dbim module#

Distorted Born Iterative Method for Electromagnetic Inverse Scattering.

This module implements the Distorted Born Iterative Method (DBIM) [1]_ for solving two-dimensional electromagnetic inverse scattering problems. The DBIM is a nonlinear iterative method that couples forward and inverse solvers to reconstruct the electromagnetic properties of unknown scatterers from scattered field measurements.

The method is based on the Born approximation with distorted incident fields, where the Green’s function is iteratively updated to account for the estimated contrast function. This approach provides better convergence properties compared to the standard Born Iterative Method, particularly for high-contrast scatterers.

Classes#

DistortedBornIterativeMethod

Main implementation of the DBIM algorithm

Functions#

update_greenf

Update Green’s function matrix with current contrast estimate

faster_computation

Optimized computation for Green’s function update (JIT-compiled)

Examples

>>> import dbim
>>> import forward
>>> import regularization
>>> import stopcriteria
>>> # Create solver components
>>> forward_solver = forward.MomentMethod()
>>> reg_solver = regularization.TikhonovRegularization(alpha=1e-3)
>>> stop_criteria = stopcriteria.MaxIterations(max_iterations=20)
>>> # Create DBIM solver
>>> solver = dbim.DistortedBornIterativeMethod(
...     forward_solver=forward_solver,
...     regularization=reg_solver,
...     stop_criteria=stop_criteria
... )
>>> # Solve inverse problem
>>> result = solver.solve(input_data, discretization)

References

class eispy2d.solvers.inverse.dbim.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)
eispy2d.solvers.inverse.dbim.faster_computation(X, I, GD, GS)#

Optimized computation for Green’s function update.

This JIT-compiled function performs the core matrix operations required for updating the Green’s function in the DBIM algorithm. The computation is optimized using Numba for maximum performance.

The function computes: .. math:

G_S^{new} = [(I - G_D \chi)^{-1} G_S^T]^T

where the transposition is used to ensure proper matrix dimensions.

Parameters:
  • X (numpy.ndarray) – Diagonal matrix representation of the contrast function, created from the flattened contrast array

  • I (numpy.ndarray) – Identity matrix of size matching the contrast function

  • GD (numpy.ndarray) – Domain Green’s function matrix

  • GS (numpy.ndarray) – Scattered field Green’s function matrix

Returns:

Updated scattered field Green’s function matrix

Return type:

numpy.ndarray

Notes

This function is JIT-compiled with Numba for high performance. The matrix inversion is performed using standard linear algebra operations. For large problems, this operation can be computationally intensive and may benefit from specialized solvers.

The function assumes that the matrix (I - GD@X) is invertible. In practice, this is generally true for physical scattering problems, but numerical issues may arise for very high contrast values.

Examples

>>> X = np.diag([1.0, 1.5, 1.2])
>>> I = np.eye(3)
>>> result = faster_computation(X, I, GD, GS)
eispy2d.solvers.inverse.dbim.update_greenf(contrast, greenf_d, greenf_s)#

Update Green’s function matrix using current contrast estimate.

This function updates the scattered field Green’s function matrix to account for the current contrast function estimate. This is the key step that distinguishes DBIM from standard Born methods.

The update is performed using the formula:

\[G_S^{new} = (I - G_D \chi)^{-1} G_S\]

where (G_S) is the scattered field Green’s function, (G_D) is the domain Green’s function, (chi) is the contrast function, and (I) is the identity matrix. :type contrast: numpy.ndarray :param contrast: Current contrast function estimate as a 2D array representing

the spatial distribution of contrast values

Parameters:
  • greenf_d (numpy.ndarray) – Domain Green’s function matrix relating contrast sources to total field within the investigation domain

  • greenf_s (numpy.ndarray) – Current scattered field Green’s function matrix

Returns:

Updated scattered field Green’s function matrix that incorporates the current contrast estimate

Return type:

numpy.ndarray

Notes

This function creates a diagonal matrix from the contrast function and uses the optimized JIT-compiled faster_computation function to perform the matrix inversion and multiplication efficiently.

The updated Green’s function provides a better approximation to the true scattering behavior, leading to improved convergence compared to methods that use fixed Green’s functions.

Examples

>>> contrast = np.array([[1.0, 1.5], [1.2, 1.8]])
>>> updated_gs = update_greenf(contrast, greenf_d, greenf_s)
>>> print(updated_gs.shape)
(num_receivers, num_domain_points)

eispy2d.solvers.inverse.deterministic module#

eispy2d.solvers.inverse.ecsi module#

Extended Contrast Source Inversion (ECSI) Method.

This module implements the Extended Contrast Source Inversion (ECSI) method for solving electromagnetic inverse scattering problems. ECSI is an advanced iterative nonlinear solver that extends the classical Contrast Source Inversion (CSI) approach by incorporating enhanced optimization techniques.

The method couples forward and inverse solvers in an iterative process, alternately updating the contrast function and current density distribution within the scattering domain. It employs conjugate gradient techniques for efficient convergence and can handle both lossy and lossless media.

Key Features#

  • Iterative nonlinear optimization for contrast reconstruction

  • Conjugate gradient-based direction updates

  • Support for both dielectric and conductive objects

  • Flexible stopping criteria

  • Integration with various forward solvers

Classes#

ExtendedContrastSourceInversion

Main implementation of the ECSI algorithm extending the deterministic solver base class.

Functions#

get_gamma

Compute the Polak-Ribière conjugate gradient parameter.

compute_constant_j

Calculate the step size for current density updates.

update_contrast

Update the contrast function using computed step size and direction.

get_gradient_x

Compute the gradient of the objective function with respect to contrast.

compute_constant_x

Calculate the step size for contrast updates.

Notes

The implementation uses Numba JIT compilation for performance-critical functions and supports both perfect dielectric and good conductor approximations.

References

class eispy2d.solvers.inverse.ecsi.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
eispy2d.solvers.inverse.ecsi.compute_constant_j(gv, GSv, eta_s, v_XGDva, eta_d)#

Compute optimal step size for current density update.

Calculates the optimal step size for updating the current density in the ECSI algorithm by minimizing the cost function along the search direction.

Parameters:
  • gv (numpy.ndarray) – Product of gradient and conjugate direction for current density.

  • GSv (numpy.ndarray) – Green’s function applied to search direction.

  • eta_s (float) – Normalization factor for scattered field data.

  • v_XGDva (numpy.ndarray) – Auxiliary vector for object error computation.

  • eta_d (float) – Normalization factor for object error.

Returns:

Optimal step size for current density update.

Return type:

float

Notes

This function is JIT-compiled with Numba for performance. The step size minimizes the quadratic approximation of the cost function along the conjugate gradient direction.

eispy2d.solvers.inverse.ecsi.compute_constant_x(D, E, chi, J, Ei)#

Compute optimal step size for contrast update.

Calculates the optimal step size for updating the contrast function by solving a quadratic optimization problem along the search direction.

Parameters:
  • D (numpy.ndarray) – Diagonal matrix representation of search direction.

  • E (numpy.ndarray) – Total electric field distribution.

  • chi (numpy.ndarray) – Current contrast function as diagonal matrix.

  • J (numpy.ndarray) – Current density distribution.

  • Ei (numpy.ndarray) – Incident electric field distribution.

Returns:

Optimal step size for contrast update.

Return type:

float

Notes

This function is JIT-compiled with Numba for performance. The step size is computed by solving the quadratic equation:

\[\begin{split}\\alpha = \\frac{-(aC - Ac) + \\sqrt{(aC - Ac)^2 - 4(aB - Ab)(bC - Bc)}}{2(aB - Ab)}\end{split}\]

where the coefficients are derived from the cost function minimization.

eispy2d.solvers.inverse.ecsi.get_gamma(g, glast)#

Compute the Polak-Ribière conjugate gradient parameter.

Calculates the beta parameter for the Polak-Ribière conjugate gradient method used to update search directions in the optimization process.

Parameters:
  • g (numpy.ndarray) – Current gradient vector.

  • glast (numpy.ndarray) – Previous gradient vector.

Returns:

Polak-Ribière parameter: \(\\beta = \\frac{\\Re(\\mathbf{g}^T (\\mathbf{g} - \\mathbf{g}_{old}))}{||\\mathbf{g}_{old}||^2}\)

Return type:

float

Notes

This function is JIT-compiled with Numba for performance. The Polak-Ribière method generally provides better convergence properties than the Fletcher-Reeves method for nonlinear optimization problems.

eispy2d.solvers.inverse.ecsi.get_gradient_x(eta_d, J, E, X)#

Compute gradient of cost function with respect to contrast.

Calculates the gradient of the ECSI cost function with respect to the contrast function using the current field and current density distributions.

Parameters:
  • eta_d (float) – Normalization factor for object error.

  • J (numpy.ndarray) – Current density distribution.

  • E (numpy.ndarray) – Electric field distribution.

  • X (numpy.ndarray) – Current contrast function values.

Returns:

Gradient vector with respect to contrast function.

Return type:

numpy.ndarray

Notes

This function is JIT-compiled with Numba for performance. The gradient is computed using the relationship between current density and contrast:

\[\begin{split}\\nabla_X F = \\eta_d \\left( \\frac{\\mathbf{J} \\cdot \\mathbf{E}^*}{||\\mathbf{E}||^2} - X \\right)\end{split}\]
eispy2d.solvers.inverse.ecsi.update_contrast(X, alpha, d)#

Update contrast function with step size and direction.

Updates the contrast function using the computed step size and search direction.

Parameters:
  • X (numpy.ndarray) – Current contrast function values.

  • alpha (float) – Step size for the update.

  • d (numpy.ndarray) – Search direction vector.

Returns:

Updated contrast function: \(X_{new} = X_{old} + \\alpha d\)

Return type:

numpy.ndarray

Notes

This function is JIT-compiled with Numba for performance. It performs a simple linear update of the contrast function.

eispy2d.solvers.inverse.evolutionary module#

class eispy2d.solvers.inverse.evolutionary.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

eispy2d.solvers.inverse.inverse module#

eispy2d.solvers.inverse.lsm module#

class eispy2d.solvers.inverse.lsm.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)
eispy2d.solvers.inverse.lsm.solve(U, s, V, solution, rhs, alpha)#
eispy2d.solvers.inverse.lsm.standard(x)#

eispy2d.solvers.inverse.mrcsi module#

The Born Iterative Method.

This module implements the Born Iterative Method [1]_ as a derivation of Solver class. The object contains an object of a forward solver and one of linear inverse solver. The method solves the nonlinear inverse problem iteratively. The implemented in BornIterativeMethod

References

class eispy2d.solvers.inverse.mrcsi.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.

eispy2d.solvers.inverse.mrcsi.compute_delta_square(chi, Ei, J, GDJ, eta_d)#
eispy2d.solvers.inverse.mrcsi.get_gradient_x(chi, E, J, eta_d, gradXx, gradXy, dx, dy, p, rho, eta_s, d2)#

eispy2d.solvers.inverse.music module#

class eispy2d.solvers.inverse.music.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)
eispy2d.solvers.inverse.music.solve(U, GS, x)#

eispy2d.solvers.inverse.osm module#

class eispy2d.solvers.inverse.osm.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)
eispy2d.solvers.inverse.osm.far_field_solution(inputdata)#
eispy2d.solvers.inverse.osm.near_field_solution(inputdata)#

eispy2d.solvers.inverse.som module#

The Born Iterative Method.

This module implements the Born Iterative Method [1]_ as a derivation of Solver class. The object contains an object of a forward solver and one of linear inverse solver. The method solves the nonlinear inverse problem iteratively. The implemented in BornIterativeMethod

References

class eispy2d.solvers.inverse.som.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.

eispy2d.solvers.inverse.som.compute_J(J_po, Gs_V_ne, alpha_ne)#
eispy2d.solvers.inverse.som.compute_X(Et, J, J_po_norm_sq)#
eispy2d.solvers.inverse.som.compute_alpha(GS, Gs_V_ne, rho, del_dat, E_s_norm_sq, Xe, GDGs_V_nerho, del_sta, J_po_norm_sq, alpha_neo, N, L)#
eispy2d.solvers.inverse.som.compute_objective_function(del_dat, E_s_norm_sq, del_sta, J_po_norm_sq)#
eispy2d.solvers.inverse.som.compute_rho(grad, grado, N, L, rhoo)#
eispy2d.solvers.inverse.som.gradient_terms(GS, Gs_V_ne, del_dat, E_s_norm_sq, N, L, del_sta, J_po_norm_sq)#
eispy2d.solvers.inverse.som.initial_parameters(GS, L, Es)#
eispy2d.solvers.inverse.som.update_last_parameters(Xe, E_po, J_po, GS, Gs_V_nealpha_ne, Es, GDGs_V_nealpha_ne)#

eispy2d.solvers.inverse.stochastic module#

Module contents#

Inverse solvers for electromagnetic inverse scattering problems.

Comprehensive collection of inverse scattering algorithms: - Deterministic methods: BIM, DBIM, CSI, ECSI, MRCSI, CGM, Born, Backprop - Qualitative methods: LSM, OSM, SOM, MUSIC - Stochastic methods: Evolutionary algorithms

class eispy2d.solvers.inverse.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.inverse.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.inverse.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.inverse.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.inverse.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.inverse.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.inverse.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.inverse.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.inverse.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.inverse.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.inverse.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.inverse.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.inverse.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.