# Winding Factors and Harmonic Spectrum


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

## Executive Summary

This notebook computes **winding factors** — the efficiency with which a
winding produces each spatial harmonic of the airgap field.

<table>
<thead>
<tr>
<th>Function</th>
<th>What it computes</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>pitch_factor</code></td>
<td>kp(ν) — chording factor</td>
</tr>
<tr>
<td><code>distribution_factor</code></td>
<td>kd(ν) — belt factor (integer-slot only)</td>
</tr>
<tr>
<td><code>winding_factor</code></td>
<td>kw(ν) = kp·kd or phasor sum</td>
</tr>
<tr>
<td><code>winding_factor_spectrum</code></td>
<td></td>
</tr>
</tbody>
</table>

## How It Fits Into Motor Design

    01_winding_sos.ipynb  (layout engine)
          │
          ▼
    01_winding_factors.ipynb   ←── YOU ARE HERE
          │
          ▼
    01_winding_mmf.ipynb       (MMF waveform & spectrum)

**Depends on:** `sos.py` — uses `build_coil_matrix`,
`winding_factor_sos`, and `_resolve_layout` to fill in a missing
`layers` or `w`.

**Feeds into:** `01_winding_mmf.ipynb` (via `winding_factor_spectrum`).

## Notation

<table>
<thead>
<tr>
<th>Symbol</th>
<th>Definition</th>
</tr>
</thead>
<tbody>
<tr>
<td>Q</td>
<td>Stator slots</td>
</tr>
<tr>
<td>P</td>
<td>Poles</td>
</tr>
<tr>
<td>p</td>
<td>Pole pairs = P/2</td>
</tr>
<tr>
<td>τp</td>
<td>Pole pitch = Q/P (one magnetic pole)</td>
</tr>
<tr>
<td>w</td>
<td>Coil span in slots</td>
</tr>
<tr>
<td>ν</td>
<td>Mechanical harmonic order</td>
</tr>
<tr>
<td>kp</td>
<td>Pitch (chording) factor</td>
</tr>
<tr>
<td>kd</td>
<td>Distribution (belt) factor</td>
</tr>
<tr>
<td>kw</td>
<td>Combined winding factor = kp·kd (ISW)</td>
</tr>
<tr>
<td>q</td>
<td>Slots per pole per phase = Q/(2mp)</td>
</tr>
</tbody>
</table>

## Imports and Setup

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

## `pitch_factor`: Chording Factor kp

### Theory

All harmonic orders ν in this module are **mechanical**: ν cycles per
revolution, so the working harmonic is ν = p. A coil spanning w of the Q
slots links the ν-th harmonic with

$$k\_{p\nu} = \left|\sin\\\left(\frac{\nu \pi w}{Q}\right)\right|$$

