Visualization Module

Contents

Visualization Module#

The visualization module contains 3D visualization and plotting components.

3D electromagnetic field visualization system for ferrite shield design optimization.

This module provides interactive 3D visualization of electromagnetic field predictions using machine learning models. It handles visualization of ferrite shields, coils, prediction points, and real-time updates based on geometric parameters.

Key components: - VisualizationConstants: Configuration constants for the visualization system - VisualizationUI: User interface controls and interactions - Visualize: Main visualization class with ML-based field predictions

The system uses Polyscope for 3D rendering and supports real-time updates of: - Ferrite shield geometry and positioning - Electromagnetic field magnitude and vector visualization - Efficiency calculations and predictions - Interactive parameter adjustment through UI controls

class EMFieldML.Visualize.Visualize.VisualizationConstants#

Bases: object

Constants used throughout the visualization system.

POINT_SIZE_MIN = 0.0#
POINT_SIZE_MAX = 10.0#
DEFAULT_POINT_SIZE = 2.0#
POSITION_MIN = 0.0#
POSITION_MAX = 24.0#
H1_MIN = 0.5#
H1_MAX = 4.0#
H2_MIN = 0.0#
H2_MAX = 4.0#
H3_MIN = 0.0#
H3_MAX = 4.0#
R1_MIN = 12.0#
R1_MAX = 24.0#
R2_MIN = 12.1#
R3_MIN = 12.0#
R4_MIN = 1.0#
R4_MAX = 7.0#
R2_R3_MIN_GAP = 0.1#
MESH_COLOR_MIN = 108.0#
MESH_COLOR_MAX = 140.0#
DEFAULT_TRANSPARENCY = 0.408#
DEFAULT_COLORMAP = 'rainbow'#
SMALL_RADIUS = 0.0001#
MEDIUM_RADIUS = 0.0003#
STL_Z_OFFSET = 0.0001#
COLOR_BLACK = (0, 0, 0)#
COLOR_GREEN = (0.0, 0.47843137254901963, 0.28627450980392155)#
COLOR_LIGHT_BLUE = (0.615686274509804, 0.8, 0.8784313725490196)#
COLOR_DARK_BLUE = (0.34509803921568627, 0.3764705882352941, 0.5607843137254902)#
COLOR_ORANGE = (0.918, 0.545, 0.075)#
class EMFieldML.Visualize.Visualize.VisualizationUI(visualizer)#

Bases: object

Handles the user interface elements for the visualization.

__init__(visualizer) None#

Initialize the UI handler with reference to the main visualizer.

Parameters:

visualizer – Reference to the main Visualize instance for accessing data and parameters.

render_controls() dict[str, bool]#

Render all UI controls and return changed parameters.

class EMFieldML.Visualize.Visualize.Visualize(number: int)#

Bases: object

Interactive 3D visualization system for electromagnetic field prediction and ferrite shield optimization.

This class provides a complete visualization pipeline that combines: - 3D geometric modeling of ferrite shields and coils - Machine learning-based electromagnetic field predictions - Real-time interactive parameter adjustment - Performance monitoring and measurement capabilities

The system uses Gaussian Process models to predict electromagnetic field magnitude, direction (theta, phi), and power transfer efficiency based on shield geometry and positioning parameters.

Key features: - Interactive 3D visualization using Polyscope - Real-time updates when geometry parameters change - Linear blend skinning for smooth deformation visualization - Color-mapped field magnitude and vector visualization - Performance timing and measurement tools

Parameters:

number – Shield configuration number to load from the dataset

number#

Shield configuration identifier

ui#

User interface handler instance

point_size#

Size of rendered points in 3D view

y_move, z_move

RX coil displacement parameters

efficiency#

Predicted power transfer efficiency

values#

Predicted electromagnetic field magnitudes

magnetic_vector#

Predicted field direction vectors

__init__(number: int)#

Initialize the visualization system.

visualize(measure_time_mode: bool = False, timeout_seconds: int = 0) None#

Launch the interactive 3D visualization window.

Initialize Polyscope 3D viewer and display the electromagnetic field visualization with interactive controls. The visualization includes ferrite shields, coils, prediction points, and real-time field magnitude/vector displays.

The right window allows you to edit the coil’s position and shape while viewing the magnetic field strength and power transfer efficiency in real time. For more detailed instructions, please refer to the Readme.

Parameters:
  • measure_time_mode – If True, collect and save timing measurements for performance analysis to time_Level2.txt file.

  • timeout_seconds – If > 0, automatically close window after specified seconds. If 0, window stays open until manually closed.

