Metadata-Version: 2.4
Name: radia
Version: 5.3.2
Summary: Radia 3D Magnetostatics with NGSolve Integration and TaskManager Parallelization
Author: Pascal Elleaume
Author-email: Oleg Chubar <chubar@bnl.gov>
Maintainer: Radia Development Team
License: RADIA SOFTWARE LICENSE
        ======================
        
        This software contains multiple components with different licenses:
        
        1. RADIA Core (BSD-style License)
        2. HACApK Library (MIT License)
        3. sparseSolv integration (Mozilla Public License 2.0)
        4. Intel Math Kernel Library runtime notices
        5. Radia SPICE/LTspice integration (MIT License)
        6. Eqnedit64 (BSD 2-Clause License with separately licensed assets)
        
        ================================================================================
        PART 1: RADIA CORE
        ================================================================================
        
        Copyright © 1997 - 2018, European Synchrotron Radiation Facility
        
        The RADIA software is distributed subject to the following license conditions:
        
        Redistribution and use in source and binary forms, with or without
        modification, are permitted provided that the following conditions are met:
        
        1. Redistributions of source code must retain the above copyright notice,
           this list of conditions and the following disclaimer.
        
        2. Redistributions in binary form must reproduce the above copyright notice,
           this list of conditions and the following disclaimer in the documentation
           and/or other materials provided with the distribution.
        
        DISCLAIMER: THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS"
        AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
        IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
        ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
        ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
        DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
        SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
        CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
        OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
        OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
        
        The views and conclusions contained in the software and documentation are
        those of the authors and should not be interpreted as representing official
        policies, either expressed or implied, of the RADIA project.
        
        ================================================================================
        PART 2: HACApK (H-matrix Library)
        ================================================================================
        
        Software Name : HACApK
        Version : 1.3.0
        Location: src/ext/HACApK/
        
        Copyright (c) 2015 Akihiro Ida and Takeshi Iwashita
        
        MIT License
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
        
        ppOpen-HPC project:
          Open Source Infrastructure for Development and Execution of Large-Scale
          Scientific Applications on Post-Peta-Scale Supercomputers with Automatic
          Tuning (AT).
        
        Sponsorship:
          Japan Science and Technology Agency (JST), Basic Research Programs: CREST,
          Development of System Software Technologies for post-Peta Scale High
          Performance Computing.
        
        ================================================================================
        PART 3: sparseSolv integration
        ================================================================================
        
        Location: src/ext/sparsesolv/
        
        The sparseSolv integration is licensed under the Mozilla Public License Version
        2.0. See src/ext/sparsesolv/LICENSE for the full license text.
        
        ================================================================================
        PART 4: Intel Math Kernel Library (MKL) Runtime
        ================================================================================
        
        This software distribution includes Intel Math Kernel Library (Intel MKL)
        runtime libraries for BLAS/LAPACK operations.
        
        Intel MKL License:
        The Intel MKL runtime libraries are redistributed under the terms of the
        Intel Simplified Software License (version August 2021) which allows
        redistribution of the software in binary form.
        
        Copyright (c) Intel Corporation. All rights reserved.
        
        The Intel MKL redistributable libraries included are:
        - mkl_rt.3.dll (or equivalent)
        - mkl_core.3.dll
        - mkl_intel_thread.3.dll
        - mkl_def.3.dll
        - mkl_avx2.3.dll
        
        Intel, the Intel logo, and Intel MKL are trademarks of Intel Corporation or
        its subsidiaries in the U.S. and/or other countries.
        
        ================================================================================
        PART 5: RADIA SPICE/LTSPICE INTEGRATION
        ================================================================================
        
        Location: src/radia/ltspice/
        
        Copyright (c) 2026 Mitsutoshi Sugahara
        
        MIT License
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
        
        For the full Intel Simplified Software License terms, please visit:
        https://www.intel.com/content/www/us/en/developer/articles/license/end-user-license-agreement.html
        
        ================================================================================
        PART 6: EQNEDIT64
        ================================================================================
        
        Location: tools/eqnedit64/
        
        Copyright (c) 2026 ksugahar
        
        Eqnedit64 is licensed under the BSD 2-Clause License. See
        tools/eqnedit64/LICENSE for the full license text.
        
        Redistributable font and icon assets retain their respective licenses. See
        tools/eqnedit64/assets/THIRD_PARTY_NOTICES.md and the license files beside
        those assets.
        
        ================================================================================
        
