eispy2d package#

Subpackages#

Module contents#

EISPY2D: Open-Source Python Library for Electromagnetic Inverse Scattering

A comprehensive framework for developing and comparing algorithms for two-dimensional electromagnetic inverse scattering problems.

class eispy2d.Ackley#

Bases: ObjectiveFunction

Ackley benchmark function (canonical, nonlinear, multimodal).

eval(x)#

Evaluate objective function for a solution.

Parameters:

x (numpy.ndarray) – Solution vector.

Returns:

Objective function value.

Return type:

float

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

Bases: ForwardSolver

Analytical Solution for Electromagnetic Scattering by Cylinders.

This class implements analytical solutions for electromagnetic scattering by dielectric and perfectly conducting cylinders using cylindrical wave expansions. It provides exact solutions that can be used for validation of numerical methods and benchmarking purposes.

name#

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

Type:

str

contrast#

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

Type:

float or None

radius#

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

Type:

float or None

incident_field(resolution, configuration)#

Compute the incident field matrix.

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

SAVE_INTERN_FIELD=True)

Solve the analytical scattering problem.

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

Solve scattering by a dielectric cylinder analytically.

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

Solve scattering by a perfectly conducting cylinder analytically.

save(file_name, file_path='')#

Save the analytical solver object to file.

importdata(file_name, file_path='')#

Import analytical solver data from file.

__init__(contrast=None, radius=None)#

Create the analytical solver object.

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

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

__str__()#

Return string representation of the analytical solver.

Returns:

String description including radius and contrast if available.

Return type:

str

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

Solve scattering by a perfectly conducting cylinder analytically.

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

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

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

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

Raises:

MissingAttributesError – If radius attribute is None.

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

Solve scattering by a dielectric cylinder analytically.

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

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

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

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

Raises:

MissingAttributesError – If radius or contrast attributes are None.

importdata(file_name, file_path='')#

Import analytical solver data from file.

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

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

incident_field(resolution, configuration)#

Compute the incident field matrix.

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

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

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

Returns:

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

Return type:

numpy.ndarray

save(file_name, file_path='')#

Save the analytical solver object to file.

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

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

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

Solve the analytical scattering problem.

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

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

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

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

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

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

Raises:

WrongValueInput – If neither perfect_dielectric nor good_conductor is True.

class eispy2d.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.Benchmark(name='', method=None, discretization=None, testset=None, import_filename=None, import_filepath='')#

Bases: Experiment

Benchmark Class for Performance Evaluation of Inverse Scattering Algorithms.

This class provides a comprehensive framework for systematic performance evaluation of electromagnetic inverse scattering algorithms. It extends the Experiment class to handle multiple test sets and provides various analysis and visualization tools.

The Benchmark class supports different parallelization strategies to efficiently run large-scale performance evaluations and provides statistical analysis capabilities for comparing algorithm performance.

Parameters:
  • name (str, default: '') – Name identifier for the benchmark instance.

  • method (InverseMethod or list of InverseMethod, optional) – Single method or list of methods to be benchmarked.

  • discretization (Discretization or list of Discretization, optional) – Single discretization or list of discretizations to be used.

  • testset (TestSet or list of TestSet, optional) – Single test set or list of test sets for evaluation.

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

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

testset#

Test set(s) used for benchmarking.

Type:

TestSet or list of TestSet

results#

Results from benchmark execution.

Type:

numpy.ndarray

_single_testset#

Whether using a single test set or multiple.

Type:

bool

_testset_available#

Whether test set data is available.

Type:

bool

import_testsets(filename, filepath='')#

Import test sets from files.

run(parallelization=None)#

Execute the benchmark with optional parallelization.

plot(indicator, \*\*kwargs)#

Generate line plots of benchmark results.

boxplot(indicator, \*\*kwargs)#

Generate box plots of benchmark results.

violinplot(indicator, \*\*kwargs)#

Generate violin plots of benchmark results.

save(file_path='', save_testset=False)#

Save benchmark state to file.

importdata(file_name, file_path='')#

Import benchmark state from file.

__init__(name='', method=None, discretization=None, testset=None, import_filename=None, import_filepath='')#

Initialize the Benchmark instance.

Parameters:
  • name (str, default: '') – Name identifier for the benchmark instance.

  • method (InverseMethod or list of InverseMethod, optional) – Single method or list of methods to be benchmarked.

  • discretization (Discretization or list of Discretization, optional) – Single discretization or list of discretizations to be used.

  • testset (TestSet or list of TestSet, optional) – Single test set or list of test sets for evaluation.

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

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

Raises:

WrongTypeInput – If testset is not None, TestSet, or list of TestSet.

boxplot(indicator, axis=None, testset=None, method=None, yscale=None, show=False, file_name=None, file_path='', file_format='eps', title=None, fontsize=10, color='b', notch=False)#

Generate box plots of benchmark results.

Creates box plots showing the distribution of algorithm performance across test instances. Useful for comparing algorithm variability and identifying outliers.

Parameters:
  • indicator (str or list of str) – Performance indicator(s) to plot. Must be valid result indicators.

  • axis (matplotlib.axes.Axes or numpy.ndarray of Axes, optional) – Matplotlib axes to plot on. If None, new figure is created.

  • testset (int or str or list, optional) – Test set(s) to include in plot. Can be indices, names, or list.

  • method (int or str or list, optional) – Method(s) to include in plot. Can be indices, names, or list.

  • yscale ({'linear', 'log'}, optional) – Y-axis scale for the plot.

  • show (bool, default: False) – Whether to display the plot.

  • file_name (str, optional) – Name for saving the plot file (without extension).

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

  • file_format (str, default: 'eps') – File format for saving the plot.

  • title (str or bool or list of str, optional) – Title(s) for the plot(s). Can be string, boolean, or list.

  • fontsize (int, default: 10) – Font size for plot text.

  • color (str, default: 'b') – Color for the box plots.

  • notch (bool, default: False) – Whether to draw notched box plots.

Returns:

The axes used for plotting (if show=False and file_name=None).

Return type:

matplotlib.axes.Axes or numpy.ndarray of Axes

Raises:
compare(indicator, method=None, testset=None, reference=None, all2all=False, all2one=None, samples='methods')#

Perform statistical comparison of algorithm performance.

Conducts statistical tests to compare the performance of different algorithms, providing p-values and significance tests for determining if performance differences are statistically significant.

Parameters:
  • indicator (str) – Performance indicator to compare.

  • method (int or str or list, optional) – Method(s) to include in comparison.

  • testset (int or str or list, optional) – Test set(s) to include in comparison.

  • reference (int or str, optional) – Reference method for comparison.

  • all2all (bool, default: False) – Whether to perform all-to-all comparison.

  • all2one (int or str, optional) – Method to use as reference for all-to-one comparison.

  • samples ({'methods', 'testsets'}, default: 'methods') – Whether to compare across methods or test sets.

Returns:

Dictionary containing statistical comparison results including p-values and test statistics.

Return type:

dict

Raises:

WrongTypeInput – If indicator is None or invalid.

confint(indicator, method=None, testset=None, print_info=True, print_obj=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>, show=False, file_name=None, file_path='', file_format='eps', fontsize=10, axis=None, title=None, confidence_level=0.95, group='methods')#

Compute and visualize confidence intervals for performance indicators.

Calculates confidence intervals for algorithm performance metrics and creates visualizations to show the statistical uncertainty in the performance estimates.

Parameters:
  • indicator (str) – Performance indicator to compute confidence intervals for.

  • method (int or str or list, optional) – Method(s) to include in analysis.

  • testset (int or str or list, optional) – Test set(s) to include in analysis.

  • print_info (bool, default: True) – Whether to print confidence interval information.

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

  • show (bool, default: False) – Whether to display the plot.

  • file_name (str, optional) – Name for saving the plot file.

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

  • file_format (str, default: 'eps') – File format for saving the plot.

  • fontsize (int, default: 10) – Font size for plot text.

  • axis (matplotlib.axes.Axes, optional) – Matplotlib axes to plot on. If None, new figure is created.

  • title (str, optional) – Title for the plot.

  • confidence_level (float, default: 0.95) – Confidence level for interval computation (between 0 and 1).

  • group ({'methods', 'testsets'}, default: 'methods') – Whether to group by methods or test sets.

Returns:

Dictionary containing confidence interval information including lower bounds, upper bounds, and means.

Return type:

dict

Raises:

WrongTypeInput – If indicator is None or invalid.

evolution(indicator, axis=None, method=None, testset=None, labels=None, xlabel=None, title=None, fontsize=10, yscale=None, variable='testset', show=False, file_name=None, file_path='', file_format='eps')#

Plot evolution of performance indicators across test sets or methods.

Creates plots showing how algorithm performance evolves across different test sets or methods, useful for analyzing trends and comparing algorithm behavior.

Parameters:
  • indicator (str) – Performance indicator to plot.

  • axis (matplotlib.axes.Axes, optional) – Matplotlib axes to plot on. If None, new figure is created.

  • method (int or str or list, optional) – Method(s) to include in plot.

  • testset (int or str or list, optional) – Test set(s) to include in plot.

  • labels (list of str, optional) – Custom labels for the plot lines.

  • xlabel (str, optional) – Label for the x-axis.

  • title (str, optional) – Title for the plot.

  • fontsize (int, default: 10) – Font size for plot text.

  • yscale ({'linear', 'log'}, optional) – Y-axis scale for the plot.

  • variable ({'testset', 'method'}, default: 'testset') – Variable to plot evolution across.

  • show (bool, default: False) – Whether to display the plot.

  • file_name (str, optional) – Name for saving the plot file.

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

  • file_format (str, default: 'eps') – File format for saving the plot.

Raises:

Error – If called with single method and single testset.

import_testsets(filename, filepath='')#

Import test sets from files.

Loads test set(s) from the specified file(s) and sets them as the benchmark’s test set(s).

Parameters:
  • filename (str or list of str) – Name(s) of the file(s) containing test set data.

  • filepath (str or list of str, default: '') – Path(s) to the file(s). If single string, used for all files. If list, must have same length as filename.

Raises:
  • WrongTypeInput – If filename or filepath are not str or list of str.

  • WrongValueInput – If filepath list length doesn’t match filename list length.

importdata(file_name, file_path='')#

Import benchmark state from file.

Loads a previously saved benchmark configuration from file.

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

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

Notes

This method restores the benchmark configuration including methods, discretizations, and test set references. If test set data was not saved with the benchmark, the test sets need to be imported separately.

normality(indicator, axis=None, method=None, testset=None, fontsize=None, title=None, show=False, file_name=None, file_path='', file_format='eps')#

Test and visualize normality of performance indicators.

Performs statistical normality tests and creates Q-Q plots to assess whether the performance indicators follow a normal distribution. This is useful for determining appropriate statistical tests.

Parameters:
  • indicator (str) – Performance indicator to test for normality.

  • axis (matplotlib.axes.Axes, optional) – Matplotlib axes to plot on. If None, new figure is created.

  • method (int or str or list, optional) – Method(s) to include in analysis.

  • testset (int or str or list, optional) – Test set(s) to include in analysis.

  • fontsize (int, optional) – Font size for plot text.

  • title (str, optional) – Title for the plot.

  • show (bool, default: False) – Whether to display the plot.

  • file_name (str, optional) – Name for saving the plot file.

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

  • file_format (str, default: 'eps') – File format for saving the plot.

Raises:
plot(indicator, axis=None, testset=None, method=None, yscale=None, show=False, file_name=None, file_path='', file_format='eps', title=None, fontsize=10)#

Generate line plots of benchmark results.

Creates line plots showing the performance of algorithms across test instances. Supports multiple indicators, methods, and test sets.

Parameters:
  • indicator (str or list of str) – Performance indicator(s) to plot. Must be valid result indicators.

  • axis (matplotlib.axes.Axes or numpy.ndarray of Axes, optional) – Matplotlib axes to plot on. If None, new figure is created.

  • testset (int or str or list, optional) – Test set(s) to include in plot. Can be indices, names, or list.

  • method (int or str or list, optional) – Method(s) to include in plot. Can be indices, names, or list.

  • yscale ({'linear', 'log'}, optional) – Y-axis scale for the plot.

  • show (bool, default: False) – Whether to display the plot.

  • file_name (str, optional) – Name for saving the plot file (without extension).

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

  • file_format (str, default: 'eps') – File format for saving the plot.

  • title (str or bool or list of str, optional) – Title(s) for the plot(s). Can be string, boolean, or list.

  • fontsize (int, default: 10) – Font size for plot text.

Returns:

The axes used for plotting (if show=False and file_name=None).

Return type:

matplotlib.axes.Axes or numpy.ndarray of Axes

Raises:
reconstruction(image='contrast', mode=None, indicator=None, axis=None, testset=None, method=None, test=None, show=False, file_name=None, file_path='', file_format='eps', title=None, fontsize=10, source=None)#

Display reconstruction results from benchmark execution.

Visualizes the reconstructed images from algorithm execution, allowing comparison of different methods and test cases.

Parameters:
  • image ({'contrast', 'total field'}, default: 'contrast') – Type of image to display.

  • mode (str, optional) – Display mode for the reconstruction.

  • indicator (str, optional) – Performance indicator to use for selection.

  • axis (matplotlib.axes.Axes, optional) – Matplotlib axes to plot on. If None, new figure is created.

  • testset (int or str or list, optional) – Test set(s) to include in visualization.

  • method (int or str or list, optional) – Method(s) to include in visualization.

  • test (int or str or list, optional) – Specific test instance(s) to visualize.

  • show (bool, default: False) – Whether to display the plot.

  • file_name (str, optional) – Name for saving the plot file.

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

  • file_format (str, default: 'eps') – File format for saving the plot.

  • title (str, optional) – Title for the plot.

  • fontsize (int, default: 10) – Font size for plot text.

  • source (int, optional) – Source index for field visualization.

Raises:

MissingAttributesError – If results are not available.

run(parallelization=None)#

Execute the benchmark with optional parallelization.

Runs all methods on all test sets and stores the results. Supports various parallelization strategies to improve performance for large benchmarks.

Parameters:

parallelization ({None, False, True, 'test', 'testset', 'method'}, optional) – Parallelization strategy: - None or False: No parallelization (sequential execution) - True: Parallel execution of tests (single method, single testset) - ‘test’: Parallelize individual test instances - ‘testset’: Parallelize test sets - ‘method’: Parallelize methods

Raises:

Notes

The method automatically sets stochastic algorithms to AVERAGE_CASE mode for consistent benchmarking. Results are stored in the results attribute as a numpy array.

save(file_path='', save_testset=False)#

Save benchmark state to file.

Saves the benchmark configuration and optionally the test set data to a file for later retrieval.

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

  • save_testset (bool, default: False) – Whether to save the full test set data or just references. If False, only test set names are saved.

Notes

The file is saved with the benchmark’s name as filename using pickle serialization. Test set data can be large, so save_testset=False is recommended for most use cases.

property testset#

Get the test set(s) used for benchmarking.

Returns:

The test set(s) or their names if not loaded.

Return type:

TestSet or list of TestSet or str or list of str

violinplot(indicator, axis=None, testset=None, method=None, yscale=None, show=False, file_name=None, file_path='', file_format='eps', title=None, fontsize=10, color='b', notch=False)#

Generate violin plots of benchmark results.

Creates violin plots showing the probability density of algorithm performance across test instances. Combines aspects of box plots and kernel density estimation to show distribution shape.

Parameters:
  • indicator (str or list of str) – Performance indicator(s) to plot. Must be valid result indicators.

  • axis (matplotlib.axes.Axes or numpy.ndarray of Axes, optional) – Matplotlib axes to plot on. If None, new figure is created.

  • testset (int or str or list, optional) – Test set(s) to include in plot. Can be indices, names, or list.

  • method (int or str or list, optional) – Method(s) to include in plot. Can be indices, names, or list.

  • yscale ({'linear', 'log'}, optional) – Y-axis scale for the plot.

  • show (bool, default: False) – Whether to display the plot.

  • file_name (str, optional) – Name for saving the plot file (without extension).

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

  • file_format (str, default: 'eps') – File format for saving the plot.

  • title (str or bool or list of str, optional) – Title(s) for the plot(s). Can be string, boolean, or list.

  • fontsize (int, default: 10) – Font size for plot text.

  • color (str, default: 'b') – Color for the violin plots.

  • notch (bool, default: False) – Whether to draw notched violin plots.

Returns:

The axes used for plotting (if show=False and file_name=None).

Return type:

matplotlib.axes.Axes or numpy.ndarray of Axes

Raises:
class eispy2d.BinaryTournament(elitism=True, pair_selection='random')#

Bases: Selection

Binary tournament selection operator.

Selects individuals by running tournaments between randomly chosen pairs.

Parameters:
  • elitism (bool, default=True) – Whether to preserve the best individual.

  • pair_selection ({'random', 'permutation'}, default='random') – How to select pairs for tournaments.

copy(new=None)#
run(P1, fx1, P2=None, fx2=None, NPOP=None)#

Perform selection.

Parameters:
  • P1 (numpy.ndarray) – First population.

  • fx1 (numpy.ndarray) – Fitness values of first population.

  • P2 (numpy.ndarray, optional) – Second population (for elitism).

  • fx2 (numpy.ndarray, optional) – Fitness values of second population.

  • NPOP (int, optional) – Number of individuals to select.

Returns:

(selected_population, selected_fitness)

Return type:

tuple

class eispy2d.Binomial(crossover_rate)#

Bases: Crossover

Binomial crossover operator.

Creates offspring by mixing variables from two parents based on a crossover rate. Commonly used in Differential Evolution.

Parameters:

crossover_rate (float) – Probability of taking variable from the second parent.

Notes

Binomial crossover is the standard crossover operator in DE. Each variable has crossover_rate probability of coming from the second parent, otherwise from the first.

copy(new=None)#

Create a copy of the crossover operator.

Parameters:

new (Crossover, optional) – If provided, copies data into this object. If None, creates a new copy.

Return type:

Crossover or None

run(x1, x2, fx1, fx2, probability=None)#

Perform crossover operation.

Parameters:
  • x1 (numpy.ndarray) – Parent solutions.

  • x2 (numpy.ndarray) – Parent solutions.

  • fx1 (numpy.ndarray or float) – Fitness values of parents.

  • fx2 (numpy.ndarray or float) – Fitness values of parents.

  • probability (float, optional) – Crossover probability.

Returns:

(offspring, fitness) where fitness may be NaN for new offspring.

Return type:

tuple

class eispy2d.BornApproximation#

Bases: Initialization

Born approximation initialization.

Initializes population using the Born approximation to estimate initial fields. Requires DiscretizationElementBased representation.

Notes

This initialization uses the first-order Born approximation to initialize the total field, providing a better starting point than random initialization for electromagnetic inverse scattering problems.

run(population_size, representation, incident_field, inputdata)#

Initialize population.

Parameters:
  • population_size (int) – Number of individuals in the population.

  • representation (Representation) – Solution representation.

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

  • inputdata (InputData) – Input data object containing problem parameters.

Returns:

Initial population matrix (POP × NVAR).

Return type:

numpy.ndarray

class eispy2d.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.BoundaryCondition#

Bases: ABC

Abstract base class for boundary conditions in evolutionary algorithms.

Boundary conditions handle how variables that go outside the allowed range are treated during evolution. This class defines the interface for all boundary handling strategies.

run(x)#

Apply boundary condition to the solution vector.

abstractmethod run(x)#

Apply boundary condition to the solution vector.

Parameters:

x (numpy.ndarray) – Solution vector (1D or 2D) to be processed.

class eispy2d.CanonicalProblems(number_variables, lb, ub)#

Bases: Representation

Representation for canonical optimization problems.

Used for testing evolutionary algorithms on standard benchmark functions.

Parameters:
  • number_variables (int) – Number of decision variables.

  • lb (float or array-like) – Lower bound(s) for variables.

  • ub (float or array-like) – Upper bound(s) for variables.

contrast(x, mode='array')#

Extract contrast function from solution vector.

Parameters:
  • x (numpy.ndarray) – Solution vector.

  • mode ({'array', 'image'}, default='array') – Output format.

Returns:

Contrast function.

Return type:

numpy.ndarray

current(x)#

Extract current from solution vector.

Parameters:
  • x (numpy.ndarray) – Solution vector.

  • mode ({'array', 'image'}, default='array') – Output format.

Returns:

Current distribution.

Return type:

numpy.ndarray

scattered_field(x)#

Compute scattered field from solution.

Parameters:

x (numpy.ndarray) – Solution vector.

Returns:

Scattered field.

Return type:

numpy.ndarray

total_field(x, mode='array')#