Note

This function corresponds to Figure 1a and Table 1 in the paper.

callback()#

Handle all user interactions in the main UI callback function.

static make_modeling_visualization(input_path: Path, y_move: float, z_move: float) tuple#

Generate 3D geometric data structures for visualization of ferrite shield system.

Create hierarchical grid structures for TX/RX coils and prediction points using multi-level refinement. Generates points, edges, planes, and tetrahedral elements for 3D visualization and electromagnetic field prediction.

When expressing a shape, a grid structure starts with a coarse grid and is refined in stages. In addition, the prediction points are created to match the shape’s grid, and these too are refined to align with the points on the surface. While a finer grid allows for a better representation of the shape, it increases computation time, which can compromise real-time prediction.

Parameters:
  • input_path – Path to input data file containing initial grid configuration

  • y_move – Y-axis displacement of RX coil relative to TX coil (cm)

  • z_move – Z-axis displacement of RX coil relative to TX coil (cm)

Returns:

Contains 8 elements:
  • points_for_3D_TX: TX coil point coordinates

  • lines_for_3D_TX: TX coil edge connectivity

  • planes_for_3D_TX: TX coil surface triangulation

  • points_for_3D_RX: RX coil point coordinates (displaced)

  • points_for_3D_prediction_move: Prediction points after linear blend skinning

  • points_for_3D_prediction: Original prediction point positions

  • out_points: Grid output points with mode information

  • boxes_for_3D_prediction: Tetrahedral boxes for color mapping

Return type:

tuple

Note

Uses 3-level hierarchical refinement (level1 -> level2 -> level3) for improved geometric accuracy and prediction point density. This function corresponds to Figure 2, Figure 3, Figure 4, Supplementary Figure 2, Supplementary Figure 5, Supplementary Figure 6, and Supplementary Figure 7 in the paper.

static linearblendskining(tx_points: numpy.array, rx_points: numpy.array, prediction_points: numpy.array) numpy.array#

Apply linear blend skinning deformation to prediction points based on coil movement.

Deform prediction points based on the transformation between TX and RX coil positions using linear blend skinning algorithm. Each prediction point is weighted by its distance to ferrite shield control points.

Parameters:
  • tx_points – Control points on TX (transmitter) ferrite shield

  • rx_points – Control points on RX (receiver) ferrite shield (displaced)

  • prediction_points – Original prediction point positions to be deformed

Returns:

Deformed prediction points after linear blend skinning transformation

Return type:

np.array

Note

Uses distance-based weighting with configurable power parameter (LBS_w_move). This function corresponds to Figure 2 and Figure 3 in the paper.

static calculate_weight(tx_points, prediction_points)#

Calculate linear blend skinning weights for prediction points based on distance to control points.

Compute normalized weights for each prediction point relative to TX and RX ferrite shield control points. Weights are inversely proportional to distance raised to a configurable power (LBS_w_move).

Parameters:
  • tx_points – Control points on TX ferrite shield (n_initial_points x 3)

  • prediction_points – Points to calculate weights for (N x 3)

Returns:

(weight, rx_ferrite_point) where:
  • weight: Normalized weights array (N x 2*n_initial_points)

  • rx_ferrite_point: Original RX control point positions before displacement

Return type:

tuple

Note

Uses config.LBS_w_move for distance weighting power and config.n_initial_points for the number of control points (typically 72 points per shield). This function corresponds to Figure 3 in the paper.

static make_tetra(boxes)#

Convert hexahedral boxes to tetrahedral elements for volume mesh visualization.

Decompose each hexahedral box into 6 tetrahedral elements for use in Polyscope volume mesh visualization. Each box is split using a consistent pattern to maintain mesh continuity.

Using this, the visualization tool can visualize the magnetic field distribution on a plane.

Parameters:

boxes – List of box objects with node indices defining hexahedral elements

Returns:

Tetrahedral connectivity array (N*6 x 4) where each row contains

4 node indices defining a tetrahedron

Return type:

np.array

Note

tetrahedralization pattern used for consistency verification.

static convert_to_db(values)#

Convert magnetic field values to decibel scale (dBµA/m).

Transform mu_star values to decibel microamperes per meter for visualization and analysis purposes.

Parameters:

values – Magnetic field values in original units

Returns:

Converted values in dBµA/m scale

Note

of mu_star and the conversion formula derivation.

measure_finish_time(start)#

Use _measure_finish_time instead (deprecated method).

update_window()#

Update the 3D visualization window with current prediction values and color mapping.