This is the textbook $\sin(\nu' \tfrac{\pi}{2} \tfrac{w}{\tau_p})$ with
electrical order ν’ = ν/p and pole pitch τp = Q/P. It is a property of
one coil, so it holds for any ν. For 12s/4p the full pitch is w = 3
slots, and the working harmonic is ν = 2.

**References:** Hanselman (2003), eq. 4.5; Pyrhönen et al. (2014), §2.4.

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

### pitch_factor

``` python
def pitch_factor(
    nu:int, *, Q:int, w:int
)->float:
```

*Pitch (chording) factor kp of one coil for mechanical harmonic nu.*

kp(nu) = |sin(nu \* pi \* w / Q)|

## Parameters

nu : int Mechanical harmonic order (working harmonic nu = p) Q : int
Number of stator slots (keyword-only) w : int Coil span in slots
(keyword-only)

## Returns

float kp in \[0, 1\]

``` python
import math
from emachines.winding.winding_factors import pitch_factor, distribution_factor, winding_factor, winding_factor_spectrum

# Examples
assert pitch_factor(2, Q=24, w=6) == 1.0                    # 24s/4p, full pitch, working harmonic
assert math.isclose(pitch_factor(2, Q=24, w=5), 0.9659, abs_tol=1e-4)   # 5/6 chording
```

``` python
from emachines.winding.winding_factors import pitch_factor

# 24s/4p: p = 2, pole pitch = Q/P = 6 slots. Working harmonic ν = 2,
# 5th and 7th electrical harmonics are ν = 10 and 14.
Q, p = 24, 2
print("Pitch factor for 24s/4p (pole pitch = 6 slots):")
print(f"{'w':>4}  {'kp(ν=2)':>8}  {'kp(ν=10)':>9}  {'kp(ν=14)':>9}")
print("-" * 38)
for w in range(1, 7):
    marker = " <- full pitch" if w == 6 else (" <- 5/6 chording" if w == 5 else "")
    print(f"  {w:>2}  {pitch_factor(2, Q=Q, w=w):>8.4f}  {pitch_factor(10, Q=Q, w=w):>9.4f}  "
          f"{pitch_factor(14, Q=Q, w=w):>9.4f}{marker}")
```

    Pitch factor for 24s/4p (pole pitch = 6 slots):
       w   kp(ν=2)   kp(ν=10)   kp(ν=14)
    --------------------------------------
       1    0.2588     0.9659     0.9659
       2    0.5000     0.5000     0.5000
       3    0.7071     0.7071     0.7071
       4    0.8660     0.8660     0.8660
       5    0.9659     0.2588     0.2588 <- 5/6 chording
       6    1.0000     1.0000     1.0000 <- full pitch

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

## `distribution_factor`: Belt Factor kd

### Theory

Spreading a phase belt over q slots (q = Q/(2mp), slots per pole per
phase) gives, in mechanical order ν,

$$k\_{d\nu} = \left|\frac{\sin(\nu q \pi / Q)}{q \sin(\nu \pi / Q)}\right|$$

which is the textbook
sin (*ν*<sup>′</sup>*π*/2*m*) / (*q*sin (*ν*<sup>′</sup>*π*/2*m**q*))
with ν’ = ν/p.

**Where the closed form is valid.** kd describes one phase belt. The
full winding also repeats every pole pair, which cancels every ν that is
not a multiple of p, and its go and return belts are mirror images,
which cancels even electrical orders. So kp·kd equals the true winding
factor only for **whole-number q** and **ν an odd multiple of p**.
Elsewhere the function raises `ValueError` instead of returning a factor
for a harmonic that does not exist. Use `winding_factor` for every other
case.

**References:** Pyrhönen et al. (2014), eq. 2.15.

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

### distribution_factor

``` python
def distribution_factor(
    nu:int, *, Q:int, P:int, m:int=3
)->float:
```

*Distribution (belt) factor kd for mechanical harmonic nu.*

kd(nu) = |sin(nu*q*pi/Q) / (q \* sin(nu*pi/Q))|, q = Q / (2*m\*p)

Valid only for whole-number q and nu an odd multiple of p, where kp\*kd
equals the winding factor. Use `winding_factor` otherwise.

## Parameters

nu : int Mechanical harmonic order (working harmonic nu = p) Q : int
Number of stator slots (keyword-only) P : int Number of poles
(keyword-only) m : int Number of phases (default 3)

## Returns

float kd in (0, 1\]

## Raises

ValueError If q is not a whole number, or nu is not an odd multiple of
p.

``` python
# Examples
assert math.isclose(distribution_factor(2, Q=12, P=4), 1.0)              # 12s/4p, q = 1
assert math.isclose(distribution_factor(2, Q=24, P=4), 0.9659, abs_tol=1e-4)   # 24s/4p, q = 2
```

``` python
from emachines.winding.winding_factors import distribution_factor

print("Distribution factor at the working harmonic ν = p, 4 poles:")
print(f"{'Config':>16}  {'q':>3}  {'kd(ν=2)':>8}  {'kd(ν=10)':>9}")
print("-" * 42)
for Q in (12, 24, 36, 48):
    q = Q // 12
    print(f"  {Q:>2}s/4p        {q:>3}  {distribution_factor(2, Q=Q, P=4):>8.4f}  "
          f"{distribution_factor(10, Q=Q, P=4):>9.4f}")

for Q, P, nu in [(36, 8, 4), (24, 4, 4)]:
    try:
        distribution_factor(nu, Q=Q, P=P)
    except ValueError as e:
        print(f"\n{Q}s/{P}p, ν={nu} → ValueError: {e}")
```

    Distribution factor at the working harmonic ν = p, 4 poles:
              Config    q   kd(ν=2)   kd(ν=10)
    ------------------------------------------
      12s/4p          1    1.0000     1.0000
      24s/4p          2    0.9659     0.2588
      36s/4p          3    0.9598     0.2176
      48s/4p          4    0.9577     0.2053

    36s/8p, ν=4 → ValueError: distribution_factor() needs a whole-number q (slots per pole per phase); got q = 3/2 for Q=36, P=8, m=3. Use winding_factor() instead.

    24s/4p, ν=4 → ValueError: distribution_factor() is valid only for nu an odd multiple of p=2; got nu=4. That harmonic cancels in the full winding. Use winding_factor() instead.

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

## `winding_factor`: Combined kw

### Theory

`winding_factor(nu, Q=…, P=…)` is the exact winding factor of harmonic ν
(mechanical order, working harmonic ν = p), from the star-of-slots
phasor sum. It works for integer-slot, fractional-slot and tooth-coil
windings, and for every ν, including sub-harmonics and orders that
cancel (which give 0).

It describes the same winding as the rest of the module: when `layers`
or `w` is left out, the best candidate from `design_windings` is used.

For whole-number q and ν an odd multiple of p, it equals the textbook
product `pitch_factor(ν, Q=Q, w=w) * distribution_factor(ν, Q=Q, P=P)`
for a double-layer winding of span w. The tests check this.

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

### winding_factor

``` python
def winding_factor(
    nu:int, *, Q:int, P:int, w:int | None=None,
    layers:int | None=None, # (see ``design_windings``); a given w implies 2.
    m:int=3
)->float:
```

*Winding factor |kw| of mechanical harmonic nu, by the star of slots.*

## Parameters

nu : int Mechanical harmonic order (working harmonic nu = p) Q : int
Number of stator slots (keyword-only) P : int Number of poles
(keyword-only) w : int | None Double-layer coil span in slots. None -\>
the best span. layers : int | None 1 or 2. None -\> the best buildable,
balanced candidate (see `design_windings`); a given w implies 2. m : int
Number of phases (default 3)

## Returns

float |kw| in \[0, 1\]

``` python
# Examples
assert math.isclose(winding_factor(5, Q=12, P=10, w=1), 0.9330, abs_tol=1e-4)   # 12s/10p tooth coil, working harmonic
assert math.isclose(winding_factor(2, Q=24, P=4, w=5), 0.9330, abs_tol=1e-4)    # 24s/4p, 5/6 chording
assert math.isclose(winding_factor(4, Q=36, P=8, w=4), 0.9452, abs_tol=1e-4)    # 36s/8p, q = 3/2
```

``` python
from emachines.winding.winding_factors import winding_factor

configs = [
    dict(Q=12, P=4,  w=3, label="12s/4p  q=1    full pitch"),
    dict(Q=24, P=4,  w=5, label="24s/4p  q=2    5/6 chording"),
    dict(Q=36, P=8,  w=4, label="36s/8p  q=3/2  fractional"),
    dict(Q=12, P=10, w=1, label="12s/10p q=2/5  tooth coil"),
    dict(Q=12, P=8,  w=1, label="12s/8p  q=1/2  tooth coil"),
]
print(f"{'Configuration':<30}  {'p':>2}  {'kw(ν=p)':>8}  {'kw(ν=1)':>8}  {'kw(ν=5p)':>8}")
print("-" * 66)
for c in configs:
    p = c['P'] // 2
    kw = [winding_factor(nu, Q=c['Q'], P=c['P'], w=c['w']) for nu in (p, 1, 5 * p)]
    print(f"  {c['label']:<28}  {p:>2}  {kw[0]:>8.4f}  {kw[1]:>8.4f}  {kw[2]:>8.4f}")
```

    Configuration                    p   kw(ν=p)   kw(ν=1)  kw(ν=5p)
    ------------------------------------------------------------------
      12s/4p  q=1    full pitch      2    1.0000    0.0000    1.0000
      24s/4p  q=2    5/6 chording    2    0.9330    0.0000    0.0670
      36s/8p  q=3/2  fractional      4    0.9452    0.0000    0.1398
      12s/10p q=2/5  tooth coil      5    0.9330    0.0670    0.0670
      12s/8p  q=1/2  tooth coil      4    0.8660    0.0000    0.8660

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

## `winding_factor_spectrum`: Full Harmonic Spectrum

### Theory

The phasor sum method computes |kw(ν)| for all mechanical harmonics:

$$k\_{w\nu} = \frac{1}{m} \sum\_{k=0}^{m-1} \frac{\left|\sum\_{i,\text{lyr}} s\_{i,\text{lyr}} e^{j\nu 2\pi i/Q}\right|}{N_k}$$

Works for all winding types. **Working harmonic:** ν = p = P/2.

**References:** Müller, Vogt & Ponick (2008), eq. 3.65.

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

### winding_factor_spectrum

``` python
def winding_factor_spectrum(
    Q:int, P:int, m:int=3, layers:int | None=None, # 1 (single-layer) or 2 (double-layer).
    # None -> the best buildable, balanced candidate (see design_windings).
    w:int | None=None, # Double-layer coil span in slots. None -> the best span.
    nu_max:int=40
)->tuple[np.ndarray, np.ndarray]:
```

*Winding factor magnitude spectrum for mechanical harmonics 1…nu_max.*

## Parameters

Q : int Number of stator slots P : int Number of poles (even, \>= 2) m :
int Number of phases (default 3) layers : int | None 1 (single-layer) or
2 (double-layer). None -\> the best buildable, balanced candidate (see
design_windings). w : int | None Double-layer coil span in slots. None
-\> the best span. nu_max : int Highest mechanical harmonic (default 40)

## Returns

nu_arr : np.ndarray, shape (nu_max,), dtype int kw_arr : np.ndarray,
shape (nu_max,), dtype float64 |kw(nu)| in \[0, 1\]

``` python
# Examples
nu, kw = winding_factor_spectrum(12, 10, layers=2)
assert math.isclose(kw[4], 0.9330, abs_tol=1e-4)          # ν = 5, working harmonic of 12s/10p
nu, kw = winding_factor_spectrum(12, 4, layers=1, w=6, nu_max=10)
assert math.isclose(kw[1], 1.0)                           # ν = 2, 12s/4p, q = 1, full pitch
```

``` python
from emachines.winding.winding_factors import winding_factor_spectrum
import numpy as np

configs = [
    dict(Q=12, P=10, layers=2, label="12s/10p FSCW DL"),
    dict(Q=12, P=8,  layers=2, label="12s/8p  FSCW DL"),
    dict(Q=24, P=4,  layers=2, label="24s/4p  ISW  DL"),
]

for cfg in configs:
    nu, kw = winding_factor_spectrum(cfg['Q'], cfg['P'], layers=cfg['layers'], nu_max=15)
    p = cfg['P'] // 2
    print(f"\n{cfg['label']}  (working nu = {p})")
    for i in range(len(nu)):
        if kw[i] > 0.01:
            marker = " <- working" if nu[i] == p else ""
            print(f"  nu={int(nu[i]):>3}  kw={float(kw[i]):>6.4f}{marker}")
```

    12s/10p FSCW DL  (working nu = 5)
      nu=  1  kw=0.0670
      nu=  3  kw=0.5000
      nu=  5  kw=0.9330 <- working
      nu=  7  kw=0.9330
      nu=  9  kw=0.5000
      nu= 11  kw=0.0670
      nu= 13  kw=0.0670
      nu= 15  kw=0.5000

    12s/8p  FSCW DL  (working nu = 4)
      nu=  4  kw=0.8660 <- working
      nu=  8  kw=0.8660

    24s/4p  ISW  DL  (working nu = 2)
      nu=  2  kw=0.9659 <- working
      nu=  6  kw=0.7071
      nu= 10  kw=0.2588
      nu= 14  kw=0.2588

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

## References

1.  Hanselman, D.C. (2003). *Brushless Permanent Magnet Motor Design*,
    2nd ed. eq. 4.5.
2.  Pyrhönen, J., Jokinen, T., & Hrabovcová, V. (2008). *Design of
    Rotating Electrical Machines*. Wiley. eq. 2.15.
3.  Müller, G., Vogt, K., & Ponick, B. (2008). *Berechnung elektrischer
    Maschinen*. Wiley-VCH. eq. 3.65.
4.  Bianchi, N., & Bolognani, S. (2002). IEEE Trans. Ind. Appl., 38(5).
    DOI: 10.1109/TIA.2002.802909.

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

## Tests