Extract total field from solution vector.

Parameters:
  • x (numpy.ndarray) – Solution vector.

  • mode ({'array', 'image'}, default='array') – Output format.

Returns:

Total field.

Return type:

numpy.ndarray

class eispy2d.CaseStudy(name=None, method=None, discretization=None, test=None, stochastic_runs=30, save_stochastic_runs=False, import_filename=None, import_filepath='')#

Bases: Experiment

Comprehensive case study framework for electromagnetic inverse scattering.

This class extends the Experiment class to provide a complete framework for conducting case studies in electromagnetic inverse scattering problems. It supports both deterministic and stochastic methods, parallel execution, and comprehensive result analysis including statistical comparisons and visualizations.

A case study includes: - Test data (ground truth) for validation - One or more inverse scattering methods - Discretization parameters - Stochastic execution configuration - Result analysis and visualization tools

Parameters:
  • name (str, optional) – Name identifier for the case study

  • method (object or list of objects, optional) – Inverse scattering method(s) to be evaluated

  • discretization (object or list of objects, optional) – Discretization parameters for the methods

  • test (InputData or str, optional) – Test data for validation or filename if string

  • stochastic_runs (int, default=30) – Number of stochastic executions for statistical analysis

  • save_stochastic_runs (bool, default=False) – Whether to save individual stochastic execution results

  • import_filename (str, optional) – Filename to import case study configuration from

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

test#

Test data for validation

Type:

InputData or str

s_nexec#

Number of stochastic executions

Type:

int

s_save#

Flag for saving stochastic runs

Type:

bool

results#

Results from method execution(s)

Type:

object or list

run(parallelization=None, save_stochastic_executions=False)#

Execute the case study with specified parallelization

reconstruction(image='contrast', \*\*kwargs)#

Visualize reconstruction results

convergence(indicator, \*\*kwargs)#

Plot convergence analysis

boxplot(indicator, \*\*kwargs)#

Create boxplot for statistical analysis

compare(indicator, method=None, all2all=False, all2one=None)#

Perform statistical comparison between methods

confint(indicator, \*\*kwargs)#

Calculate and visualize confidence intervals

Examples

>>> # Single method case study
>>> case = CaseStudy(name='bim_test', method=bim_method,
...                  discretization=disc, test=test_data)
>>> case.run(parallelization=True)
>>> case.reconstruction(show=True)
>>> # Multiple method comparison
>>> methods = [bim_method, born_method]
>>> case = CaseStudy(name='comparison', method=methods,
...                  discretization=disc, test=test_data)
>>> case.run()
>>> case.compare('total_error')
>>> case.boxplot('total_error', show=True)
>>> # Stochastic analysis
>>> case = CaseStudy(name='stochastic', method=pso_method,
...                  discretization=disc, test=test_data,
...                  stochastic_runs=50, save_stochastic_runs=True)
>>> case.run()
>>> case.convergence('total_error', mean=True, show=True)
__init__(name=None, method=None, discretization=None, test=None, stochastic_runs=30, save_stochastic_runs=False, import_filename=None, import_filepath='')#

Initialize a case study for electromagnetic inverse scattering.

Creates a new case study with specified parameters or imports from an existing saved case study file.

Parameters:
  • name (str, optional) – Name identifier for the case study

  • method (object or list of objects, optional) – Inverse scattering method(s) to be evaluated

  • discretization (object or list of objects, optional) – Discretization parameters for the methods

  • test (InputData or str, optional) – Test data for validation or filename if string

  • stochastic_runs (int, default=30) – Number of stochastic executions for statistical analysis

  • save_stochastic_runs (bool, default=False) – Whether to save individual stochastic execution results

  • import_filename (str, optional) – Filename to import case study configuration from

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

Examples

>>> # Create new case study
>>> case = CaseStudy(name='test', method=my_method,
...                  discretization=my_disc, test=my_test)
>>> # Import from saved file
>>> case = CaseStudy(import_filename='saved_case.pkl')
__str__()#

Return string representation of the case study.

Creates a formatted string containing comprehensive information about the case study configuration, including inherited experiment details, test data status, and stochastic execution parameters.

Returns:

Formatted string representation of the case study

Return type:

str

Examples

>>> print(case)
CASE STUDY
Name: my_case
Method: Born Iterative Method
Test: test_scenario_1
Save stochastic runs? yes
Number of stochastic runs: 50
boxplot(indicator, axis=None, method=None, file_name=None, file_path='', file_format='eps', show=False, fontsize=10, title=None, mean=False, yscale=None, notch=False)#

Create boxplot visualization for stochastic method results.

Generates boxplot visualizations of performance indicators for stochastic methods to show statistical distributions of results across multiple executions.

Parameters:
  • indicator (str or list of str) – Performance indicator(s) to plot (e.g., ‘total_error’, ‘data_error’)

  • axis (matplotlib.axes.Axes or ndarray, optional) – Axes for plotting. If None, new figure is created

  • method (int, str, or list, optional) – Method indices or names to plot. If None, all stochastic methods are used

  • file_name (str, optional) – Name for saving the figure

  • file_path (str, default='') – Path for saving the figure

  • file_format (str, default='eps') – Format for saving the figure

  • show (bool, default=False) – Whether to display the figure

  • fontsize (int, default=10) – Font size for labels and titles

  • title (str, bool, list, or None, optional) – Figure title(s). If None, automatic titles are used

  • mean (bool, default=False) – Whether to show mean indicators (unused parameter)

  • yscale (str, optional) – Y-axis scale (‘linear’, ‘log’, etc.)

  • notch (bool, default=False) – Whether to show notches in boxplots

Returns:

(fig, ax) if axis is None and show is False

Return type:

tuple or None

Raises:

Examples

>>> # Basic boxplot
>>> case.boxplot('total_error', show=True)
>>> # Multiple indicators
>>> case.boxplot(['total_error', 'data_error'], show=True)
>>> # Compare stochastic methods
>>> case.boxplot('total_error', method=[0, 1], show=True)
>>> # Boxplot with notches
>>> case.boxplot('total_error', notch=True, show=True)
compare(indicator, method=None, all2all=False, all2one=None)#

Perform statistical comparison between methods.

Conducts statistical tests to compare performance indicators between different methods. Supports pairwise comparisons and multiple comparison procedures for stochastic methods.

Parameters:
  • indicator (str or list of str) – Performance indicator(s) to compare (e.g., ‘total_error’, ‘data_error’)

  • method (int, str, or list, optional) – Method indices or names to compare. If None, all methods are used

  • all2all (bool, default=False) – Whether to perform all-to-all comparisons in multiple comparison

  • all2one (int, optional) – Index of reference method for all-to-one comparisons

Raises:

Notes

The method automatically selects appropriate statistical tests: - Two-sample tests for stochastic vs. stochastic comparisons - One-sample tests for stochastic vs. deterministic comparisons - Multiple comparison procedures for more than two methods

Only stochastic methods with saved runs can be compared statistically. Deterministic methods are included as reference points.

Examples

>>> # Compare two methods
>>> case.compare('total_error', method=[0, 1])
>>> # Compare multiple indicators
>>> case.compare(['total_error', 'data_error'])
>>> # All-to-one comparison
>>> case.compare('total_error', all2one=0)
>>> # All-to-all comparison
>>> case.compare('total_error', all2all=True)
confint(indicator, method=None, axis=None, file_name=None, file_path='', file_format='eps', show=False, fontsize=10, title=None, print_info=True, print_obj=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>, confidence_level=0.95, xscale=None)#

Calculate and visualize confidence intervals for performance indicators.

Computes confidence intervals for performance indicators from stochastic method executions and creates visualization plots with optional statistical information output.

Parameters:
  • indicator (str or list of str) – Performance indicator(s) to analyze (e.g., ‘total_error’, ‘data_error’)

  • method (int, str, or list, optional) – Method indices or names to analyze. If None, all methods are used

  • axis (matplotlib.axes.Axes or ndarray, optional) – Axes for plotting. If None, new figure is created

  • file_name (str, optional) – Name for saving the figure

  • file_path (str, default='') – Path for saving the figure

  • file_format (str, default='eps') – Format for saving the figure

  • show (bool, default=False) – Whether to display the figure

  • fontsize (int, default=10) – Font size for labels and titles

  • title (str, bool, list, or None, optional) – Figure title(s). If None, automatic titles are used

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

  • print_obj (file-like object, default=sys.stdout) – Object to print statistical information to

  • confidence_level (float, default=0.95) – Confidence level for interval calculation (0 < confidence_level < 1)

  • xscale (str, optional) – X-axis scale (‘linear’, ‘log’, etc.)

Returns:

Axes object if axis is None and show is False

Return type:

matplotlib.axes.Axes or None

Raises:

Notes

Confidence intervals are calculated using appropriate statistical methods based on the distribution of the performance indicator values. The method requires stochastic methods with saved executions.

Examples

>>> # Basic confidence interval plot
>>> case.confint('total_error', show=True)
>>> # Multiple indicators with custom confidence level
>>> case.confint(['total_error', 'data_error'],
...              confidence_level=0.99, show=True)
>>> # Specific method analysis
>>> case.confint('total_error', method=0, show=True)
convergence(indicator, axis=None, method=None, file_name=None, file_path='', file_format='eps', show=False, fontsize=10, title=None, mean=False, yscale=None, sample_rate=None, widths=None, color=None, legend_size=None)#

Plot convergence analysis for performance indicators.

Visualizes the convergence behavior of specified performance indicators throughout the iterative process. Supports both deterministic and stochastic methods with options for mean curves and boxplots.

Parameters:
  • indicator (str or list of str) – Performance indicator(s) to plot (e.g., ‘total_error’, ‘data_error’)

  • axis (matplotlib.axes.Axes or ndarray, optional) – Axes for plotting. If None, new figure is created

  • method (int, str, or list, optional) – Method indices or names to plot. If None, all methods are used

  • file_name (str, optional) – Name for saving the figure

  • file_path (str, default='') – Path for saving the figure

  • file_format (str, default='eps') – Format for saving the figure

  • show (bool, default=False) – Whether to display the figure

  • fontsize (int, default=10) – Font size for labels and titles

  • title (str, bool, list, or None, optional) – Figure title(s). If None, automatic titles are used

  • mean (bool, default=False) – Whether to show mean curves for stochastic methods

  • yscale (str, optional) – Y-axis scale (‘linear’, ‘log’, etc.)

  • sample_rate (int, optional) – Sampling rate for stochastic convergence (default=20)

  • widths (float or array-like, optional) – Width of boxplots for stochastic methods

  • color (str, optional) – Color for plots

  • legend_size (int, optional) – Font size for legend

Returns:

(fig, axis) if axis is None and show is False

Return type:

tuple or None

Raises:

Examples

>>> # Basic convergence plot
>>> case.convergence('total_error', show=True)
>>> # Multiple indicators
>>> case.convergence(['total_error', 'data_error'], show=True)
>>> # Mean convergence for stochastic methods
>>> case.convergence('total_error', mean=True, show=True)
>>> # Compare methods
>>> case.convergence('total_error', method=[0, 1], show=True)
importdata(file_name, file_path='')#

Import case study configuration from a saved file.

Loads a previously saved case study configuration including test data, stochastic execution parameters, and all inherited experiment settings.

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

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

Examples

>>> case = CaseStudy()
>>> case.importdata('my_case.pkl', '/path/to/files/')
reconstruction(image='contrast', axis=None, method=None, file_name=None, file_path='', file_format='eps', show=False, fontsize=10, title=None, indicator=None, include_true=False, mode='all')#

Visualize reconstruction results from the case study.

Creates visualization plots of the reconstructed electromagnetic properties, with options to include ground truth, compare multiple methods, and handle stochastic results.

Parameters:
  • image (str, default='contrast') – Property to visualize: - ‘epsilon_r’: Relative permittivity - ‘sigma’: Conductivity - ‘both’: Both properties - ‘contrast’: Contrast function

  • axis (matplotlib.axes.Axes or ndarray, optional) – Axes for plotting. If None, new figure is created

  • method (int, str, or list, optional) – Method indices or names to plot. If None, all methods are used

  • file_name (str, optional) – Name for saving the figure

  • file_path (str, default='') – Path for saving the figure

  • file_format (str, default='eps') – Format for saving the figure

  • show (bool, default=False) – Whether to display the figure

  • fontsize (int, default=10) – Font size for labels and titles

  • title (str, bool, or None, optional) – Figure title. If None, automatic titles are used

  • indicator (str, optional) – Performance indicator for selecting best execution

  • include_true (bool, default=False) – Whether to include ground truth in the visualization

  • mode (str, default='all') – Mode for stochastic results: - ‘all’: Show all executions - ‘best’: Show only best execution

Returns:

Axes object if axis is None and show is False

Return type:

matplotlib.axes.Axes or None

Raises:

error.WrongValueInput – If image type is invalid for the problem configuration

Examples

>>> # Basic reconstruction plot
>>> case.reconstruction(show=True)
>>> # Include ground truth with both properties
>>> case.reconstruction(image='both', include_true=True, show=True)
>>> # Compare specific methods
>>> case.reconstruction(method=[0, 1], show=True)
>>> # Save reconstruction plot
>>> case.reconstruction(file_name='reconstruction',
...                    file_path='/results/', show=True)
run(parallelization=None, save_stochastic_executions=False)#

Execute the case study with the configured methods.

Runs the inverse scattering method(s) on the test data with specified parallelization strategy. Supports both deterministic and stochastic methods with different parallelization approaches.

Parameters:
  • parallelization (bool, str, or None, default=None) – Parallelization strategy: - None or True: Enable parallelization (default strategy) - False: Disable parallelization - ‘method’: Parallelize across methods - ‘executions’: Parallelize across executions

  • save_stochastic_executions (bool, default=False) – Whether to save individual stochastic execution results (parameter name kept for backward compatibility)

Raises:

error.MissingAttributesError – If test data is not available

Notes

The method automatically detects single vs. multiple methods and applies appropriate parallelization strategies:

  • For single deterministic methods: Simple parallel execution

  • For single stochastic methods: Parallel stochastic executions

  • For multiple methods: Choice between method-level or execution-level parallelization

Examples

>>> # Run with default parallelization
>>> case.run()
>>> # Run without parallelization
>>> case.run(parallelization=False)
>>> # Run with method-level parallelization
>>> case.run(parallelization='method')
save(file_path='', save_test=False)#

Save the case study configuration to a file.

Saves the complete case study configuration including test data, stochastic execution parameters, and all inherited experiment settings using pickle serialization.

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

  • save_test (bool, default=False) – Whether to save the complete test data object or just the name

Examples

>>> case.save('/path/to/save/', save_test=True)
property test#

Get the test data for validation.

Returns:

Test data object, filename string, or None if not set

Return type:

InputData or str or None

class eispy2d.Collocation(configuration=None, trial=None, elements=None, name=None, alias='clc', import_filename=None, import_filepath='')#

Bases: Discretization

Collocation method for electromagnetic inverse scattering discretization.

This class implements the collocation method for discretizing electromagnetic inverse scattering problems. The method uses trial functions and collocation points to approximate the solution of integral equations, providing an efficient framework for electromagnetic reconstruction algorithms.

The collocation method is particularly well-suited for problems where the Green’s function can be computed analytically or semi-analytically, making it computationally efficient for iterative reconstruction methods.

Parameters:
  • configuration (configuration.Configuration, optional) – Problem configuration object containing geometry and material properties

  • trial (str, optional) – Type of trial function to use (e.g., ‘pulse’, ‘linear’, ‘cubic’)

  • elements (int or tuple of int, optional) – Number of discretization elements. If int, creates square grid (N×N). If tuple, creates rectangular grid (NY×NX)

  • name (str, optional) – Custom name for the discretization method

  • alias (str, default='clc') – Short alias for the method used in file operations

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

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

trial#

Type of trial function used

Type:

str

elements#

Grid dimensions (NY, NX)

Type:

tuple of int

name#

Descriptive name of the discretization method

Type:

str

alias#

Short alias for the method

Type:

str

copy(new=None)#

Create a copy of the collocation instance

save(file_path='')#

Save configuration to file

importdata(file_name, file_path='')#

Import configuration from file

Raises:

error.MissingInputError – If required elements parameter is not provided

Notes

The collocation method discretizes the electromagnetic integral equation by choosing specific collocation points where the equation is enforced exactly. This approach transforms the continuous integral equation into a system of linear equations that can be solved numerically.

Trial functions commonly used include: - pulse: Piecewise constant functions - linear: Piecewise linear functions - cubic: Piecewise cubic functions

Examples

>>> # Create square grid collocation
>>> collocation = Collocation(configuration=config,
...                          trial='pulse',
...                          elements=64)
>>> # Create rectangular grid collocation
>>> collocation = Collocation(configuration=config,
...                          trial='linear',
...                          elements=(32, 64))
>>> # Import from saved configuration
>>> collocation = Collocation(import_filename='collocation_config.pkl')
>>> # Print method information
>>> print(collocation)
Collocation Method (64x64), trial function: pulse
__init__(configuration=None, trial=None, elements=None, name=None, alias='clc', import_filename=None, import_filepath='')#

Initialize the Collocation discretization method.

Parameters:
  • configuration (Configuration, optional) – Problem configuration object.

  • trial (str, optional) – Type of trial function (e.g., ‘pulse’, ‘linear’, ‘cubic’).

  • elements (int or tuple of int) – Number of discretization elements. If int, creates square grid (N×N). If tuple, creates rectangular grid (NY×NX).

  • name (str, optional) – Custom name for the discretization method.

  • alias (str, default='clc') – Short alias for file operations.

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

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

__str__()#

Return string representation of the collocation method.

Creates a formatted string containing the method configuration including discretization details and alias.

Returns:

Formatted string representation of the collocation method

Return type:

str

Examples

>>> print(collocation)
Collocation Method (64x64), trial function: pulse
Alias: clc
copy(new=None)#

Create a copy of the collocation instance.

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

Parameters:

