eispy2d.data package#

Submodules#

eispy2d.data.inputdata module#

A module to represent problem case.

Based on the same problem configuration, there may be infinite scenarios describing different geometries and resolutions. So, this module provides a class in which we may store information about a scenario, i.e., a problem case in which we may the scattered field measurements and some other information which will be received by the solver describing the problem to be solved.

The InputData implements a container which will be the standard input to solvers and include all the information necessary to solve a inverse scattering problem.

The following class is defined

InputData

The container representing an instance of a inverse scattering problem.

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

eispy2d.data.inputdata.degrees_nonlinearity(inputdata)#

Compute the Degree of Non-Linearity (DNL) for the given input data.

The DNL is computed following the traditional model (H₀ [1]) based on the data equation and Richmond discretization.

Parameters:

inputdata (InputData) – Input data object containing ground truth maps and configuration.

Returns:

Degree of non-linearity value.

Return type:

float

References

eispy2d.data.result module#

Results storage and visualization module for electromagnetic inverse scattering.

This module provides comprehensive functionality for storing, analyzing, and visualizing results from electromagnetic inverse scattering algorithms. It contains the main Result class for storing reconstruction results and error metrics, along with plotting utilities for visualization of reconstructed images and convergence curves.

The module supports various error metrics for quantitative evaluation of reconstruction quality, including residual norm errors, percentage average deviation (PAD) errors, and shape/position errors. It also provides sophisticated plotting capabilities for displaying contrast maps, field distributions, and convergence behavior.

Key Features#

  • Comprehensive result storage with multiple error metrics

  • Advanced plotting capabilities for maps and convergence curves

  • Support for both permittivity and conductivity reconstructions

  • Flexible visualization options with customizable layouts

  • Statistical analysis tools for reconstruction quality assessment

  • Pickle-based serialization for result persistence

Classes#

Result

Main class for storing and managing reconstruction results from inverse scattering methods.

Functions#

add_image

Add image plots to matplotlib axes with standardized formatting.

add_plot

Add line plots to matplotlib axes for convergence visualization.

add_box

Add box plots for statistical analysis of reconstruction metrics.

get_figure

Create figure layouts for different plot configurations.

indicator_label

Get formatted labels for error indicators.

check_indicator

Validate error indicator names.

compute_*

Various functions for computing specific error metrics.

Constants#

Error Indicator Constants

RESIDUAL_NORM_ERROR, RESIDUAL_PAD_ERROR, REL_PERMITTIVITY_PAD_ERROR, etc. String constants for accessing different error metrics.

Plot Label Constants

XLABEL_STANDARD, YLABEL_STANDARD, COLORBAR_REL_PERMITTIVITY, etc. Pre-defined labels for consistent plot formatting.

Image Type Constants

PERMITTIVITY, CONDUCTIVITY, CONTRAST, TOTAL_FIELD, BOTH_PROPERTIES Constants for specifying different visualization types.

Notes

The module integrates closely with the electromagnetic inverse scattering framework, providing standardized result storage and visualization capabilities. It supports both single-frequency and multi-frequency reconstruction results.

Examples

>>> import result as rst
>>>
>>> # Create result object
>>> result = rst.Result(name='test_reconstruction')
>>>
>>> # Store reconstruction data
>>> result.rel_permittivity = reconstructed_permittivity
>>> result.conductivity = reconstructed_conductivity
>>>
>>> # Plot results
>>> result.plot_map(image=rst.BOTH_PROPERTIES, show=True)
>>>
>>> # Plot convergence
>>> result.plot_convergence(indicators=[rst.RESIDUAL_NORM_ERROR], show=True)
class eispy2d.data.result.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())
eispy2d.data.result.add_box(data, axis=None, meanline=False, labels=None, xlabel=None, ylabel=None, color='b', legend=None, title=None, notch=False, legend_fontsize=None, fontsize=10, positions=None, yscale=None, widths=0.5)#

Improved boxplot routine.

This routine does not show any plot. It only draws the graphic.

Parameters:
  • data (list of numpy.ndarray) – A list of 1-d arrays meaning the samples.

  • axis (matplotlib.Axes.axes, default: None) – A specified axis for plotting the graphics. If none is provided, then one will be created and returned.

  • meanline (bool, default: False) – Draws a line through linear regression of the means among the samples.

  • labels (list of str, default: None) – Names of the samples.

  • xlabel (str, default: None)

  • ylabel (list of str, default: None)

  • color (str, default: 'b') – Color of boxes. Check some here

  • legend (str, default: None) – Label for meanline.

  • 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(loc=2., size=30)
>>> y2 = np.random.normal(loc=4., size=60)
>>> y3 = np.random.normal(loc=6., size=10)
>>> boxplot([y1, y2, y3], title='Samples',
            labels=['Sample 1', 'Sample 2', 'Sample 3'],
            xlabel='Samples', ylabel='Unit', color='tab:blue',
            meanline=True, legend='Progression')
>>> plt.show()
eispy2d.data.result.add_image(axes, image, title, colorbar_name, bounds=(-1.0, 1.0, -1.0, 1.0), origin='lower', xlabel='x [$\\lambda_b$]', ylabel='y [$\\lambda_b$]', aspect='equal', interpolation=None, fontsize=10)#

Add standardized image plot to matplotlib axes.

Creates a standardized image plot with proper scaling, colorbar, and labels for electromagnetic inverse scattering visualizations. Handles both real and complex-valued images appropriately.

