# MEC Solution and Results


<!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->

## Executive Summary

**Purpose:** Store and query magnetic circuit analysis results

**What it does:** Structure and post-process MEC solution results.

### Why It Matters

After solving MEC, access flux, torque, efficiency in organized data
structure.

### Quick Start

**Inputs:** Solution from 04_mec_solver.ipynb

**Outputs:** Formatted results: branch flux, winding flux linkage, field
energy, convergence info

## How It Fits Into the Motor Design Workflow

**Upstream (depends on):** Output stage of MEC solver pipeline

**Downstream (used by):** See notebook connections

## MEC Solution Interpretation

The MEC solver returns a **MECSolution** object containing all circuit
variables:

### Flux Variables

- **φ_mesh** — Mesh loop fluxes \[Wb\] (one per independent loop)
- **φ_nodal** — Nodal potentials \[Wb\] (used by permeance branches)
- **φ_branches** — Net flux through every branch \[Wb\]

### Magnetomotive Force (MMF)

- **mmf_branches** — MMF drop across every branch \[A-turns\]

Branch equation: F = R(Φ) · Φ + F_s (at convergence)

### Winding Flux Linkage

For a winding with N turns linked with multiple branches:
*λ* = ∑<sub>*k*</sub>*N*<sub>*k*</sub> ⋅ *Φ*<sub>*k*</sub>

where N_k is signed (positive = aligned with flux direction).

### Convergence and Energy

- **converged** — Whether Newton-Raphson converged
- **residual** — Final convergence error ‖ΔΦ‖ \[Wb\]
- **field_energy** — Stored magnetic field energy \[J\]

$$W_f = \frac{1}{2} \sum_k R\_{\text{eff},k} \cdot \Phi_k^2$$

------------------------------------------------------------------------

### MECSolution

``` python
def MECSolution(
    phi_mesh:Dict[int, float]=<factory>, phi_nodal:Dict[int, float]=<factory>,
    phi_branches:Dict[int, float]=<factory>, mmf_branches:Dict[int, float]=<factory>,
    flux_linkages:Dict[Any, float]=<factory>, converged:bool=False, n_iterations:int=0, residual:float=inf,
    field_energy:float=0.0, phi_base:Optional[float]=None, F_base:Optional[float]=None
)->None:
```

*Solution of a Magnetic Equivalent Circuit.*

All branch quantities are stored in dictionaries keyed by branch number
(the integer assigned when the branch was added to the MEC).

## Attributes

phi_mesh : dict\[int, float\] Mesh flux variables Φₘ \[Wb\]. One entry
per mesh branch. phi_nodal : dict\[int, float\] Nodal flux variables Φₙ
\[Wb\]. One entry per nodal branch. phi_branches : dict\[int, float\]
Net flux through every branch \[Wb\]. mmf_branches : dict\[int, float\]
MMF drop across every branch \[A-turns\]. flux_linkages : dict\[Any,
float\] Winding flux linkages \[Wb-turns\]. Keys are winding IDs
registered via :meth:`MEC.add_winding`. Empty if no windings were
defined. converged : bool True if Newton-Raphson converged within the
iteration limit. n_iterations : int Number of Newton-Raphson iterations
performed. residual : float Final convergence residual ‖ΔΦ‖ (absolute,
\[Wb\]). field_energy : float Stored magnetic field energy \[J\] Wf = ½
Σ R_eff · Φ² (sum over reluctance branches). phi_base : float or None
Base flux used for per-unit scaling \[Wb\]. F_base : float or None Base
MMF used for per-unit scaling \[A-turns\].

------------------------------------------------------------------------

### MECSolution

``` python
def MECSolution(
    phi_mesh:Dict[int, float]=<factory>, phi_nodal:Dict[int, float]=<factory>,
    phi_branches:Dict[int, float]=<factory>, mmf_branches:Dict[int, float]=<factory>,
    flux_linkages:Dict[Any, float]=<factory>, converged:bool=False, n_iterations:int=0, residual:float=inf,
    field_energy:float=0.0, phi_base:Optional[float]=None, F_base:Optional[float]=None
)->None:
```

*Solution of a Magnetic Equivalent Circuit.*

All branch quantities are stored in dictionaries keyed by branch number
(the integer assigned when the branch was added to the MEC).

## Attributes