new (Collocation 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:

Collocation or None

Examples

>>> # Create independent copy
>>> collocation_copy = collocation.copy()
>>> # Copy configuration to existing instance
>>> new_collocation = Collocation(configuration=config,
...                              trial='pulse',
...                              elements=(32, 32))
>>> collocation.copy(new_collocation)
importdata(file_name, file_path='')#

Import collocation configuration from a saved file.

Loads a previously saved collocation configuration including trial function type and discretization elements.

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

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

Examples

>>> collocation = Collocation()
>>> collocation.importdata('collocation_config.pkl', '/path/to/files/')
save(file_path='')#

Save the collocation configuration to a file.

Saves the complete collocation method configuration including trial function type and discretization elements using pickle serialization.

Parameters:

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

Examples

>>> collocation.save('/path/to/save/')
>>> collocation.save()  # Save in current directory
class eispy2d.Configuration(name=None, number_measurements=None, number_sources=None, observation_radius=None, frequency=None, wavelength=None, background_permittivity=1.0, background_conductivity=0.0, image_size=[1.0, 1.0], wavelength_unit=True, magnitude=1.0, perfect_dielectric=False, good_conductor=False, import_filename=None, import_filepath='', path='')#

Bases: object

The container of all fixed information shared between scenarios.

It stores all the information regarding domains sizes, background media and flags for indicating simplifications.

name#

A string naming the problem configuration.

path#

The path where the object file was saved.

NM#

Number of measurements

NS#

Number of sources

Ro#

Radius of observation (S-domain) [m]

Lx#

Size of image domain (D-domain) in x-axis [m]

epsilon_rb#

Background relative permittivity

sigma_b#

Background conductivity [S/m]

frequency#

Linear frequency of operation [Hz]

lambda_b#

Background wavelength [m]

kb#

Background wavenumber [1/m]

perfect_dielectric#

Flag for assuming perfect dielectric objects

good_conductor#

Flag for assuming good conductor objects

E0#

Magnitude of incident field [V/m].

__init__(name=None, number_measurements=None, number_sources=None, observation_radius=None, frequency=None, wavelength=None, background_permittivity=1.0, background_conductivity=0.0, image_size=[1.0, 1.0], wavelength_unit=True, magnitude=1.0, perfect_dielectric=False, good_conductor=False, import_filename=None, import_filepath='', path='')#

Build or import a configuration object.

You may either give the parameters or import information from a save object. In addition, you must give either the frequency of operation or the wavelength.

Parameters:
  • name (string) – A string naming the problem configuration.

  • number_measurements (int, default: 10) – Receivers in S-domain.

  • number_sources (int, default: 10) – Sources in S-domain

  • observation_radius (float, default: 1.1*sqrt(2)*max([Lx,Ly])) – Radius for circular array of sources and receivers at S-domain [m]

  • frequency (float) – Linear frequency of operation [Hz]

  • wavelength (float) – Background wavelength [m]

  • background_permittivity (float, default: 1.) – Relative permittivity.

  • background_conductivity (float, default: .0 [S/m])

  • image_size (2-tuple of int, default: (1., 1.)) – Side length of the image domain (D-domain). It may be given in meters or in wavelengths.

  • wavelength_unit (boolean, default: True) – If True, the variable image_size will be interpreted as given in wavelegnths. Otherwise, it will be interpreted in meters.

  • magnitude (float, default: 1.0) – Magnitude of the incident field.

  • perfect_dielectric (boolean, default: False) – If True, it indicates the assumption of only perfect dielectric objects. Then, only the relative permittivity map will be recovered.

  • good_conductor (boolean, default: False) – If True, it indicates the assumption of only good conductors objects. Then, only the conductivity map will be recovered.

  • import_filename (string, default: None) – A string with the name of the pickle file containing the information of a previous Configuration object.

  • import_filepath (string, default: '') – A string containing the path to the object to be imported.

__str__()#

Print object information.

copy(configuration=None)#

Return or set a copy of an object.

draw(epsr=None, sig=None, file_path='', file_format='eps', show=False)#

Draw domain, sources and probes.

Plot an illustration of the problem configuration based on the values defined in the object. You may plot an empty problem or give a map.

Parameters:
  • epsr (numpy.ndarray, default: None) – A matrix with the relative permittivity map that you may want to draw as example.

  • sig (numpy.ndarray, default: None) – A matrix with the conductivity [S/m] map that you may want to draw as example.

  • show (boolean, default: False) – If True, a window with the figure will appear. If False, the figure will be saved as a file.

  • file_path (string, default: '') – A string indicating the path where you want to save the figure.

  • file_format (string, default: 'eps') – Format of the saved figure. It must be the same supported formats of matplotlib.pyplot.savefig().

importdata(file_name, file_path='')#

Import data from a saved object.

save(file_path=None)#

Save the problem configuration within a pickle file.

It will only be saved the attribute variables, not the object itself. If you want to load these variables, you may use the constant string variables for a more friendly usage.

class eispy2d.ConjugatedGradient(iterations)#

Bases: Regularization

__init__(iterations)#

Initialize Conjugated Gradient regularization.

Parameters:

iterations (int) – Number of iterations for the CG method.

solve(K, y)#

Solve the linear system using Conjugated Gradient method.

Parameters:
  • K (numpy.ndarray) – Coefficient matrix (kernel) with shape (M, N).

  • y (numpy.ndarray) – Right-hand side vector or matrix with shape (M,) or (M, P).

Returns:

Solution vector or matrix with shape (N,) or (N, P).

Return type:

numpy.ndarray

Notes

The CG method solves the normal equations: \(K^*K x = K^*y\) using an iterative approach.

class eispy2d.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.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.Crossover#

Bases: ABC

Abstract base class for crossover operators in evolutionary algorithms.

Crossover operators combine two parent solutions to produce offspring.

run(x1, x2, fx1, fx2, probability=None)#

Perform crossover operation.

copy(new=None)#

Create a copy of the crossover operator.

copy(new=None)#

Create a copy of the crossover operator.

Parameters:

new (Crossover, optional) – If provided, copies data into this object. If None, creates a new copy.

Return type:

Crossover or None

abstractmethod run(x1, x2, fx1, fx2, probability=None)#

Perform crossover operation.

Parameters:
  • x1 (numpy.ndarray) – Parent solutions.

  • x2 (numpy.ndarray) – Parent solutions.

  • fx1 (numpy.ndarray or float) – Fitness values of parents.

  • fx2 (numpy.ndarray or float) – Fitness values of parents.

  • probability (float, optional) – Crossover probability.

Returns:

(offspring, fitness) where fitness may be NaN for new offspring.

Return type:

tuple

class eispy2d.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.DifferentialEvolution(boundary_condition, selection, mutation, scaling_factor, crossover, pcross=1.0, index_selection='random')#

Bases: Mechanism

Differential Evolution (DE) evolutionary mechanism.

Implements various DE mutation strategies including: - Rand: DE/rand/1 - Best: DE/best/1 - Current-to-best: DE/current-to-best/1 - Rand-to-best: DE/rand-to-best/1

Parameters:
  • boundary_condition (BoundaryCondition) – Boundary handling strategy.

  • selection (Selection) – Selection operator.

  • mutation ({'rand', 'best', 'current-to-best', 'rand-to-best'}) – DE mutation strategy.

  • scaling_factor (float) – Mutation scaling factor (F).

  • crossover (Crossover) – Crossover operator.

  • pcross (float, default=1.0) – Crossover probability.

  • index_selection ({'random', 'permutation'}, default='random') – How to select indices for mutation.

run(population, population_fitness, objective_function, current_nevals)#

Execute one generation of DE.

copy(new=None)#
reset_variables(population_size, representation)#

Reset internal variables for a new run.

Parameters:
  • population_size (int) – Size of the population.

  • representation (Representation) – Solution representation.

run(population, population_fitness, objective_function, current_nevals)#

Execute one generation of Differential Evolution.

Parameters:
  • population (numpy.ndarray) – Current population matrix (POP × NVAR).

  • population_fitness (numpy.ndarray) – Fitness values of current population.

  • objective_function (ObjectiveFunction) – Objective function to evaluate.

  • current_nevals (int) – Current number of evaluations.

Returns:

(population, population_fitness, new_evaluation_count)

Return type:

tuple

class eispy2d.Discretization(configuration=None, name=None, alias='', import_filename=None, import_filepath='')#

Bases: ABC

Abstract base class for spatial discretization methods.

This class defines the interface that all discretization methods must implement for electromagnetic inverse scattering problems. It provides the foundation for converting continuous field problems into discrete algebraic systems that can be solved numerically.

The discretization handles the spatial aspect of the inverse scattering problem, defining how continuous electromagnetic fields are represented on discrete grids and how the governing equations are discretized.

Key responsibilities include: - Spatial grid generation and management - Field representation using basis functions - Residual computation for data and state equations - Linear system solution for field reconstruction - Resolution conversion and field interpolation - Green’s function matrix computation and storage

Parameters:
  • configuration (Configuration, optional) – Problem configuration object containing electromagnetic parameters, geometry definitions, and solver settings. If None, must be set before solving.

  • name (str, optional) – Human-readable name for the discretization method

  • alias (str, default='') – Short identifier for the discretization, used in file naming and method identification

  • import_filename (str, optional) – If provided, loads discretization state from this file

  • import_filepath (str, default='') – Directory path for import file

configuration#

Problem configuration object

Type:

Configuration

name#

Discretization method name

Type:

str

alias#

Method identifier string

Type:

str

residual_data(scattered_field, contrast=None, total_field=None, current=None)#

Compute residual for data equation

residual_state(incident_field, contrast=None, total_field=None, current=None)#

Compute residual for state equation

solve(scattered_field=None, incident_field=None, contrast=None, total_field=None, current=None, linear_solver=None)#

Solve linear system for field reconstruction

scattered_field(contrast=None, total_field=None, current=None)#

Compute scattered field from given parameters

contrast_image(coefficients, resolution)#

Convert coefficients to contrast image at given resolution

total_image(coefficients, resolution)#

Convert coefficients to total field image at given resolution

copy(new=None)#

Create copy of discretization instance

save(file_path='')#

Save discretization state to file

importdata(file_name, file_path='')#

Load discretization state from file

Notes

This is an abstract base class - all methods marked with @abstractmethod must be implemented by derived classes. The class provides parameter validation and error checking for the abstract methods.

Different discretization methods will implement these abstract methods according to their specific mathematical formulations: - Method of Moments uses basis functions and testing functions - Finite Differences use grid-based approximations - Finite Elements use element-based basis functions - Collocation uses point-wise matching

Examples

This class cannot be instantiated directly. Use derived classes:

>>> # Example derived class usage
>>> from collocation import Collocation
>>> discretization = Collocation(configuration, name='Pulse Collocation')
>>>
>>> # Solve linear inverse problem
>>> contrast = discretization.solve(
...     scattered_field=measured_data,
...     incident_field=incident_data,
...     linear_solver=regularization_method
... )
>>>
>>> # Convert to image format
>>> image = discretization.contrast_image(contrast, resolution)

See also

collocation.Collocation

Collocation method implementation

__init__(configuration=None, name=None, alias='', import_filename=None, import_filepath='')#

Initialize the discretization method.

Parameters:
  • configuration (Configuration, optional) – Problem configuration object containing electromagnetic parameters, geometry, frequency, and other problem-specific settings. If None, must be set before solving any problems.

  • name (str, optional) – Human-readable name for the discretization method. Used for identification and display purposes.

  • alias (str, default='') – Short identifier string for the discretization method. Used in file naming and method identification within algorithms.

  • import_filename (str, optional) – If provided, loads the discretization state from this file instead of initializing with the other parameters.

  • import_filepath (str, default='') – Directory path where the import file is located.

Notes

If import_filename is provided, the method loads its state from the specified file and ignores other initialization parameters. Otherwise, it initializes with the provided parameters.

The configuration object is copied to avoid unintended modifications to the original configuration during discretization operations.

Examples

>>> # Initialize with configuration
>>> config = Configuration(frequency=1e9, background_epsilon=1.0)
>>> discretization = MyDiscretization(
...     configuration=config,
...     name='My Method',
...     alias='mymeth'
... )
>>> # Initialize from saved state
>>> discretization = MyDiscretization(
...     import_filename='saved_state.pkl',
...     import_filepath='/path/to/files/'
... )
abstractmethod __str__()#

Return string representation of the discretization.

This method provides a string representation of the discretization method for display and debugging purposes. The base implementation provides a generic identifier.

Returns:

String representation of the discretization method

Return type:

str

Notes

Derived classes should override this method to provide more specific information about the discretization:

```python def __str__(self):

return f”{self.name}: {self.alias} - {self.configuration}”

```

Examples

>>> print(discretization)
Discretization: MyMethod - Config(freq=1GHz, nx=64, ny=64)
abstractmethod contrast_image(coefficients, resolution)#

Convert contrast coefficients to image format.

This method converts the discrete contrast function coefficients from the discretization basis to a regular image grid at the specified resolution. This is useful for visualization and analysis of reconstruction results.

Parameters:
  • coefficients (array_like) – Contrast function coefficients at discretization points, typically obtained from solving the inverse problem

  • resolution (array_like or tuple) – Desired image resolution as (nx, ny) where nx and ny are the number of pixels in x and y directions respectively

Returns:

2D array representing the contrast function image with shape matching the specified resolution

Return type:

array_like

Notes

The conversion process typically involves: 1. Interpolation from discretization points to image grid 2. Proper handling of boundary conditions 3. Scaling and normalization if needed

The image format allows for easy visualization and comparison with reference solutions or other reconstruction methods.

Examples

>>> # Convert to 64x64 image
>>> image = discretization.contrast_image(
...     coefficients=solution_coeffs,
...     resolution=(64, 64)
... )
>>>
>>> # Display the reconstruction
>>> import matplotlib.pyplot as plt
>>> plt.imshow(image.real, cmap='jet')
>>> plt.title('Reconstructed Contrast Function')
copy(new=None)#

Create a copy of the discretization instance.

This method creates a copy of the current discretization instance with the same configuration and settings. Since this is an abstract base class, the method cannot create a new instance directly.

Parameters:

new (Discretization, optional) – If provided, the current discretization’s configuration will be copied into this existing instance. If None, raises an error since abstract classes cannot be instantiated.

Returns:

This method only supports copying into an existing instance due to the abstract nature of the base class.

Return type:

None

Raises:

TypeError – If new is None, since abstract classes cannot be instantiated

Notes

This method is designed to be overridden by derived classes to provide proper copying functionality:

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

if new is None:
return MyDiscretization(

configuration=self.configuration, name=self.name, alias=self.alias

)

else:

new.name = self.name new.configuration = self.configuration new.alias = self.alias

```

Examples

>>> # Copy into existing instance (derived class)
>>> target = MyDiscretization()
>>> source.copy(target)
>>> print(target.name)  # Same as source.name
abstractmethod importdata(file_name, file_path='')#

Load discretization state from file.

This method loads discretization configuration and state from a previously saved file. The base implementation handles common parameters, but derived classes should extend this to restore method-specific data.

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

  • file_path (str, default='') – Directory path where the save file is located

Returns:

Dictionary containing the loaded discretization state data

Return type:

dict

Notes

Derived classes should override this method to restore additional method-specific data:

```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’] return data

```

The method completely replaces the current discretization state with the loaded configuration.

Examples

>>> # Load discretization state
>>> data = discretization.importdata(
...     file_name='discretization_state.pkl',
...     file_path='/path/to/files/'
... )
>>> print(f"Loaded discretization: {discretization.name}")
Raises:
  • FileNotFoundError – If the specified file does not exist

  • KeyError – If required keys are missing from the saved data

abstractmethod residual_data(scattered_field, contrast=None, total_field=None, current=None)#

Compute residual for the data equation.

This method computes the residual (error) between measured scattered field data and the scattered field predicted by the current estimate of the scatterer properties. The residual is used in optimization algorithms to minimize the data misfit.

The data equation relates the scattered field to the scatterer properties and internal fields:

\[E^s = G^s J\]

where \(E^s\) is the scattered field, \(G^s\) is the scattered field Green’s function, and \(J\) is the contrast source.

Parameters:
  • scattered_field (array_like) – Measured scattered field data at receiver locations.

  • contrast (array_like, optional) – Contrast function values at discretization points. Required if total_field is provided.

  • total_field (array_like, optional) – Total electric field at discretization points. Required if contrast is provided.

  • current (array_like, optional) – Contrast source (current) at discretization points. If provided, contrast and total_field are ignored.

Returns:

Data residual vector representing the difference between measured and computed scattered field.

Return type:

array_like

Raises:
  • MissingInputError – If required parameter combinations are not provided.

  • Error – If no valid parameter combination is given.

Notes

The method requires either: - Both contrast and total_field parameters, or - The current parameter alone.

The residual is computed as: residual = measured_scattered_field - predicted_scattered_field

A small residual indicates good agreement between the model and data.

Examples

>>> # Using contrast and total field
>>> residual = discretization.residual_data(
...     scattered_field=measured_data,
...     contrast=current_contrast,
...     total_field=current_total_field
... )
>>> # Using current directly
>>> residual = discretization.residual_data(
...     scattered_field=measured_data,
...     current=current_source
... )
abstractmethod residual_state(incident_field, contrast=None, total_field=None, current=None)#

Compute residual for the state equation.

This method computes the residual (error) in the state equation, which relates the total field, contrast function, and current source. The state equation ensures consistency between the electromagnetic field quantities within the scattering domain.

The state equation can be written as:

\[J = \chi E^t\]

where \(J\) is the contrast source, \(\chi\) is the contrast function, and \(E^t\) is the total electric field.

Parameters:
  • incident_field (array_like) – Incident electric field at discretization points.

  • contrast (array_like, optional) – Contrast function values at discretization points. Required if total_field or current is provided.

  • total_field (array_like, optional) – Total electric field at discretization points. Used with contrast to compute current source.

  • current (array_like, optional) – Contrast source (current) at discretization points. Used with contrast to validate state equation.

Returns:

State residual vector representing the inconsistency in the state equation.

Return type:

array_like

Raises:
  • MissingInputError – If required parameter combinations are not provided.

  • Error – If no valid parameter combination is given.

Notes

The method requires: - contrast parameter along with either total_field or current.

The residual measures how well the state equation is satisfied: - If using total_field: residual = contrast * total_field - current - If using current: residual = contrast * (incident + scattered) - current

A small residual indicates good consistency between field quantities.

Examples

>>> # Using contrast and total field
>>> residual = discretization.residual_state(
...     incident_field=incident_data,
...     contrast=current_contrast,
...     total_field=current_total_field
... )
>>> # Using contrast and current
>>> residual = discretization.residual_state(
...     incident_field=incident_data,
...     contrast=current_contrast,
...     current=current_source
... )
abstractmethod save(file_path='')#

Save discretization state to file.

This method saves the discretization configuration and state to a file for later restoration. The base implementation provides the common data structure, but derived classes should extend this to include method-specific parameters.

Parameters:

file_path (str, default='') – Base path for saving the discretization state. The specific filename will be determined by the derived class implementation.

Returns:

Dictionary containing the discretization state data including: - name: Discretization method name - alias: Method identifier - configuration: Problem configuration object

Return type:

dict

Notes

Derived classes should override this method to include additional method-specific data:

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

data = super().save(file_path=file_path) data[‘my_specific_param’] = self.my_specific_param # Save to file using file_path return data

```

The returned dictionary contains all necessary information to restore the discretization state using importdata.

Examples

>>> # Save discretization state
>>> data = discretization.save(file_path='/path/to/save/')
>>> print(f"Saved {len(data)} parameters")
abstractmethod scattered_field(contrast=None, total_field=None, current=None)#

Compute scattered field from scatterer properties.

This method computes the scattered electric field at receiver locations given the scatterer properties (contrast function, total field, or current source). This is the forward scattering operation.

The scattered field is computed using: .. math:

E^s = G^s J

where \(G^s\) is the scattered field Green’s function matrix and \(J\) is the contrast source.

Parameters:
  • contrast (array_like, optional) – Contrast function values at discretization points. Required if total_field is provided.

  • total_field (array_like, optional) – Total electric field at discretization points. Required if contrast is provided.

  • current (array_like, optional) – Contrast source (current) at discretization points. Alternative to providing contrast and total_field separately.

Returns:

Scattered electric field at receiver locations

Return type:

array_like

Raises:

MissingInputError – If required parameter combinations are not provided

Notes

The method requires either: - Both contrast and total_field parameters, or - The current parameter alone

If contrast and total_field are provided, the current source is computed as J = chi E^t, then used to calculate the scattered field.

Examples

>>> # Using contrast and total field
>>> scattered = discretization.scattered_field(
...     contrast=contrast_values,
...     total_field=total_field_values
... )
>>> # Using current directly
>>> scattered = discretization.scattered_field(
...     current=current_source
... )
abstractmethod solve(scattered_field=None, incident_field=None, contrast=None, total_field=None, current=None, linear_solver=None)#

Solve the linear inverse scattering problem.

This method solves the discretized linear inverse scattering problem to reconstruct the contrast function from measured scattered field data. The solution involves solving a linear system that may be ill-conditioned, requiring regularization techniques.

The linear problem typically has the form:

\[G \chi = E^s\]

where \(G\) is the system matrix, \(\chi\) is the contrast function to be reconstructed, and \(E^s\) is the scattered field data.

Parameters:
  • scattered_field (array_like, optional) – Measured scattered field data at receiver locations.

  • incident_field (array_like, optional) – Incident electric field at discretization points.

  • contrast (array_like, optional) – Initial or known contrast function values.

  • total_field (array_like, optional) – Total electric field at discretization points.

  • current (array_like, optional) – Contrast source (current) at discretization points.

  • linear_solver (Regularization, optional) – Regularization/linear solver method to use for solving the potentially ill-conditioned linear system.

Returns:

Reconstructed contrast function coefficients at discretization points.

Return type:

array_like

Notes

The specific parameters required depend on the discretization method and the formulation of the linear system. Common approaches include: - Born approximation: uses incident field as total field - Moment method: requires Green’s function matrices - Finite differences: uses grid-based operators

The linear solver handles regularization to deal with ill-conditioning that is common in inverse scattering problems.

Examples

>>> # Basic Born approximation solution
>>> contrast = discretization.solve(
...     scattered_field=measured_data,
...     incident_field=incident_data,
...     linear_solver=tikhonov_solver
... )
>>> # Advanced solution with known total field
>>> contrast = discretization.solve(
...     scattered_field=measured_data,
...     total_field=computed_total_field,
...     linear_solver=truncated_svd_solver
... )
abstractmethod total_image(coefficients, resolution)#

Convert total field coefficients to image format.

This method converts the discrete total field coefficients from the discretization basis to a regular image grid at the specified resolution. This is useful for visualization and analysis of field distributions.

Parameters:
  • coefficients (array_like) – Total field coefficients at discretization points, typically obtained from solving the forward problem

  • resolution (array_like or tuple) – Desired image resolution as (nx, ny) where nx and ny are the number of pixels in x and y directions respectively

Returns:

2D array representing the total field image with shape matching the specified resolution

Return type:

array_like

Notes

The conversion process typically involves: 1. Interpolation from discretization points to image grid 2. Proper handling of boundary conditions 3. Phase and amplitude representation 4. Scaling and normalization if needed