Parameters:
  • axes (matplotlib.axes.Axes) – The axes object where the image will be plotted.

  • image (numpy.ndarray) – 2D array containing the image data. If complex-valued, the magnitude will be displayed.

  • title (str) – Title to be displayed above the image.

  • colorbar_name (str) – Label for the colorbar indicating the physical quantity and units.

  • bounds (4-tuple of float, optional) – Spatial bounds for the image: (xmin, xmax, ymin, ymax). Default is (-1., 1., -1., 1.).

  • origin ({'lower', 'upper'}, optional) – Origin of the y-axis. ‘lower’ places origin at bottom-left. Default is ‘lower’.

  • xlabel (str, optional) – Label for the x-axis. Default is standard wavelength-normalized label.

  • ylabel (str, optional) – Label for the y-axis. Default is standard wavelength-normalized label.

  • aspect (str or float, optional) – Aspect ratio of the image. Default is ‘equal’.

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

  • fontsize (int, optional) – Font size for all text elements. Default is 10.

Notes

  • Complex images are automatically converted to magnitude

  • Colorbar is positioned with standard fraction and padding

  • All text elements use consistent font sizing

  • Spatial coordinates are typically normalized by background wavelength

Examples

>>> import matplotlib.pyplot as plt
>>> import numpy as np
>>>
>>> fig, ax = plt.subplots()
>>> image_data = np.random.rand(64, 64) * 2 + 1
>>> add_image(ax, image_data, 'Relative Permittivity', r'$\\epsilon_r$',
...           bounds=(-2, 2, -2, 2), fontsize=12)
>>> plt.show()
eispy2d.data.result.add_plot(axes, data, x=None, title=None, xlabel='Iterations', ylabel=None, style='--*', xticks=None, legend=None, legend_fontsize=None, yscale=None, fontsize=10, color=None, markersize=None)#

Add standardized line plot to matplotlib axes.

Creates a standardized line plot with proper formatting for convergence curves and other time-series data in electromagnetic inverse scattering analysis.

Parameters:
  • axes (matplotlib.axes.Axes) – The axes object where the plot will be created.

  • data (numpy.ndarray) – 1D array containing the y-data to be plotted.

  • x (numpy.ndarray, optional) – 1D array containing the x-data. If None, uses range(len(data)).

  • title (str, optional) – Title to be displayed above the plot.

  • xlabel (str, optional) – Label for the x-axis. Default is ‘Iterations’.

  • ylabel (str, optional) – Label for the y-axis. If None, no y-label is set.

  • style (str, optional) – Line style specification (e.g., ‘–’, ‘-o’, ‘:^’). Default is ‘–‘.

  • xticks (array-like, optional) – Custom x-axis tick positions. If None, uses matplotlib defaults.

  • legend (str, optional) – Legend label for the plot line. If None, no legend is added.

  • legend_fontsize (int, optional) – Font size for legend text. If None, uses default.

  • yscale ({'linear', 'log', 'symlog', 'logit'}, optional) – Scale for the y-axis. Default is None (linear).

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

  • color (str, optional) – Color specification for the plot line. Default is None (automatic).

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

Notes

  • Automatically generates x-data if not provided

  • Supports various matplotlib scales including logarithmic

  • Consistent font sizing across all text elements

  • Flexible styling options for different visualization needs

Examples

>>> import matplotlib.pyplot as plt
>>> import numpy as np
>>>
>>> fig, ax = plt.subplots()
>>> error_data = np.logspace(-1, -4, 50)  # Decreasing error
>>> add_plot(ax, error_data, title='Convergence', ylabel='Error',
...          yscale='log', fontsize=12)
>>> plt.show()
eispy2d.data.result.add_violin(data, axis=None, meanline=False, labels=None, xlabel=None, ylabel=None, color='b', legend=None, title=None, legend_fontsize=None, fontsize=10, positions=None, yscale=None)#

Create violin plots for data distribution visualization.

Creates violin plots to visualize the distribution of data samples, with optional mean line overlays and customizable formatting. Violin plots show the probability density of data at different values.

Parameters:
  • data (list of numpy.ndarray) – List of 1D arrays containing the data samples for each violin. Each array represents one distribution to be plotted.

  • axis (matplotlib.axes.Axes, optional) – Pre-existing axes for plotting. If None, creates new figure and axes.

  • meanline (bool or str, optional) – Controls mean line overlay. Options: - False: No mean line - True or ‘regression’: Linear regression through means - ‘pointwise’: Point-to-point line through means Default is False.

  • labels (list of str, optional) – Labels for each violin (x-axis tick labels). If None, uses default numbering.

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

  • ylabel (str, optional) – Label for the y-axis. Default is None.

  • color (str, optional) – Color for the violin faces. Default is ‘b’ (blue). See matplotlib color specification for options.

  • legend (str, optional) – Legend label for the mean line. Only used if meanline is True. Default is None.

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

  • legend_fontsize (float, optional) – Font size for legend text. Default is None (uses matplotlib default).

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

  • positions (array-like, optional) – Positions for the violins along the x-axis. If None, uses sequential positions starting from 1.

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

Returns:

The axes object containing the violin plot.

Return type:

matplotlib.axes.Axes

Raises:

error.WrongValueInput – If meanline parameter has an invalid value.

Examples

