eispy2d.solvers.base package#

Base classes for solvers in eispy2d.

Provides abstract base classes that define the interface for all solvers: - ForwardSolver: Base for forward problem solvers - InverseSolver: Base for inverse problem solvers - Deterministic: Base for deterministic inverse methods - Stochastic: Base for stochastic inverse methods

class eispy2d.solvers.base.Deterministic(alias='', parallelization=False)#

Bases: InverseSolver

Base class for deterministic inverse scattering solvers.

This class provides the foundation for all deterministic inverse scattering methods in the eispy2d library. It inherits from InverseSolver and implements the common interface required by all deterministic algorithms.

Deterministic solvers are characterized by their reproducible behavior - given the same input data and parameters, they will always produce the same output. This is in contrast to stochastic methods that may produce different results on different runs due to random components.

The class serves as an abstract base that defines the standard workflow for deterministic inverse solvers: 1. Initialize solver with configuration parameters 2. Solve the inverse problem using deterministic algorithm 3. Save/load solver state for persistence 4. Copy solver instances for parallel or comparative studies

Parameters:
  • alias (str, default='') – Unique identifier for the solver instance. Used for file naming when saving/loading solver state and for identification in multi-solver comparisons.

  • parallelization (bool, default=False) – Whether to enable parallel processing capabilities. When True, the solver may utilize multiple CPU cores or parallel algorithms where available.

alias#

Solver identifier string

Type:

str

parallelization#

Parallelization flag

Type:

bool

name#

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

Type:

str

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

Solve the inverse scattering problem

save(file_path='')#

Save solver state to file

importdata(file_name, file_path='')#

Load solver state from file

copy(new=None)#

Create copy of solver instance

Notes

This class is designed to be inherited by specific deterministic algorithms. The base implementation provides standard functionality while derived classes implement algorithm-specific behavior.

All methods in this class call the parent InverseSolver methods, ensuring consistent behavior across the solver hierarchy. Derived classes should override these methods to add algorithm-specific functionality while maintaining the standard interface.

Examples

This class is not used directly, but serves as base for specific solvers:

>>> # Example derived class structure
>>> class MyDeterministicMethod(Deterministic):
...     def __init__(self, my_param, **kwargs):
...         super().__init__(**kwargs)
...         self.my_param = my_param
...         self.name = 'My Deterministic Method'
...
...     def solve(self, inputdata, discretization, **kwargs):
...         result = super().solve(inputdata, discretization, **kwargs)
...         # Add algorithm-specific processing
...         return result

See also

inverse.InverseSolver

Parent class providing basic solver interface

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

Initialize the deterministic inverse solver.

Parameters:
  • alias (str, default='') – Unique identifier for the solver instance. This string is used for file naming when saving/loading solver state and for identification in multi-solver studies. Should be descriptive and unique within the application context.

  • parallelization (bool, default=False) – Flag to enable parallel processing capabilities. When True, the solver may utilize multiple CPU cores or parallel algorithms where available in the specific implementation.

Notes

This method calls the parent InverseSolver initialization to establish the basic solver framework. Derived classes should call this method via super() and then add their specific initialization requirements.

The parallelization flag is stored for use by derived classes but does not activate any parallel processing by itself. Each specific algorithm implementation decides how to utilize this flag.

Examples

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

Create a copy of the solver instance.

This method creates a deep copy of the current solver instance, including all configuration parameters and settings. The copy can be used independently without affecting the original solver.

Parameters:

new (Deterministic, optional) – If provided, the current solver’s configuration will be copied into this existing instance. If None, a new instance will be created and returned.

Returns:

If new is None, returns a new Deterministic instance with the same configuration. If new is provided, returns None and the configuration is copied into the new instance.

Return type:

Deterministic or None

Notes

This method creates independent copies that can be used for parallel processing, parameter studies, or comparative analysis without interference between instances.

The base implementation copies common solver attributes. Derived classes should override this method to handle algorithm-specific parameters:

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

if new is None:
return MyDeterministicSolver(

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

)

else:

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