The image format allows for visualization of field patterns and understanding of scattering behavior.

Examples

>>> # Convert to 128x128 image
>>> field_image = discretization.total_image(
...     coefficients=field_coeffs,
...     resolution=(128, 128)
... )
>>>
>>> # Display field magnitude
>>> import matplotlib.pyplot as plt
>>> plt.imshow(np.abs(field_image), cmap='viridis')
>>> plt.title('Total Field Magnitude')
class eispy2d.DiscretizationElementBased(discretization, contrast_bounds, total_bounds)#

Bases: Representation

Representation for electromagnetic inverse scattering problems.

Represents the contrast function and total field using discretization elements. Supports perfect dielectric and good conductor assumptions.

Parameters:
  • discretization (Discretization) – Discretization method.

  • contrast_bounds (float, tuple, or list) – Bounds for contrast variables.

  • total_bounds (float, complex, tuple, or list) – Bounds for total field variables.

contrast(x, mode='array')#

Extract contrast function from solution vector.

Parameters:
  • x (numpy.ndarray) – Solution vector.

  • mode ({'array', 'image'}, default='array') – Output format.

Returns:

Contrast function.

Return type:

numpy.ndarray

current(x, mode='array')#

Extract current from solution vector.

Parameters:
  • x (numpy.ndarray) – Solution vector.

  • mode ({'array', 'image'}, default='array') – Output format.

Returns:

Current distribution.

Return type:

numpy.ndarray

scattered_field(x)#

Compute scattered field from solution.

Parameters:

x (numpy.ndarray) – Solution vector.

Returns:

Scattered field.

Return type:

numpy.ndarray

total_field(x, mode='array')#

Extract total field from solution vector.

Parameters:
  • x (numpy.ndarray) – Solution vector.

  • mode ({'array', 'image'}, default='array') – Output format.

Returns:

Total field.

Return type:

numpy.ndarray

class eispy2d.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)
exception eispy2d.EmptyAttribute(class_name, attribute_name)#

Bases: Error

Exception for empty class attribute.

class_name#

Name of the class.

Type:

str

attribute_name#

Name of the empty attribute.

Type:

str

message#

Explanation of the error.

Type:

str

__init__(class_name, attribute_name)#

Store exception information.

exception eispy2d.Error#

Bases: Exception

Base class for exceptions in this module.

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

exception eispy2d.ExcessiveInputsError(function_name, input_names)#

Bases: Error

An error exception for excessive inputs.

function_name#

A string with the name of the function.

Type:

str

input_names#

A list of strings with the input names.

Type:

list of str

__init__(function_name, input_names)#

Save the name of the function and inputs.

class eispy2d.Experiment(name, method=None, discretization=None)#

Bases: ABC

__init__(name, method=None, discretization=None)#

Initialize an Experiment instance.

Parameters:
  • name (str) – Name identifier for the experiment.

  • method (InverseSolver or list of InverseSolver, optional) – Single method or list of methods to be evaluated.

  • discretization (Discretization or list of Discretization, optional) – Single discretization or list of discretizations to be used.

Raises:
  • WrongTypeInput – If parameters have invalid types.

  • Error – If discretization list length doesn’t match method list length.

property discretization#
abstractmethod importdata(file_name, file_path='')#

Import experiment state from a file.

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

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

Returns:

Dictionary containing the imported data.

Return type:

dict

property method#
abstractmethod save(file_path='')#

Save the experiment state to a file.

Parameters:

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

Returns:

Dictionary containing the experiment data.

Return type:

dict

class eispy2d.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.FFTProduct(discretization=None, adjoint=False, conjugate=False)#

Bases: object

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

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

discretization#

Discretization object containing the Green’s function matrix.

Type:

Discretization

G#

Extended Green’s function matrix for FFT convolution.

Type:

numpy.ndarray

adjoint#

Whether to use the adjoint operator.

Type:

bool

conjugate#

Whether to use the conjugate operator.

Type:

bool

compute(J)#

Compute the convolution product.

compute(J)#

Compute the convolution product.

Parameters:

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

Returns:

Result of the convolution product.

Return type:

numpy.ndarray

property discretization#
class eispy2d.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.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.Gaussian(std=0.5)#

Bases: Mutation

Gaussian mutation operator.

Adds Gaussian noise to solution vector.

Parameters:

std (float, default=0.5) – Standard deviation of Gaussian noise.

copy(new=None)#
run(x, fx, probability=None)#

Apply mutation to solution vector.

Parameters:
  • x (numpy.ndarray) – Solution vector to mutate.

  • fx (numpy.ndarray or float) – Fitness values of solutions.

  • probability (float, optional) – Mutation probability.

Returns:

(mutated_x, mutated_fx) where mutated_fx may be NaN for new mutations.

Return type:

tuple

class eispy2d.GeneticAlgorithm(boundary_condition, crossover, pcross, mutation, pmut, selection, pair_selection='random')#

Bases: Mechanism

Genetic Algorithm (GA) evolutionary mechanism.

Implements a standard genetic algorithm with crossover and mutation operators.

Parameters:
  • boundary_condition (BoundaryCondition) – Boundary handling strategy.

  • crossover (Crossover) – Crossover operator.

  • pcross (float) – Crossover probability.

  • mutation (Mutation) – Mutation operator.

  • pmut (float) – Mutation probability.

  • selection (Selection) – Selection operator.

  • pair_selection ({'random', 'permutation'}, default='random') – How to select pairs for crossover.

run(population, population_fitness, objective_function, current_nevals)#

Execute one generation of GA.

copy(new=None)#
reset_variables(population_size, representation)#

Reset internal variables for a new run.

Parameters:
  • population_size (int) – Size of the population.

  • representation (Representation) – Solution representation.

run(population, population_fitness, objective_function, current_nevals)#

Execute one generation of Genetic Algorithm.

Parameters:
  • population (numpy.ndarray) – Current population matrix (POP × NVAR).

  • population_fitness (numpy.ndarray) – Fitness values of current population.

  • objective_function (ObjectiveFunction) – Objective function to evaluate.

  • current_nevals (int) – Current number of evaluations.

Returns:

(population, population_fitness, new_evaluation_count)

Return type:

tuple

class eispy2d.Initialization#

Bases: ABC

Abstract base class for population initialization strategies.

run(population_size, representation, incident_field, inputdata)#

Initialize population.

abstractmethod run(population_size, representation, incident_field, inputdata)#

Initialize population.

Parameters:
  • population_size (int) – Number of individuals in the population.

  • representation (Representation) – Solution representation.

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

  • inputdata (InputData) – Input data object containing problem parameters.

Returns:

Initial population matrix (POP × NVAR).

Return type:

numpy.ndarray

class eispy2d.InputData(name=None, configuration=None, resolution=None, scattered_field=None, total_field=None, incident_field=None, rel_permittivity=None, conductivity=None, noise=None, indicators=None, import_filename=None, import_filepath='')#

Bases: object

The container representing an instance of a problem.

name#

A string naming the instance.

configuration_filename#

A string for referencing the problem configuration.

resolution#

A tuple with the size, in pixels, of the recovered image. Y-X ordered.

scattered_field#

Matrix containing the scattered field information at S-domain.

total_field#

Matrix containing the total field information at D-domain.

incident_field#

Matrix containing the incident field information at D-domain.

relative_permittivity_map#

Matrix with the discretized image of the relative permittivity map.

conductivity_map#

Matrix with the discretized image of the conductivity map.

noise#

noise level of scattered field data.

homogeneous_objects#

A flag to indicate if the instance only contains homogeneous objects.

Type:

bool

compute_residual_error#

A flag to indicate the measurement of the residual error throughout or at the end of the solver executation.

Type:

bool

compute_map_error#

A flag to indicate the measurement of the error in predicting the dielectric properties of the image.

Type:

bool

compute_totalfield_error#

A flag to indicate the measurement of the estimation error of the total field throughout or at the end of the solver executation.

Type:

bool

__init__(name=None, configuration=None, resolution=None, scattered_field=None, total_field=None, incident_field=None, rel_permittivity=None, conductivity=None, noise=None, indicators=None, import_filename=None, import_filepath='')#

Build or import an object.

You must give either the import file name and path or the required variables.

Call signatures:

InputData(import_filename='my_file', import_filepath='./data/')
InputData(name='instance00', configuration=config_obj, ...)
Parameters:
  • name (str) – The name of the instance.

  • configuration (Configuration or str) – A Configuration object or a string with the name of the problem configuration file.

  • resolution (2-tuple of int) – The size, in pixels, of the image to be recovered. Y-X ordered. Required if rel_permittivity and conductivity are None.

  • scattered_field (numpy.ndarray, optional) – A matrix containing the scattered field information at S-domain. Shape: (N_measurements, N_sources).

  • total_field (numpy.ndarray, optional) – A matrix containing the total field information at D-domain.

  • incident_field (numpy.ndarray, optional) – A matrix containing the incident field information at D-domain.

  • rel_permittivity (numpy.ndarray, optional) – A matrix with the discretized image of the relative permittivity map.

  • conductivity (numpy.ndarray, optional) – A matrix with the discretized image of the conductivity map.

  • noise (float, optional) – Noise level of scattered field data (percentage).

  • indicators (list of str or str, optional) – List of indicator names to compute. If None, uses default set.

  • import_filename (str, optional) – A string with the name of the saved file.

  • import_filepath (str, optional) – A string with the path to the saved file.

__str__()#

Print information.

compute_dnl()#
property configuration#

Get the configuration.

copy(new=None)#

Set or return a copy of the object.

draw(image='contrast', axis=None, title=None, file_path='', file_format='eps', show=False, save=False, suptitle=None, fontsize=10)#

Draw the relative permittivity/conductivity map.

Parameters:
  • image (str, optional) – Type of image to draw. Options: ‘epsilon_r’, ‘sigma’, ‘both’, ‘contrast’. Default is ‘contrast’.

  • axis (matplotlib.axes.Axes or numpy.ndarray, optional) – Axes to plot on. If None, new figure is created.

  • title (str or bool, optional) – Title for the plot(s). If False, no title. If True, uses default.

  • file_path (str, default: '') – A path where you want to save the figure.

  • file_format (str, default: 'eps') – The file format (e.g., ‘eps’, ‘png’, ‘pdf’).

  • show (bool, default: False) – If True, a window will be raised to show the image.

  • save (bool, default: False) – If True, the figure will be saved.

  • suptitle (str, optional) – Super title for the whole figure (used only for ‘both’).

  • fontsize (int, default: 10) – Font size for labels and titles.

importdata(file_name, file_path='')#

Import data from a saved object.

plot_scattered_field(figure_title=None, file_path='', file_format='eps', show=False, fontsize=10, interpolation='spline36', axes=None)#

Plot the scattered field pattern as a 2D heatmap.

Displays the magnitude of the scattered field for all source-measurement combinations.

Parameters:
  • figure_title (str, optional) – Title for the plot. Default uses object name.

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

  • file_format (str, default: 'eps') – File format for saving.

  • show (bool, default: False) – If True, display the plot.

  • fontsize (int, default: 10) – Font size.

  • interpolation (str, default: 'spline36') – Interpolation method for imshow.

  • axes (matplotlib.axes.Axes, optional) – Axes to plot on. If None, creates new figure.

plot_total_field(axis=None, source=None, title=None, file_path='', file_format='eps', show=False, fontsize=10, file_name=None)#

Plot total field magnitude maps for one or more sources.

Parameters:
  • axis (matplotlib.axes.Axes or numpy.ndarray, optional) – Axes to plot on.

  • source (int or list of int, optional) – Source index(es) to plot. If None, plots all sources.

  • title (str, optional) – Title for the plot(s).

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

  • file_format (str, default: 'eps') – File format.

  • show (bool, default: False) – If True, display the plot.

  • fontsize (int, default: 10) – Font size.

  • file_name (str, optional) – Custom filename for saving.

save(file_path='')#

Save object information.

class eispy2d.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.Landweber(iterations)#

Bases: Regularization

__init__(iterations)#

Initialize Landweber regularization.

Parameters:

iterations (int) – Number of iterations for the Landweber method.

solve(K, y)#

Solve the linear system using Landweber iteration.

Parameters:
  • K (numpy.ndarray) – Coefficient matrix (kernel) with shape (M, N).

  • y (numpy.ndarray) – Right-hand side vector or matrix with shape (M,) or (M, P).

Returns:

Solution vector or matrix with shape (N,) or (N, P).

Return type:

numpy.ndarray

Notes

The Landweber iteration is given by:

\[x_{n+1} = x_n + a K^*(y - Kx_n)\]

where \(a = 1/\|K\|^2\).

class eispy2d.LeastSquares(cutoff=None)#

Bases: Regularization

__init__(cutoff=None)#

Initialize Least Squares regularization with spectral cutoff.

Parameters:

cutoff (float, optional) – Cutoff threshold for singular values (rcond parameter). If None, uses default from numpy.linalg.lstsq.

solve(K, y)#

Solve the linear system using least squares with spectral cutoff.

Parameters:
  • K (numpy.ndarray) – Coefficient matrix (kernel) with shape (M, N).

  • y (numpy.ndarray) – Right-hand side vector or matrix with shape (M,) or (M, P).

Returns:

Solution vector or matrix with shape (N,) or (N, P).

Return type:

numpy.ndarray

Notes

Uses numpy.linalg.lstsq with specified rcond cutoff for regularization by truncating small singular values.

class eispy2d.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.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.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)
exception eispy2d.MissingAttributesError(class_name, attribute_name)#

Bases: Error

Exception raised when some attribute is missing within an object.

class_name#

A string with the name of the class.

Type:

str

attribute_name#

The name of the missing attribute.

Type:

str

__init__(class_name, attribute_name)#

Save the class of the object and the missing attribute.

exception eispy2d.MissingInputError(function_name, input_names)#

Bases: Error

Exception raised for errors in the input.

function_name#

A string containing the name of the function.

Type:

str

input_names#

A string or a list of strings with the names of the missing inputs.

Type:

str or list of str

message#

Explanation of the error.

Type:

str

__init__(function_name, input_names)#

Save the name of the function and the missing inputs.

class eispy2d.MoM_CG_FFT(tolerance=0.001, maximum_iterations=5000, parallelization=True)#

Bases: ForwardSolver

Method of Moments with Conjugated-Gradient FFT method.

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

TOL#

Tolerance level for convergence.

Type:

float

MAX_IT#

Maximum number of iterations.

Type:

int

name#

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

Type:

str

incident_field(resolution, configuration)#

Compute the incident field matrix.

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

COMPUTE_SCATTERED_FIELD=True, SAVE_INTERN_FIELD=True)

Solve the forward problem.

save(file_name, file_path='')#

Save solver state to file.

importdata(file_name, file_path='')#

Import solver state from file.

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

Apply the Conjugated-Gradient Method to the forward problem.

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

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

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

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

  • NS (int) – Number of incidences.

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

  • MAX_IT (int) – Maximum number of iterations

  • TOL (float) – Error tolerance

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

Returns:

Jnumpy:ndarray

Current density, (NX.NY)xNS

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

Create the object.

Parameters:
  • configuration (string or Configuration:Configuration) – Either a configuration object or a string with the name of file in which the configuration is saved. In this case, the file path may also be provided.

  • configuration_filepath (string, optional) – A string with the path to the configuration file (when the file name is provided).

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

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

__str__()#

Print method parametrization.

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

Compute the incident field matrix.

Given the configuration information stored in the object, it computes the incident field matrix considering plane waves in different from different angles.

Parameters:

resolution (2-tuple) – The image size of D-domain in pixels (y and x).

Returns:

einumpy.ndarray

Incident field matrix. The rows correspond to the points in the image following C-order and the columns corresponds to the sources.

save(file_name, file_path='')#

Save simulation data.

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

Solve the forward problem.

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

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

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

Returns:

es, et, einumpy:ndarray

Matrices with the scattered, total and incident field information.

Examples

>>> solver = MoM_CG_FFT(configuration)
>>> es, et, ei = solver.solve(inputdata)
>>> es, ei = solver.solve(inputdata, COMPUTE_INTERN_FIELD=False)
class eispy2d.Mutation#

Bases: ABC

Abstract base class for mutation operators.

Mutation operators introduce random variations to solutions.

run(x, fx, probability=None)#

Apply mutation to solution vector.

copy(new=None)#

Create a copy of the mutation operator.

copy(new=None)#
abstractmethod run(x, fx, probability=None)#

Apply mutation to solution vector.

Parameters:
  • x (numpy.ndarray) – Solution vector to mutate.

  • fx (numpy.ndarray or float) – Fitness values of solutions.

  • probability (float, optional) – Mutation probability.

Returns:

(mutated_x, mutated_fx) where mutated_fx may be NaN for new mutations.

Return type:

tuple

class eispy2d.ObjectiveFunction#

Bases: ABC

Abstract base class for objective functions.

Defines the interface for evaluating solution quality in evolutionary algorithms.

set_parameters(representation, scattered_field, incident_field)#

Set parameters for objective function evaluation.

eval(x)#

Evaluate objective function for a solution.

abstractmethod eval(x)#

Evaluate objective function for a solution.

Parameters:

x (numpy.ndarray) – Solution vector.

Returns:

Objective function value.

Return type:

float

set_parameters(representation, scattered_field, incident_field)#

Set parameters for objective function evaluation.

Parameters:
  • representation (Representation) – Solution representation.

  • scattered_field (numpy.ndarray) – Scattered field data.

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

class eispy2d.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.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.ParticleSwarmOptimization(boundary_condition, acceleration=2.0, inertia=0.4)#

Bases: Mechanism

Particle Swarm Optimization (PSO) evolutionary mechanism.

Implements standard PSO with inertia weight and acceleration coefficients.

Parameters:
  • boundary_condition (BoundaryCondition) – Boundary handling strategy.

  • acceleration (float or tuple, default=2.0) – Acceleration coefficients (c1, c2). If float, both are equal.

  • inertia (float, default=0.4) – Inertia weight (w).

run(population, population_fitness, objective_function, current_nevals)#

Execute one generation of PSO.

copy(new=None)#
reset_variables(population_size, representation)#

Reset internal variables for a new run.

Parameters:
  • population_size (int) – Size of the population.

  • representation (Representation) – Solution representation.

run(population, population_fitness, objective_function, current_nevals)#

Execute one generation of evolution.

Parameters:
  • population (numpy.ndarray) – Current population matrix (POP × NVAR).

  • population_fitness (numpy.ndarray) – Fitness values of current population.

  • objective_function (ObjectiveFunction) – Objective function to evaluate.

  • current_nevals (int) – Current number of evaluations.

Returns:

(population, population_fitness, new_evaluation_count)

Return type:

tuple

class eispy2d.Polynomial(eta)#

Bases: Mutation

Polynomial mutation operator.

Implements polynomial mutation commonly used in real-coded GAs.

Parameters:

eta (float) – Distribution index. Higher values produce mutations closer to parent.

copy(new=None)#
run(x, fx, probability)#

Apply mutation to solution vector.

Parameters:
  • x (numpy.ndarray) – Solution vector to mutate.

  • fx (numpy.ndarray or float) – Fitness values of solutions.

  • probability (float, optional) – Mutation probability.

Returns:

(mutated_x, mutated_fx) where mutated_fx may be NaN for new mutations.

Return type:

tuple

class eispy2d.Rastrigin(amplitude=10)#

Bases: ObjectiveFunction

Rastrigin benchmark function (canonical, nonlinear, multimodal).

Parameters:

amplitude (float, default=10) – Amplitude parameter controlling the function’s shape.

eval(x)#

Evaluate objective function for a solution.

Parameters:

x (numpy.ndarray) – Solution vector.

Returns:

Objective function value.

Return type:

float

class eispy2d.Reflection#

Bases: BoundaryCondition

Reflection boundary condition.

Reflects values that fall outside [0, 1] back into the range using a reflection strategy. Values are reflected multiple times if needed.

Notes

This boundary handling strategy preserves the interval [0, 1] by reflecting out-of-bounds values back into the valid range using a mirroring technique.

run(x)#

Apply reflection to the solution vector.

Parameters:

x (numpy.ndarray) – Solution vector to be reflected.

class eispy2d.Regularization#

Bases: ABC

abstractmethod solve(K, y)#
class eispy2d.Representation#

Bases: ABC

Abstract base class for solution representation.

Defines how solutions are encoded and decoded in evolutionary algorithms.

nvar#

Number of decision variables.

Type:

int

lb#

Lower bounds for variables.

Type:

numpy.ndarray

ub#

Upper bounds for variables.

Type:

numpy.ndarray

dtype#

Data type of variables.

Type:

type

abstractmethod contrast(x, mode='array')#