>>> import numpy as np
>>> from matplotlib import pyplot as plt
>>>
>>> # Create sample data
>>> y1 = np.random.normal(loc=2., size=30)
>>> y2 = np.random.normal(loc=4., size=60)
>>> y3 = np.random.normal(loc=6., size=10)
>>>
>>> # Create violin plot
>>> ax = add_violin([y1, y2, y3], title='Error Distributions',
...                 labels=['Method 1', 'Method 2', 'Method 3'],
...                 xlabel='Methods', ylabel='Error Value',
...                 color='tab:blue', meanline=True, legend='Mean Trend')
>>> plt.show()
>>>
>>> # Violin plot with custom positions
>>> ax = add_violin([y1, y2, y3], positions=[1, 3, 5],
...                 meanline='pointwise', yscale='log')
>>> plt.show()

Notes

  • Violin plots show the full distribution shape, not just summary statistics

  • Mean line helps visualize trends across different data groups

  • Useful for comparing reconstruction error distributions across methods

  • Color can be specified using matplotlib color names or hex codes

eispy2d.data.result.check_indicator(indicator)#

Validate whether the given indicator name(s) are valid.

Checks if the provided indicator name or list of indicator names correspond to valid error indicators supported by the Result class. This function is used internally for input validation.

Parameters:

indicator (str or list of str) – Error indicator name(s) to validate. Can be a single string or a list of strings representing indicator names.

Returns:

True if all provided indicator names are valid, False otherwise.

Return type:

bool

Notes

Valid indicator names are defined in the INDICATOR_SET constant and include metrics such as: - ‘zeta_rn’: Residual norm error - ‘zeta_rpad’: Residual percentage average deviation - ‘zeta_epad’: Permittivity percentage average deviation - ‘zeta_sad’: Conductivity average deviation - ‘zeta_tv’: Total variation - And many others…

Examples

>>> # Check single indicator
>>> is_valid = check_indicator('zeta_rn')
>>> print(is_valid)  # True
>>>
>>> # Check invalid indicator
>>> is_valid = check_indicator('invalid_indicator')
>>> print(is_valid)  # False
>>>
>>> # Check multiple indicators
>>> is_valid = check_indicator(['zeta_rn', 'zeta_epad'])
>>> print(is_valid)  # True
>>>
>>> # Check with one invalid indicator
>>> is_valid = check_indicator(['zeta_rn', 'invalid_indicator'])
>>> print(is_valid)  # False
eispy2d.data.result.compute_rre(es_o, es_a)#

Compute the Relative Residual Error (RRE) between scattered fields.

Calculates the relative residual error as defined in the literature [1]_ for electromagnetic inverse scattering problems.

Parameters:
  • es_o (numpy.ndarray) – Original (measured) scattered field matrix. Shape: (N_measurements, N_sources). Units: [V/m].

  • es_a (numpy.ndarray) – Approximated (computed) scattered field matrix. Shape: (N_measurements, N_sources). Units: [V/m].

Returns:

Relative residual error as a percentage. Formula:

\[\text{RRE} = 100 \times \frac{\left\|\mathbf{E}^s_{\mathrm{meas}} - \mathbf{E}^s_{\mathrm{comp}}\right\|_2}{\left\|\mathbf{E}^s_{\mathrm{meas}}\right\|_2}\]

Return type:

float

References

Examples

>>> measured_field = np.random.complex128((64, 8))
>>> computed_field = measured_field + 0.05 * measured_field
>>> rre = compute_rre(measured_field, computed_field)
>>> print(f"Relative residual error: {rre:.2f}%")
>>>
>>> # Perfect reconstruction
>>> rre_perfect = compute_rre(measured_field, measured_field)
>>> print(f"Perfect reconstruction RRE: {rre_perfect:.2f}%")  # Should be 0%
eispy2d.data.result.compute_ssim(chi_o, chi_r)#

Compute the Structural Similarity Index (SSIM) between two contrast maps.

Calculates the Structural Similarity Index (SSIM) to assess the similarity between the original and reconstructed contrast maps. SSIM is a perceptual metric that considers changes in structural information, luminance, and contrast.

Parameters:
  • chi_o (numpy.ndarray) – Original (ground truth) contrast map. Shape: (N_x, N_y). Complex-valued, dimensionless.

  • chi_r (numpy.ndarray) – Reconstructed contrast map. Shape: (N_x, N_y). Complex-valued, dimensionless.

Returns:

  • float – Structural Similarity Index (SSIM) value between the two contrast maps. Ranges from -1 to 1, where 1 indicates perfect similarity.

Notes

SSIM is computed using the structural_similarity function from skimage.metrics, which evaluates local patterns of pixel intensities that have been normalized for luminance and contrast. The SSIM value provides a more comprehensive assessment of image quality compared to traditional metrics like Mean Squared Error (MSE).

Examples

>>> # Create sample contrast maps
>>> chi_true = np.zeros((64, 64), dtype=complex)
>>> chi_true[20:40, 20:40] = 2.0 + 0.5j  # Original object
>>> chi_recon = np.zeros((64, 64), dtype=complex)
>>> chi_recon[22:38, 22:38] = 1.8 + 0.4j  # Reconstructed object
>>> # Compute SSIM
>>> ssim_value = compute_ssim(chi_true, chi_recon)
>>> print(f"SSIM: {ssim_value:.4f}")
eispy2d.data.result.compute_zeta_ebe(epsilon_ro, epsilon_rr, epsilon_rb)#

Compute the background relative permittivity estimation error.

Calculates the estimation error for background regions in the relative permittivity reconstruction. This metric quantifies false-positive-like errors where the background is incorrectly reconstructed as having different permittivity values.