Project-URL: Homepage, https://github.com/ksugahar/Radia
Project-URL: Documentation, https://github.com/ksugahar/Radia/blob/main/README.md
Project-URL: Repository, https://github.com/ksugahar/Radia
Project-URL: Issues, https://github.com/ksugahar/Radia/issues
Project-URL: Original Radia, https://github.com/ochubar/Radia
Project-URL: ESRF Radia Page, https://www.esrf.fr/Accelerators/Groups/InsertionDevices/Software/Radia
Keywords: magnetostatics,magnetic field,radia,ngsolve,fem,synchrotron,cubit,mesh,export,gmsh,nastran,netgen
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Science/Research
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: C++
Classifier: Topic :: Scientific/Engineering :: Physics
Requires-Python: >=3.12
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy>=1.20
Requires-Dist: scipy>=1.12
Requires-Dist: threadpoolctl>=3.1
Requires-Dist: mkl<2027,>=2026
Requires-Dist: intel-cmplr-lib-rt<2027,>=2026
Requires-Dist: ngsolve==6.2.2607
Requires-Dist: netgen-mesher==6.2.2607
Provides-Extra: optuna
Requires-Dist: optuna==5.0.0; extra == "optuna"
Provides-Extra: cubit
Requires-Dist: cubit-mesh-export; extra == "cubit"
Provides-Extra: topopt-cad
Requires-Dist: scikit-image>=0.22; extra == "topopt-cad"
Requires-Dist: trimesh>=4.0; extra == "topopt-cad"
Requires-Dist: netCDF4>=1.6; extra == "topopt-cad"
Requires-Dist: fast-simplification>=0.1; extra == "topopt-cad"
Provides-Extra: build123d
Requires-Dist: build123d>=0.9; extra == "build123d"
Provides-Extra: beam
Requires-Dist: xtrack>=0.109.1; extra == "beam"
Provides-Extra: viz
Requires-Dist: matplotlib>=3.5; extra == "viz"
Provides-Extra: docs
Requires-Dist: anywidget>=0.11; extra == "docs"
Requires-Dist: jupyter>=1.0; extra == "docs"
Requires-Dist: matplotlib>=3.5; extra == "docs"
Requires-Dist: nbconvert>=7.0; extra == "docs"
Requires-Dist: nbformat>=5.0; extra == "docs"
Provides-Extra: urn
Requires-Dist: torch>=2.0; extra == "urn"
Provides-Extra: test
Requires-Dist: pytest>=7.0; extra == "test"
Requires-Dist: pytest-cov>=4.0; extra == "test"
Requires-Dist: setuptools>=45; extra == "test"
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == "dev"
Requires-Dist: pytest-cov>=4.0; extra == "dev"
Requires-Dist: setuptools>=45; extra == "dev"
Requires-Dist: matplotlib>=3.5; extra == "dev"
Dynamic: license-file

# Radia

<p align="center">
  <strong>Electromagnetic CAE you can operate through AI and MCP</strong><br>
  Connect CAD, mesh control, field analysis, and result inspection on NGSolve,
  with Python, MCP, MATLAB, and Simulink interfaces.
</p>

<p align="center">
  <a href="https://github.com/ksugahar/Radia/actions/workflows/build-test.yml"><img alt="CI" src="https://github.com/ksugahar/Radia/actions/workflows/build-test.yml/badge.svg"></a>
  <a href="https://github.com/ksugahar/Radia/actions/workflows/radia-mcp-matrix.yml"><img alt="MCP matrix" src="https://github.com/ksugahar/Radia/actions/workflows/radia-mcp-matrix.yml/badge.svg"></a>
  <a href="https://pypi.org/project/radia/"><img alt="radia on PyPI" src="https://img.shields.io/pypi/v/radia?label=radia&color=006dad"></a>
  <a href="https://pypi.org/project/radia-mcp/"><img alt="radia-mcp on PyPI" src="https://img.shields.io/pypi/v/radia-mcp?label=radia-mcp&color=006dad"></a>
  <a href="https://github.com/ksugahar/Radia/releases"><img alt="GitHub release" src="https://img.shields.io/github/v/release/ksugahar/Radia?display_name=tag&sort=semver"></a>
  <a href="LICENSE"><img alt="License" src="https://img.shields.io/badge/license-see%20LICENSE-blue"></a>
  <a href="https://github.com/ksugahar/Radia/stargazers"><img alt="GitHub stars" src="https://img.shields.io/github/stars/ksugahar/Radia?style=social"></a>
</p>

<p align="center">
  <img src="docs/stream_function/demo_active_shield.png"
       alt="Active-shield coil demonstration comparing external stray fields with and without shielding"
       width="1100">
</p>
<p align="center">
  <sub>Design for a field target: a stream-function active-shield demonstration.
  This comparison is for the illustrated coil configuration, not a universal
  shielding-performance claim.</sub>
</p>

**You set the analysis direction. AI helps operate the CAE tools.**

Radia is an open-source electromagnetic CAE platform that an AI assistant can
operate through MCP. Specify the analysis task and conditions; connected tools
can prepare geometry, control meshing, execute supported calculations, and
inspect results. This reduces the need to memorize each tool's commands and
interaction sequences while keeping the model and results inspectable.

The distributions are independent within this monorepo:

| Distribution | Runtime and integration scope |
| --- | --- |
| `radia` | CPU electromagnetic execution through Python/pybind11 and NGSolve |
| [`radia-gpu`](packages/radia-gpu/README.md) | CUDA MEX, MATLAB, Simulink and LTspice integration code |
| [`radia-mcp`](packages/radia-mcp/README.md) | AI tools and knowledge spanning both distributions |

The normal `radia` distribution excludes CUDA MEX, MATLAB, Simulink and LTspice
integration payloads and dependencies. Install `radia-gpu` separately for those
interfaces. External products are installed separately under their own licenses.