Refresh the Polyscope visualization by updating prediction point positions and scalar field values. Creates new volume mesh with current dB values and applies color mapping within specified min/max bounds.

Note

and add error handling for visualization updates.

make_prediction_structure()#

Initialize 3D geometric structures for electromagnetic field prediction.

Create the complete 3D modeling framework including TX/RX coil geometries, prediction point grids, and linear blend skinning weights. Loads data from the circle_move_x dataset and sets up all geometric relationships needed for field prediction and visualization.

Sets up:
  • TX/RX coil point coordinates, edges, and planes

  • Prediction point grid with linear blend skinning weights

  • Tetrahedral boxes for volume mesh color mapping

Note

focused methods for better maintainability.

make_ferrite_shield()#

Initialize ferrite shield geometric parameters and constraints.

Set up all ferrite shield dimensional parameters (h1, h2, h3, r1, r2, r3, r4) and their allowable ranges for optimization. Uses the Deformation module to prepare ferrite shield movement and deformation capabilities.

Initializes:
  • Shield height parameters (h1, h2, h3) and their ranges

  • Shield radius parameters (r1, r2, r3, r4) and constraints

  • Parameter lists for UI controls and optimization bounds

Note

meaning of each parameter (h1=inner height, r1=outer radius, etc.). This function corresponds to Supplementary Figure 1 in the paper.

prediction_prepare()#

Prepare ML models and initial predictions with comprehensive error handling.

visualization_prepare()#

Prepare all Polyscope visualization objects with error handling.

update_values_for_move()#

Update prediction values when position changes.

update_values_for_shape(changed_h1: bool, changed_h2: bool, changed_h3: bool, changed_r1: bool, changed_r2: bool, changed_r3: bool, changed_r4: bool)#

Update ferrite shield geometry based on changed shape parameters.

Modify the 3D geometry of TX and RX ferrite shields when dimensional parameters change. Updates both point positions and mesh geometry, then triggers prediction recalculation and visualization refresh.

Parameters:
  • changed_h1 – Whether h1 (height parameter 1) has changed

  • changed_h2 – Whether h2 (height parameter 2) has changed

  • changed_h3 – Whether h3 (height parameter 3) has changed

  • changed_r1 – Whether r1 (radius parameter 1) has changed

  • changed_r2 – Whether r2 (radius parameter 2) has changed

  • changed_r3 – Whether r3 (radius parameter 3) has changed

  • changed_r4 – Whether r4 (radius parameter 4) has changed

Note

multiple boolean flags for better maintainability.

get_values()#

Get current electromagnetic field magnitude prediction values.

Returns:

Current predicted field magnitude values at all prediction points

get_efficiency()#

Get current power transfer efficiency prediction.

Returns:

Current predicted efficiency value with uncertainty bounds

get_prediction_points()#

Get current prediction point coordinates after deformation.

Returns:

3D coordinates of prediction points after linear blend skinning deformation

Note

for clarity about the coordinate system.

test_setup() bool#

Test visualization setup for pytest.

test_predictions() bool#

Test prediction pipeline for pytest.

Gaussian Process prediction utilities for electromagnetic field analysis.

This module provides functions for Gaussian Process regression and prediction in electromagnetic field modeling and visualization.

EMFieldML.Visualize.Prediction.rbf_kernel(X1, X2, lengthscale, scale)#

Calculate RBF kernel matrix for Gaussian Process regression.

EMFieldML.Visualize.Prediction.mean_function(mean_constant, X)#

Calculate mean function for Gaussian Process regression.

EMFieldML.Visualize.Prediction.mean_function_one(mean_constant, X)#

Calculate mean function for single point prediction.

EMFieldML.Visualize.Prediction.calculate_mu_star(X_test, k_star, K_inv_Y_train, mean_constant)#

Calculate mu_star for Gaussian Process prediction.

EMFieldML.Visualize.Prediction.calculate_mu_star_one(k_star, K_inv_Y_train, mean_constant)#

Calculate mu_star for single point prediction.

EMFieldML.Visualize.Prediction.make_y_data(Y_train, input_path, preprocessing_value)#

Load and preprocess Y training data from CSV file.