Parameters:
  • epsilon_ro (numpy.ndarray) – Original (ground truth) relative permittivity map. Shape: (N_x, N_y). Dimensionless.

  • epsilon_rr (numpy.ndarray) – Recovered (reconstructed) relative permittivity map. Shape: (N_x, N_y). Dimensionless.

  • epsilon_rb (float) – Background relative permittivity value used to identify background regions. Dimensionless.

Returns:

Background relative permittivity estimation error as a percentage. Units: [%].

Return type:

float

Notes

The error is computed only for pixels where the original permittivity equals the background value:

\[\begin{split}\\zeta_{\\epsilon BE} = \\frac{100}{N_{bg}} \\sum_{i \\in \\text{background}} \\frac{|\\epsilon_{r,o,i} - \\epsilon_{r,r,i}|}{|\\epsilon_{r,o,i}|}\end{split}\]

where \(N_{bg}\) is the number of background pixels and the sum is over pixels where \(\\epsilon_{r,o,i} = \\epsilon_{rb}\).

This metric is analogous to the false-positive rate in classification, measuring how well the background regions are preserved in the reconstruction.

Examples

>>> # Create ground truth with background and object
>>> epsilon_true = np.ones((64, 64)) * 1.0  # Background: εᵣ = 1.0
>>> epsilon_true[20:40, 20:40] = 3.0  # Object: εᵣ = 3.0
>>>
>>> # Simulated reconstruction with background errors
>>> epsilon_recon = epsilon_true.copy()
>>> epsilon_recon[0:20, 0:20] = 1.1  # Background error
>>>
>>> # Compute background error
>>> bg_error = compute_zeta_ebe(epsilon_true, epsilon_recon, 1.0)
>>> print(f"Background estimation error: {bg_error:.2f}%")
eispy2d.data.result.compute_zeta_eoe(epsilon_ro, epsilon_rr, epsilon_rb)#

Compute the object relative permittivity estimation error.

Calculates the estimation error for object regions in the relative permittivity reconstruction. This metric quantifies false-negative-like errors where object regions are incorrectly reconstructed with wrong permittivity values.

Parameters:
  • epsilon_ro (numpy.ndarray) – Original (ground truth) relative permittivity map. Shape: (N_x, N_y). Dimensionless.

  • epsilon_rr (numpy.ndarray) – Recovered (reconstructed) relative permittivity map. Shape: (N_x, N_y). Dimensionless.

  • epsilon_rb (float) – Background relative permittivity value used to identify object regions (pixels with values different from background). Dimensionless.

Returns:

Object relative permittivity estimation error as a percentage. Units: [%].

Return type:

float

Notes

The error is computed only for pixels where the original permittivity differs from the background value:

\[\begin{split}\\zeta_{\\epsilon OE} = \\frac{100}{N_{obj}} \\sum_{i \\in \\text{object}} \\frac{|\\epsilon_{r,o,i} - \\epsilon_{r,r,i}|}{|\\epsilon_{r,o,i}|}\end{split}\]

where \(N_{obj}\) is the number of object pixels and the sum is over pixels where \(\\epsilon_{r,o,i} \\neq \\epsilon_{rb}\).

This metric is analogous to the false-negative rate in classification, measuring how accurately the object regions are reconstructed.

Examples

>>> # Create ground truth with background and object
>>> epsilon_true = np.ones((64, 64)) * 1.0  # Background: εᵣ = 1.0
>>> epsilon_true[20:40, 20:40] = 3.0  # Object: εᵣ = 3.0
>>>
>>> # Simulated reconstruction with object errors
>>> epsilon_recon = epsilon_true.copy()
>>> epsilon_recon[20:40, 20:40] = 2.5  # Object reconstruction error
>>>
>>> # Compute object error
>>> obj_error = compute_zeta_eoe(epsilon_true, epsilon_recon, 1.0)
>>> print(f"Object estimation error: {obj_error:.2f}%")
eispy2d.data.result.compute_zeta_epad(epsilon_ro, epsilon_rr)#

Compute the percentage average deviation of relative permittivity.

Calculates the percentage average deviation between the original (true) and reconstructed relative permittivity maps. This metric quantifies the pixel-wise accuracy of permittivity reconstruction.

Parameters:
  • epsilon_ro (numpy.ndarray) – Original (true) relative permittivity map. Shape: (N_x, N_y). Dimensionless.

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

Returns:

Percentage average deviation of relative permittivity. Units: [%/pixel].

Return type:

float

Notes

The error is computed as:

\[\zeta_{\epsilon \mathrm{PAD}} = \frac{100}{N_p} \sum_{i=1}^{N_p} \frac{|\epsilon_{r,r,i}^{\text{rec}} - \epsilon_{r,o,i}^{\text{true}}|}{|\epsilon_{r,o,i}^{\text{true}}|}\]

where \(\epsilon_{r,\mathrm{o},i}\) is the original permittivity at pixel \(i\), \(\epsilon_{r,\mathrm{r},i}\) is the reconstructed permittivity, and \(N_p\) is the total number of pixels.

Examples

>>> true_eps = np.ones((64, 64)) * 2.0  # Background permittivity
>>> true_eps[20:40, 20:40] = 4.0  # Object with higher permittivity
>>> reconstructed_eps = true_eps + 0.1 * np.random.randn(64, 64)
>>> error = compute_zeta_epad(true_eps, reconstructed_eps)
>>> print(f"Permittivity PAD error: {error:.2f}%/pixel")
eispy2d.data.result.compute_zeta_p(chi_o, chi_r)#

Compute the position error between original and reconstructed objects.

Calculates the percentage position error by comparing the centroids of the original and reconstructed scattering objects. This metric quantifies how accurately the object location is recovered in the reconstruction.