Extract contrast function from solution vector.

Parameters:
  • x (numpy.ndarray) – Solution vector.

  • mode ({'array', 'image'}, default='array') – Output format.

Returns:

Contrast function.

Return type:

numpy.ndarray

abstractmethod current(x, mode='array')#

Extract current from solution vector.

Parameters:
  • x (numpy.ndarray) – Solution vector.

  • mode ({'array', 'image'}, default='array') – Output format.

Returns:

Current distribution.

Return type:

numpy.ndarray

real2unit(x)#

Convert real-space values to unit-space values.

Parameters:

x (numpy.ndarray) – Values in real space.

Returns:

Values in [0, 1] range.

Return type:

numpy.ndarray

abstractmethod scattered_field(x)#

Compute scattered field from solution.

Parameters:

x (numpy.ndarray) – Solution vector.

Returns:

Scattered field.

Return type:

numpy.ndarray

abstractmethod total_field(x, mode='array')#

Extract total field from solution vector.

Parameters:
  • x (numpy.ndarray) – Solution vector.

  • mode ({'array', 'image'}, default='array') – Output format.

Returns:

Total field.

Return type:

numpy.ndarray

unit2real(x)#

Convert unit-space values to real-space values.

Parameters:

x (numpy.ndarray) – Values in [0, 1] range.

Returns:

Values in real space.

Return type:

numpy.ndarray

class eispy2d.Result(name=None, method_name=None, configuration=None, scattered_field=None, total_field=None, rel_permittivity=None, conductivity=None, execution_time=None, number_evaluations=None, objective_function=None, number_iterations=None, import_filename=None, import_filepath='', path=None)#

Bases: object

Storage and analysis class for electromagnetic inverse scattering results.

This class provides comprehensive storage and analysis capabilities for results from electromagnetic inverse scattering algorithms. It stores reconstructed fields, material properties, and various error metrics, while providing sophisticated plotting and analysis tools.

The class supports multiple error indicators for quantitative evaluation of reconstruction quality, including residual norm errors, percentage average deviation (PAD) errors, and shape/position analysis. It also provides extensive plotting capabilities for visualizing reconstructed images and convergence behavior.

name#

Unique identifier for the stored result, typically combining method, input data, and configuration names.

Type:

str

method_name#

Name of the inverse scattering method that generated this result.

Type:

str

configuration#

Problem configuration object containing frequency, geometry, and other parameters used in the reconstruction.

Type:

configuration.Configuration

total_field#

Reconstructed total electric field distribution in the investigation domain. Shape: (N_pixels, N_sources). Units: [V/m].

Type:

numpy.ndarray

scattered_field#

Computed scattered electric field at measurement points. Shape: (N_measurements, N_sources). Units: [V/m].

Type:

numpy.ndarray

rel_permittivity#

Reconstructed relative permittivity distribution. Shape: (N_x, N_y). Dimensionless.

Type:

numpy.ndarray

conductivity#

Reconstructed conductivity distribution. Shape: (N_x, N_y). Units: [S/m].

Type:

numpy.ndarray

execution_time#

Total execution time for the reconstruction algorithm. Units: [sec].

Type:

float

number_evaluations#

Number of objective function evaluations (relevant for stochastic methods).

Type:

int

number_iterations#

Number of iterations performed by the reconstruction algorithm.

Type:

int

objective_function#

History of objective function values throughout the iterative process.

Type:

list

Error Metrics
-------------
zeta_rn#

Residual norm error: \(\\zeta_{RN} = ||\\mathbf{E}^s_{meas} - \\mathbf{E}^s_{comp}||_2\)

Type:

list

zeta_rpad#

Residual percentage average deviation: \(\\zeta_{RPAD} = \\frac{100}{N_m} \\sum_{i=1}^{N_m} \\frac{|E^s_{meas,i} - E^s_{comp,i}|}{|E^s_{meas,i}|}\)

Type:

list

zeta_epad#

Permittivity percentage average deviation: \(\\zeta_{\\epsilon PAD} = \\frac{100}{N_p} \\sum_{i=1}^{N_p} \\frac{|\\epsilon_{r,true,i} - \\epsilon_{r,rec,i}|}{\\epsilon_{r,true,i}}\)

Type:

list

zeta_ebe#

Background permittivity error for pixels outside the object region.

Type:

list

zeta_eoe#

Object permittivity error for pixels inside the object region.

Type:

list

zeta_sad#

Conductivity average deviation: \(\\zeta_{\\sigma AD} = \\frac{1}{N_p} \\sum_{i=1}^{N_p} |\\sigma_{true,i} - \\sigma_{rec,i}|\)

Type:

list

zeta_sbe#

Background conductivity error for pixels outside the object region.

Type:

list

zeta_soe#

Object conductivity error for pixels inside the object region.

Type:

list

zeta_tv#

Total variation: \(\\zeta_{TV} = \\sum_{i,j} |\\nabla \\chi_{i,j}|\)

Type:

list

zeta_p#

Position error: percentage difference in object centroid location.

Type:

list

zeta_s#

Shape error: percentage difference in object area/shape.

Type:

list

zeta_tfmpad#

Total field magnitude percentage average deviation.

Type:

list

zeta_tfpad#

Total field phase average deviation.

Type:

list

Examples

>>> import result as rst
>>> import numpy as np
>>>
>>> # Create result object
>>> result = rst.Result(name='csi_reconstruction')
>>>
>>> # Store reconstruction data
>>> result.rel_permittivity = np.random.rand(64, 64) * 2 + 1
>>> result.conductivity = np.random.rand(64, 64) * 0.1
>>>
>>> # Update with error metrics
>>> result.zeta_rn.append(1e-3)
>>> result.zeta_epad.append(15.5)
>>>
>>> # Plot results
>>> result.plot_map(image=rst.BOTH_PROPERTIES, show=True)
>>> result.plot_convergence(show=True)
>>>
>>> # Save results
>>> result.save(file_path='/path/to/results/')

Notes

The class automatically computes various error metrics when the update_error() method is called with appropriate input data and ground truth information. Error metrics are stored as lists to track evolution during iterative reconstruction processes.

__init__(name=None, method_name=None, configuration=None, scattered_field=None, total_field=None, rel_permittivity=None, conductivity=None, execution_time=None, number_evaluations=None, objective_function=None, number_iterations=None, import_filename=None, import_filepath='', path=None)#

Initialize a Result object for storing reconstruction results.

Creates a new Result object to store electromagnetic inverse scattering reconstruction results. The object can be initialized with reconstruction data directly or loaded from a previously saved file.

Parameters:
  • name (str, optional) – Unique identifier for this result. Required if not loading from file. Typically combines method name, input data, and configuration info.

  • method_name (str, optional) – Name of the reconstruction method that generated this result. Examples: ‘CSI’, ‘DBIM’, ‘Born’, ‘Gauss-Newton’.

  • configuration (configuration.Configuration, optional) – Problem configuration object containing frequency, geometry, and material parameters used in the reconstruction.

  • scattered_field (numpy.ndarray, optional) – Computed scattered field at measurement points. Shape: (N_measurements, N_sources). Units: [V/m].

  • total_field (numpy.ndarray, optional) – Reconstructed total field in the investigation domain. Shape: (N_pixels, N_sources). Units: [V/m].

  • rel_permittivity (numpy.ndarray, optional) – Reconstructed relative permittivity map. Shape: (N_x, N_y). Dimensionless.

  • conductivity (numpy.ndarray, optional) – Reconstructed conductivity map. Shape: (N_x, N_y). Units: [S/m].

  • execution_time (float, optional) – Total execution time for the reconstruction. Units: [sec].

  • number_evaluations (int, optional) – Number of objective function evaluations (for stochastic methods).

  • number_iterations (int, optional) – Number of iterations performed by the reconstruction algorithm.

  • objective_function (list or float, optional) – Objective function value(s) recorded during reconstruction.

  • import_filename (str, optional) – Name of file containing previously saved Result object. If provided, all other parameters are ignored.

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

Raises:
  • error.MissingInputError – If name is None and import_filename is None.

  • FileNotFoundError – If import_filename is specified but file cannot be found.

Examples

>>> # Create new result object
>>> result = Result(name='csi_test', method_name='CSI')
>>>
>>> # Create with reconstruction data
>>> result = Result(
...     name='dbim_reconstruction',
...     method_name='DBIM',
...     rel_permittivity=epsilon_r_map,
...     conductivity=sigma_map,
...     execution_time=45.2
... )
>>>
>>> # Load from saved file
>>> result = Result(import_filename='saved_result.pkl')

Notes

If import_filename is provided, the object is initialized from the saved file and all other parameters are ignored. Otherwise, a new object is created with the provided parameters.

All error metric lists (zeta_*) are initialized as empty lists and can be populated using the update_error() method.

__str__()#

Return a comprehensive string representation of the Result object.

Generates a detailed text summary of the Result object including all reconstruction data, error metrics, and algorithm performance statistics. This method provides a human-readable overview of the complete result.

Returns:

Multi-line string containing: - Result name and configuration - Field data dimensions and resolution - Material property map resolutions - Execution time and performance metrics - Complete error metric histories with formatting - Algorithm iteration and evaluation counts

Return type:

str

Examples

>>> result = Result(name='csi_experiment')
>>> result.rel_permittivity = np.random.rand(64, 64)
>>> result.zeta_rn = [1e-2, 5e-3, 1e-3]
>>> result.execution_time = 45.2
>>>
>>> print(result)
Results name: csi_experiment
Configuration: test_config
Relative Permit. map resolution: 64x64
Residual norm error: [1.00e-02, 5.00e-03, 1.00e-03]
Execution time: 45.20 [sec]

Notes

  • Error metrics are formatted with appropriate precision

  • Long error histories (>30 values) are truncated with ellipsis

  • Field dimensions show both measurement and source sample counts

  • Material property maps show spatial resolution

  • Performance metrics include execution time and iteration counts

copy(new=None)#

Create a deep copy of the Result object or copy data from another Result.

Creates a complete deep copy of the current Result object with all reconstruction data and error metrics, or copies data from another Result object into the current one. This method is useful for creating backups or comparing different reconstruction results.

Parameters:

new (Result, optional) – If provided, copies data from this Result object into the current object, overwriting existing data. If None, creates a new Result object as a copy of the current one.

Returns:

If new is None, returns a new Result object containing a deep copy of all data. If new is provided, returns None and modifies the current object in-place.

Return type:

Result or None

Examples

>>> # Create a backup copy
>>> result = Result(name='original')
>>> result.zeta_rn = [1e-2, 5e-3, 1e-3]
>>> result.rel_permittivity = np.random.rand(64, 64)
>>>
>>> backup = result.copy()
>>> print(backup.name)  # 'original'
>>> print(len(backup.zeta_rn))  # 3
>>>
>>> # Copy data from another result
>>> result2 = Result(name='experiment2')
>>> result2.zeta_rn = [2e-2, 1e-2, 5e-3]
>>>
>>> result.copy(result2)  # Copies result2 data into result
>>> print(result.name)  # 'experiment2'
>>> print(result.zeta_rn)  # [2e-2, 1e-2, 5e-3]

Notes

  • Deep copy is performed on all array data and error metric lists

  • Configuration objects are also copied to avoid reference sharing

  • When copying from another Result (new parameter), all existing data in the current object is overwritten

  • The copy includes all reconstruction data, error metrics, and metadata such as execution time and iteration counts

final_value(indicator)#

Get the final (most recent) value of a specific error indicator.

Retrieves the last computed value from the specified error indicator’s history. This method is useful for accessing the final reconstruction quality metrics after algorithm completion.

Parameters:

indicator (str) – Name of the error indicator to retrieve. Must be a valid indicator constant such as ‘zeta_rn’, ‘zeta_epad’, ‘zeta_sad’, etc. Use valid_indicators() to see available indicators.

Returns:

The final (most recent) value of the specified indicator. For list-type indicators, returns the last element. For scalar indicators, returns the scalar value.

Return type:

float

Raises:

Examples

>>> result = Result(name='test')
>>> result.zeta_rn = [1e-2, 5e-3, 1e-3]
>>> result.zeta_epad = [25.0, 15.0, 8.5]
>>>
>>> # Get final residual norm error
>>> final_rn = result.final_value('zeta_rn')
>>> print(f"Final residual norm: {final_rn:.3e}")
Final residual norm: 1.000e-03
>>>
>>> # Get final permittivity error
>>> final_epad = result.final_value('zeta_epad')
>>> print(f"Final permittivity PAD: {final_epad:.1f}%")
Final permittivity PAD: 8.5%
>>>
>>> # Error handling
>>> try:
...     result.final_value('invalid_indicator')
... except error.WrongValueInput as e:
...     print(f"Error: {e}")

Notes

This method assumes that the indicator has been computed and contains at least one value. If the indicator list is empty, IndexError will be raised when trying to access the last element.

importdata(file_name, file_path='')#

Load Result object data from a saved pickle file.

Restores a previously saved Result object by loading all reconstruction data, error metrics, and configuration information from a pickle file.

Parameters:
  • file_name (str) – Name of the pickle file containing the saved Result object.

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

Raises:
  • FileNotFoundError – If the specified file cannot be found.

  • pickle.UnpicklingError – If the file cannot be unpickled or contains invalid data.

Examples

>>> result = Result(name='empty')
>>> result.importdata('saved_result.pkl', '/path/to/results/')
>>> print(result.name)  # Will show the name from saved file
>>> print(result.rel_permittivity.shape)  # Access loaded data

Notes

This method completely overwrites the current object state with data from the saved file. Any existing data in the object is lost.

last_error_message(pre_message=None)#

Generate a formatted summary of the latest error metrics.

Creates a comprehensive text summary of the most recent error indicator values for display or logging purposes. This method is typically used to provide concise status updates during iterative reconstruction processes.

Parameters:

pre_message (str, optional) – Custom prefix message to prepend to the error summary. If None, uses default prefix “Indicators:”.

Returns:

Formatted string containing the latest values of all available error indicators. Format: “Indicators: Residual norm: 1.23e-4, Residual PAD: 12.34%, Rel. Per. PAD: 8.56%, …”

Return type:

str

Notes

Only error indicators that have been computed (non-empty lists) are included in the summary. The formatting is optimized for readability with appropriate precision for each metric type:

  • Residual norm errors: scientific notation with 3 decimal places

  • Percentage errors: fixed point with 2 decimal places + % symbol

  • Regularization metrics: fixed point with 2 decimal places

Examples

>>> result = Result(name='test')
>>> result.zeta_rn = [1e-3, 5e-4, 1e-4]
>>> result.zeta_epad = [20.5, 15.2, 12.8]
>>> print(result.last_error_message())
Indicators: Residual norm: 1.000e-04, Rel. Per. PAD: 12.80%,
>>> # With custom prefix
>>> print(result.last_error_message("Final results:"))
Final results: Residual norm: 1.000e-04, Rel. Per. PAD: 12.80%,
plot_convergence(axis=None, indicators=None, show=False, file_name=None, file_path='', file_format='eps', fontsize=10, title=None, style='--*', yscale=None, markersize=None)#

Plot convergence curves for error indicators over iterations.

Creates line plots showing the evolution of error metrics during the iterative reconstruction process. Supports multiple indicators in separate subplots with customizable styling and formatting.

Parameters:
  • axis (matplotlib.axes.Axes or numpy.ndarray, optional) – Pre-existing axes for plotting. If None, new figure is created. For multiple indicators, provide array of axes objects.

  • indicators (str, list of str, or None, optional) – Error indicators to plot. If None, plots all valid indicators. If string, plots single indicator. If list, plots multiple indicators. Valid indicators are returned by valid_indicators().

  • show (bool, optional) – If True, display the plot window. Default is False.

  • file_name (str, optional) – Filename for saving the figure (without extension). If None, figure is not saved. Default is None.

  • file_path (str, optional) – Directory path for saving the figure. Default is current directory.

  • file_format (str, optional) – File format for saving (‘eps’, ‘png’, ‘pdf’, etc.). Default is ‘eps’.

  • fontsize (int, optional) – Font size for labels and titles. Default is 10.

  • title (str, list of str, or None, optional) – Plot title(s). If None, uses standard titles. If string, uses same title for all plots. If list, uses separate titles for each plot.

  • style (str, optional) – Line style for plots (matplotlib format). Default is ‘–*’.

  • yscale (str, list of str, or None, optional) – Y-axis scale (‘linear’, ‘log’, ‘symlog’, etc.). If None, uses linear scale. If string, uses same scale for all plots. If list, uses separate scales for each plot.

  • markersize (float, optional) – Size of markers in the plot. Default is None (matplotlib default).

Returns:

  • fig (matplotlib.figure.Figure) – Figure object (only if axis is None and show=False and file_name=None).

  • ax (numpy.ndarray) – Array of axes objects (only if axis is None and show=False and file_name=None).

Raises:

error.WrongValueInput – If provided axis array size doesn’t match number of indicators.

Examples

>>> # Plot all available indicators
>>> result.plot_convergence(show=True)
>>>
>>> # Plot specific indicators with logarithmic scale
>>> result.plot_convergence(
...     indicators=['zeta_rn', 'zeta_epad'],
...     yscale='log',
...     show=True
... )
>>>
>>> # Save convergence plot
>>> result.plot_convergence(
...     file_name='convergence_plot',
...     file_path='/path/to/figures/',
...     file_format='png'
... )
>>>
>>> # Custom styling
>>> result.plot_convergence(
...     style='-o',
...     markersize=6,
...     fontsize=12,
...     title='Algorithm Convergence',
...     show=True
... )

Notes

  • X-axis represents iteration numbers starting from 1

  • Each indicator is plotted in a separate subplot

  • Grid is enabled for all plots to improve readability

  • Automatic titles are generated based on indicator types

  • Supports both linear and logarithmic y-axis scaling

plot_map(axis=None, image='contrast', groundtruth=None, title=None, show=False, save=False, file_path='', file_format='eps', fontsize=10, file_name=None, source=None, interpolation=None)#

Plot reconstructed maps and field distributions.

Creates visualizations of reconstructed material properties and field distributions with optional ground truth comparison. Supports various image types including permittivity, conductivity, contrast, and total field.

Parameters:
  • axis (matplotlib.axes.Axes or numpy.ndarray, optional) – Pre-existing axes for plotting. If None, new figure is created. For multiple plots, provide array of axes objects.

  • image (str, optional) – Type of image to plot. Options: ‘contrast’, ‘epsilon_r’, ‘sigma’, ‘both’, ‘total field’. Default is ‘contrast’.

  • groundtruth (inputdata.InputData, optional) – Ground truth data for comparison plotting. If provided, both ground truth and reconstructed images are displayed.

  • title (str, list, or bool, optional) – Plot title(s). If list, separate titles for each subplot. If False, no titles are shown. Default is None (automatic titles).

  • show (bool, optional) – If True, display the plot window. Default is False.

  • save (bool, optional) – If True, save the figure to file. Default is False.

  • file_path (str, optional) – Directory path for saving the figure. Default is current directory.

  • file_format (str, optional) – File format for saving (‘eps’, ‘png’, ‘pdf’, etc.). Default is ‘eps’.

  • fontsize (int, optional) – Font size for labels and titles. Default is 10.

  • file_name (str, optional) – Custom filename for saving. If None, uses object name. Default is None.

  • source (int, list, or None, optional) – Source indices for total field plotting. If None, plots all sources. For int, plots single source. For list, plots multiple sources.

  • interpolation (str, optional) – Interpolation method for imshow (‘nearest’, ‘bilinear’, etc.). Default is None (matplotlib default).

Returns:

  • fig (matplotlib.figure.Figure) – Figure object (only if show=False and save=False).

  • ax (numpy.ndarray) – Array of axes objects (only if show=False and save=False).

Raises:

Examples

>>> # Plot contrast map
>>> result.plot_map(image='contrast', show=True)
>>>
>>> # Plot both properties with ground truth
>>> result.plot_map(image='both', groundtruth=input_data,
...                  title=['Ground Truth', 'Reconstructed'], show=True)
>>>
>>> # Plot total field for specific source
>>> result.plot_map(image='total field', source=0, show=True)
>>>
>>> # Save high-resolution figure
>>> result.plot_map(image='epsilon_r', save=True, file_format='png',
...                  file_path='/path/to/figures/', fontsize=14)

Notes

  • Spatial coordinates are normalized by background wavelength λ_b

  • Color bars are automatically added with appropriate units

  • Ground truth comparison creates side-by-side plots

  • Total field plotting supports multiple sources

  • Images are displayed with ‘lower’ origin (bottom-left corner)

save(file_path='')#

Save the Result object to a pickle file.