```

Examples

>>> # Create independent copy
>>> solver_copy = solver.copy()
>>> print(f"Original: {solver.alias}, Copy: {solver_copy.alias}")
>>> # Copy configuration into existing instance
>>> target_solver = Deterministic()
>>> solver.copy(target_solver)
>>> print(f"Target now has alias: {target_solver.alias}")
>>> # Use for parameter studies
>>> solvers = [solver.copy() for _ in range(5)]
>>> # Modify each copy independently for different parameters

See also

__init__

Initialize new solver instance

importdata(file_name, file_path='')#

Load solver state from previously saved file.

This method deserializes solver state from a file that was previously created using the save method. It restores all configuration parameters, algorithm settings, and internal state to recreate the exact solver configuration.

Parameters:
  • file_name (str) – Name of the file containing the saved solver state. This should match the filename created by the save method.

  • file_path (str, default='') – Directory path where the save file is located. If empty, looks in the current directory.

Returns:

Dictionary containing the loaded solver state data. This provides access to all restored parameters and settings.

Return type:

dict

Notes

The base implementation loads common solver attributes. Derived classes should override this method to restore algorithm-specific state information:

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

data = super().importdata(file_name, file_path=file_path) self.my_specific_param = data[‘my_specific_param’] # Restore additional algorithm-specific data return data

```

The method completely replaces the current solver state with the loaded configuration, so any existing settings will be lost.

Examples

>>> # Load from current directory
>>> data = solver.importdata('solver_state.pkl')
>>> print(f"Loaded {len(data)} parameters")
>>> # Load from specific directory
>>> data = solver.importdata('state.pkl', file_path='/path/to/files/')
>>> print(f"Restored solver configuration from {file_path}")
Raises:
  • FileNotFoundError – If the specified file does not exist

  • pickle.UnpicklingError – If the file is corrupted or incompatible

See also

save

Save solver state to file

save(file_path='')#

Save solver state to file for later restoration.

This method serializes the current solver state including all configuration parameters, algorithm settings, and internal state to a file. The saved state can later be restored using the importdata method.

Parameters:

file_path (str, default='') – Base path for saving the solver state. The actual filename will be constructed by appending the solver’s alias to this base path. If empty, saves to current directory.

Returns:

Dictionary containing the serialized solver state data. This includes all necessary information to fully restore the solver configuration and state.

Return type:

dict

Notes

The base implementation saves common solver attributes. Derived classes should override this method to include algorithm-specific state information:

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

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

```

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

Examples

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

See also

importdata

Load solver state from file

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

Solve the electromagnetic inverse scattering problem.

This method provides the standard interface for solving inverse scattering problems using deterministic methods. The base implementation calls the parent InverseSolver method to handle common setup and validation tasks.

Parameters:
  • inputdata (InputData) – Input data object containing: - scattered_field: Measured scattered field data - configuration: Problem configuration (frequency, background, etc.) - resolution: Desired reconstruction resolution - indicators: Performance metrics to compute

  • discretization (Discretization) – Discretization object containing: - elements: Spatial discretization grid - GS: Scattered field Green’s function matrix - GD: Domain Green’s function matrix (if needed) - Methods for field interpolation and imaging

  • print_info (bool, default=True) – Whether to print algorithm progress and iteration information during the solving process. Useful for monitoring convergence and debugging.

  • print_file (file-like object, default=sys.stdout) – Output stream for printing information. Can be redirected to files or other output streams as needed.

Returns:

Result object containing reconstruction results and performance metrics. The specific contents depend on the algorithm implementation but typically include: - Reconstructed electromagnetic properties - Convergence history - Performance metrics - Algorithm-specific information

Return type:

Result

Notes

This base implementation performs common setup tasks and validation that are required by all deterministic solvers. Derived classes should override this method to implement their specific algorithm while calling the parent method for initialization:

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

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

```

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

Examples

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

Bases: ABC

Abstract base class for forward solvers.

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

name#

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

Type:

str

parallelization#

Whether parallel processing is enabled.

Type:

bool

et#

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

Type:

numpy.ndarray

ei#

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

Type:

numpy.ndarray

es#

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

Type:

numpy.ndarray