Parameters:
  • chi_o (numpy.ndarray) – Original (ground truth) contrast map. Shape: (N_x, N_y). Complex-valued, dimensionless.

  • chi_r (numpy.ndarray) – Reconstructed contrast map. Shape: (N_x, N_y). Complex-valued, dimensionless.

Returns:

Position error as a percentage of the domain size. Units: [%].

Return type:

float

Notes

The position error is computed as:

\[\begin{split}\\zeta_p = 100 \\times \\sqrt{(x_{co} - x_{cr})^2 + (y_{co} - y_{cr})^2}\end{split}\]

where \((x_{co}, y_{co})\) and \((x_{cr}, y_{cr})\) are the centroids of the original and reconstructed objects, respectively.

The algorithm: 1. Identifies object regions using thresholding 2. Computes weighted centroids of the objects 3. Calculates Euclidean distance between centroids 4. Normalizes by domain size and converts to percentage

If no object is detected in the reconstruction, returns 100% error.

Examples

>>> # Create original contrast with centered object
>>> chi_true = np.zeros((64, 64), dtype=complex)
>>> chi_true[28:36, 28:36] = 2.0 + 0.5j  # Centered object
>>>
>>> # Create reconstructed contrast with shifted object
>>> chi_recon = np.zeros((64, 64), dtype=complex)
>>> chi_recon[30:38, 30:38] = 1.8 + 0.4j  # Slightly shifted
>>>
>>> # Compute position error
>>> pos_error = compute_zeta_p(chi_true, chi_recon)
>>> print(f"Position error: {pos_error:.2f}%")
eispy2d.data.result.compute_zeta_rn(es_o, es_a)#

Compute the residual norm error between measured and computed scattered fields.

Calculates the L2 norm of the difference between the original (measured) and approximated (computed) scattered field data. This metric quantifies the data fidelity of the reconstruction.

Parameters:
  • es_o (numpy.ndarray) – Original (measured) scattered field matrix. Shape: (N_measurements, N_sources). Units: [V/m].

  • es_a (numpy.ndarray) – Approximated (computed) scattered field matrix. Shape: (N_measurements, N_sources). Units: [V/m].

Returns:

Residual norm error. Units: [V/m].

Return type:

float

Notes

The error is computed using the L2 norm with trapezoidal integration:

\[\begin{split}\\zeta_{RN} = \\sqrt{\\iint_S |E^s - E^{s,\\delta}|^2 d\\theta d\\phi}\end{split}\]

where \(E^s\) is the measured scattered field, \(E^{s,\\delta}\) is the computed scattered field, and the integration is over the measurement surface with angles θ and φ.

Examples

>>> measured_field = np.random.complex128((64, 8))
>>> computed_field = measured_field + 0.1 * np.random.complex128((64, 8))
>>> error = compute_zeta_rn(measured_field, computed_field)
>>> print(f"Residual norm error: {error:.3e} V/m")
eispy2d.data.result.compute_zeta_rpad(es_o, es_r)#

Compute the residual percentage average deviation.

Calculates the percentage average deviation between original (measured) and reconstructed (computed) scattered field data. This metric provides a relative measure of reconstruction accuracy normalized by the data magnitude.

Parameters:
  • es_o (numpy.ndarray) – Original (measured) scattered field matrix. Shape: (N_measurements, N_sources). Units: [V/m].

  • es_r (numpy.ndarray) – Reconstructed (computed) scattered field matrix. Shape: (N_measurements, N_sources). Units: [V/m].

Returns:

Residual percentage average deviation. Units: [%/sample].

Return type:

float

Notes

The error is computed as:

\[\begin{split}\\zeta_{RPAD} = \\frac{100}{N} \\sum_{i=1}^{N} \\frac{|y_i - y_i^\\delta|}{|y_i|}\end{split}\]

where \(y_i\) represents the real and imaginary parts of the measured scattered field, \(y_i^\\delta\) represents the computed values, and \(N\) is the total number of real-valued samples.

Examples

>>> measured_field = np.random.complex128((64, 8)) + 1j
>>> computed_field = measured_field * 0.95  # 5% error
>>> error = compute_zeta_rpad(measured_field, computed_field)
>>> print(f"Residual PAD error: {error:.2f}%/sample")
eispy2d.data.result.compute_zeta_s(chi_o, chi_r)#

Compute the shape error between original and reconstructed objects.

Calculates the percentage shape error by comparing the areas of the original and reconstructed scattering objects. This metric quantifies how accurately the object shape and size are recovered in the reconstruction.

Parameters:
  • chi_o (numpy.ndarray) – Original (ground truth) contrast map. Shape: (N_x, N_y). Complex-valued, dimensionless.

  • chi_r (numpy.ndarray) – Reconstructed contrast map. Shape: (N_x, N_y). Complex-valued, dimensionless.

Returns:

Shape error as a percentage of the original object area. Units: [%].

Return type:

float

Notes

The shape error is computed as:

\[\begin{split}\\zeta_s = \\frac{100 \\times |A_{diff}|}{A_{original}}\end{split}\]

where \(A_{diff}\) is the area of the symmetric difference between the original and reconstructed object regions, and \(A_{original}\) is the area of the original object.

The algorithm: 1. Identifies object regions using thresholding 2. Finds contours of both objects 3. Normalizes spatial scales and centers objects 4. Computes symmetric difference using XOR operation 5. Calculates area ratio as percentage

If no object is detected in the reconstruction, returns 100% error.

Examples