Serializes the complete Result object including all reconstruction data and error metrics to a pickle file for later loading and analysis.

Parameters:

file_path (str, optional) – Directory path where the file will be saved. The file is saved with the object’s name as the filename. Default is current directory.

Notes

The saved file contains all reconstruction results, error metrics, and configuration information. The file can be loaded later using the importdata() method or by initializing a new Result object with the import_filename parameter.

Examples

>>> result = Result(name='my_reconstruction')
>>> result.rel_permittivity = epsilon_r_map
>>> result.save(file_path='/path/to/results/')
>>> # Creates file: /path/to/results/my_reconstruction
update_error(inputdata, scattered_field=None, total_field=None, rel_permittivity=None, conductivity=None, contrast=None, objective_function=None, optimum=None)#

Compute and update error metrics for reconstruction quality assessment.

Calculates various error indicators based on the specified input data indicators and updates the corresponding error metric lists. This method is typically called during iterative reconstruction to track convergence and quality metrics.

Parameters:
  • inputdata (inputdata.InputData) – Input data object containing ground truth information and indicator specifications. The indicators attribute determines which error metrics will be computed.

  • scattered_field (numpy.ndarray, optional) – Computed scattered field for comparison with measured data. Shape: (N_measurements, N_sources). Units: [V/m]. Required for residual norm and PAD error calculations.

  • total_field (numpy.ndarray, optional) – Reconstructed total field distribution. Shape: (N_pixels, N_sources). Units: [V/m]. Required for total field error calculations.

  • rel_permittivity (numpy.ndarray, optional) – Reconstructed relative permittivity map. Shape: (N_x, N_y). Dimensionless. Required for permittivity error calculations.

  • conductivity (numpy.ndarray, optional) – Reconstructed conductivity map. Shape: (N_x, N_y). Units: [S/m]. Required for conductivity error calculations.

  • contrast (numpy.ndarray, optional) – Reconstructed contrast function. Shape: (N_x, N_y). Complex-valued. Alternative to providing separate permittivity and conductivity.

  • objective_function (float, optional) – Current objective function value for tracking convergence.

Raises:

Notes

The method computes the following error metrics based on inputdata.indicators:

Field-Based Errors: - RESIDUAL_NORM_ERROR: \(\\zeta_{RN} = ||\\mathbf{E}^s_{meas} - \\mathbf{E}^s_{comp}||_2\) - RESIDUAL_PAD_ERROR: \(\\zeta_{RPAD} = \\frac{100}{N_m} \\sum_{i=1}^{N_m} \\frac{|E^s_{meas,i} - E^s_{comp,i}|}{|E^s_{meas,i}|}\)

Permittivity Errors: - REL_PERMITTIVITY_PAD_ERROR: Percentage average deviation of permittivity - REL_PERMITTIVITY_BACKGROUND_ERROR: Background region permittivity error - REL_PERMITTIVITY_OBJECT_ERROR: Object region permittivity error - SSIM_ERROR: Structural Similarity Index Measure between true and reconstructed permittivity

Conductivity Errors: - CONDUCTIVITY_AD_ERROR: Average deviation of conductivity - CONDUCTIVITY_BACKGROUND_ERROR: Background region conductivity error - CONDUCTIVITY_OBJECT_ERROR: Object region conductivity error

Shape and Position Errors: - SHAPE_ERROR: Percentage difference in reconstructed object shape - POSITION_ERROR: Percentage difference in reconstructed object position

Regularization Metrics: - TOTAL_VARIATION: Total variation of the reconstructed contrast

Total Field Errors: - TOTALFIELD_MAGNITUDE_PAD: Magnitude percentage average deviation - TOTALFIELD_PHASE_AD: Phase average deviation

Examples

>>> import result as rst
>>>
>>> # During iterative reconstruction
>>> for iteration in range(max_iterations):
...     # ... perform reconstruction step ...
...
...     # Update error metrics
...     result.update_error(
...         inputdata=input_data,
...         scattered_field=computed_scattered_field,
...         rel_permittivity=reconstructed_permittivity,
...         conductivity=reconstructed_conductivity,
...         objective_function=current_obj_value
...     )
...
...     # Check convergence
...     if len(result.zeta_rn) > 1:
...         if result.zeta_rn[-1] < convergence_threshold:
...             break
>>> # Access error history
>>> print(f"Final residual norm: {result.zeta_rn[-1]:.3e}")
>>> print(f"Final permittivity PAD: {result.zeta_epad[-1]:.2f}%")
valid_indicators()#

Identify which error indicators have been computed and contain data.

Examines all error metric attributes to determine which indicators have been calculated and contain valid data. This method is used internally for plotting and analysis functions to determine which metrics are available for display.

Returns:

List of indicator names (constants) that have been computed and contain at least one data point. Possible indicators include:

  • RESIDUAL_NORM_ERROR: Residual norm error

  • RESIDUAL_PAD_ERROR: Residual percentage average deviation

  • REL_PERMITTIVITY_PAD_ERROR: Permittivity PAD error

  • REL_PERMITTIVITY_OBJECT_ERROR: Object permittivity error

  • REL_PERMITTIVITY_BACKGROUND_ERROR: Background permittivity error

  • CONDUCTIVITY_AD_ERROR: Conductivity average deviation

  • CONDUCTIVITY_OBJECT_ERROR: Object conductivity error

  • CONDUCTIVITY_BACKGROUND_ERROR: Background conductivity error

  • SHAPE_ERROR: Shape reconstruction error

  • POSITION_ERROR: Position reconstruction error

  • TOTAL_VARIATION: Total variation regularization metric

  • TOTALFIELD_MAGNITUDE_PAD: Total field magnitude PAD

  • TOTALFIELD_PHASE_AD: Total field phase average deviation

  • OBJECTIVE_FUNCTION: Objective function values

Return type:

list of str

Notes

This method checks both that the attribute exists (is not None) and that it contains data (length > 0). Empty lists are considered invalid indicators and are excluded from the results.

Examples

>>> result = Result(name='test')
>>> result.zeta_rn = [1e-3, 5e-4]
>>> result.zeta_epad = [20.5, 15.2]
>>> result.zeta_sad = []  # Empty list
>>>
>>> indicators = result.valid_indicators()
>>> print(indicators)
['zeta_rpad', 'zeta_epad']  # Only non-empty indicators
>>>
>>> # Use with plotting
>>> result.plot_convergence(indicators=result.valid_indicators())
class eispy2d.Richmond(configuration=None, elements=None, state=True, alias='ric', import_filename=None, import_filepath='')#

Bases: Collocation

Richmond discretization method for electromagnetic inverse scattering.

Implements the Richmond discretization method, which is a specific case of the collocation method using pulse basis functions. This method is widely used in electromagnetic inverse scattering for its simplicity and numerical stability, particularly when dealing with the singularities in the Green’s function integrals.

The Richmond method approximates the scattered field using: - Pulse basis functions for the contrast function - Collocation points at the center of each discretization cell - Analytical treatment of the Green’s function singularity

Parameters:
  • configuration (Configuration) – Problem configuration object.

  • elements (int or tuple of int) – Number of discretization elements. If int, creates square grid (N×N). If tuple, creates rectangular grid (NY×NX).

  • state (bool, default: True) – If True, computes the state-space Green’s function matrix (GD).

  • alias (str, default: 'ric') – Short alias for the method.

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

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

GS#

Data-space Green’s function matrix (measurements × elements).

Type:

numpy.ndarray

GD#

State-space Green’s function matrix (elements × elements). None if state=False at initialization.

Type:

numpy.ndarray or None

residual_data()#

Compute residual for the data equation.

residual_state()#

Compute residual for the state equation.

solve()#

Solve linear inverse scattering problem.

scattered_field()#

Compute scattered field from scatterer properties.

contrast_image()#

Convert contrast coefficients to image format.

total_image()#

Convert total field coefficients to image format.

Notes

The Green’s function matrices are computed using the analytical formulas from Richmond’s method, which handles the singularity at the origin by using the small-argument approximation of the Hankel function.

Examples

>>> config = Configuration(name='test', wavelength=1.0)
>>> discretization = Richmond(configuration=config, elements=(32, 32))
>>>
>>> # Access Green's function matrices
>>> print(f"GS shape: {discretization.GS.shape}")
>>> print(f"GD shape: {discretization.GD.shape}")
contrast_image(coefficients, resolution)#

Convert contrast coefficients to image format.

This method converts the discrete contrast function coefficients from the discretization basis to a regular image grid at the specified resolution. This is useful for visualization and analysis of reconstruction results.

Parameters:
  • coefficients (array_like) – Contrast function coefficients at discretization points, typically obtained from solving the inverse problem

  • resolution (array_like or tuple) – Desired image resolution as (nx, ny) where nx and ny are the number of pixels in x and y directions respectively

Returns:

2D array representing the contrast function image with shape matching the specified resolution

Return type:

array_like

Notes

The conversion process typically involves: 1. Interpolation from discretization points to image grid 2. Proper handling of boundary conditions 3. Scaling and normalization if needed

The image format allows for easy visualization and comparison with reference solutions or other reconstruction methods.

Examples

>>> # Convert to 64x64 image
>>> image = discretization.contrast_image(
...     coefficients=solution_coeffs,
...     resolution=(64, 64)
... )
>>>
>>> # Display the reconstruction
>>> import matplotlib.pyplot as plt
>>> plt.imshow(image.real, cmap='jet')
>>> plt.title('Reconstructed Contrast Function')
copy(new=None)#

Create a copy of the collocation instance.

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

Parameters:

new (Collocation 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:

Collocation or None

Examples

>>> # Create independent copy
>>> collocation_copy = collocation.copy()
>>> # Copy configuration to existing instance
>>> new_collocation = Collocation(configuration=config,
...                              trial='pulse',
...                              elements=(32, 32))
>>> collocation.copy(new_collocation)
importdata(file_name, file_path='')#

Import collocation configuration from a saved file.

Loads a previously saved collocation configuration including trial function type and discretization elements.

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

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

Examples

>>> collocation = Collocation()
>>> collocation.importdata('collocation_config.pkl', '/path/to/files/')
residual_data(scattered_field, contrast=None, total_field=None, current=None)#

Compute residual for the data equation using Richmond discretization.

Parameters

contrastarray_like, optional

Contrast function values.

total_fieldarray_like, optional

Total electric field.

currentarray_like, optional

Contrast source (current).

Returns:

Residual vector: \(E^s - G^s J\) where \(J\) is either \(\chi E^t\) or the provided current.

Return type:

array_like

Notes

The residual is computed as: - If current is None: \(\text{res} = E^s - G^s \chi E^t\) - If current is provided: \(\text{res} = E^s - G^s J\)

residual_state(incident_field, contrast=None, total_field=None, current=None)#

Compute residual for the state equation using Richmond discretization.

Parameters:
  • incident_field (array_like) – Incident electric field.

  • contrast (array_like, optional) – Contrast function values.

  • total_field (array_like, optional) – Total electric field.

  • current (array_like, optional) – Contrast source (current).

Returns:

Residual vector.

Return type:

array_like

Notes

The residual depends on the parameters provided: - If current is None: \(\text{res} = E^t - E^i - G^D \chi E^t\) - If current is provided: \(\text{res} = J - \chi E^i - \chi G^D J\)

save(file_path='')#

Save the collocation configuration to a file.

Saves the complete collocation method configuration including trial function type and discretization elements using pickle serialization.

Parameters:

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

Examples

>>> collocation.save('/path/to/save/')
>>> collocation.save()  # Save in current directory
scattered_field(contrast=None, total_field=None, current=None)#

Compute scattered field from scatterer properties.

This method computes the scattered electric field at receiver locations given the scatterer properties (contrast function, total field, or current source). This is the forward scattering operation.

The scattered field is computed using: .. math:

E^s = G^s J

where \(G^s\) is the scattered field Green’s function matrix and \(J\) is the contrast source.

Parameters:
  • contrast (array_like, optional) – Contrast function values at discretization points. Required if total_field is provided.

  • total_field (array_like, optional) – Total electric field at discretization points. Required if contrast is provided.

  • current (array_like, optional) – Contrast source (current) at discretization points. Alternative to providing contrast and total_field separately.

Returns:

Scattered electric field at receiver locations

Return type:

array_like

Raises:

MissingInputError – If required parameter combinations are not provided

Notes

The method requires either: - Both contrast and total_field parameters, or - The current parameter alone

If contrast and total_field are provided, the current source is computed as J = chi E^t, then used to calculate the scattered field.

Examples

>>> # Using contrast and total field
>>> scattered = discretization.scattered_field(
...     contrast=contrast_values,
...     total_field=total_field_values
... )
>>> # Using current directly
>>> scattered = discretization.scattered_field(
...     current=current_source
... )
solve(scattered_field=None, incident_field=None, contrast=None, total_field=None, current=None, linear_solver=None)#

Solve the linear inverse scattering problem using Richmond discretization.

Parameters:
  • scattered_field (array_like, optional) – Measured scattered field data.

  • incident_field (array_like, optional) – Incident electric field.

  • contrast (array_like, optional) – Contrast function values.

  • total_field (array_like, optional) – Total electric field.

  • current (array_like, optional) – Contrast source.

  • linear_solver (Regularization, optional) – Regularization method for solving the linear system.

Returns:

Reconstructed contrast function or field coefficients.

Return type:

array_like

Notes

The method can solve for: - Contrast function X: requires scattered_field and total_field - Total field E: requires scattered_field and contrast - Current source J: requires scattered_field - Other combinations for state-space problems.

total_image(coefficients, resolution)#

Convert total field coefficients to image format.

This method converts the discrete total field coefficients from the discretization basis to a regular image grid at the specified resolution. This is useful for visualization and analysis of field distributions.

Parameters:
  • coefficients (array_like) – Total field coefficients at discretization points, typically obtained from solving the forward problem

  • resolution (array_like or tuple) – Desired image resolution as (nx, ny) where nx and ny are the number of pixels in x and y directions respectively

Returns:

2D array representing the total field image with shape matching the specified resolution

Return type:

array_like

Notes

The conversion process typically involves: 1. Interpolation from discretization points to image grid 2. Proper handling of boundary conditions 3. Phase and amplitude representation 4. Scaling and normalization if needed

The image format allows for visualization of field patterns and understanding of scattering behavior.

Examples

>>> # Convert to 128x128 image
>>> field_image = discretization.total_image(
...     coefficients=field_coeffs,
...     resolution=(128, 128)
... )
>>>
>>> # Display field magnitude
>>> import matplotlib.pyplot as plt
>>> plt.imshow(np.abs(field_image), cmap='viridis')
>>> plt.title('Total Field Magnitude')
class eispy2d.Rosenbrock#

Bases: ObjectiveFunction

Rosenbrock benchmark function (canonical, nonlinear, multimodal).

eval(x)#

Evaluate objective function for a solution.

Parameters:

x (numpy.ndarray) – Solution vector.

Returns:

Objective function value.

Return type:

float

class eispy2d.Roullete(elitism=True)#

Bases: Selection

Roulette wheel selection operator.

Selects individuals proportionally to their fitness (probability proportional to fitness). Also known as fitness proportional selection.

Parameters:

elitism (bool, default=True) – Whether to preserve the best individual.

copy(new=None)#
run(P1, fx1, P2=None, fx2=None, NPOP=None)#

Perform selection.

Parameters:
  • P1 (numpy.ndarray) – First population.

  • fx1 (numpy.ndarray) – Fitness values of first population.

  • P2 (numpy.ndarray, optional) – Second population (for elitism).

  • fx2 (numpy.ndarray, optional) – Fitness values of second population.

  • NPOP (int, optional) – Number of individuals to select.

Returns:

(selected_population, selected_fitness)

Return type:

tuple

class eispy2d.Selection#

Bases: ABC

Abstract base class for selection operators.

Selection operators choose individuals for reproduction based on fitness.

run(P1, fx1, P2, fx2, NPOP)#

Perform selection.

copy(new=None)#

Create a copy of the selection operator.

copy(new=None)#
abstractmethod run(P1, fx1, P2=None, fx2=None, NPOP=None)#

Perform selection.

Parameters:
  • P1 (numpy.ndarray) – First population.

  • fx1 (numpy.ndarray) – Fitness values of first population.

  • P2 (numpy.ndarray, optional) – Second population (for elitism).

  • fx2 (numpy.ndarray, optional) – Fitness values of second population.

  • NPOP (int, optional) – Number of individuals to select.

Returns:

(selected_population, selected_fitness)

Return type:

tuple

class eispy2d.SimulatedBinary(eta)#

Bases: Crossover

Simulated Binary Crossover (SBX) operator.

Creates offspring by simulating the behavior of binary crossover in real-valued spaces. The distribution index eta controls the spread of offspring around parents.

Parameters:

eta (float) – Distribution index. Higher values produce offspring closer to parents.

Notes

SBX is commonly used in real-coded genetic algorithms and produces offspring with a probability distribution that mimics binary crossover.

copy(new=None)#

Create a copy of the crossover operator.

Parameters:

new (Crossover, optional) – If provided, copies data into this object. If None, creates a new copy.

Return type:

Crossover or None

run(x1, x2, fx1, fx2, probability=None)#

Perform crossover operation.

Parameters:
  • x1 (numpy.ndarray) – Parent solutions.

  • x2 (numpy.ndarray) – Parent solutions.

  • fx1 (numpy.ndarray or float) – Fitness values of parents.

  • fx2 (numpy.ndarray or float) – Fitness values of parents.

  • probability (float, optional) – Crossover probability.

Returns:

(offspring, fitness) where fitness may be NaN for new offspring.

Return type:

tuple

class eispy2d.SingularValueDecomposition(tikhonov=0.0, cutoff=0.0)#

Bases: Regularization

__init__(tikhonov=0.0, cutoff=0.0)#

Initialize SVD-based regularization.

Parameters:
  • tikhonov (float, default: 0.0) – Tikhonov regularization parameter.

  • cutoff (float, default: 0.0) – Cutoff threshold for singular values.

solve(K=None, y=None, U=None, s=None, V=None)#

Solve the linear system using SVD-based regularization.

Parameters:
  • K (numpy.ndarray, optional) – Coefficient matrix (kernel) with shape (M, N). Required if U, s, V not provided.

  • y (numpy.ndarray, optional) – Right-hand side vector or matrix with shape (M,) or (M, P).

  • U (numpy.ndarray, optional) – Left singular vectors matrix from SVD.

  • s (numpy.ndarray, optional) – Singular values vector from SVD.

  • V (numpy.ndarray, optional) – Right singular vectors matrix from SVD.

Returns:

Solution vector or matrix with shape (N,) or (N, P).

Return type:

numpy.ndarray

Notes

The solution is computed using singular value decomposition:

\[x = \sum_{n} \frac{s_n}{s_n^2 + \alpha} (U_n^* y) V_n\]

where \(\alpha\) is the Tikhonov parameter and singular values below cutoff are truncated.

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

Bases: InverseSolver

Base class for stochastic inverse scattering solvers.

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

nexec#

Number of executions to perform.

Type:

int

outputmode#

Strategy for processing multiple execution results.

Type:

OutputMode

_single_execution#

Whether only one execution is required.

Type:

bool

copy(new=None)#

Create a copy of the solver instance.

Parameters:

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

Returns:

New instance if new=None, otherwise None.

Return type:

InverseSolver or None

importdata(file_name, file_path='')#

Import solver configuration from file.

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

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

Returns:

Dictionary containing the imported data.

Return type:

dict

property nexec#

Set the number of executions.

Parameters:

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

Raises:
abstractmethod save(file_path='')#

Save solver configuration to file.

Parameters:

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

Returns:

Dictionary containing the serialized solver data.

Return type:

dict

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

Solve the inverse scattering problem.

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

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

  • discretization (Discretization) – Discretization scheme to use.

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

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

Returns:

Result object containing the reconstruction results.

Return type:

Result

class eispy2d.StopCriteria(max_evaluations=None, max_iterations=None, max_evals_woimp=None, max_iter_woimp=None, cost_function_threshold=None, improvement_threshold=None)#

Bases: object

__init__(max_evaluations=None, max_iterations=None, max_evals_woimp=None, max_iter_woimp=None, cost_function_threshold=None, improvement_threshold=None)#

Initialize stopping criteria for iterative algorithms.

Parameters:
  • max_evaluations (int, optional) – Maximum number of objective function evaluations.

  • max_iterations (int, optional) – Maximum number of iterations.

  • max_evals_woimp (int, optional) – Maximum number of evaluations without improvement.

  • max_iter_woimp (int, optional) – Maximum number of iterations without improvement.

  • cost_function_threshold (float, optional) – Threshold for the objective function value.

  • improvement_threshold (float, optional) – Minimum relative improvement (percentage) to be considered as improvement. Required if max_evals_woimp or max_iter_woimp is set.

Raises:
  • Error – If no stopping criterion is provided, or if improvement_threshold is missing when using improvement-based criteria.

  • MissingInputError – If improvement_threshold is missing when required.

__str__()#

Return string representation of the stopping criteria.

copy(new=None)#

Create a copy of the StopCriteria object.

Parameters:

new (StopCriteria, optional) – If provided, copies data into this object. If None, creates a new copy.

Returns:

New StopCriteria object if new=None, otherwise None.

Return type:

StopCriteria or None

reset_memory()#

Reset internal counters and stored values for stopping criteria.

stop(number_evaluations, number_iterations, current_best_evaluation)#

Check if any stopping criterion has been met.

Parameters:
  • number_evaluations (int) – Current number of objective function evaluations.

  • number_iterations (int) – Current number of iterations.

  • current_best_evaluation (float) – Current best objective function value.

Returns:

True if any stopping criterion is met, False otherwise.

Return type:

bool

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

class eispy2d.TestSet(name=None, configuration=None, contrast=None, object_size=None, resolution=None, density=None, map_pattern='regular_polygons', sample_size=30, noise=1.0, indicators=None, contrast_mode='fixed', object_size_mode='fixed', density_mode='single', min_size_proportion=40.0, allow_rotation=True, random_position=True, import_filename=None, import_filepath='')#

Bases: object

__init__(name=None, configuration=None, contrast=None, object_size=None, resolution=None, density=None, map_pattern='regular_polygons', sample_size=30, noise=1.0, indicators=None, contrast_mode='fixed', object_size_mode='fixed', density_mode='single', min_size_proportion=40.0, allow_rotation=True, random_position=True, import_filename=None, import_filepath='')#

Initialize a TestSet object.

Parameters:
  • name (str) – Name of the test set.

  • configuration (Configuration, optional) – Configuration object. If None, auto-generated.

  • contrast (float) – Reference contrast value.

  • object_size (float) – Reference object size (in wavelengths).

  • resolution (tuple of int or int, optional) – Resolution of the images (Ny, Nx). If int, square resolution.

  • density (int or float, optional) – Number of objects (if mode uses number) or minimum contrast density.

  • map_pattern (str, optional) – ‘random_polygons’, ‘regular_polygons’, or ‘surfaces’.

  • sample_size (int, default: 30) – Number of test cases.

  • noise (float, default: 1.) – Noise level in percentage.

  • indicators (list of str or str, optional) – Indicators to compute.

  • contrast_mode (str, default: 'fixed') – ‘fixed’ or ‘maximum’.

  • object_size_mode (str, default: 'fixed') – ‘fixed’ or ‘maximum’.

  • density_mode (str, default: 'single') – ‘single’, ‘fixed’, ‘max_number’, or ‘min_density’.

  • min_size_proportion (float, default: 40.) – Minimum size proportion (0-100%) of the smallest object.

  • allow_rotation (bool, default: True) – Allow random rotation of objects.

  • random_position (bool, default: True) – Allow random positioning of objects.

  • import_filename (str, optional) – File to import a saved TestSet.

  • import_filepath (str, optional) – Path to the import file.

property configuration#

Get the configuration.

copy(new=None)#

Create a deep copy or copy data from another TestSet.

Parameters:

new (TestSet, optional) – If provided, copies data from this TestSet into the current one.

Returns:

If new is None, returns a new TestSet copy. If new is provided, returns None (in-place copy).

Return type:

TestSet or None

generate_field_data(solver=None, parallelization=False)#

Generate scattered field data for all tests using a forward solver.

Parameters:
  • solver (ForwardSolver, optional) – Forward solver to use. Default uses MoM-CG-FFT.

  • parallelization (bool, default: False) – If True, uses parallel processing for multiple tests.

importdata(file_name, file_path='')#

Import data from a saved object.

plot(tests='all', axis=None, show=False, save=False, file_path='', file_format='eps')#

Plot a selection of test images.

Parameters:
  • tests ({'all', int, list of int}, default: 'all') – Which tests to plot.

  • axis (matplotlib.axes.Axes or numpy.ndarray, optional) – Axes to plot on.

  • show (bool, default: False) – Display the plot.

  • save (bool, default: False) – Save the figure.

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

  • file_format (str, default: 'eps') – File format.

randomize_tests(parallelization=True)#

Generate random test images according to the test set parameters.

Parameters:

parallelization (bool, default: True) – If True, uses parallel processing to generate tests.

save(file_path='')#

Save the problem configuration within a pickle file.

It will only be saved the attribute variables, not the object itself. If you want to load these variables, you may use the constant string variables for a more friendly usage.

property test#
class eispy2d.Tikhonov(choice, parameter=None)#

Bases: Regularization

__init__(choice, parameter=None)#

Initialize Tikhonov regularization.

Parameters:
  • choice (int, float, or {'fixed', 'mozorov', 'lcurve'}) – Regularization parameter selection strategy: - If int or float: fixed regularization parameter value. - ‘fixed’: use a fixed parameter value (must provide parameter). - ‘mozorov’: use Morozov’s discrepancy principle. - ‘lcurve’: use L-curve criterion.

  • parameter (float, optional) – Fixed regularization parameter value (required if choice=’fixed’).

Raises:
solve(K, y)#

Solve the linear system using Tikhonov regularization.

Parameters:
  • K (numpy.ndarray) – Coefficient matrix (kernel) with shape (M, N).

  • y (numpy.ndarray) – Right-hand side vector or matrix with shape (M,) or (M, P).

Returns:

Solution vector or matrix with shape (N,) or (N, P).

Return type:

numpy.ndarray

Notes

The solution is computed as: - For fixed parameter: \(x = (K^*K + \alpha I)^{-1}K^*y\) - For Morozov: automatically selects \(\alpha\) using discrepancy principle - For L-curve: automatically selects \(\alpha\) using L-curve criterion

class eispy2d.UniformRandomDistribution#

Bases: Initialization

Uniform random distribution initialization.

Initializes population with random values uniformly distributed in [0, 1] for all variables.

run(population_size, representation, incident_field, inputdata)#

Initialize population.

Parameters:
  • population_size (int) – Number of individuals in the population.

  • representation (Representation) – Solution representation.

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

  • inputdata (InputData) – Input data object containing problem parameters.

Returns:

Initial population matrix (POP × NVAR).

Return type:

numpy.ndarray

class eispy2d.WeightedSum#

Bases: ObjectiveFunction

Weighted sum of data and state equation residuals.

Objective function for electromagnetic inverse scattering problems. Combines data misfit and state equation misfit.

eval(x)#

Evaluate objective function for a solution.

Parameters:

x (numpy.ndarray) – Solution vector.

Returns:

Objective function value.

Return type:

float

exception eispy2d.WrongTypeInput(function_name, input_name, right_type, wrong_type)#

Bases: Error

Exception raised when some argument is passed in wrong type.

function_name, input_name

Names of the function/method and the name of the input.

Type:

str

right_type, wrong_type

Names of the expected and given type, respectively.

Type:

str

__init__(function_name, input_name, right_type, wrong_type)#

Save the basic information.

exception eispy2d.WrongValueInput(function_name, input_name, expect_values, given_value)#

Bases: Error

Exception raised when some argument is given with wrong value.

function_name, input_name

Names of the function and input.

Type:

str

expected_values#

A string with the rule or options of inputs.

Type:

str

given_value#

A string with the given value impressed.

Type:

str

__init__(function_name, input_name, expect_values, given_value)#

Save the basic information.

eispy2d.circle(radius, axis_length_x=2.0, axis_length_y=2.0, resolution=None, background_rel_permittivity=1.0, background_conductivity=0.0, object_rel_permittivity=1.0, object_conductivity=0.0, rel_permittivity=None, conductivity=None, center=[0.0, 0.0])#

Draw a circle.

Parameters:
  • radius (float) – Radius of the circle.

  • axis_length_x (float, default: 2.0) – Length of the size of the image.

  • axis_length_y (float, default: 2.0) – Length of the size of the image.

  • resolution (2-tuple) – Image resolution, in y and x directions, i.e., (NY, NX). Either this argument or rel_permittivity or conductivity must be given!

  • background_rel_permittivity (float, default: 1.0)

  • background_conductivity (float, default: 0.0)

  • object_rel_permittivity (float, default: 1.0)

  • object_conductivity (float, default: 0.0)

  • center (list, default: [0.0, 0.0]) – Center of the object in the image. The center of the image corresponds to the origin of the coordinates.

  • rel_permittivity (numpy.ndarray, default:None) – A predefined image in which the object will be drawn.

  • conductivity (numpy.ndarray, default:None) – A predefined image in which the object will be drawn.

eispy2d.compare1sample(x, offset=0.0)#
eispy2d.compare2samples(x1, x2, paired=False)#
eispy2d.compare_multiple(data, all2all=False, all2one=None, paired=False)#
eispy2d.confint(data, alpha=0.05, alternative='two-sided')#
eispy2d.confintplot(data, axes=None, xlabel=None, ylabel=None, title=None, fontsize=10, confidence_level=0.95, xscale=None)#

Plot the confidence interval of means.

This routine plots a figure comparing the confidence interval of means among samples. The confidence intervals are computed at a 0.95 confidence level. This routine does not show any plot. It only draws the graphic.

Parameters:
  • data (either numpy.ndarray or list) – A 2-d array with the samples in which each column is a single sample or a list of 1-d arrays.

  • axes (matplotlib.Axes.axes, default: None) – A specified axes for plotting the graphics. If none is provided, then one will be created and returned.

  • title (str, default: None) – A possible title to the plot.

  • xlabel (str, default: None) – The label of the x-axis which represent the unit of the data.

  • ylabel (list of str, default: None) – A list with the name of the samples.

Returns:

fig : matplotlib.figure.Figure

Example

>>> import numpy as np
>>> from matplotlib import pyplot as plt
>>> y1 = np.random.normal(loc=2., size=30)
>>> y2 = np.random.normal(loc=4., size=60)
>>> y3 = np.random.normal(loc=6., size=10)
>>> confintplot([y1, y2, y3], title='Samples',
                ylabel=['Sample 1', 'Sample 2', 'Sample 3'])
>>> plt.show()
eispy2d.cross(height, width, thickness, axis_length_x=2.0, axis_length_y=2.0, resolution=None, background_rel_permittivity=1.0, background_conductivity=0.0, object_rel_permittivity=1.0, object_conductivity=0.0, center=[0.0, 0.0], rotate=0.0, rel_permittivity=None, conductivity=None)#

Draw a cross.

Parameters:
  • height (float) – Parameters of the cross.

  • width (float) – Parameters of the cross.

  • thickness (float) – Parameters of the cross.

  • axis_length_x (float, default: 2.0) – Length of the size of the image.

  • axis_length_y (float, default: 2.0) – Length of the size of the image.

  • resolution (2-tuple) – Image resolution, in y and x directions, i.e., (NY, NX). Either this argument or rel_permittivity or conductivity must be given!

  • background_rel_permittivity (float, default: 1.0)

  • background_conductivity (float, default: 0.0)

  • object_rel_permittivity (float, default: 1.0)

  • object_conductivity (float, default: 0.0)

  • center (list, default: [0.0, 0.0]) – Center of the object in the image. The center of the image corresponds to the origin of the coordinates.

  • rel_permittivity (numpy.ndarray, default:None) – A predefined image in which the object will be drawn.

  • conductivity (numpy.ndarray, default:None) – A predefined image in which the object will be drawn.

  • rotate (float, default: 0.0 degrees) – Rotation of the object around its center. In degrees.

eispy2d.dunnetttest(y0, y)#

Perform all-to-one comparisons through Dunnett’s test.

The Dunnett’s test is a procedure for comparing a set of \(a-1\) treatments against a single one called the control group [1]_. The test is a modification of the usual t-test where, in each comparison, the null hypothesis is the equality of means. The significance level is fixed in 0.05.

Parameters:
  • y0 (numpy.ndarray) – Control sample (1-d array).

  • y (list or numpy.ndarray) – \(a-1\) treatments to be compared. The argument must be either a list of Numpy arrays or a matrix with shape (a-1, n).

Returns:

null_hypothesislist of bool

List of boolean values indicating the result of the null hypothesis. If True, it means that the test has failed in rejecting the null hypothesis. If False, then the null hypothesis of equality of means for the respective comparison has been reject at a 0.05 significance level.

References

eispy2d.ellipse(x_radius, y_radius, axis_length_x=2.0, axis_length_y=2.0, resolution=None, background_rel_permittivity=1.0, background_conductivity=0.0, object_rel_permittivity=1.0, object_conductivity=0.0, rel_permittivity=None, conductivity=None, center=[0.0, 0.0], rotate=0.0)#

Draw an ellipse.

Parameters:
  • x_radius (float) – Ellipse radii in each axis.

  • y_radius (float) – Ellipse radii in each axis.

  • axis_length_x (float, default: 2.0) – Length of the size of the image.

  • axis_length_y (float, default: 2.0) – Length of the size of the image.

  • resolution (2-tuple) – Image resolution, in y and x directions, i.e., (NY, NX). Either this argument or rel_permittivity or conductivity must be given!

  • background_rel_permittivity (float, default: 1.0)

  • background_conductivity (float, default: 0.0)

  • object_rel_permittivity (float, default: 1.0)

  • object_conductivity (float, default: 0.0)

  • center (list, default: [0.0, 0.0]) – Center of the object in the image. The center of the image corresponds to the origin of the coordinates.

  • rel_permittivity (numpy.ndarray, default:None) – A predefined image in which the object will be drawn.

  • conductivity (numpy.ndarray, default:None) – A predefined image in which the object will be drawn.

  • rotate (float, default: 0.0 degrees) – Rotation of the object around its center. In degrees.

eispy2d.factorial_analysis(data, alpha=0.05, group_names=None, ylabel=None)#

Perform factorial analysis.

Given a data set with some amount of factors and levels, the method performs the factorial analysis in order to find evidences for impact of single factors (main effects) and combination among them (interaction effects) [1]_.

In this current version, it only supports two or three factors and balanced data.

Parameters:
  • data (numpy.ndarray) – The data set in array format in which each dimension represents a factor and the number of elements represents the number of levels of respective factor. The shape must be either (a, b, n), for two-factors, or (a, b, c, n), for three factors. Obs.: the last dimension is the number of samples for each combination of factors-levels.

  • alpha (float, default: 0.05) – Significance level.

  • group_names (list, default: None) – Factor names for plot purposes.

  • ylabel (str) – Y-axis label for plot purposes (meaning of the data).

Returns:

null_hypothesislist

The list with the results of the null hypothesis of the statistic tests. If True, means that the test failed to reject the null hypothesis; if False, means the null hypothesis was rejected. For two-factor anaylsis, the each element represents the test on the following factors [A, B, AB]. For three-factor, [A, B, C, AB, AC, BC, ABC].

pvalueslist

The list with the p-values of each test. The order follows the same defined for null_hypothesis.

shapiro_pvalue: float

The p-value of the Shapiro-Wilk’s test for normality of residuals assumption. A p-value less than 0.05 means the rejection of the assumption.

fligner_pvalue: float

The p-value of the Fligner-Killen’s test for homoscedascity (variance equality) of samples. A p-value less than 0.05 means the rejection of the assumption.

figmatplotlib.figure.Figure

A plot showing the normality and homoscedascity assumption. The graphic way to anaylise the assumptions.

transformationNone or str

If None, no transformation was applied on the data in order to fix it for following the assumption. Otherwise, it is a string saying the type of transformation.

References

eispy2d.homoscedasticityplot(data, axes=None, title=None, ylabel=None, names=None, legend_fontsize=None)#

Graphic investigation of homoscedasticity assumption.

This routine plots a figure comparing variance of samples for the purpose of investigating the assumption of homoscedasticity (samples with equal variance). Each samples is positioned in the x-axis in the correspondent value of its own mean. This routine does not show any plot. It only draws the graphic.

Parameters:
  • data (either numpy.ndarray or list) – A 2-d array with the samples in which each row is a single sample or a list of 1-d arrays.

  • axes (matplotlib.Axes.axes, default: None) – A specified axes for plotting the graphics. If none is provided, then one will be created and returned.

  • title (str, default: None) – A possible title to the plot.

  • ylabel (str, default: None) – The label of the y-axis which represent the unit of the data.

  • names (list of str, default: None) – A list with the name of the samples for legend purpose.

Returns:

fig : matplotlib.figure.Figure

Example

>>> import numpy as np
>>> from matplotlib import pyplot as plt
>>> y1 = np.random.normal(loc=2., size=30)
>>> y2 = np.random.normal(loc=4., size=60)
>>> homoscedasticityplot([y1, y2], title='Samples',
                         names=['Sample 1', 'Sample 2'])
>>> plt.show()
eispy2d.line(length, thickness, axis_length_x=2.0, axis_length_y=2.0, resolution=None, background_rel_permittivity=1.0, background_conductivity=0.0, object_rel_permittivity=1.0, object_conductivity=0.0, center=[0.0, 0.0], rotate=0.0, rel_permittivity=None, conductivity=None)#

Draw a cross.

Parameters:
  • length (float) – Parameters of the line.

  • thickness (float) – Parameters of the line.

  • axis_length_x (float, default: 2.0) – Length of the size of the image.

  • axis_length_y (float, default: 2.0) – Length of the size of the image.

  • resolution (2-tuple) – Image resolution, in y and x directions, i.e., (NY, NX). Either this argument or rel_permittivity or conductivity must be given!

  • background_rel_permittivity (float, default: 1.0)

  • background_conductivity (float, default: 0.0)

  • object_rel_permittivity (float, default: 1.0)

  • object_conductivity (float, default: 0.0)

  • center (list, default: [0.0, 0.0]) – Center of the object in the image. The center of the image corresponds to the origin of the coordinates.

  • rel_permittivity (numpy.ndarray, default:None) – A predefined image in which the object will be drawn.

  • conductivity (numpy.ndarray, default:None) – A predefined image in which the object will be drawn.

  • rotate (float, default: 0.0 degrees) – Rotation of the object around its center. In degrees.

eispy2d.normalitiyplot(data, axes=None, title=None, fontsize=10)#

Graphic investigation of normality assumption.

This routine plots a figure comparing a sample to a standard normal distribution for the purpose of investigating the assumption of normality. This routine does not show any plot. It only draws the graphic.

Parameters:
  • data (numpy.ndarray) – An 1-d array representing the sample.

  • axes (matplotlib.Axes.axes, default: None) – A specified axes for plotting the graphics. If none is provided, then one will be created and returned.

  • title (str, default: None) – A possible title to the plot.

Returns:

fig : matplotlib.figure.Figure

Example

>>> import numpy as np
>>> from matplotlib import pyplot as plt
>>> y1 = np.random.normal(size=30)
>>> y2 = np.random.normal(size=60)
>>> fig = plt.figure()
>>> axes1 = fig.add_subplot(1, 2, 1)
>>> normalityplot(y1, axes=axes1, title='Sample 1')
>>> axes2 = fig.add_subplot(1, 2, 1)
>>> normalityplot(y2, axes=axes2, title='Sample 2')
>>> plt.show()
eispy2d.parallelogram(length, height, inclination, center=[0.0, 0.0], rotate=0.0, axis_length_x=2.0, axis_length_y=2.0, resolution=None, background_rel_permittivity=1.0, background_conductivity=0.0, object_rel_permittivity=1.0, object_conductivity=0.0, rel_permittivity=None, conductivity=None)#

Draw a paralellogram.

Parameters:
  • length (float) – Dimensions.

  • height (float) – Dimensions.

  • inclination (float) – In degrees.

  • axis_length_x (float, default: 2.0) – Length of the size of the image.

  • axis_length_y (float, default: 2.0) – Length of the size of the image.

  • resolution (2-tuple) – Image resolution, in y and x directions, i.e., (NY, NX). Either this argument or rel_permittivity or conductivity must be given!

  • background_rel_permittivity (float, default: 1.0)

  • background_conductivity (float, default: 0.0)

  • object_rel_permittivity (float, default: 1.0)

  • object_conductivity (float, default: 0.0)

  • center (list, default: [0.0, 0.0]) – Center of the object in the image. The center of the image corresponds to the origin of the coordinates.

  • rel_permittivity (numpy.ndarray, default:None) – A predefined image in which the object will be drawn.

  • conductivity (numpy.ndarray, default: None) – A predefined image in which the object will be drawn.

  • rotate (float, default: 0.0 degrees) – Rotation of the object around its center. In degrees.

eispy2d.polygon(number_sides, radius, axis_length_x=2.0, axis_length_y=2.0, resolution=None, center=[0.0, 0.0], rotate=0.0, background_rel_permittivity=1.0, background_conductivity=0.0, object_rel_permittivity=1.0, object_conductivity=0.0, rel_permittivity=None, conductivity=None)#

Draw a polygon with equal sides.

Parameters:
  • number_sides (int) – Number of sides.

  • radius (float) – Radius from the center to each vertex.

  • axis_length_x (float, default: 2.0) – Length of the size of the image.

  • axis_length_y (float, default: 2.0) – Length of the size of the image.

  • resolution (2-tuple) – Image resolution, in y and x directions, i.e., (NY, NX). Either this argument or rel_permittivity or conductivity must be given!

  • background_rel_permittivity (float, default: 1.0)

  • background_conductivity (float, default: 0.0)

  • object_rel_permittivity (float, default: 1.0)

  • object_conductivity (float, default: 0.0)

  • center (list, default: [0.0, 0.0]) – Center of the object in the image. The center of the image corresponds to the origin of the coordinates.

  • rel_permittivity (numpy.ndarray, default:None) – A predefined image in which the object will be drawn.

  • conductivity (numpy.ndarray, default:None) – A predefined image in which the object will be drawn.

  • rotate (float, default: 0.0 degrees) – Rotation of the object around its center. In degrees.

eispy2d.random(number_sides, maximum_radius, minimum_radius=None, center=[0.0, 0.0], axis_length_x=2.0, axis_length_y=2.0, resolution=None, background_rel_permittivity=1.0, background_conductivity=0.0, object_rel_permittivity=1.0, object_conductivity=0.0, rel_permittivity=None, conductivity=None)#

Draw a random polygon.

Parameters:
  • number_sides (int) – Number of sides of the polygon.

  • maximum_radius (float) – Maximum radius from the origin to each vertex.

  • axis_length_x (float, default: 2.0) – Length of the size of the image.

  • axis_length_y (float, default: 2.0) – Length of the size of the image.

  • resolution (2-tuple) – Image resolution, in y and x directions, i.e., (NY, NX). Either this argument or rel_permittivity or conductivity must be given!

  • background_rel_permittivity (float, default: 1.0)

  • background_conductivity (float, default: 0.0)

  • object_rel_permittivity (float, default: 1.0)

  • object_conductivity (float, default: 0.0)

  • center (list, default: [0.0, 0.0]) – Center of the object in the image. The center of the image corresponds to the origin of the coordinates.

  • rel_permittivity (numpy.ndarray, default:None) – A predefined image in which the object will be drawn.

  • conductivity (numpy.ndarray, default:None) – A predefined image in which the object will be drawn.

  • rotate (float, default: 0.0 degrees) – Rotation of the object around its center. In degrees.

eispy2d.random_gaussians(number_distributions, maximum_spread=0.8, minimum_spread=0.5, distance_from_border=0.1, resolution=None, surface_area=(1.0, 1.0), rel_permittivity_amplitude=0.0, conductivity_amplitude=0.0, axis_length_x=2.0, axis_length_y=2.0, background_conductivity=0.0, background_rel_permittivity=1.0, rel_permittivity=None, center=[0.0, 0.0], conductivity=None, rotate=0.0, edge_smoothing=0.03)#

Draw random Gaussian distributions with specified electromagnetic properties.

Parameters:
  • number_distributions (int) – Number of Gaussian distributions.

  • maximum_spread (float, default=0.8) – Maximum spread of Gaussian (proportional to area).

  • minimum_spread (float, default=0.5) – Minimum spread of Gaussian.

  • distance_from_border (float, default=0.1) – Minimum distance from border for distribution centers.

  • resolution (tuple of int, optional) – Image resolution as (NY, NX).

  • surface_area (tuple, default=(1.0, 1.0)) – Proportion of image dimensions for distribution area.

  • rel_permittivity_amplitude (float, default=0.0) – Maximum amplitude of relative permittivity variation.

  • conductivity_amplitude (float, default=0.0) – Maximum amplitude of conductivity variation in S/m.

  • axis_length_x (float, default=2.0) – Physical length in x-direction.

  • axis_length_y (float, default=2.0) – Physical length in y-direction.

  • background_conductivity (float, default=0.0) – Background conductivity in S/m.

  • background_rel_permittivity (float, default=1.0) – Background relative permittivity.

  • rel_permittivity (numpy.ndarray, optional) – Existing permittivity array to overlay on.

  • center (list of float, default=[0.0, 0.0]) – Center position as [x, y] coordinates.

  • conductivity (numpy.ndarray, optional) – Existing conductivity array to overlay on.

  • rotate (float, default=0.0) – Rotation angle in degrees.

  • edge_smoothing (float, default=0.03) – Percentage of cells at boundary to smooth.

Returns:

(epsilon_r, sigma) arrays with the Gaussian distributions drawn.

Return type:

tuple of numpy.ndarray

eispy2d.random_waves(number_waves, maximum_number_peaks, maximum_number_peaks_y=None, resolution=None, rel_permittivity_amplitude=0.0, conductivity_amplitude=0.0, axis_length_x=2.0, axis_length_y=2.0, background_rel_permittivity=1.0, background_conductivity=0.0, rel_permittivity=None, conductivity=None, wave_bounds_proportion=(1.0, 1.0), center=[0.0, 0.0], rotate=0.0, edge_smoothing=0.03)#

Draw random wave patterns with specified electromagnetic properties.

Parameters:
  • number_waves (int) – Number of wave components.

  • maximum_number_peaks (int) – Maximum number of peaks (controls smallest wavelength).

  • maximum_number_peaks_y (int, optional) – Maximum number of peaks in y-direction. If None, uses maximum_number_peaks.

  • resolution (tuple of int, optional) – Image resolution as (NY, NX).

  • rel_permittivity_amplitude (float, default=0.0) – Maximum amplitude of relative permittivity variation.

  • conductivity_amplitude (float, default=0.0) – Maximum amplitude of conductivity variation in S/m.

  • axis_length_x (float, default=2.0) – Physical length in x-direction.

  • axis_length_y (float, default=2.0) – Physical length in y-direction.

  • background_rel_permittivity (float, default=1.0) – Background relative permittivity.

  • background_conductivity (float, default=0.0) – Background conductivity in S/m.

  • rel_permittivity (numpy.ndarray, optional) – Existing permittivity array to overlay on.

  • conductivity (numpy.ndarray, optional) – Existing conductivity array to overlay on.

  • wave_bounds_proportion (tuple, default=(1.0, 1.0)) – Proportion of image dimensions for wave area.

  • center (list of float, default=[0.0, 0.0]) – Center position as [x, y] coordinates.

  • rotate (float, default=0.0) – Rotation angle in degrees.

  • edge_smoothing (float, default=0.03) – Percentage of cells at boundary to smooth.

Returns:

(epsilon_r, sigma) arrays with the random wave pattern drawn.

Return type:

tuple of numpy.ndarray

eispy2d.rcbd(data, alpha=0.05)#

Randomized Complete Block Design (RCBD) analysis.

Performs ANOVA for randomized complete block design.

Parameters:
  • data (numpy.ndarray or list) – 2D array where rows represent blocks and columns represent treatments.

  • alpha (float, default=0.05) – Significance level.

Returns:

  • F0 (float) – F-statistic.

  • pvalue (float) – P-value.

  • H0 (bool) – True if null hypothesis is not rejected.

eispy2d.rhombus(x_radius, y_radius, axis_length_x=2.0, axis_length_y=2.0, resolution=None, center=[0.0, 0.0], rotate=0.0, background_rel_permittivity=1.0, background_conductivity=0.0, object_rel_permittivity=1.0, object_conductivity=0.0, rel_permittivity=None, conductivity=None)#

Draw a rhombus.

Parameters:
  • x_radius (float) – Radii in each axis.

  • y_radius (float) – Radii in each axis.

  • axis_length_x (float, default: 2.0) – Length of the size of the image.

  • axis_length_y (float, default: 2.0) – Length of the size of the image.

  • resolution (2-tuple) – Image resolution, in y and x directions, i.e., (NY, NX). Either this argument or rel_permittivity or conductivity must be given!

  • background_rel_permittivity (float, default: 1.0)

  • background_conductivity (float, default: 0.0)

  • object_rel_permittivity (float, default: 1.0)

  • object_conductivity (float, default: 0.0)

  • center (list, default: [0.0, 0.0]) – Center of the object in the image. The center of the image corresponds to the origin of the coordinates.

  • rel_permittivity (numpy.ndarray, default:None) – A predefined image in which the object will be drawn.

  • conductivity (numpy.ndarray, default: None) – A predefined image in which the object will be drawn.

  • rotate (float, default: 0.0 degrees) – Rotation of the object around its center. In degrees.

eispy2d.ring(inner_radius, outer_radius, axis_length_x=2.0, axis_length_y=2.0, resolution=None, center=[0.0, 0.0], background_rel_permittivity=1.0, background_conductivity=0.0, object_rel_permittivity=1.0, object_conductivity=0.0, rel_permittivity=None, conductivity=None)#

Draw a ring.

Parameters:
  • inner_radius (float) – Inner and outer radii of the ring.

  • outer_radius (float) – Inner and outer radii of the ring.

  • axis_length_x (float, default: 2.0) – Length of the size of the image.

  • axis_length_y (float, default: 2.0) – Length of the size of the image.

  • resolution (2-tuple) – Image resolution, in y and x directions, i.e., (NY, NX). Either this argument or rel_permittivity or conductivity must be given!

  • background_rel_permittivity (float, default: 1.0)

  • background_conductivity (float, default: 0.0)

  • object_rel_permittivity (float, default: 1.0)

  • object_conductivity (float, default: 0.0)

  • center (list, default: [0.0, 0.0]) – Center of the object in the image. The center of the image corresponds to the origin of the coordinates.

  • rel_permittivity (numpy.ndarray, default:None) – A predefined image in which the object will be drawn.

  • conductivity (numpy.ndarray, default:None) – A predefined image in which the object will be drawn.

eispy2d.square(side_length, axis_length_x=2.0, axis_length_y=2.0, resolution=None, background_rel_permittivity=1.0, background_conductivity=0.0, object_rel_permittivity=1.0, object_conductivity=0.0, center=[0.0, 0.0], rotate=0.0, rel_permittivity=None, conductivity=None)#

Draw a square with specified electromagnetic properties.

This function creates a square object with customizable electromagnetic properties, positioning, and rotation on a 2D grid. The square can be drawn on a new image or overlaid on existing permittivity and conductivity arrays.

Parameters:
  • side_length (float) – Length of the square’s side in the same units as axis_length_x/y.

  • axis_length_x (float, default=2.0) – Physical length of the image in the x-direction.

  • axis_length_y (float, default=2.0) – Physical length of the image in the y-direction.

  • resolution (tuple of int, optional) – Image resolution as (NY, NX). Required if rel_permittivity and conductivity are not provided.

  • background_rel_permittivity (float, default=1.0) – Relative permittivity of the background medium.

  • background_conductivity (float, default=0.0) – Conductivity of the background medium in S/m.

  • object_rel_permittivity (float, default=1.0) – Relative permittivity of the square object.

  • object_conductivity (float, default=0.0) – Conductivity of the square object in S/m.

  • center (list of float, default=[0.0, 0.0]) – Center position of the square as [x, y] coordinates.

  • rotate (float, default=0.0) – Rotation angle in degrees (counterclockwise).

  • rel_permittivity (numpy.ndarray, optional) – Existing relative permittivity array to overlay on.

  • conductivity (numpy.ndarray, optional) – Existing conductivity array to overlay on.

Returns:

(epsilon_r, sigma) arrays with the square drawn.

Return type:

tuple of numpy.ndarray

eispy2d.star4(radius, axis_length_x=2.0, axis_length_y=2.0, resolution=None, background_rel_permittivity=1.0, background_conductivity=0.0, object_rel_permittivity=1.0, object_conductivity=0.0, rel_permittivity=None, conductivity=None, center=[0.0, 0.0], rotate=0.0)#

Draw a 4-point star.

Parameters:
  • radius (float) – Radius of the vertex from the center of the star.

  • axis_length_x (float, default: 2.0) – Length of the size of the image.

  • axis_length_y (float, default: 2.0) – Length of the size of the image.

  • resolution (2-tuple) – Image resolution, in y and x directions, i.e., (NY, NX). Either this argument or rel_permittivity or conductivity must be given!

  • background_rel_permittivity (float, default: 1.0)

  • background_conductivity (float, default: 0.0)

  • object_rel_permittivity (float, default: 1.0)

  • object_conductivity (float, default: 0.0)

  • center (list, default: [0.0, 0.0]) – Center of the object in the image. The center of the image corresponds to the origin of the coordinates.

  • rel_permittivity (numpy.ndarray, default:None) – A predefined image in which the object will be drawn.

  • conductivity (numpy.ndarray, default: None) – A predefined image in which the object will be drawn.

  • rotate (float, default: 0.0 degrees) – Rotation of the object around its center. In degrees.

eispy2d.star5(radius, axis_length_x=2.0, axis_length_y=2.0, resolution=None, background_rel_permittivity=1.0, background_conductivity=0.0, object_rel_permittivity=1.0, object_conductivity=0.0, rel_permittivity=None, conductivity=None, center=[0.0, 0.0], rotate=0.0)#

Draw a 5-point star.

Parameters:
  • radius (int) – Length from the center of the star to the main vertices.

  • maximum_radius (float) – Maximum radius from the origin to each vertex.

  • axis_length_x (float, default: 2.0) – Length of the size of the image.

  • axis_length_y (float, default: 2.0) – Length of the size of the image.

  • resolution (2-tuple) – Image resolution, in y and x directions, i.e., (NY, NX). Either this argument or rel_permittivity or conductivity must be given!

  • background_rel_permittivity (float, default: 1.0)

  • background_conductivity (float, default: 0.0)

  • object_rel_permittivity (float, default: 1.0)

  • object_conductivity (float, default: 0.0)

  • center (list, default: [0.0, 0.0]) – Center of the object in the image. The center of the image corresponds to the origin of the coordinates.

  • rel_permittivity (numpy.ndarray, default:None) – A predefined image in which the object will be drawn.

  • conductivity (numpy.ndarray, default:None) – A predefined image in which the object will be drawn.

  • rotate (float, default: 0.0 degrees) – Rotation of the object around its center. In degrees.

eispy2d.star6(radius, axis_length_x=2.0, axis_length_y=2.0, resolution=None, background_rel_permittivity=1.0, background_conductivity=0.0, object_rel_permittivity=1.0, object_conductivity=0.0, rel_permittivity=None, conductivity=None, rotate=0.0, center=[0.0, 0.0])#

Draw a six-pointed star (hexagram).

Parameters:
  • radius (float) – Length from the center to the maximum edge.

  • axis_length_x (float, default: 2.0) – Length of the size of the image.

  • axis_length_y (float, default: 2.0) – Length of the size of the image.

  • resolution (2-tuple) – Image resolution, in y and x directions, i.e., (NY, NX). Either this argument or rel_permittivity or conductivity must be given!

  • background_rel_permittivity (float, default: 1.0)

  • background_conductivity (float, default: 0.0)

  • object_rel_permittivity (float, default: 1.0)

  • object_conductivity (float, default: 0.0)

  • center (list, default: [0.0, 0.0]) – Center of the object in the image. The center of the image corresponds to the origin of the coordinates.

  • rel_permittivity (numpy.ndarray, default:None) – A predefined image in which the object will be drawn.

  • conductivity (numpy.ndarray, default:None) – A predefined image in which the object will be drawn.

  • rotate (float, default: 0.0 degrees) – Rotation of the object around its center. In degrees.

eispy2d.trapezoid(upper_length, lower_length, height, axis_length_x=2.0, axis_length_y=2.0, resolution=None, center=[0.0, 0.0], rotate=0.0, background_rel_permittivity=1.0, background_conductivity=0.0, object_rel_permittivity=1.0, object_conductivity=0.0, rel_permittivity=None, conductivity=None)#

Draw a trapezoid.

Parameters:
  • upper_length (float) – Dimensions.

  • lower_length (float) – Dimensions.

  • height (float) – Dimensions.

  • axis_length_x (float, default: 2.0) – Length of the size of the image.

  • axis_length_y (float, default: 2.0) – Length of the size of the image.

  • resolution (2-tuple) – Image resolution, in y and x directions, i.e., (NY, NX). Either this argument or rel_permittivity or conductivity must be given!

  • background_rel_permittivity (float, default: 1.0)

  • background_conductivity (float, default: 0.0)

  • object_rel_permittivity (float, default: 1.0)

  • object_conductivity (float, default: 0.0)

  • center (list, default: [0.0, 0.0]) – Center of the object in the image. The center of the image corresponds to the origin of the coordinates.

  • rel_permittivity (numpy.ndarray, default:None) – A predefined image in which the object will be drawn.

  • conductivity (numpy.ndarray, default: None) – A predefined image in which the object will be drawn.

  • rotate (float, default: 0.0 degrees) – Rotation of the object around its center. In degrees.

eispy2d.triangle(side_length, axis_length_x=2.0, axis_length_y=2.0, resolution=None, background_rel_permittivity=1.0, background_conductivity=0.0, object_rel_permittivity=1.0, object_conductivity=0.0, rel_permittivity=None, conductivity=None, rotate=0.0, center=[0.0, 0.0])#

Draw an equilateral triangle with specified electromagnetic properties.

Parameters:
  • side_length (float) – Length of the triangle’s side.

  • axis_length_x (float, default=2.0) – Physical length of the image in the x-direction.

  • axis_length_y (float, default=2.0) – Physical length of the image in the y-direction.

  • resolution (tuple of int, optional) – Image resolution as (NY, NX). Required if rel_permittivity and conductivity are not provided.

  • background_rel_permittivity (float, default=1.0) – Background relative permittivity.

  • background_conductivity (float, default=0.0) – Background conductivity in S/m.

  • object_rel_permittivity (float, default=1.0) – Triangle’s relative permittivity.

  • object_conductivity (float, default=0.0) – Triangle’s conductivity in S/m.

  • rel_permittivity (numpy.ndarray, optional) – Existing permittivity array to overlay on.

  • conductivity (numpy.ndarray, optional) – Existing conductivity array to overlay on.

  • rotate (float, default=0.0) – Rotation angle in degrees (counterclockwise).

  • center (list of float, default=[0.0, 0.0]) – Center position as [x, y] coordinates.

Returns:

(epsilon_r, sigma) arrays with the triangle drawn.

Return type:

tuple of numpy.ndarray

eispy2d.wave(number_peaks, rel_permittivity_peak=1.0, conductivity_peak=0.0, rel_permittivity_valley=None, conductivity_valley=None, resolution=None, number_peaks_y=None, axis_length_x=2.0, axis_length_y=2.0, background_rel_permittivity=1.0, background_conductivity=0.0, rel_permittivity=None, conductivity=None, wave_bounds_proportion=(1.0, 1.0), center=[0.0, 0.0], rotate=0.0)#

Draw a wave pattern with specified electromagnetic properties.

Parameters:
  • number_peaks (int) – Number of peaks for both directions or for x-axis (if number_peaks_y is None).

  • rel_permittivity_peak (float, default=1.0) – Peak value of relative permittivity.

  • conductivity_peak (float, default=0.0) – Peak value of conductivity in S/m.

  • rel_permittivity_valley (float, optional) – Valley value of relative permittivity. If None, uses peak value.

  • conductivity_valley (float, optional) – Valley value of conductivity. If None, uses peak value.

  • resolution (tuple of int, optional) – Image resolution as (NY, NX).

  • number_peaks_y (int, optional) – Number of peaks in y-direction. If None, uses number_peaks.

  • axis_length_x (float, default=2.0) – Physical length in x-direction.

  • axis_length_y (float, default=2.0) – Physical length in y-direction.

  • background_rel_permittivity (float, default=1.0) – Background relative permittivity.

  • background_conductivity (float, default=0.0) – Background conductivity in S/m.

  • rel_permittivity (numpy.ndarray, optional) – Existing permittivity array to overlay on.

  • conductivity (numpy.ndarray, optional) – Existing conductivity array to overlay on.

  • wave_bounds_proportion (tuple, default=(1.0, 1.0)) – Proportion of image dimensions for wave area.

  • center (list of float, default=[0.0, 0.0]) – Center position as [x, y] coordinates.

  • rotate (float, default=0.0) – Rotation angle in degrees.

Returns:

(epsilon_r, sigma) arrays with the wave pattern drawn.

Return type:

tuple of numpy.ndarray