Start from supported CAD, mesh, or model data where available, instead of
rebuilding every input. What transfers depends on the format and workflow;
materials, sources, boundary conditions, and units still need to be checked.
The user defines the physical assumptions, analysis plan, and acceptance criteria
and evaluates the engineering conclusions. Radia's current positioning is
AI-operable CAE, not autonomous design decision-making.

Radia is deliberately **not** another monolithic finite-element solver. It is
built on [NGSolve](https://ngsolve.org/), which remains the numerical
foundation for finite-element spaces, mappings, quadrature, weak forms,
assembly, and field evaluation. Radia adds electromagnetic methods,
open-boundary operators, application workflows, native kernels, and
orchestration around that foundation.

> **Radia extends NGSolve; it does not compete with it.**

[Quick start](#quick-start) | [NGSolve from MATLAB](#ngsolve-from-matlab) | [Capabilities](#capabilities) |
[Simulink](#simulink) | [MCP](#python-and-mcp) |
[Eqnedit64](#eqnedit64) |
[Documentation](#documentation) | [Contributing](#contributing)

## Find your next engineering workflow

Use the documentation to discover capabilities and inspect results. Carry out
analysis through MCP, or through human–AI collaboration using Cubit and Simulink.
The executable samples live in [tests/](tests/README.md) for small usage and
contract examples, and [validation_test/](validation_test/README.md) for physics
and application cases with numerical evidence.

[**Start here**](docs/START_HERE.md) · [**Result gallery**](docs/APPLICATION_GUIDE.md#browse-results) ·
[**Accuracy and validation**](docs/VALIDATION_GUIDE.md)

| Explore | What you will find |
| :--- | :--- |
| [Calculate your first field](#quick-start) | A small analytical magnet example with SI inputs and output |
| [See geometry and results](docs/APPLICATION_GUIDE.md#browse-results) | A curved coil, motor torque and thermal response, linked to their conditions and saved calculations |
| [Inspect the numerical evidence](docs/VALIDATION_GUIDE.md) | Analytical references, force checks, holdout comparisons and their limits |
| [Choose an interface and get help](docs/START_HERE.md#choose-how-you-want-to-work) | Python/MCP, MATLAB/Simulink, installation and reproducible issue reports |

## NGSolve from MATLAB

CPU execution belongs to `radia` through Python/pybind11/NGSolve.
GPU execution belongs to `radia-gpu` through MATLAB mexcuda.
CPU Radia MEX is unsupported. NGSolve owns FE assembly; the initial GPU
kernel accepts assembled CSR operators and verifies the true residual.

MATLAB, Simulink and LTspice integration source, builds and distribution live
in [radia-gpu](packages/radia-gpu/README.md), within this monorepo.
`radia-mcp` provides cross-package knowledge and operation. The independently
released `radia-optuna` retains its own MATLAB optimization API and MEX.

The initial GPU alpha supports CSR Jacobi-PCG, its readable Simulink block
and LTspice integration. Historical CPU MEX models are source-only until
ported and validated. Poisson acceptance does not certify AMS, ICCG or HDiv-MMM.
Deploy GPU artifacts to 100 and A100, never 102. A100 acceptance stays pending
while unavailable.

## Why Radia?

- **Operate CAE through an AI assistant.** Use MCP to invoke supported operations
  from a stated analysis task, reducing tool-specific command and UI memorization.
- **Build on existing inputs.** Reuse supported geometry, meshes and model data,
  with explicit checks on the physical information carried into the calculation.
- **Connect geometry, mesh and analysis.** Drive CAD operations through MCP and
  control the mesh through the connected meshing workflow before solving.
- **Use optimization when you choose it.** Run coil, material, geometry or other
  supported optimization workflows with user-defined objectives and constraints.
- **Open boundaries are first-class.** Combine analytical source fields,
  Kelvin and DtN techniques, volume and boundary integral methods, SIBC, and
  model reduction without automatically surrounding every problem with a
  large air mesh.
- **AI and humans share the engineering contract.** Python and MCP are the
  first-class AI surface; MATLAB and masked Simulink blocks are the production
  human surface; both produce inspectable artifacts rather than hidden GUI
  state.
- **The numerical backend stays visible.** NGSolve owns finite-element
  mathematics. Radia supplies the missing physical operator or coupling and
  keeps independent analytical or integral routes where they improve trust.
- **Integration is a feature.** build123d, Coreform Cubit, Netgen, Gmsh,
  LTspice, MATLAB, Simulink, NumPy, SciPy, MKL, HACApK, and proven sparse
  solvers are connected through explicit boundaries instead of reimplemented.
- **Results carry evidence.** Production runs write checked meshes, logs,
  machine-readable result metadata, and visualization artifacts. Executable
  samples in `tests/` and `validation_test/` show expected behavior;
  documentation notebooks introduce features through saved results.

## What can you build?

| Engineering need | Radia route |
| :--- | :--- |
| Permanent magnets and coils | Analytical Radia source fields, CAD-driven coils, multipoles, forces, and open-space evaluation |
| Soft magnetic materials | HDiv-VIM, magnetic-moment and multipole-moment methods, nonlinear material laws, and HACApK charge-Gram operators |
| Accelerator and precision magnets | Clebsch-Hodograph pole design, field quality and multipoles, isochronous topology optimization, and charged-particle tracking |
| Eddy currents and shielding | NGSolve HCurl workflows, BEM-A, SIBC, ESIM, cohomology-aware formulations, and reduced transient models |
| Coil and current-sheet design | Stream-function inverse design, ACA+ / TSVD compression, contour extraction, and manufacturable single-stroke paths |
| Conductors and circuits | PEEC, proximity and skin effects, PRIMA/Foster reduction, SPICE export, KiCad/LTspice workflows, and circuit-field coupling |
| Induction heating | Geometry-to-operator assembly, distributed Eddy/Thermal Simulink blocks, temperature fields, and checked Gmsh outputs |
| Motors and magnetic levitation | Angle-periodic native reduced models, HCurl/Foster moving plants, Lorentz force, and Simulink control integration |
| Electromagnetic optimization | TPE, CMA-ES, MMA, SQP, adjoints, density/shape optimization, sheet-metal deformation, and CAD/mesh regeneration |
| Post-processing | Saved NGSolve WebGUI scenes, Gmsh field views, LIC, isosurfaces, streamlines, sweeps, and flying particle-orbit animations |
| TeX equation authoring | Eqnedit64 structural/TeX dual editing, keyboard-first templates, and native Office Math or image clipboard export |

## Quick start

The current production wheel targets **Windows x64**, **Python 3.12**, and
**NGSolve/Netgen 6.2.2607**.

```powershell
python -m pip install --upgrade radia
```

Evaluate an analytical open-boundary magnetic field in SI units:

```python
import numpy as np
import radia as rad

mu0 = 4.0 * np.pi * 1e-7
remanence_t = 1.2

magnet = rad.ObjRecMag(
    [0.0, 0.0, 0.0],
    [0.01, 0.01, 0.01],
    [0.0, 0.0, remanence_t / mu0],
)

b_t = rad.Fld(magnet, "b", [0.0, 0.0, 0.02])
print(f"Bz [T] = {b_t[2]:.8f}")
rad.UtiDelAll()
```

```text
Bz [T] = 0.02356629
```

This first example needs no air mesh. Move to NGSolve when the problem needs
finite-element spaces, material domains, weak forms, or coupled field
equations.

Turn solved SI field samples into electromagnetic force and torque through
Lorentz volume integration, air-side Maxwell stress, time-averaged complex
phasors, virtual work/coenergy, or a cylindrical air-gap shear estimate:

```python
from radia.force import integrate_lorentz_force

# One quadrature sample: J = 2 MA/m^2 in +z, B = 0.3 T in +y,
# with 2.5 cm^3 of physical volume. The force points in -x.
force_n = integrate_lorentz_force(
    [0.0, 0.0, 2.0e6],
    [0.0, 0.3, 0.0],
    2.5e-6,
)
print(force_n)  # [-1.5, 0.0, 0.0] N
```

Supplying quadrature positions and a pivot to
`integrate_lorentz_force_and_torque` returns both resultants. The same
contracts are available in MATLAB under `radia.force`, including
`integrateLorentzForceTorque`, `integrateTimeAverageMaxwellSurfaceForceTorque`,
`virtualWorkForce`, and `coenergyTorque`.
The [force and torque validation corpus](validation_test/force_validation/README.md)
records the Lorentz, Maxwell-stress, and virtual-work checks used to verify
signs and force extraction before attaching them to a production field solve.

Install only the integrations you need:

```powershell
# AI-facing domain tools and executable workflow knowledge
python -m pip install radia-mcp

# Coreform Cubit export and strict .vol checking
python -m pip install "radia[cubit]"
cubit-plugin-install
cubit-plugin-install --verify-only

# Optional accelerator tracking and topology-to-CAD workflows
python -m pip install "radia[beam]"
python -m pip install "radia[topopt-cad]"
```

See [Installation](#installation) for MATLAB/Simulink, visualization, and
source-build paths.

## Eqnedit64

[Eqnedit64](tools/eqnedit64) is a portable Windows x64 equation editor and a
browser edition maintained together in Radia. The native application connects
fast structural input directly to UTF-8 TeX. Its structural canvas
and live TeX pane are both editable, `Tab` traverses template slots, and the
palette teaches the TeX spelling of inserted structures without a separate
command-entry mode.

The single executable needs no installer, Python runtime, or file-type
registration. Copy places equivalent TeX, editable Office Math, EMF, and
opaque bitmap representations on the clipboard; Google Slides and headless
TeX-to-PNG paths are included. Eqnedit64 is released independently from Radia:
the Python/API distribution is on [PyPI](https://pypi.org/project/eqnedit64/),
and the matching signed standalone binary is published in the
[Eqnedit64 3.0.13 release](https://github.com/ksugahar/Radia/releases/tag/eqnedit64-v3.0.13).
`radia-mcp.presentation` discovers that installation as an optional rendering
and clipboard backend; neither package depends on the other at runtime.
Legacy Eqnedit32/MTEF binaries and conversion sources are deliberately not
part of the public component.

The laboratory homepage publishes the browser edition, while
[`tools/eqnedit64/web`](tools/eqnedit64/web) remains its source of truth. Native
and Web changes share the same TeX-learning and Office Math parity policy.

## Architecture

```mermaid
flowchart TB
    AI["AI / LLM"] --> MCP["radia-mcp"]
    Human["Human engineer"] --> Simulink["MATLAB / Simulink"]
    Python["Python API"] --> Contract["DesignSpec + typed artifacts"]
    MCP --> Contract
    Simulink --> Contract

    Contract --> CAD["CAD and mesh<br/>build123d | Cubit | Netgen"]
    Contract --> Methods["Radia physical methods<br/>Hodograph | VIM | Eddy | PEEC | Stream Function"]
    CAD --> NGSolve["NGSolve / ngsolve.bem<br/>spaces | mappings | quadrature | assembly"]
    NGSolve <--> Methods

    Methods --> Native["C++ / pybind11 / standalone MEX<br/>HACApK | sparse solvers | reduced state"]
    Methods --> Results["Durable results<br/>result.json | run.log | .msh | notebooks"]
    Native --> Results
    Results --> Viz["WebGUI | Gmsh | plots | animation"]
```

The same engineering model can therefore be driven by an AI agent, a Python
program, or a Simulink composition without making the user-facing interface
the source of numerical truth.

### Responsibility boundaries

| Layer | Owns |
| :--- | :--- |
| **NGSolve / ngsolve.bem** | FE spaces, element orientation, Piola maps, curved geometry, quadrature, weak-form assembly, GridFunctions, and BEM operators |
| **Radia C++ and Python** | Analytical fields, electromagnetic physical methods, open-boundary operators, material/circuit coupling, reduced models, and artifact schemas |
| **MATLAB and Simulink** | Human-facing composition, typed signal flow, lifecycle, controls, monitoring, and native MEX state ownership |
| **radia-mcp** | Executable domain knowledge, tool discovery, workflow selection, validation guidance, and AI orchestration |
| **CAD and visualization tools** | Geometry/mesh authoring and durable inspection through explicit STEP, VOL, MSH, and result boundaries |

## Capabilities

### Analytical and open-boundary magnetics

Radia retains the analytical magnetostatic strengths of the original Radia
project: permanent magnets, coils, source fields, forces, energies, and field
evaluation in open space. Around those sources, the current platform provides
Kelvin transformations, exterior DtN formulations, infinite elements,
equivalent sources, and integral formulations for problems where truncating a
large air domain is undesirable.

Radia targets the **magneto-quasi-static to Darwin regime**. Its propagation
kernels are Laplace kernels; frequency enters conductor physics through skin
depth, impedance, and reduced dynamics. Radia is not a full-wave Helmholtz
solver for radiation-dominated problems.

### Clebsch-Hodograph design

Hodograph methods transform selected nonlinear magnetic-design problems into
tractable design problems in a transformed coordinate space. The implementation
supports flux-line and pole-face design, field-quality studies, end effects,
and accelerator-magnet workflows.

- [Clebsch-Hodograph documentation](docs/clebsch_hodograph/README.md)
- [Result-bearing accelerator design notebooks](docs/clebsch_hodograph/demos/README.md)

### HDiv-VIM and magnetic materials

The HDiv Volume Integral Method uses NGSolve meshes and finite-element spaces
while Radia supplies the magnetic charge-Gram and open-boundary interaction.
The C++ HACApK path provides compressed operators for large repeated actions,
and the Python surface stays compatible with NGSolve's field and space
vocabulary.

This is Radia's forward path for soft magnetic materials, nonlinear
magnetization, demagnetizing fields, topology-aware material design, and
independent FEM/integral cross-checks.

- [HDiv-VIM documentation](docs/hdiv_vim/README.md)
- [Open-boundary method map](docs/open_boundary/OPEN_BOUNDARY_MAP.md)

### Eddy currents, SIBC, and ESIM

Radia combines high-order NGSolve HCurl discretizations with BEM-A, surface
impedance, effective surface impedance, cohomology handling, and reduced
models. The `Eddyable` concept packages response bases for repeated
low-frequency solves while preserving the underlying field formulation.

- [Eddy-current method guide](docs/solver/EDDY_CURRENT_METHODS.md)
- [ESIM formulation and usage](docs/esim/README.md)
- [Foster, PRIMA, and Modal-bulk SIBC models](docs/solver/REDUCED_EDDY_MODELS.md)

### Stream functions and coil topology

The stream-function layer solves inverse source problems for target magnetic
fields, supports regularized ACA+ / TSVD compression, extracts current
contours, and turns them into connected winding paths. It is used for planar,
cylindrical, and free-form current sheets as well as field-shaping and coil
optimization.

- [Stream Function documentation](docs/stream_function/README.md)
- [Single-stroke winding policy and algorithms](docs/stream_function/single_stroke.md)

### PEEC, circuits, and model reduction

PEEC workflows cover partial inductance, resistance, proximity and skin
effects, shield coupling, circuit assembly, and SPICE-compatible extraction.
PRIMA, block Lanczos, Foster modal models, and universal relaxation networks provide reusable
reduced models for circuit and transient studies.

The independent `radia_gpu.ltspice` package connects SPICE netlists, editable LTspice
schematics, KiCad-derived circuits, RAW results, and sampled-data Simulink
plants. Circuit conversion has one Python source of truth and exposes checked
MATLAB adapters.

- [PEEC integration](docs/peec_integration/README.md)
- [SPICE and LTspice integration](docs/ltspice/README.md)
- [Universal relaxation networks](docs/universal_relaxation_network/model_inventory.md)

### Optimization and geometry regeneration

Radia supports global, local, and gradient-based design loops:

- TPE, CMA-ES, GP, NSGA-II/III, QMC, and finite define-by-run search;
- MATLAB-native Optuna 5.0.0-oracled Study/Trial workflows, table-backed
  resume/replay, parameter importance, termination callbacks, automatic
  sampler routing, and live Pareto monitoring;
- analytic-adjoint MMA and SQP for continuous field optimization;
- HDiv-VIM and HCurl material topology;
- stream-function, sheet-metal, and electromagnet topology optimization;
- density/level-set to watertight STL and checked Cubit/Netgen mesh
  regeneration.

Optimization is tied to the same mesh, material, result, and provenance
contracts as direct analysis. A new geometry is not accepted merely because
an optimizer produced it.

### Accelerator fields and particle trajectories

Radia's C++ core provides inspectable SI field sampling, relativistic Lorentz
equations, RK4/Boris steps, fixed-step trajectories, and distributed R/T/U
transfer attribution. It can also hand solved magnetic fields to CERN Xsuite
for accelerator-coordinate tracking or use SciPy for adaptive trajectories,
event handling, and closed-orbit workflows. Gmsh exports preserve trajectory
quantities and can animate a beam through the solved field.

For high-order map analysis, NGSolve remains the source of truth for conforming
HCurl/HDiv projection and curved finite-element evaluation. Radia adds a
tracking-specialized CanonicalHCurl vacuum chain fitted from full-volume field
samples, with adaptive fringe grading, periodic ring closure, and direct
longitudinal-polynomial coupling to a nonautonomous fourth-order Lie-map
integrator. Independent canonical A-map and projected B-map Runge--Kutta routes
keep field-projection error separate from Lie truncation error.

<p align="center">
  <img src="docs/application_cases/particles_rerun.png"
       alt="Recorded electron dispersion in a saddle-coil magnetic field"
       width="520">
</p>

- [Executed particle-orbit notebook](docs/gmsh_post/em_particle_orbits.ipynb)
- [Native beam and transfer API design](docs/api/EARLY_TIMES_CPP_API_DESIGN.md)
- [Canonical HCurl and Lie-map validation](validation_test/ffag_topopt/README.md)
- [Gmsh post-processing guide](docs/gmsh_post/README.md)

## Interfaces

### Python and MCP

Python is the complete programmable API. MCP makes the same platform
discoverable and executable by AI agents.

The user chooses the analysis purpose, assumptions and success criteria. An AI
assistant uses the available MCP tools to carry out the requested operations and
return inspectable artifacts. Tool execution can be automated; responsibility
for the analysis plan and engineering judgement remains with the user.

The [radia-mcp package](packages/radia-mcp/) provides domain servers for Radia,
NGSolve, Cubit, Gmsh, build123d, PEEC, induction heating, optimization,
materials, electric machines, accelerator magnets, and supporting engineering
knowledge. It is intentionally lightweight at import time: knowledge and
contract tools can run without loading the full native Radia/NGSolve stack.

```powershell
python -m pip install radia-mcp
```

Treat `radia-mcp` as the executable operating manual for agent-driven work.
The top-level README explains the platform; MCP returns the current workflow,
arguments, prerequisites, failure modes, and validation route for a concrete
operation.

- [MCP package and client setup](packages/radia-mcp/README.md)
- Use each server's live `tools/list` response for the authoritative tool
  inventory; the checked `radia_mcp.meta` catalog supplies discovery metadata.

### MATLAB and native MEX

Use the independently distributed [radia-gpu](packages/radia-gpu/README.md).
Its supported solver route is MATLAB mexcuda, with explicit transfer and
numerical validation against Python CPU execution. Build on 100 with
`Build.ps1 -CudaMexOnly -RequireNativeProvenance`.

MathWorks' official MATLAB MCP Server and Simulink Agentic Toolkit own generic
MATLAB/Simulink operations; `radia-mcp` adds domain and distribution contracts.

### Simulink

`radia-gpu` owns the readable CUDA PCG Level-2 S-Function, typed ports and
lifecycle checks. Standalone numerical MEX remains independently callable.
`radia-optuna` independently owns its optimization blocks. Historical library
models remain in the owning package's source tree and require migration and
validation before GPU release; they are not supported CPU MEX routes.

### Documentation and visualization

`docs/**/*.ipynb` is the feature-introduction layer. Demonstrations are
executed notebooks with narrative, code, saved results, and
saved `ngsolve.webgui.Draw` or `netgen.webgui.Draw` scenes. They are not hidden
production workbenches. Executable samples live in `tests/` and
`validation_test/`. Benchmarks and numerical evidence live under
`validation_test/` with machine-readable JSON; docs notebooks need no sidecar.

Field-producing application runs write checked Gmsh `.msh v4.1` artifacts.
The Gmsh toolchain supports scalar/vector/tensor fields, sections, clipping,
isosurfaces, LIC, streamlines, file-series statistics, shared-camera
comparisons, and particle-track animation. Geometry is shown at physical
1:1:1 axis scale unless an explicit display exaggeration is recorded.

## Engineering contracts

Radia favors fail-loud, inspectable boundaries over convenient ambiguity.

| Contract | Rule |
| :--- | :--- |
| Units | Public geometry and field APIs use SI units; geometry is in meters and magnetic flux density is in tesla |
| Physical regime | Magneto-quasi-static to Darwin; Laplace propagation kernels, no hidden full-wave Helmholtz path |
| Finite elements | NGSolve owns orientation, mappings, quadrature, assembly, and GridFunction evaluation |
| Mesh interchange | Netgen `.vol` is the solver mesh boundary; STEP is geometry, not a labeled solver mesh |
| Mesh acceptance | Every solver-bound VOL passes `check-vol`; production modes add strict, versioned label contracts |
| Results | Runs write `run.log`, `result.json`, checks, hashes, and spatial `.msh` output where a field exists |
| Native state | MEX handles validate type, generation, ownership, and liveness; stale handles fail loudly |
| Release | Package versions, compatibility constants, source hashes, native assets, and Simulink archives are checked across independent hosts before publication |

For Cubit-to-NGSolve workflows, Cubit produces the mesh and Radia/NGSolve
consumes it. The exporter does not infer material constants from labels;
conductivity, permeability, BH data, frequency, and other physics remain
explicit configuration.

## Installation

### Supported production stack

| Component | Current target |
| :--- | :--- |
| Operating system | Windows 10/11 or Windows Server, x64 |
| Python core | 3.12 |
| Lightweight radia-mcp | Python 3.10-3.12 |
| NGSolve / Netgen | 6.2.2607 |
| MATLAB / Simulink package | R2026a, Windows x64 |
| Coreform Cubit | 2025.12, optional |
| Native build | Visual Studio 2022, CMake/Ninja, pip `mkl-devel` oneMKL |

### Python packages

This monorepo contains five independently versioned distributions. SPICE/LTspice
integration ships inside `radia`; its extra only adds schemdraw support.

| Package or extra | Install | Purpose |
| :--- | :--- | :--- |
| `radia` | `python -m pip install radia` | C++ core, Python APIs, NGSolve integration, physical methods, and application logic |
| `radia-mcp` | `python -m pip install radia-mcp` | AI-facing MCP servers and executable domain knowledge |
| `cubit-mesh-export` | `python -m pip install cubit-mesh-export` | Solver-neutral high-order Cubit export, `check-vol`, plugin, and independently owned Cubit MCP |
| `radia-optuna` | `python -m pip install radia-optuna` | Standalone MATLAB Optuna namespace and 21-command native gateway; no Radia solver, NGSolve, or MKL runtime |
| `eqnedit64` | `python -m pip install eqnedit64` | Windows equation editor, structural Python API, native TeX/MathML/SVG/clipboard backend, and Web assets |
| `radia[optuna]` | `python -m pip install "radia[optuna]"` | Radia plus the independently versioned, validated native MATLAB/Simulink `radia-optuna` release |
| `radia[optuna-upstream]` | `python -m pip install "radia[optuna-upstream]"` | Also installs pinned upstream Python/SciPy/PyTorch paths used by GP, scrambled QMC, and importance parity |
| `radia[ltspice]` | `python -m pip install "radia[ltspice]"` | Radia plus schemdraw support for built-in SPICE/LTspice conversion and circuit coupling |

The separately verified `radia-optuna` wheel is also emitted as a CI artifact.
Release-quad validates that exact candidate on four hosts; the dedicated release
workflow publishes the verified artifact without rebuilding it.

Pin release versions together when reproducing a validated deployment. Release
notes and immutable native/Simulink assets are published on the
[GitHub Releases page](https://github.com/ksugahar/Radia/releases).

### Build from source

```powershell
git clone https://github.com/ksugahar/Radia.git
Set-Location Radia
python -m pip install -e ".[dev]"
python -m pip install -e packages/radia-mcp
python -m pip install -e packages/cubit-mesh-export
python -m pip install packages/eqnedit64
pwsh -NoProfile -ExecutionPolicy Bypass -File .\Build.ps1 -RadiaOnly
```

See [BUILD.md](BUILD.md) for compiler, NGSolve, MKL, and packaging details.

## Repository map

```text
src/core/                       C++ Radia and native electromagnetic kernels
src/radia/                      Python package, NGSolve integration, methods
src/radia/ltspice/              SPICE, LTspice, KiCad, and circuit workflows
packages/radia-gpu/matlab/+radia/                  MATLAB API, MEX wrappers, Simulink builders
packages/radia-mcp/             MCP servers and executable domain knowledge
packages/cubit-mesh-export/     Cubit exporters, plugin, and check-vol
packages/radia-optuna/          Standalone MATLAB/Simulink Optuna package
packages/eqnedit64/             Windows Eqnedit64 Python/API distribution
tools/eqnedit64/                Canonical native and browser editor source
tests/                          Small executable samples and fast regressions
validation_test/                Physics/application samples and validation gates
docs/                           Feature introductions, saved results and theory
tools/                          Build, policy, release, and verification tools
```

Loose `examples/` scripts are retired. New experiments begin outside the
repository and are promoted only when they become a reusable API, focused
test, validation problem, or result-bearing docs notebook.

## Documentation

Start with the path closest to your task:

- [Documentation index](docs/README.md)
- [Python API reference](docs/api/API_REFERENCE.md)
- [Radia and NGSolve integration notebook](docs/ngsolve_integration/integration_basics.ipynb)
- [Analytical electromagnetic formulas](docs/analytical_formulas.md)
- [HDiv-VIM](docs/hdiv_vim/README.md)
- [Clebsch-Hodograph](docs/clebsch_hodograph/README.md)
- [Eddy-current methods](docs/solver/EDDY_CURRENT_METHODS.md)
- [Stream Function](docs/stream_function/README.md)
- [PEEC integration](docs/peec_integration/README.md)
- [Induction heating](docs/induction_heating/README.md)
- [Electric machines](docs/electric_machine/README.md)
- [Magnetic levitation](docs/maglev/demos/README.md)
- [Gmsh post-processing](docs/gmsh_post/README.md)
- [MATLAB and Simulink](packages/radia-gpu/matlab/README.md)
- [MCP servers and tools](packages/radia-mcp/README.md)
- [Cubit mesh export](docs/cubit_mesh_export/README.md)

## Contributing

Radia welcomes focused contributions to physical methods, NGSolve-native
integration, independent validation, CAD/mesh boundaries, MATLAB/MEX parity,
documentation, and application workflows.

```powershell
# Run one focused regression while developing
python -m pytest -q tests/test_vim_eddy_hybrid.py

# Broaden only after the focused lane is green
python -m pytest -q tests
```

Fast regressions belong in `tests/`. Long numerical studies, convergence
sweeps, and benchmark-quality checks belong in `validation_test/`. These two
directories also provide executable samples. Feature introductions and saved
demonstrations belong under `docs/`; operational workflows use MCP or
human–AI collaboration through Cubit and Simulink.

- Read [CONTRIBUTING.md](CONTRIBUTING.md) before opening a pull request.
- Use the [issue tracker](https://github.com/ksugahar/Radia/issues) for bugs and
  concrete feature requests.
- Report vulnerabilities through the private process in
  [SECURITY.md](SECURITY.md).
- Include the smallest reproducible geometry/configuration and the generated
  `result.json` or checker report when reporting a numerical workflow issue.

If Radia is useful to your engineering or research, **star the repository**.
It helps other electromagnetic developers discover the project and follow its
progress.

## Project status

Radia is an active research and engineering platform. The core analytical
magnetostatics package is mature; newer VIM, Eddy, optimization, MATLAB/MEX,
and Simulink families are developed behind explicit tests and release gates.
Not every method has the same maturity or platform coverage, and unsupported
paths are expected to fail loudly rather than select a weaker substitute.

Current priorities are:

1. strengthen HDiv-VIM, topology optimization, and scalable open-boundary
   operators;
2. complete robust Hodograph and accelerator-magnet design workflows;
3. deepen Eddy, SIBC/ESIM, PEEC, Foster reduction, and thermal coupling;
4. expand measured Python/MATLAB/MEX parity and native Simulink dynamics;
5. improve executed documentation, independent validation, and reproducible
   application artifacts.

## Heritage, acknowledgements, and license

Radia originates from the magnetostatics work developed by Oleg Chubar,
Pascal Elleaume, and collaborators at the European Synchrotron Radiation
Facility. The current project extends that heritage with NGSolve integration,
open-boundary engineering methods, high-order formulations, optimization,
native MATLAB/Simulink interfaces, and AI-oriented automation.

We gratefully acknowledge Joachim Schöberl and the Netgen/NGSolve development
team and community for the numerical foundation that makes these workflows
possible. [NGSolve](https://ngsolve.org/) provides the finite-element spaces,
geometric mappings, quadrature, assembly, and field evaluation on which Radia
builds its electromagnetic applications. Radia also integrates the
HACApK H-matrix library, sparseSolv, Netgen, Gmsh, build123d, Coreform Cubit,
and the broader Python/MATLAB scientific ecosystems.

The repository contains components under different compatible terms,
including the BSD-style Radia core, MIT-licensed HACApK, MPL-2.0 sparseSolv
integration, and redistributable runtime notices. See [LICENSE](LICENSE) for
the complete terms.