>>> # Create original contrast with square object
>>> chi_true = np.zeros((64, 64), dtype=complex)
>>> chi_true[20:40, 20:40] = 2.0 + 0.5j  # Square object
>>>
>>> # Create reconstructed contrast with similar but different shape
>>> chi_recon = np.zeros((64, 64), dtype=complex)
>>> chi_recon[22:38, 22:38] = 1.8 + 0.4j  # Smaller square
>>>
>>> # Compute shape error
>>> shape_error = compute_zeta_s(chi_true, chi_recon)
>>> print(f"Shape error: {shape_error:.2f}%")
eispy2d.data.result.compute_zeta_sad(sigma_o, sigma_r)#

Compute the average deviation of conductivity maps.

Calculates the pixel-wise average deviation between the original and reconstructed conductivity maps. This metric provides a global measure of conductivity reconstruction accuracy.

Parameters:
  • sigma_o (numpy.ndarray) – Original (ground truth) conductivity map. Shape: (N_x, N_y). Units: [S/m].

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

Returns:

Average deviation of conductivity values. Units: [S/m].

Return type:

float

Notes

The error is computed as:

\[\begin{split}\\zeta_{\\sigma AD} = \\frac{1}{N_p} \\sum_{i=1}^{N_p} |\\sigma_{o,i} - \\sigma_{r,i}|\end{split}\]

where \(\\sigma_{o,i}\) and \(\\sigma_{r,i}\) are the original and reconstructed conductivity values at pixel \(i\), and \(N_p\) is the total number of pixels.

This metric provides an absolute measure of conductivity reconstruction error that is useful for comparing different reconstruction methods.

Examples

>>> # Create sample conductivity maps
>>> sigma_true = np.zeros((64, 64))  # Background: σ = 0 S/m
>>> sigma_true[20:40, 20:40] = 0.1  # Object: σ = 0.1 S/m
>>>
>>> # Simulated reconstruction with errors
>>> sigma_recon = sigma_true + 0.01 * np.random.randn(64, 64)
>>>
>>> # Compute average deviation
>>> avg_dev = compute_zeta_sad(sigma_true, sigma_recon)
>>> print(f"Conductivity average deviation: {avg_dev:.4f} S/m")
eispy2d.data.result.compute_zeta_sbe(sigma_o, sigma_r, sigma_b)#

Compute the background conductivity estimation error.

Calculates the estimation error for background regions in the conductivity reconstruction. This metric quantifies false-positive-like errors where the background is incorrectly reconstructed as having different conductivity values.

Parameters:
  • sigma_o (numpy.ndarray) – Original (ground truth) conductivity map. Shape: (N_x, N_y). Units: [S/m].

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

  • sigma_b (float) – Background conductivity value used to identify background regions. Units: [S/m].

Returns:

Background conductivity estimation error. Units: [S/m].

Return type:

float

Notes

The error is computed only for pixels where the original conductivity equals the background value:

\[\begin{split}\\zeta_{\\sigma BE} = \\frac{1}{N_{bg}} \\sum_{i \\in \\text{background}} |\\sigma_{o,i} - \\sigma_{r,i}|\end{split}\]

where \(N_{bg}\) is the number of background pixels and the sum is over pixels where \(\\sigma_{o,i} = \\sigma_b\).

This metric is analogous to the false-positive rate in classification, measuring how well the background conductivity is preserved in the reconstruction.

Examples

>>> # Create ground truth with background and object
>>> sigma_true = np.zeros((64, 64))  # Background: σ = 0 S/m
>>> sigma_true[20:40, 20:40] = 0.1  # Object: σ = 0.1 S/m
>>>
>>> # Simulated reconstruction with background errors
>>> sigma_recon = sigma_true.copy()
>>> sigma_recon[0:20, 0:20] = 0.01  # Background error
>>>
>>> # Compute background error
>>> bg_error = compute_zeta_sbe(sigma_true, sigma_recon, 0.0)
>>> print(f"Background conductivity error: {bg_error:.3f} S/m")
eispy2d.data.result.compute_zeta_soe(sigma_o, sigma_r, sigma_b)#

Compute the object conductivity estimation error.

Calculates the estimation error for object regions in the conductivity reconstruction. This metric quantifies false-negative-like errors where object regions are incorrectly reconstructed with wrong conductivity values.

Parameters:
  • sigma_o (numpy.ndarray) – Original (ground truth) conductivity map. Shape: (N_x, N_y). Units: [S/m].

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

  • sigma_b (float) – Background conductivity value used to identify object regions (pixels with values different from background). Units: [S/m].

Returns:

Object conductivity estimation error. Units: [S/m].

Return type:

float

Notes

The error is computed only for pixels where the original conductivity differs from the background value:

\[\begin{split}\\zeta_{\\sigma OE} = \\frac{1}{N_{obj}} \\sum_{i \\in \\text{object}} |\\sigma_{o,i} - \\sigma_{r,i}|\end{split}\]

where \(N_{obj}\) is the number of object pixels and the sum is over pixels where \(\\sigma_{o,i} \\neq \\sigma_b\).

This metric is analogous to the false-negative rate in classification, measuring how accurately the object conductivity is reconstructed.

Examples