phi_mesh : dict\[int, float\] Mesh flux variables Φₘ \[Wb\]. One entry
per mesh branch. phi_nodal : dict\[int, float\] Nodal flux variables Φₙ
\[Wb\]. One entry per nodal branch. phi_branches : dict\[int, float\]
Net flux through every branch \[Wb\]. mmf_branches : dict\[int, float\]
MMF drop across every branch \[A-turns\]. flux_linkages : dict\[Any,
float\] Winding flux linkages \[Wb-turns\]. Keys are winding IDs
registered via :meth:`MEC.add_winding`. Empty if no windings were
defined. converged : bool True if Newton-Raphson converged within the
iteration limit. n_iterations : int Number of Newton-Raphson iterations
performed. residual : float Final convergence residual ‖ΔΦ‖ (absolute,
\[Wb\]). field_energy : float Stored magnetic field energy \[J\] Wf = ½
Σ R_eff · Φ² (sum over reluctance branches). phi_base : float or None
Base flux used for per-unit scaling \[Wb\]. F_base : float or None Base
MMF used for per-unit scaling \[A-turns\].

## Example: Post-Processing MEC Results

``` python
# Create a mock solution for demonstration
sol = MECSolution(
    phi_branches={0: 0.001, 1: 0.0015},
    mmf_branches={0: 50.0, 1: 75.0},
    flux_linkages={'coil_a': 0.01, 'coil_b': 0.015},
    converged=True,
    n_iterations=5,
    residual=1.2e-5,
    field_energy=0.025,
)

# Access branch flux
flux_0 = sol.flux(0)
print(f"Branch 0 flux: {flux_0:.6e} Wb")

# Access MMF drop
mmf_0 = sol.mmf(0)
print(f"Branch 0 MMF: {mmf_0:.2f} A-turns")

# Access winding flux linkage
flux_linkage_a = sol.flux_linkage('coil_a')
print(f"Coil A flux linkage: {flux_linkage_a:.6e} Wb-turns")

# Check convergence
print(f"\nConvergence status: {sol.converged}")
print(f"Iterations: {sol.n_iterations}")
print(f"Residual: {sol.residual:.3e} Wb")
print(f"Field energy: {sol.field_energy:.6g} J")

# String representation
print(f"\nSolution: {sol}")
```

    Branch 0 flux: 1.000000e-03 Wb
    Branch 0 MMF: 50.00 A-turns
    Coil A flux linkage: 1.000000e-02 Wb-turns

    Convergence status: True
    Iterations: 5
    Residual: 1.200e-05 Wb
    Field energy: 0.025 J

    Solution: MECSolution(converged, iter=5, residual=1.200e-05, Wf=0.025 J, heuristic-scaled)

## Tests

``` python
# Test default initialization
sol = MECSolution()
assert sol.converged == False, "Default convergence should be False"
assert sol.n_iterations == 0, "Default iterations should be 0"
assert sol.residual == float('inf'), "Default residual should be inf"
assert sol.field_energy == 0.0, "Default field energy should be 0"
print("✓ Default initialization tests passed")

# Test flux and mmf access
sol = MECSolution(
    phi_branches={1: 0.001, 2: 0.002},
    mmf_branches={1: 50.0, 2: 100.0},
)
assert sol.flux(1) == 0.001, "Flux access failed"
assert sol.mmf(2) == 100.0, "MMF access failed"
assert sol.flux(99) == 0.0, "Non-existent branch should return 0"
print("✓ Branch access tests passed")

# Test flux linkage access
sol = MECSolution(
    flux_linkages={'winding_a': 0.01, 'winding_b': 0.02},
)
assert sol.flux_linkage('winding_a') == 0.01, "Flux linkage access failed"
assert sol.flux_linkage('winding_b') == 0.02, "Flux linkage access failed"
print("✓ Winding flux linkage tests passed")

# Test error handling
try:
    sol.flux_linkage('nonexistent')
    assert False, "Should raise KeyError for non-existent winding"
except KeyError:
    print("✓ Error handling tests passed")

# Test string representation
sol = MECSolution(converged=True, n_iterations=10, residual=1e-4, field_energy=0.05)
repr_str = repr(sol)
assert 'converged' in repr_str.lower(), "Representation should include convergence status"
assert '10' in repr_str, "Representation should include iteration count"
print("✓ String representation tests passed")
```

    ✓ Default initialization tests passed
    ✓ Branch access tests passed
    ✓ Winding flux linkage tests passed
    ✓ Error handling tests passed
    ✓ String representation tests passed
