EM simulation tools for electromagnetic field analysis, visualization, and benchmarking.
- Modular solvers for EM field calculations (Python and Fortran/COSY backends)
- Source modeling (dipoles, wires, loops/RingCoil, solenoids)
- Advanced plotting and visualization
- Demo scripts for validation and exploration
- Benchmarking utilities
- Extensible architecture for research and teaching
The platform is built on a high-performance hybrid stack:
- EM Solvers (Python): High-level physics logic (Biot-Savart, sources).
- Sandalwood Core: Differential Algebra engine for symbolic derivatives and Taylor maps.
- COSY Infinity (Fortran): HPC-grade compiled core for massive batch operations.
- Acceleration: OpenMP (Fortran) and Numba (Python) parallel kernels.
The v0.3.0 Release introduces a complete overhaul of the simulation pipeline:
-
Robust Memory Pooling: Integrated with
sandalwood>=0.1.2for$O(1)$ variable allocation. -
Performance Benchmarking: Added
benchmarks/stress_test_memory.pyto verify stability. - Dual-Mode Testing: Optimized test suite with dynamic regex patching for faster development cycles (~30s vs ~15m).
- Strict Pre-commit: Automated hook installation for consistent code quality and demo verification.
This project uses pyproject.toml to manage dependencies. For development, it is recommended to install the package in "editable" mode along with the development extras.
# Clone the repository
git clone https://github.com/shashi-manikonda/em-simulation-platform.git
cd em-simulation-platform
# (Recommended) Create a virtual environment
python3 -m venv .venv
source .venv/bin/activate
# Install the package in editable mode with all development dependencies
uv pip install -e .[dev,benchmark]- Install Git Hooks:
pre-commit installThe [dev] extra includes dependencies for running tests and building the documentation. The [benchmark] extra includes dependencies for running the benchmark scripts.
python scripts/run_all_demos.pyTo run a specific demo, you can execute the script directly. For notebooks, you can use a tool like jupytext to run it as a script:
jupytext --execute demos/em/01_validation_demo.ipynb- Standard (Fast):
pytestRuns unit tests only; excludes slow demos.
- Commit Check (Quick Demos):
pre-commit run --all-filesRuns the "Quick" version of demo verification.
- Full Verification (Slow):
export EM_APP_TEST_FULL_DEMOS=1
pytest tests/test_demos.pyRuns full physics simulations (unmodified demos).
This project uses Sphinx to generate API documentation from the source code. The necessary dependencies are included in the [dev] extra.
A helper script is provided to simplify the build process. To build the documentation, run the following command from the project root:
./docs/build_docs.shThe script will clean the previous build and generate the HTML documentation in the docs/_build/html directory.
To view the documentation, open the docs/_build/html/index.html file in your web browser.
This example demonstrates how to define a current source, calculate its magnetic field on a grid, and visualize the results.
import numpy as np
import matplotlib.pyplot as plt
from em_app.sources import RingCoil
from em_app.solvers import calculate_b_field, Backend
from sandalwood import mtf
# Initialize the MTF library (Optional - defaults to Order 4, Dim 3 if omitted)
# mtf.initialize_mtf(max_order=1, max_dimension=4)
# --- 1. Setup the Coil Geometry ---
coil = RingCoil(
current=1.0,
radius=0.5,
num_segments=20,
center_point=np.array([0, 0, 0]),
axis_direction=np.array([0, 0, 1]),
)
# --- 2. Define the Field Points for Calculation ---
grid_size = 1.0
num_points = 15
x_points = np.linspace(-grid_size, grid_size, num_points)
z_points = np.linspace(-grid_size, grid_size, num_points)
X, Z = np.meshgrid(x_points, z_points)
field_points = np.vstack([X.ravel(), np.zeros_like(X.ravel()), Z.ravel()]).T
# --- 3. Calculate the Magnetic Field ---
# --- 3. Calculate the Magnetic Field ---
# You can specify the backend explicitly using the Backend Enum
b_field = calculate_b_field(coil, field_points, backend=Backend.PYTHON)
b_vectors = np.array([b.to_numpy_array() for b in b_field._vectors_mtf])
# --- 4. Plot the Results ---
fig = plt.figure(figsize=(8, 8))
ax = fig.add_subplot(111, projection="3d")
# Plot the coil geometry
coil.plot(ax, color="b", wire_thickness=0.02)
# Plot the magnetic field vectors
ax.quiver(
field_points[:, 0],
field_points[:, 1],
field_points[:, 2],
b_vectors[:, 0],
b_vectors[:, 1],
b_vectors[:, 2],
length=0.2,
normalize=True,
color="gray",
)
# --- 5. Customize and Show the Plot ---
ax.set_title("Magnetic Field of a Ring Coil")
ax.set_xlabel("X (m)")
ax.set_ylabel("Y (m)")
ax.set_zlabel("Z (m)")
ax.view_init(elev=20.0, azim=-60)
plt.show()For more detailed examples, see the demo scripts in the demos/em directory. These scripts cover topics such as solver validation, dipole approximation, and advanced plotting.
You can run all demos at once using the following command:
python scripts/run_all_demos.pyThis will generate output files and plots in the runoutput directory.
src/em_app/- Core library modulesdemos/em/- Demo scriptsbenchmarks/- Performance and accuracy benchmarkstests/- Unit tests
MIT
This platform employs several advanced design patterns and algorithms to ensure high performance and flexibility:
- Structure of Arrays (SoA): The
VectorFieldclass detects input formats and switches to SoA storage (_storage_mode = "soa") when initialized with component arrays (vx, vy, vz). This improves memory locality and SIMD vectorization potential compared to Array of Structures (AoS). - Hybrid Storage: Seamlessly handles both numerical data (NumPy arrays) and symbolic objects (
sandalwoodMTFs) within the same API.
- Factory Pattern:
Vector.from_array_of_vectorsprovides optimizing factory methods for bulk object creation. - Strategy/Adapter Pattern: The
solversmodule uses a backend selection strategy (Backend.PYTHON,Backend.COSY,Backend.MPI) to dispatch computation to the most appropriate engine (local CPU, optimized Fortran, or distributed MPI).
This project (and its dependency sandalwood) requires specific setup on Windows to support the high-performance Fortran COSY backend.
- Python 3.9+
- Git
- Visual Studio Build Tools 2022: Ensure "Desktop development with C++" is selected during installation. This provides
link.exeandnmake. - Intel oneAPI HPC Kit: Required for the
ifxFortran compiler. - Intel oneAPI Base Kit: Required for Intel MPI libraries.
We recommend setting up a common workspace for both sandalwood and em-simulation-platform to share a virtual environment.
# Directory Structure
# C:\Users\YourName\Work\
# ├── sandalwood/
# ├── em-simulation-platform/
# └── .venv/ (or inside one repo)We provide a unified setup script that handles the complex environment configuration (detecting Visual Studio, setting up Intel compilers, installing libraries, and building extensions).
Method A: Automated Setup (Recommended)
cd C:\Users\YourName\Work\DAProjects
.\em-simulation-platform\scripts\windows\setup_env.batThis script will:
- Initialize Intel oneAPI environment (
setvars.bat). - Set up Visual Studio integration.
- Create/Update the
.venv. - Build
sandalwood(compiling Fortran withifx). - Install
em-simulation-platform.
Method B: Manual Installation If you prefer manual control:
Step 1: Clone Repositories
cd C:\Users\YourName\Work
git clone https://github.com/shashi-manikonda/sandalwood.git
git clone https://github.com/shashi-manikonda/em-simulation-platform.gitStep 2: Setup Virtual Environment It is easiest to use a single virtual environment for both projects.
cd sandalwood
uv venv .venv
# Activate
.venv\Scripts\activateStep 3: Build and Install Sandalwood (The Compiler Step)
This step compiles the Fortran backend (libcosy.dll).
# Ensure you are in the sandalwood directory
# Note: You MUST have 'ifx' and 'link.exe' in your PATH (run 'setvars.bat' first)
uv pip install -e .[dev]Step 4: Install EM Platform
cd ..\em-simulation-platform
# Install into the SAME virtual environment
uv pip install -e .[dev,benchmark]Step A: Clone Repositories
cd C:\Users\YourName\Work
git clone https://github.com/shashi-manikonda/sandalwood.git
git clone https://github.com/shashi-manikonda/em-simulation-platform.gitStep B: setup Virtual Environment It is easiest to use a single virtual environment for both projects.
cd sandalwood
uv venv .venv
# Activate
.venv\Scripts\activateStep C: Build and Install Sandalwood (The Compiler Step)
This step compiles the Fortran backend (libcosy.dll).
# Ensure you are in the sandalwood directory
uv pip install -e .[dev]- Note: The build script (
setup.py) will automatically detect your Visual Studio and Intel compilers. - Troubleshooting: If you see linker errors, ensure you have the Intel Base Kit installed and
libiomp5md.libis reachable.
Step D: Install EM Platform
cd ..\em-simulation-platform
# Install into the SAME virtual environment
uv pip install -e .[dev,benchmark]The COSY backend is a compiled Fortran extension.
-
Modifying Fortran Code: If you modify
src/sandalwood/backends/cosy/wrapper.fin thesandalwoodrepo, changes do not take effect automatically. You must re-compile:cd ..\sandalwood uv pip install -e .This triggers the custom build command to regenerate the DLL.
-
Memory Configuration (Windows vs Linux): Windows has a 2GB limit for static object file sections.
sandalwoodhandles this automatically viasrc/sandalwood/backends/cosy/cosy_config.env:- Linux:
COSY_LMEMdefaults to 1GB (allows large simulations). - Windows:
COSY_LMEM_WIN32overrides this to ~150MB to fit within OS limits. - If you need more memory on Windows, consider using the Linux Subsystem for Windows (WSL2).
- Linux:
cd ..\em-simulation-platform
pytest(See previous documentation for Linux-specific bash instructions) [...MPI instructions remain similar...]