>>> # Create ground truth with background and object
>>> sigma_true = np.zeros((64, 64))  # Background: σ = 0 S/m
>>> sigma_true[20:40, 20:40] = 0.1  # Object: σ = 0.1 S/m
>>>
>>> # Simulated reconstruction with object errors
>>> sigma_recon = sigma_true.copy()
>>> sigma_recon[20:40, 20:40] = 0.08  # Object reconstruction error
>>>
>>> # Compute object error
>>> obj_error = compute_zeta_soe(sigma_true, sigma_recon, 0.0)
>>> print(f"Object conductivity error: {obj_error:.3f} S/m")
eispy2d.data.result.compute_zeta_tfmpad(et_o, et_r)#

Compute the total field magnitude percentage average deviation.

Calculates the percentage average deviation between the magnitudes of the original and reconstructed total electric field distributions. This metric quantifies how accurately the field magnitude is recovered throughout the investigation domain.

Parameters:
  • et_o (numpy.ndarray) – Original (ground truth) total electric field. Shape: (N_pixels, N_sources). Units: [V/m].

  • et_r (numpy.ndarray) – Reconstructed total electric field. Shape: (N_pixels, N_sources). Units: [V/m].

Returns:

Total field magnitude percentage average deviation. Units: [%].

Return type:

float

Notes

The error is computed as:

\[\begin{split}\\zeta_{TF MAG PAD} = \\frac{100}{N} \\sum_{i=1}^{N} \\frac{||E_{t,o,i}| - |E_{t,r,i}||}{|E_{t,o,i}|}\end{split}\]

where \(|E_{t,o,i}|\) and \(|E_{t,r,i}|\) are the magnitudes of the original and reconstructed total field at pixel \(i\), and \(N\) is the total number of field samples.

This metric is particularly useful for evaluating the accuracy of field-based reconstruction methods where the total field distribution is of primary interest.

Examples

>>> # Create sample total field data
>>> et_true = np.random.complex128((1024, 8))  # 1024 pixels, 8 sources
>>> et_true *= np.exp(1j * np.random.uniform(0, 2*np.pi, et_true.shape))
>>>
>>> # Simulated reconstruction with magnitude errors
>>> et_recon = et_true * (1 + 0.05 * np.random.randn(*et_true.shape))
>>>
>>> # Compute magnitude error
>>> mag_error = compute_zeta_tfmpad(et_true, et_recon)
>>> print(f"Total field magnitude PAD: {mag_error:.2f}%")
eispy2d.data.result.compute_zeta_tfpad(et_o, et_r)#

Compute the total field phase average deviation.

Calculates the average deviation between the phases of the original and reconstructed total electric field distributions. This metric quantifies how accurately the field phase is recovered throughout the investigation domain.

Parameters:
  • et_o (numpy.ndarray) – Original (ground truth) total electric field. Shape: (N_pixels, N_sources). Units: [V/m].

  • et_r (numpy.ndarray) – Reconstructed total electric field. Shape: (N_pixels, N_sources). Units: [V/m].

Returns:

Total field phase average deviation. Units: [rad].

Return type:

float

Notes

The error is computed as:

\[\begin{split}\\zeta_{TF PHASE AD} = \\frac{1}{N} \\sum_{i=1}^{N} |\\arg(E_{t,o,i}) - \\arg(E_{t,r,i})|\end{split}\]

where \(\\arg(E_{t,o,i})\) and \(\\arg(E_{t,r,i})\) are the phases of the original and reconstructed total field at pixel \(i\), and \(N\) is the total number of field samples.

Phase information is crucial for many inverse scattering applications, particularly those involving interferometric or holographic techniques.

Examples

>>> # Create sample total field data
>>> et_true = np.random.complex128((1024, 8))  # 1024 pixels, 8 sources
>>> et_true *= np.exp(1j * np.random.uniform(0, 2*np.pi, et_true.shape))
>>>
>>> # Simulated reconstruction with phase errors
>>> phase_error = 0.1 * np.random.randn(*et_true.shape)
>>> et_recon = np.abs(et_true) * np.exp(1j * (np.angle(et_true) + phase_error))
>>>
>>> # Compute phase error
>>> phase_dev = compute_zeta_tfpad(et_true, et_recon)
>>> print(f"Total field phase AD: {phase_dev:.3f} rad")
eispy2d.data.result.compute_zeta_tv(chi, x, y)#

Compute the total variation of a contrast map.

Calculates the total variation (TV) regularization functional commonly used in electromagnetic inverse scattering to promote smooth solutions and suppress artifacts. The TV functional measures the variation of the contrast function across the spatial domain.

Parameters:
  • chi (numpy.ndarray) – Complex-valued contrast map representing the scattering properties. Shape: (N_x, N_y). Units: [dimensionless].

  • x (numpy.ndarray) – Meshgrid array of x-coordinates corresponding to the contrast map. Shape: (N_x, N_y). Units: [m].

  • y (numpy.ndarray) – Meshgrid array of y-coordinates corresponding to the contrast map. Shape: (N_x, N_y). Units: [m].

Returns:

Total variation value. Units: [dimensionless].

Return type:

float

Notes

The total variation is computed using a modified formulation:

\[\begin{split}TV = \\int \\int \\frac{|\\nabla \\chi|^2}{|\\nabla \\chi|^2 + 1} \\, dx \\, dy\end{split}\]

where \(\\nabla \\chi\) is the spatial gradient of the contrast function. This formulation provides better numerical stability compared to the standard TV functional.

References

Examples