Parameters:
  • Y_train – Training data array (unused parameter -

  • input_path – Path to CSV file containing target values

  • preprocessing_value – Value used for power transformation (1/preprocessing_value)

Returns:

Preprocessed training data with shape (n_samples, 1)

Return type:

numpy.ndarray

Note

Please verify if this is the correct preprocessing approach for the target values.

EMFieldML.Visualize.Prediction.calculate_K_inv_Y_train(Y_train, K_inv, mean_constant, x_train_data)#

Calculate K_inv_Y_train for Gaussian Process regression.

EMFieldML.Visualize.Prediction.prediction_prepare(prediction_point_number: int = EMFieldML.config.config.n_prediction_points_level2)#

Prepare data for Gaussian Process prediction.

EMFieldML.Visualize.Prediction.prediction_prepare_efficiency()#

Prepare data for efficiency prediction.

EMFieldML.Visualize.Prediction.mu_star(X_train, X_test, K_inv_Y_train, lengthscale, scale, mean_constant)#

Calculate mu_star for Gaussian Process prediction.

EMFieldML.Visualize.Prediction.mu_star_one(X_train, X_test, K_inv_Y_train, lengthscale, scale, mean_constant, preprocessing_value)#

Calculate mu_star for single point prediction.

EMFieldML.Visualize.Prediction.mu_star_efficiency(X_train, X_test, K_inv_Y_train, lengthscale, scale, K_inv, mean_constant, noise)#

Calculate mu_star for efficiency prediction.

EMFieldML.Visualize.Prediction.vector(X_train, X_test, K_inv_Y_train_theta, K_inv_Y_train_phi, lengthscale, scale, mean_constant_theta, mean_constant_phi)#

Calculate vector field for electromagnetic field prediction.

EMFieldML.Visualize.Prediction.vector_one(phi, theta)#

Convert spherical coordinates to Cartesian coordinates for single values.

Parameters:
  • phi – Azimuthal angle in radians

  • theta – Polar angle in radians

Returns:

Cartesian coordinates [x, y, z]

Return type:

numpy.ndarray

EMFieldML.Visualize.Prediction.calculate_error_no_devide(a, b)#

Calculate simple difference between two values.

Parameters:
  • a – First value

  • b – Second value

Returns:

Difference (a - b)

Return type:

float

EMFieldML.Visualize.Prediction.calculate_error(a, b)#

Calculate relative error between two values.

Parameters:
  • a – Predicted value

  • b – True value

Returns:

Relative error |a - b| / |b|

Return type:

float

EMFieldML.Visualize.Prediction.calculate_error_square(a, b)#

Calculate squared error between two values.

Parameters:
  • a – Predicted value

  • b – True value

Returns:

Squared error (a - b)²

Return type:

float

EMFieldML.Visualize.Prediction.pre_magneticfield(model_path: Path, input_path_train_list: Path, input_path_test_list: Path, input_path_y_train_data: str, input_path_y_test_data: str, output_path: Path, func_calculate_error: Callable[[float, float], float], n_point: int = None, input_path_circle: str = None, input_path_circle_test: str = None, preprocessing_value: float = 1.0, noise_scale_change: bool = False)#

Predict magnetic field using Gaussian Process regression.

EMFieldML.Visualize.Prediction.pre_vector(model_path: Path, input_path_train_list: Path, input_path_test_list: Path, input_path_y_train_data_phi: str, input_path_y_train_data_theta: str, input_path_y_test_data_phi: str, input_path_y_test_data_theta: str, output_path: Path, n_point: int = None, input_path_circle: str = None, input_path_circle_test: str = None, preprocessing_value: float = 1.0, noise_scale_change: bool = False)#

Predict vector field using Gaussian Process regression.

Coil deformation utilities for electromagnetic field visualization.

This module provides functions for deforming coils during electromagnetic field analysis and visualization.

EMFieldML.Visualize.Deformation.change_X_test(X_test, TX_point)#

Update X_test data with TX_point coordinates.

EMFieldML.Visualize.Deformation.change_h1(TX_point, RX_point, z_move, h1, h1_low, h1_middle)#

Modify height parameter h1 for coil deformation.

EMFieldML.Visualize.Deformation.change_h2(TX_point, RX_point, z_move, h2, h2_list)#

Modify height parameter h2 for coil deformation.

EMFieldML.Visualize.Deformation.change_h3(TX_point, RX_point, z_move, h3, h3_list)#

Modify height parameter h3 for coil deformation.

EMFieldML.Visualize.Deformation.change_r1(TX_point, RX_point, y_move, r1, r1_list)#

Modify radius parameter r1 for coil deformation.

EMFieldML.Visualize.Deformation.change_r2(TX_point, RX_point, y_move, r2, r3, r2_list, r2_r3_list)#

Modify radius parameter r2 for coil deformation.

EMFieldML.Visualize.Deformation.change_r3(TX_point, RX_point, y_move, r2, r3, r3_list, r2_r3_list)#

Modify radius parameter r3 for coil deformation.

EMFieldML.Visualize.Deformation.change_r4(TX_point, RX_point, y_move, r4, r4_list)#

Modify radius parameter r4 for coil deformation.

EMFieldML.Visualize.Deformation.set_points(TX_point, TX_edge, TX_plane, RX_point, RX_edge, RX_plane, points_for_3D_TX, points_for_3D_RX)#

Set point coordinates for coil deformation.

EMFieldML.Visualize.Deformation.prepare_ferrite_move(points_for_3D_TX)#

Prepare ferrite deformation parameters.

EMFieldML.Visualize.Deformation.move_out_points(out_points, points_for_3D_TX, y_move, z_move, points_for_3D_prediction_move, linearblend_skining_weight, points_for_3D_RX_original)#

Move out points for coil deformation.

EMFieldML.Visualize.Deformation.calculate_change(next_point)#

Calculate change in point positions for coil deformation.

First-level grid generation for electromagnetic field visualization.

This module provides functionality to create the initial grid structure for electromagnetic field analysis and visualization.

class EMFieldML.Visualize.make_first_grid.Point_outside(point)#

Bases: object

Information for outside prediction points.

This class represents prediction points outside the ferrite shield.

xyz#

Point coordinates

Type:

ndarray(3)

index#

Index of the corresponding point on the ferrite shield surface

Type:

int

mode#

Point type: 0=prediction, 1=TX, 2=RX

Type:

int

default_point#

Original coordinates before movement (used for weight calculation when ferrite shape changes)

Type:

ndarray(3)

weight#

Weights for linear blend skinning with ferrite shield points

Type:

ndarray(n)

parent#

Index of connected points (original points)

Type:

ndarray(3)

edges#

Edge indices extending from this point (for easier search)

Type:

list

planes#

Plane indices this point belongs to (for easier search)

Type:

list

__init__(point)#

Initialize point with coordinates.

calculate_weight(point)#

Calculate weight for linear blend skinning.

calculate_nextpoint(changes)#

Calculate next point position with changes.

class EMFieldML.Visualize.make_first_grid.Edge(point1_index, point2_index)#

Bases: object

Edge class for visualization.

__init__(point1_index, point2_index)#

Initialize edge between two points.

class EMFieldML.Visualize.make_first_grid.Edge_outside(index1, index2)#

Bases: object

Edge class for outside points in visualization.

__init__(index1, index2)#

Initialize outside edge between two points.

class EMFieldML.Visualize.make_first_grid.Plane(edges, points_index)#

Bases: object

Plane class for visualization.

__init__(edges, points_index)#

Initialize plane with four points.

class EMFieldML.Visualize.make_first_grid.Plane_outside(index1, index2, index3, index4)#

Bases: object

Plane class for outside points in visualization.

__init__(index1, index2, index3, index4)#

Initialize outside plane with four points.

class EMFieldML.Visualize.make_first_grid.Box(points_index)#

Bases: object

Box class for visualization.

__init__(points_index)#

Initialize box with eight corner points.

EMFieldML.Visualize.make_first_grid.initial_point(i, data_list)#

Create initial point from data list.

Parameters:
  • i – Point index

  • data_list – List containing coordinate data

Returns:

Initialized point object

Return type:

Point

EMFieldML.Visualize.make_first_grid.initial_plane_point(i, data_list)#

Create initial plane point from data list.

Parameters:
  • i – Point index

  • data_list – List containing coordinate data

Returns:

Initialized point object

Return type:

Point

EMFieldML.Visualize.make_first_grid.make_first_point_edge_plane(input_path: Path)#

Create first-level grid points, edges, and planes.

EMFieldML.Visualize.make_first_grid.make_first_out_points(points, planes)#

Create first-level out points for grid generation.

Second-level grid generation for electromagnetic field visualization.

This module provides functionality to create refined grid structures for electromagnetic field analysis and visualization.

EMFieldML.Visualize.make_second_grid.set_boxes(box, out_points, edges_outside, planes_outside)#

Set box edges and planes based on predefined patterns.

the topology of a box. Please verify if these indices are correct for the current box structure and update if the topology has changed.

EMFieldML.Visualize.make_second_grid.make_second_grid(input_path: Path, points: list[Point], edges: list[Edge], planes: list[Plane]) tuple#

Create second-level grid for electromagnetic field visualization.

EMFieldML.Visualize.make_second_grid.make_second_out_points(out_points, boxes, edges_outside, planes_outside, points, edges, planes)#

Create second-level out points for grid generation.