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.
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.
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.
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.
>>> importresultasrst>>> importnumpyasnp>>>>>> # 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.
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].
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.
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
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.
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.
>>> 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')... excepterror.WrongValueInputase:... 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.
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.
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
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
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).
>>> # 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)
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.
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.
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.
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
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
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())
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
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 ‘–‘.
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.
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…
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.
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).
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.
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.
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:
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.
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")
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.
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}%")
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].
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 φ.
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].
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")
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.
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}%")
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.
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.
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.
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.
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.
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: [%].
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}%")
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].
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")
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:
where \(\\nabla \\chi\) is the spatial gradient of the contrast function.
This formulation provides better numerical stability compared to the
standard TV functional.
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)
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.
>>> # 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')... excepterror.WrongValueInputase:... 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.
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.
Contains data container classes:
- InputData: Problem input data and configuration
- Result: Reconstruction results and error metrics
- TestSet: Test generation for benchmarking
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.
>>> importresultasrst>>> importnumpyasnp>>>>>> # 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.
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].
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.
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
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.
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.
>>> 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')... excepterror.WrongValueInputase:... 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.
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.
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
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
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).
>>> # 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)
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.
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.
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.
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
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
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())
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.