epsilon_r#

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

Type:

numpy.ndarray

sigma#

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

Type:

numpy.ndarray

configuration#

Problem configuration object.

Type:

Configuration

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

Execute the forward solver given a problem input.

incident_field(resolution, configuration)#

Return the incident field for a given resolution.

save(file_name, file_path='')#

Save simulation data.

importdata(file_name, file_path='')#

Import solver data from file.

__init__(parallelization=False)#

Create a forward solver object.

Parameters:

None

abstractmethod __str__()#

Print information of the method object.

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

Return the incident field for a given resolution.

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

  • configuration (Configuration) – Problem configuration object.

Returns:

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

Return type:

numpy.ndarray

abstractmethod save(file_name, file_path='')#

Save simulation data.

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

Execute the forward solver given a problem input.

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

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

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

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

Returns:

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

Return type:

tuple

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

Bases: ABC

Abstract base class for inverse scattering solvers.

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

name#

The name of the solver.

Type:

str

alias#

Short identifier for the solver.

Type:

str

parallelization#

Whether parallel processing is enabled.

Type:

bool

execution_time#

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

Type:

float

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

Solve the inverse scattering problem.

save(file_path='')#

Save solver state to file.

importdata(file_name, file_path='')#

Load solver state from file.

copy(new=None)#

Create a copy of the solver instance.

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

Create an inverse solver object.

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

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

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

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

copy(new=None)#

Create a copy of the solver instance.

Parameters:

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

Returns:

New instance if new=None, otherwise None.

Return type:

InverseSolver or None

abstractmethod importdata(file_name, file_path='')#

Import solver configuration from file.

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

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

Returns:

Dictionary containing the imported data.

Return type:

dict

abstractmethod save(file_path='')#

Save solver configuration to file.

Parameters:

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

Returns:

Dictionary containing the serialized solver data.

Return type:

dict

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

Solve the inverse scattering problem.

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

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

  • discretization (Discretization) – Discretization scheme to use.

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

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

Returns:

Result object containing the reconstruction results.

Return type:

Result

class eispy2d.solvers.base.OutputMode(rule, reference=None, sample_rate=5)#

Bases: object

Processing strategy for stochastic method results.

Defines how multiple execution results are combined into a single output result.

Parameters:
  • rule ({'each', 'best', 'worst', 'average'}) – Processing rule: - ‘each’: Return all individual results - ‘best’: Return the result with best reference indicator - ‘worst’: Return the result with worst reference indicator - ‘average’: Return averaged results using reference indicator

  • reference (str, optional) – Indicator name used for best/worst/average selection (required unless rule=’each’).

  • sample_rate (float, default=5) – Sampling rate for averaging (0-100%).

make(name, method_name, results)#

Process results according to the specified rule.

copy(new=None)#

Create a copy of the OutputMode object.

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

Process results according to the specified rule.

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

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

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

Returns:

Processed result(s) according to the rule.

Return type:

Result or list of Result

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

Bases: InverseSolver

Base class for stochastic inverse scattering solvers.

This class provides the foundation for stochastic inverse scattering methods in the eispy2d library. Stochastic solvers use random processes during execution and may produce different results on different runs even with identical inputs.

nexec#

Number of executions to perform.

Type:

int

outputmode#

Strategy for processing multiple execution results.

Type:

OutputMode

_single_execution#

Whether only one execution is required.

Type:

bool

copy(new=None)#

Create a copy of the solver instance.

Parameters:

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

Returns:

New instance if new=None, otherwise None.

Return type:

InverseSolver or None

importdata(file_name, file_path='')#

Import solver configuration from file.

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

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

Returns:

Dictionary containing the imported data.

Return type:

dict

property nexec#

Set the number of executions.

Parameters:

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

Raises:
abstractmethod save(file_path='')#

Save solver configuration to file.

Parameters:

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

Returns:

Dictionary containing the serialized solver data.

Return type:

dict

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

Solve the inverse scattering problem.

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

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

  • discretization (Discretization) – Discretization scheme to use.

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

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

Returns:

Result object containing the reconstruction results.

Return type:

Result