>>> # Create a simple contrast map
>>> nx, ny = 64, 64
>>> x = np.linspace(-0.1, 0.1, nx)
>>> y = np.linspace(-0.1, 0.1, ny)
>>> X, Y = np.meshgrid(x, y)
>>>
>>> # Piecewise constant contrast (low TV)
>>> chi_smooth = np.ones_like(X, dtype=complex)
>>> chi_smooth[20:40, 20:40] = 2.0 + 0.1j
>>> tv_smooth = compute_zeta_tv(chi_smooth, X, Y)
>>>
>>> # Noisy contrast (high TV)
>>> chi_noisy = chi_smooth + 0.1 * np.random.randn(*X.shape)
>>> tv_noisy = compute_zeta_tv(chi_noisy, X, Y)
>>>
>>> print(f"Smooth TV: {tv_smooth:.2f}, Noisy TV: {tv_noisy:.2f}")
eispy2d.data.result.get_figure(nsubplots=1, number_lines=1)#

Create a matplotlib figure with optimized layout and sizing.

… (restante já está correto)

Returns:

  • fig (matplotlib.figure.Figure) – The created figure object.

  • axes (numpy.ndarray) – Flattened array of axes objects (1D). For nsubplots=1, returns array with one element.

  • legend_fontsize (float) – Recommended font size for legends.

eispy2d.data.result.get_legend_fontsize(number_lines, nrows)#

Calculate optimal legend font size based on plot layout.

Determines the appropriate font size for legends based on the number of legend entries and the number of subplot rows. This helps maintain readability as plot complexity increases.

Parameters:
  • number_lines (int) – Number of lines/entries expected in the legend.

  • nrows (int) – Number of rows in the subplot grid.

Returns:

Recommended font size for legends. Returns None if the standard matplotlib font size is appropriate (no adjustment needed).

Return type:

float or None

Notes

The function uses empirically determined scaling factors to reduce font size when there are many legend entries or many subplot rows. Different scaling factors are used for different numbers of rows:

  • For nrows ≤ 2: More gentle scaling (factor 0.55)

  • For nrows > 2: More aggressive scaling (factor 0.65)

The maximum recommended number of lines decreases with more rows: - 1 row: up to 15 lines - 2 rows: up to 13 lines - 3 rows: up to 8 lines - 4 rows: up to 5 lines - etc.

Examples

>>> # For single row with many lines
>>> fontsize = get_legend_fontsize(number_lines=20, nrows=1)
>>> print(f"Recommended font size: {fontsize}")
>>>
>>> # For multiple rows with few lines
>>> fontsize = get_legend_fontsize(number_lines=3, nrows=4)
>>> print(f"Recommended font size: {fontsize}")  # None (use default)
eispy2d.data.result.indicator_label(indicator)#

Get the display label for an error indicator.

Retrieves the human-readable label associated with a specific error indicator. These labels are used for plot axes, legends, and other display purposes.

Parameters:

indicator (str) – Name of the error indicator. Must be a valid indicator name as defined in INDICATOR_SET.

Returns:

Human-readable label for the indicator, typically including units and mathematical notation where appropriate.

Return type:

str

Raises:

error.WrongValueInput – If the indicator name is not valid.

Examples

>>> # Get label for residual norm error
>>> label = indicator_label('zeta_rn')
>>> print(label)  # "Residual Norm Error [V/m]"
>>>
>>> # Get label for permittivity error
>>> label = indicator_label('zeta_epad')
>>> print(label)  # "Permittivity PAD Error [%]"
>>>
>>> # Error for invalid indicator
>>> try:
...     label = indicator_label('invalid_indicator')
... except error.WrongValueInput as e:
...     print(f"Error: {e}")

Notes

The labels are stored in the LABELS dictionary and are designed to be suitable for use in plots, tables, and other display contexts. They typically include units and use mathematical notation where appropriate.

eispy2d.data.testset module#

class eispy2d.data.testset.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#
eispy2d.data.testset.contrast_density(contrast_map)#

Compute the contrast density of a map.

The contrast density is defined as the mean of the absolute value per pixel.

Parameters:

contrast_map (numpy.ndarray) – 2D array representing the contrast map.

Returns:

Mean absolute contrast value per pixel.

Return type:

float

eispy2d.data.testset.create_input_image(name, configuration, resolution, map_pattern, contrast, density=None, noise=None, object_size=None, indicators=None, contrast_mode='maximum', object_size_mode='maximum', min_size_prop=40.0, density_mode='single', rotate=True, random_position=True)#

Create a single input case.

Parameters:
  • name (str) – The name of the case.

  • configuration (Configuration) – Configuration object.

  • resolution (2-tuple of int) – Y-X resolution (number of pixels) of the scenario image.

  • map_pattern ({'random_polygons', 'regular_polygons', 'surfaces'}) – Pattern of dielectric information on the image.

  • contrast (float) – Reference value for contrast.

  • density (int or float, optional) – Number of objects or minimum contrast density.

  • noise (float, optional) – Noise level added into the scattered field.

  • object_size (float, optional) – Reference object size in wavelengths.

  • indicators (list of str or str, optional) – Indicators to compute.

  • contrast_mode (str, default: 'maximum') – ‘fixed’ or ‘maximum’.

  • object_size_mode (str, default: 'maximum') – ‘fixed’ or ‘maximum’.

  • min_size_prop (float, default: 40.) – Minimum size proportion (0-100%).

  • density_mode (str, default: 'single') – ‘single’, ‘fixed’, ‘max_number’, or ‘min_density’.

  • rotate (bool, default: True) – Allow random rotation.

  • random_position (bool, default: True) – Allow random position.

Returns:

The generated input data object.

Return type:

InputData

Module contents#

Data module for eispy2d.

Contains data container classes: - InputData: Problem input data and configuration - Result: Reconstruction results and error metrics - TestSet: Test generation for benchmarking

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