stem_core 0.2.0

Magnetic core definition for stem - a Simulation Toolbox for Electric Motors.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
/*!
This module contains the [`CoreExt`] trait, which provides shared functionality
for all core types: [`LinCore`](crate::core::LinCore),
[`RotCore`](crate::core::RotCore), and the [`Core`](crate::core::Core) and
[`CoreRef`] enums. It is a sealed trait. See its docstring for more.
*/

use std::{
    f64::consts::FRAC_PI_2,
    num::{NonZeroU16, NonZeroU32, NonZeroUsize},
    sync::Arc,
};

use planar_geo::prelude::*;
use rayon::prelude::*;
use stem_magnet::prelude::*;
use stem_slot::{
    current_displacement::CurrentDisplacementCalculator,
    slot::Slot,
    stem_types::{CoilLayout, SpatialOrder},
};

use super::CoreRef;
use crate::{
    LinOrRot,
    air_gap::AirGap,
    flux_barrier::FluxBarrier,
    magnets::Magnets,
    winding_zones::{PositionedZoneContour, WindingZones},
};

pub(crate) mod private {
    /// Sealed trait for [`CoreExt`]
    pub trait Sealed {}
}

/**
When a [`assembly_check`](CoreExt::assembly_check) fails, this enum describes
one of the components which collided with another component. See
[`AssemblyFailure`] for more information.
 */
#[derive(Clone, Debug)]
pub enum Component {
    /// Shape of the core  which collided with another component.
    Core(Shape),
    /// Contour of a winding zone which collided with another component.
    Zone {
        /// The nth element of the [`WindingZones`] iterator created by
        /// [`CoreExt::winding_zones`], which collided with another component.
        idx: usize,
        /// The winding zone contour and the
        /// [`Zone`](stem_slot::stem_types::Zone) index.
        contour: PositionedZoneContour,
    },
    /// Shape of a surface magnet which collided with another component.
    SurfaceMagnet {
        /// The nth element of the [`Magnets`] iterator created by
        /// [`CoreExt::surface_magnets`], which collided with another component.
        idx: usize,
        /// The shape of the colliding surface magnet.
        shape: Shape,
    },
    /// Shape of an interior magnet which collided with another component.
    InteriorMagnet {
        /// The nth element of the [`Magnets`] iterator created by
        /// [`CoreExt::interior_magnets`], which collided with another
        /// component.
        idx: usize,
        /// The shape of the colliding interior magnet.
        shape: Shape,
    },
}

/**
An error type created by [`CoreExt::assembly_check`] which describes a
collision between two components of an active part (magnetic core,
winding zones, surface magnets, interior magnets). It holds the two colliding
components and the reason for the collision.
 */
#[derive(Clone, Debug)]
pub struct AssemblyFailure {
    /// One of the colliding components.
    pub left_component: Component,
    /// The component which collided with the `left_component`.
    pub right_component: Component,
    /// Reason for the collision.
    pub reason: AssemblyFailureReason,
}

/**
An enum which describes the reason for a collision between the two components of
an active part. It is created as part of the [`AssemblyFailure`] error when a
[`assembly_check`](CoreExt::assembly_check) fails.
 */
#[derive(Clone, Debug)]
pub enum AssemblyFailureReason {
    /// The two components are overlapping.
    Overlap(Overlap),
    /// One component which should be contained by another one isn't. An example
    /// would be an interior magnet which is not contained by the
    /// [`CoreExt::shape`].
    NotContained(NotContained),
}

impl From<Overlap> for AssemblyFailureReason {
    fn from(value: Overlap) -> Self {
        Self::Overlap(value)
    }
}

impl From<NotContained> for AssemblyFailureReason {
    fn from(value: NotContained) -> Self {
        Self::NotContained(value)
    }
}

/**
A sealed trait providing shared functionality for all core types:
[`LinCore`](crate::core::LinCore), [`RotCore`](crate::core::RotCore), and the
[`Core`](crate::core::Core) and [`CoreRef`] enums.

The main purpose of this trait is to provide a common interface for all core
types, allowing for polymorphic behavior and code reuse. It is sealed to prevent
external implementations, ensuring that only the intended core types can
implement it.

Some of the trait methods require different implementations depending on the
[`AirGap`] or [`FluxBarrier`] of the core. These methods are wrappers around
the methods of [`AirGap`] / [`FluxBarrier`]; an example would be
[`CoreExt::winding_zones`] which wraps [`AirGap::winding_zones`]. The wrappers
always have the signature `wrapper(core, ...)`, while the wrapped methods look
like this: `wrapped(air_gap / flux_barrier, core, ...)`:

```ignore
fn winding_zones(&self, coil_layout: &CoilLayout) -> WindingZones {
    return self
        .air_gap()
        .winding_zones(self.as_core_ref(), coil_layout);
}
```

The docstrings of the [`CoreExt`] trait will generally focus on the _use_ of the
methods, whereas the [`AirGap`] / [`FluxBarrier`] docstrings will give details
on how to _implement_ them.

The wrapped methods exist to implement polymorphism and are not intended to be
used standalone. In particular, calling them with a `core` which wasn't build
using the specified [`AirGap`] / [`FluxBarrier`] trait object may
result in incorrect or unexpected results (although it must never result in
undefined behaviour)! The implementation of the [`AirGap`] / [`FluxBarrier`]
traits is not required to guard against this misuse of the interface.
*/
pub trait CoreExt: Sync + Send + std::fmt::Debug + private::Sealed {
    /// Converts the reference of `self` into a [`CoreRef`] enum.
    ///
    /// This method is used for the [`AirGap`] and [`FluxBarrier`] traits to
    /// access the core's properties without requiring generics, because those
    /// traits need to be object-safe. The [`CoreRef`] enum acts as a
    /// type-erased wrapper around the core, allowing for dynamic dispatch
    /// and polymorphism.
    fn as_core_ref(&self) -> CoreRef<'_>;

    /// Returns a reference to the [`AirGap`] trait object describing the air
    /// gap contour of the core.
    fn air_gap(&self) -> &dyn AirGap;

    /// Returns a reference to the [`FluxBarrier`] trait object describing the
    /// flux barrier of the core, if it has one. If it hasn't, this method
    /// returns `None`.
    fn flux_barrier(&self) -> Option<&dyn FluxBarrier>;

    /// Returns the axial length of the core, i.e., the length into the image
    /// plane when looking at the cross section of the core.
    ///
    /// This method should NOT be used to determine the axial length of a coil,
    /// use [`CoreExt::coil_axial_length`] instead.
    ///
    /// See the docstrings of [`LinCore`](crate::core::LinCore) and
    /// [`RotCore`](crate::core::RotCore) for a visualization.
    fn axial_length(&self) -> Length;

    /// Returns the number of pole pairs of `self`.
    fn pole_pairs(&self) -> NonZeroU16;

    /// Returns a reference to the core [`Material`].
    fn material(&self) -> &Arc<Material>;

    /// Returns the iron fill factor of the core, which is the ratio of the iron
    /// volume to the total core volume.
    ///
    /// Magnetic cores are often made from laminated steel sheets which are
    /// glued together in order to reduce eddy current losses. This reduces the
    /// effective iron volume and hence the magnetic permeability of the core.
    /// This can be accounted for by using a fictive [`CoreExt::iron_length`],
    /// which is the product of the [`CoreExt::axial_length`] and the iron fill
    /// factor. The iron fill factor is the ratio between the steel and the
    /// total lamination thickness as shown in the image below. Typical values
    /// are between 0.9 and 1, depending on the glue thickness.
    #[doc = ""]
    #[cfg_attr(
        feature = "doc-images",
        doc = "![Iron fill factor][cad_iron_fill_factor]"
    )]
    #[cfg_attr(
        feature = "doc-images",
        embed_doc_image::embed_doc_image(
            "cad_iron_fill_factor",
            "docs/img/cad_iron_fill_factor.svg"
        )
    )]
    #[cfg_attr(
        not(feature = "doc-images"),
        doc = "**Doc images not enabled**. Compile docs with
        `cargo doc --features 'doc-images'` and Rust version >= 1.54."
    )]
    fn iron_fill_factor(&self) -> f64 {
        // embed_doc_image does not support documenting trait methods without
        // a body, so a dummy implementation is provided (which is overridden
        // by the actual implementors).
        return 0.0;
    }

    /// Returns the yoke height of the core.
    ///
    /// The yoke is the "backbone" of the core, where the magnetic flux lines
    /// coming from the air gap closes. Its height is the
    /// [`LinCore::height`](crate::core::LinCore::height) or the absolute
    /// difference between
    /// [`RotCore::yoke_radius`](crate::core::RotCore::yoke_radius) and
    /// [`RotCore::air_gap_radius`](crate::core::RotCore::air_gap_radius) minus
    /// the [`CoreExt::tooth_height`]. The following image shows the dimensions
    /// for a [`PlainAirGap`](crate::air_gap::PlainAirGap) and a
    /// [`SlottedAirGap`](crate::air_gap::SlottedAirGap):
    #[doc = ""]
    #[cfg_attr(feature = "doc-images", doc = "![Yoke height][cad_yoke_tooth_height]")]
    #[cfg_attr(
        feature = "doc-images",
        embed_doc_image::embed_doc_image(
            "cad_yoke_tooth_height",
            "docs/img/cad_yoke_tooth_height.svg"
        )
    )]
    #[cfg_attr(
        not(feature = "doc-images"),
        doc = "**Doc images not enabled**. Compile docs with
        `cargo doc --features 'doc-images'` and Rust version >= 1.54."
    )]
    fn yoke_height(&self) -> Length {
        // embed_doc_image does not support documenting trait methods without
        // a body, so a dummy implementation is provided (which is overridden
        // by the actual implementors).
        return Length::new::<meter>(0.0);
    }

    /// Returns the skew angle of the core.
    ///
    /// The magnetic field in the air gap is composed of various harmonics,
    /// which result from both the magnet field sources (windings and magnets)
    /// and the core geometry, particularly the air gap contour. For example,
    /// when a core is slotted, the resulting field will have "slot harmonics"
    /// whose order is a multiple of [`CoreExt::slots`]. With the exception of
    /// the pole pair (main) harmonic, which provides the continuous force
    /// driving the motor, These harmonics should usually be minimized because
    /// they result in force fluctuations and noise.
    ///
    /// One way to suppress the harmonics is to "skew" the motor by the
    /// so-called skew angle. In the case of a linear motor, this means shifting
    /// one end by `skew_angle / (2*π) * core.width()` against the other. A
    /// rotary motor is twisted along its rotational axis by the skew angle.
    /// Depending on the skew angle, this leads to destructive interference of
    /// undesired harmonics. For example, to suppress the aforementioned slot
    /// harmonics, the core needs to be skewed by `2 * π / core.slots()`. See
    /// [\[1\]](#core_ext_skew_angle_1), section 6.5 for more. Be aware that
    /// skewing affects all harmonics, including the useful (force-producing)
    /// first stator harmonic. The general goal is therefore to find an angle
    /// which suppresses the unwanted harmonics while reducing the useful ones
    /// as little as possible.
    ///
    /// The exact realization of the skewing depends on
    /// [`CoreExt::num_segments`]. If this number is zero, the core is skewed
    /// continuously along its axial length. For the typical case of a laminated
    /// core, each lamination sheet is shifted a bit against its neighbors.
    /// Otherwise, the core is discretized ("staggered") into the specified
    /// number of segments which are shifted by `skew_angle / num_segments`
    /// against each other. The amount of segments heavily influences which
    /// harmonics are suppressed, see the docstring of [`skew_factor`] for
    /// details.
    ///
    /// # Literature
    /// <a id="core_ext_skew_angle_1">\[1\]</a>
    /// Binder, Andreas: Elektrische Maschinen und Antriebe (2012), Springer-
    /// Verlag, Berlin Heidelberg
    fn skew_angle(&self) -> f64;

    /**
    Returns the air gap "length" of the core.

    For a linear core, this is [`LinCore::width`](crate::core::LinCore::width).
    For a rotary core, this is the circumference of the air gap
    ([`RotCore::air_gap_radius`](crate::core::RotCore::air_gap_radius) times 2π).

    # Examples

    ```
    use std::sync::Arc;
    use std::f64::consts::TAU;
    use stem_core::prelude::*;

    let lin_core: LinCore = LinCoreBuilder {
        height: Length::new::<millimeter>(20.0),
        width: Length::new::<millimeter>(100.0),
        axial_length: Length::new::<millimeter>(100.0),
        axial_coil_overhang: Length::new::<millimeter>(0.0),
        skew_angle: 0.0,
        iron_fill_factor: 1.0,
        material: Arc::new(Material::default()),
        pole_pairs: 2.try_into().expect("not zero"),
        air_gap: Box::new(PlainAirGap::default()),
        flux_barrier: None,
    }.try_into().expect("valid inputs");
    assert_eq!(lin_core.air_gap_length().get::<millimeter>(), 100.0);

    let rot_core: RotCore = RotCoreBuilder {
        air_gap_radius: Length::new::<millimeter>(50.0),
        yoke_radius: Length::new::<millimeter>(90.0),
        axial_length: Length::new::<millimeter>(165.0),
        axial_coil_overhang: Length::new::<millimeter>(0.0),
        iron_fill_factor: 1.0,
        material: Arc::new(Material::default()),
        pole_pairs: 2.try_into().expect("not zero"),
        skew_angle: 0.0,
        air_gap: Box::new(PlainAirGap::default()),
        flux_barrier: None,
    }.try_into().expect("valid inputs");
    assert_eq!(rot_core.air_gap_length().get::<millimeter>(), 50.0 * TAU);
    ```
     */
    fn air_gap_length(&self) -> Length;

    /// Returns if the core is linear or rotary.
    fn lin_or_rot(&self) -> LinOrRot;

    /**
    Returns the total axial coil overhang on both sides of the magnetic core.

    If the core holds a winding, its coils can generally be separated into two
    different parts: A straight one where the coil goes along the axial length
    of the core and the end winding, where the coil closes. Sometimes, the
    straight part extends a bit from the core ends due to e.g., the slot
    insulation extending outside the core. This "extended" coil length is called
    the axial coil overhang. The ASCII art below visualizes it with equal signs
    `=`. If `=` equals one mm, the return value of `axial_coil_overhang` would be
    3 mm.
    ```text
         ┌──────┐
    ┌──==│      │=──┐
    │    │ Core │   │ <-- Coil
    └──==│      │=──┘
         └──────┘
    ```

    The total length of a full turn is therefore
    `2 * (axial_length + axial_coil_overhang + end_winding_half_turn_length)`.
    Since this part of the coil is outside the core, it is not considered when
    calculating core-dependent parameters such as the main inductance. Instead,
    it is treated as part of the end winding and therefore is added to the
    `end_winding_half_turn_length` when calculating parameters such as the end
    winding resistance or inductance.
     */
    fn axial_coil_overhang(&self) -> Length;

    /// Returns a reference to the cross-section shape of `self`.
    fn shape(&self) -> &Shape;

    /// Returns the d-axis pole coverage of `self` as a relative fraction of the
    /// entire air gap surface (value between 0 and 1). 0 means that the entire
    /// air gap surface is covered by the q-axis, 1 means that it is completely
    /// covered by the d-axis.
    ///
    /// If the core holds no magnets and has no flux barrier, this value is
    /// simply 0.5 (air gap evenly split between d- and q-axis). If a surface
    /// magnet assembly is provided as the second argument, the area covered by
    /// magnets is divided by the entire air gap area to get the pole
    /// coverage. If no surface magnet assembly is given, but the core holds a
    /// flux barrier, this method forwards to [`FluxBarrier::pole_coverage`].
    ///
    /// The image below shows all three of these cases, using a
    /// [`V1rFluxBarrier`](crate::flux_barrier::V1rFluxBarrier) for the
    /// rightmost core, where the
    /// d-axis covers 4 of 7 teeth per pole and hence the resulting pole
    /// coverage is 4/7 ≈ 0.571.
    #[doc = ""]
    #[cfg_attr(
        feature = "doc-images",
        doc = "![Pole coverage comparison][pole_coverage]"
    )]
    #[cfg_attr(
        feature = "doc-images",
        embed_doc_image::embed_doc_image("pole_coverage", "docs/img/pole_coverage.svg")
    )]
    #[cfg_attr(
        not(feature = "doc-images"),
        doc = "**Doc images not enabled**. Compile docs with
        `cargo doc --features 'doc-images'` and Rust version >= 1.54."
    )]
    ///
    /// # Examples
    ///
    /// This example calculates the pole coverages for the three core
    /// configurations shown in the image above.
    ///
    /// ```
    /// use std::f64::consts::FRAC_PI_2;
    /// use std::sync::Arc;
    ///
    /// use approxim::assert_abs_diff_eq;
    ///
    /// use stem_core::prelude::*;
    ///
    /// let slot: SemiTrapezoidSlot = SemiTrapezoidWidthsAndHeightsBuilder {
    ///     bottom_width: Length::new::<millimeter>(6.76),
    ///     bottom_side_width: Length::new::<millimeter>(6.76),
    ///     top_side_width: Length::new::<millimeter>(8.0),
    ///     top_width: Length::new::<millimeter>(1.5),
    ///     opening_width: Length::new::<millimeter>(1.5),
    ///     bottom_height: Length::new::<millimeter>(0.0),
    ///     side_height: Length::new::<millimeter>(6.79 - 0.75 - 0.5),
    ///     top_height: Length::new::<millimeter>(0.5),
    ///     opening_height: Length::new::<millimeter>(0.75),
    ///     bottom_radius: Length::new::<millimeter>(0.0),
    ///     bottom_side_radius: Length::new::<millimeter>(0.0),
    ///     top_radius: Length::new::<millimeter>(0.0),
    ///     top_side_radius: Length::new::<millimeter>(0.0),
    ///     opening_radius: Length::new::<millimeter>(0.0),
    ///     consider_tooth_tip_leakage: true,
    /// }
    /// .try_into().expect("valid slot");
    ///
    /// let air_gap = SlottedAirGap::new(28.try_into().expect("not zero"), false, CarterFactorModel::Bin12, Arc::new(slot));
    /// let mut core: RotCore = RotCoreBuilder {
    ///     air_gap_radius: Length::new::<millimeter>(54.4),
    ///     yoke_radius: Length::new::<millimeter>(19.0),
    ///     axial_length: Length::new::<millimeter>(165.0),
    ///     axial_coil_overhang: Length::new::<millimeter>(0.0),
    ///     iron_fill_factor: 1.0,
    ///     material: Arc::new(Material::default()),
    ///     pole_pairs: 2.try_into().expect("not zero"),
    ///     skew_angle: 0.0,
    ///     air_gap: Box::new(air_gap),
    ///     flux_barrier: None,
    /// }
    /// .try_into().expect("valid core");
    ///
    /// // Core without surface magnets or surface assembly
    /// assert_eq!(core.pole_coverage(None), 0.5);
    ///
    /// // With surface magnets
    /// let angle = 0.35 * FRAC_PI_2; // One pole is one quarter arc, 2 magnets per pole -> 0.7 pole coverage
    /// let magnet = ArcParallelMagnet::with_const_thickness(
    ///     core.axial_length(),
    ///     core.air_gap_radius(),
    ///     SideHeightOrThickness::Thickness(Length::new::<millimeter>(4.0)),
    ///     AngleOrWidth::Angle(angle),
    ///     Arc::new(Material::default()),
    /// ).expect("valid magnet");
    /// let mag_assembly = MagnetAssembly::new(magnet, 1.try_into().expect("not zero"), 2.try_into().expect("not zero"));
    ///
    /// assert_abs_diff_eq!(core.pole_coverage(Some(&mag_assembly)), 0.7, epsilon = 1e-4);
    ///
    /// // With flux barrier
    /// let barrier = V1rFluxBarrier {
    ///     yoke_distance: Length::new::<millimeter>(4.5),
    ///     relief_path_air_gap_width: Length::new::<millimeter>(3.5),
    ///     relief_path_length: Length::new::<millimeter>(1.33),
    ///     relief_path_width: Length::new::<millimeter>(4.0),
    ///     opening_angle: FRAC_PI_2,
    ///     magnet_space_width: Length::new::<millimeter>(10.0),
    ///     magnet_space_height: Length::new::<millimeter>(20.0),
    ///     glue_gap: Length::new::<millimeter>(0.2),
    ///     leakage_path_width: Length::new::<millimeter>(1.0),
    ///     magnet_material: Some(Arc::new(Material::default())),
    ///     cache: None,
    /// };
    /// core.set_flux_barrier(Some(Box::new(barrier))).expect("compatible to core");
    ///
    /// assert_abs_diff_eq!(core.pole_coverage(None), 4.0 / 7.0, epsilon = 1e-4);
    /// ```
    fn pole_coverage(&self, _surface_magnet_assembly: Option<&MagnetAssembly>) -> f64 {
        // embed_doc_image does not support documenting trait methods without
        // a body, so a dummy implementation is provided (which is overridden
        // by the actual implementors).
        return 0.5;
    }

    /// Returns the mass of a single tooth.
    ///
    /// In pseudo-code, this function calculates the tooth mass as follows:
    ///
    /// ```ignore
    /// slot_area = core.total_area - core.yoke_area
    /// tooth_area = slot_area - core.num_slots * slot.shape.area
    /// tooth_mass = tooth_area * core.iron_length * core.material.mass_density
    /// ```
    ///
    /// If [`CoreExt::slot`] returns `None`, this function returns a mass of 0
    /// kg.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::f64::consts::PI;
    /// use std::sync::Arc;
    ///
    /// use approxim::assert_abs_diff_eq;
    ///
    /// use stem_core::prelude::*;
    ///
    /// let slot: SemiTrapezoidSlot = SemiTrapezoidWithoutSlopesBuilder {
    ///     bottom_width: Length::new::<millimeter>(9.0),
    ///     opening_width: Length::new::<millimeter>(2.0),
    ///     height: Length::new::<millimeter>(20.0),
    ///     opening_height: Length::new::<millimeter>(2.0),
    ///     slot_angle: 10.0 * PI / 180.0,
    ///     bottom_radius: Length::new::<millimeter>(2.0),
    ///     top_radius: Length::new::<millimeter>(1.0),
    ///     opening_radius: Length::new::<millimeter>(0.0),
    ///     consider_tooth_tip_leakage: true,
    /// }
    /// .try_into()
    /// .unwrap();
    ///
    /// let air_gap_slotted = SlottedAirGap::new(36.try_into().expect("not zero"), false, CarterFactorModel::Bin12, Arc::new(slot));
    ///
    /// let core: RotCore = RotCoreBuilder {
    ///     air_gap_radius: Length::new::<millimeter>(55.0),
    ///     yoke_radius: Length::new::<millimeter>(90.0),
    ///     axial_length: Length::new::<millimeter>(165.0),
    ///     axial_coil_overhang: Length::new::<millimeter>(0.0),
    ///     iron_fill_factor: 1.0,
    ///     material: Arc::new(Material::default()),
    ///     pole_pairs: 2.try_into().expect("not zero"),
    ///     skew_angle: 0.0,
    ///     air_gap: Box::new(air_gap_slotted),
    ///     flux_barrier: None,
    /// }
    /// .try_into()
    /// .unwrap();
    ///
    /// assert_abs_diff_eq!(core.tooth_mass().eval(&[]).get::<kilogram>(), 0.015, epsilon = 1e-3);
    /// ```
    fn tooth_mass(&self) -> VarQuantity<Mass>;

    // =========================================================================

    /// Returns the total number of poles.
    ///
    /// This is 2 * [`Self::pole_pairs`].
    fn poles(&self) -> NonZeroU16 {
        return NonZeroU16::new(2 * self.pole_pairs().get())
            .expect("self.pole_pairs cannot be zero");
    }

    /**
    Checks if the core can be assembled with the given `coil_layout` and
    `surface_magnet_assembly`, using `epsilon` and `max_relative` as tolerances
    for overlap checks.

    This method first collects all geometric bodies ([`Shape`]s and
    [`Contour`]s) belonging to the assembly:
    - The core shape itself ([`CoreExt::shape`]),
    - The [`PositionedZoneContour`]s returned by the [`CoreExt::winding_zones`]
    method, using `coil_layout` as the second argument (if the core is not
    windable, the iterator will return `None`),
    - If a `surface_magnet_assembly` was provided, the magnet shapes created via
    [`CoreExt::surface_magnets`],
    - If the core has a [`flux_barrier`](`CoreExt::flux_barrier`) which can hold
    magnets, their shapes returned by [`CoreExt::interior_magnets`].

    If any two of these bodies overlap (checked with
    [`Composite::contains_any`] using the provided `epsilon` and
    `max_relative` tolerances, an [`AssemblyFailure`] is returned, containing
    both the two overlapping bodies as well as the exact [`Overlap`] provided by
    [`Composite::contains_any`]. Furthermore, all interior magnets
    should be contained within the [`Shape::contour`] of the core shape, which
    is tested with [`Composite::contains`]. If this is not the case,
    the core shape and the magnet shape are returned together with a
    [`NotContained`] enum providing more details.

    These checks are performed concurrently. If multiple issues exist, the one
    found first will be returned. Hence, this method may return different
    [`AssemblyFailure`]s when called repeatedly.

    # Examples

    The following example shows a successful and a failing assembly check for
    two different surface magnet assemblies. In the failing case, the magnet
    covers a full quarter circle, which leads to an overlap due to the core
    having 6 magnets.

    ```
    use std::f64::consts::FRAC_PI_2;
    use std::sync::Arc;

    use stem_core::prelude::*;
    use stem_core::planar_geo::prelude::*;

    let air_gap_plain = PlainAirGap::default();

    let core: RotCore = RotCoreBuilder {
        air_gap_radius: Length::new::<millimeter>(53.0),
        yoke_radius: Length::new::<millimeter>(19.0),
        axial_length: Length::new::<millimeter>(165.0),
        axial_coil_overhang: Length::new::<millimeter>(0.0),
        iron_fill_factor: 1.0,
        material: Arc::new(Material::default()),
        pole_pairs: 3.try_into().expect("not zero"),
        skew_angle: 0.0,
        air_gap: Box::new(air_gap_plain),
        flux_barrier: None,
    }
    .try_into()
    .unwrap();

    // Magnet covers one eight of a circle (0.5 * FRAC_PI_2)
    let magnet = ArcParallelMagnet::with_const_thickness(
        core.axial_length(),
        core.air_gap_radius(),
        SideHeightOrThickness::Thickness(Length::new::<millimeter>(4.0)),
        AngleOrWidth::Angle(0.5 * FRAC_PI_2),
        Arc::new(Material::default()),
    ).expect("valid magnet");
    let assembly_1 = MagnetAssembly::new(magnet, 1.try_into().expect("not zero"), 1.try_into().expect("not zero"));

    assert!(core.assembly_check(&CoilLayout::SingleFilled, Some(&assembly_1), DEFAULT_EPSILON, DEFAULT_MAX_RELATIVE).is_ok());

    // Magnet covers one quarter of a circle (FRAC_PI_2)
    let magnet = ArcParallelMagnet::with_const_thickness(
        core.axial_length(),
        core.air_gap_radius(),
        SideHeightOrThickness::Thickness(Length::new::<millimeter>(4.0)),
        AngleOrWidth::Angle(FRAC_PI_2),
        Arc::new(Material::default()),
    ).expect("valid magnet");
    let assembly_2 = MagnetAssembly::new(magnet, 1.try_into().expect("not zero"), 1.try_into().expect("not zero"));

    assert!(core.assembly_check(&CoilLayout::SingleFilled, Some(&assembly_2), DEFAULT_EPSILON, DEFAULT_MAX_RELATIVE).is_err());
    ```
     */
    fn assembly_check(
        &self,
        coil_layout: &CoilLayout,
        surface_magnet_assembly: Option<&MagnetAssembly>,
        epsilon: f64,
        max_relative: f64,
    ) -> Result<(), AssemblyFailure> {
        let core_shape = self.shape();
        let zones: Vec<PositionedZoneContour> = self.winding_zones(coil_layout).collect();
        if let Some(o) = zones.par_iter().enumerate().find_map_any(|(i1, z1)| {
            if let Ok(overlap) = core_shape
                .with_tolerance(epsilon, max_relative)
                .contains_any(&z1.contour)
            {
                return Some(AssemblyFailure {
                    left_component: Component::Core(core_shape.clone()),
                    right_component: Component::Zone {
                        idx: i1,
                        contour: z1.clone(),
                    },
                    reason: overlap.into(),
                });
            }

            if let Some(o) = zones.par_iter().enumerate().find_map_any(|(i2, z2)| {
                if i1 <= i2 {
                    return None;
                }
                if let Ok(overlap) = z2
                    .contour
                    .with_tolerance(epsilon, max_relative)
                    .contains_any(&z1.contour)
                {
                    return Some(AssemblyFailure {
                        left_component: Component::Zone {
                            idx: i1,
                            contour: z1.clone(),
                        },
                        right_component: Component::Zone {
                            idx: i2,
                            contour: z2.clone(),
                        },
                        reason: overlap.into(),
                    });
                }
                return None;
            }) {
                return Some(o);
            }

            return None;
        }) {
            return Err(o);
        }

        // Check surface magnets
        if let Some(magnets) = surface_magnet_assembly.map(|m| {
            self.surface_magnets(m, false)
                .map(|e| e.shape)
                .collect::<Vec<_>>()
        }) {
            if let Some(o) = magnets.par_iter().enumerate().find_map_any(|(i1, m1)| {
                if let Ok(overlap) = core_shape
                    .with_tolerance(epsilon, max_relative)
                    .contains_any(m1)
                {
                    return Some(AssemblyFailure {
                        left_component: Component::Core(core_shape.clone()),
                        right_component: Component::SurfaceMagnet {
                            idx: i1,
                            shape: m1.clone(),
                        },
                        reason: overlap.into(),
                    });
                }

                if let Some(o) = magnets.par_iter().enumerate().find_map_any(|(i2, m2)| {
                    if i1 <= i2 {
                        return None;
                    }

                    if let Ok(overlap) = m2.with_tolerance(epsilon, max_relative).contains_any(m1) {
                        return Some(AssemblyFailure {
                            left_component: Component::SurfaceMagnet {
                                idx: i1,
                                shape: m1.clone(),
                            },
                            right_component: Component::SurfaceMagnet {
                                idx: i2,
                                shape: m2.clone(),
                            },
                            reason: overlap.into(),
                        });
                    }
                    return None;
                }) {
                    return Some(o);
                }

                if let Some(o) = zones.par_iter().enumerate().find_map_any(|(i, z)| {
                    if let Ok(overlap) = m1.contains_any(&z.contour) {
                        return Some(AssemblyFailure {
                            left_component: Component::Zone {
                                idx: i,
                                contour: z.clone(),
                            },
                            right_component: Component::SurfaceMagnet {
                                idx: i1,
                                shape: m1.clone(),
                            },
                            reason: overlap.into(),
                        });
                    }
                    return None;
                }) {
                    return Some(o);
                }

                return None;
            }) {
                return Err(o);
            }
        }

        // Check interior magnets
        // Condition A: Must be inside core contour
        // Condition B: Must not overlap core contour
        let interior_magnets: Vec<_> = self.interior_magnets(false).collect();
        if let Some(o) = interior_magnets
            .par_iter()
            .enumerate()
            .find_map_any(|(i, m)| {
                if let Err(e) = core_shape
                    .contour()
                    .with_tolerance(epsilon, max_relative)
                    .contains(&m.shape)
                {
                    return Some(AssemblyFailure {
                        left_component: Component::Core(core_shape.clone()),
                        right_component: Component::InteriorMagnet {
                            idx: i,
                            shape: m.shape.clone(),
                        },
                        reason: e.into(),
                    });
                }

                if let Ok(overlap) = core_shape
                    .with_tolerance(epsilon, max_relative)
                    .contains_any(&m.shape)
                {
                    return Some(AssemblyFailure {
                        left_component: Component::Core(core_shape.clone()),
                        right_component: Component::InteriorMagnet {
                            idx: i,
                            shape: m.shape.clone(),
                        },
                        reason: overlap.into(),
                    });
                }

                return None;
            })
        {
            return Err(o);
        }

        return Ok(());
    }

    /**
    Returns the slot pitch of the core. This is the quotient of the
    [`air_gap_length`](CoreExt::air_gap_length) and the number of
    [`slots`](CoreExt::slots).
     */
    fn slot_pitch(&self) -> Length {
        self.air_gap_length() / self.slots() as f64
    }

    /**
    Returns the Carter factor of `self`.

    The _Carter factor_ `kc` describes the effect of non-smooth (e.g., slotted)
    air gaps contours on the magnetic resistance / reluctance of the air gap.
    The magnetically effective air gap width can be calculated as
    `kc_stator_core * kc_rotor_core * geometrical_air_gap` with both factors
    being equal to or larger than 1.

    The exact implementation of the Carter factor calculation depends on the
    [`AirGap`] itself, hence this method forwards to [`AirGap::carter_factor`],
    using `self` as the second argument and `geometrical_air_gap` as the third. See
    the docstring of [`AirGap::carter_factor`] for details and examples.
     */
    fn carter_factor(&self, geometrical_air_gap: Length) -> f64 {
        self.air_gap()
            .carter_factor(self.as_core_ref(), geometrical_air_gap)
    }

    /// Returns the discretization / number of segments of the core.
    ///
    /// Depending on its [`AirGap`], a core may be composed of multiple
    /// individual segments  against each other as defined by the
    /// [`CoreExt::skew_angle`]. This affects the [`skew_factor`] of the core,
    /// which can be used to suppress unwanted magnetic harmonics. See the
    /// docstrings of [`CoreExt::skew_angle`] and [`skew_factor`] for details.
    /// If this value is zero, the core is continuously skewed. If it is one,
    /// the component is not skewed at all, as it consists of a single straight
    /// (non-twisted) segment.
    ///
    /// This method forwards to [`AirGap::num_segments`], using `self` as the
    /// second argument.
    fn num_segments(&self) -> usize {
        return self.air_gap().num_segments(self.as_core_ref());
    }

    /// Returns the staggering angle of a particular `segment`.
    ///
    /// Each segment in a staggered laminated core has the same angular offset
    /// to its neighbors:
    ///
    /// `offset_angle = skew_angle / num_segments`.
    ///
    /// The segment count starts at zero, the last segment of a staggered
    /// component has therefore the index `num_segments-1`.
    ///
    /// The angle is given relative to the reference axis, which intersects the
    /// skew angle line at its middle. Therefore, the sum of all segment angles
    /// is always zero.
    #[doc = ""]
    #[cfg_attr(feature = "doc-images", doc = "![Staggering angle][segment_angle]")]
    #[cfg_attr(
        feature = "doc-images",
        embed_doc_image::embed_doc_image("segment_angle", "docs/img/cad_segment_angle.svg")
    )]
    #[cfg_attr(
        not(feature = "doc-images"),
        doc = "**Doc images not enabled**. Compile docs with
        `cargo doc --features 'doc-images'` and Rust version >= 1.54."
    )]
    ///
    /// If [`CoreExt::num_segments`] is zero, this method just returns 0.
    /// Otherwise, it forwards to [`segment_angle`], using
    /// [`CoreExt::skew_angle`] and [`CoreExt::num_segments`] as the second and
    /// third argument.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::sync::Arc;
    ///
    /// use approxim::assert_abs_diff_eq;
    /// use stem_core::prelude::*;
    ///
    /// let mut ag = PlainAirGap::default();
    /// ag.num_segments = 3;
    ///
    /// let core: RotCore = RotCoreBuilder {
    ///     air_gap_radius: Length::new::<millimeter>(55.0),
    ///     yoke_radius: Length::new::<millimeter>(90.0),
    ///     axial_length: Length::new::<millimeter>(165.0),
    ///     axial_coil_overhang: Length::new::<millimeter>(0.0),
    ///     iron_fill_factor: 1.0,
    ///     material: Arc::new(Material::default()),
    ///     pole_pairs: 2.try_into().expect("not zero"),
    ///     skew_angle: 6.0,
    ///     air_gap: Box::new(ag),
    ///     flux_barrier: None,
    /// }
    /// .try_into()
    /// .unwrap();
    ///
    /// assert_abs_diff_eq!(core.segment_angle(0), -2.0);
    /// assert_abs_diff_eq!(core.segment_angle(1), 0.0);
    /// assert_abs_diff_eq!(core.segment_angle(2), 2.0);
    /// ```
    fn segment_angle(&self, segment: usize) -> f64 {
        match NonZeroUsize::new(self.num_segments()) {
            Some(num_segments) => segment_angle(segment, self.skew_angle(), num_segments),
            None => 0.0,
        }
    }

    /// Returns an iterator over the [`PositionedZoneContour`]s for the given
    /// `coil_layout`.
    ///
    /// If a core [`is_windable`](CoreExt::is_windable), this iterator returns
    /// the contours of all of its winding zones positioned relative to the
    /// [`CoreExt::shape`] of `self`. The winding zone contours shape and
    /// positions depend on the [`AirGap`] of the core: For example, the winding
    /// zones of a [`SlottedAirGap`](crate::air_gap::SlottedAirGap) are inside
    /// its slots, whereas those of a
    /// [`PlainAirGap`](crate::air_gap::PlainAirGap) are located on the top of
    /// the air gap contour / inside the air gap itself. The image below
    /// shows the contours and their return order for the aforementioned
    /// examples of a slotted and a plain air gap with
    /// a [`CoilLayout::DoubleVertical`].
    #[doc = ""]
    #[cfg_attr(
        feature = "doc-images",
        doc = "![Winding zones for a slotted and a plain air gap][winding_zones]"
    )]
    #[cfg_attr(
        feature = "doc-images",
        embed_doc_image::embed_doc_image("winding_zones", "docs/img/winding_zones.svg")
    )]
    #[cfg_attr(
        not(feature = "doc-images"),
        doc = "**Doc images not enabled**. Compile docs with
        `cargo doc --features 'doc-images'` and Rust version >= 1.54."
    )]
    /// _This image was produced with `examples/winding_zones.rs`._
    ///
    /// This method forwards to [`AirGap::winding_zones`], using `self` as the
    /// second and `coil_layout` as the third argument. The
    /// [`winding_zones`](crate::winding_zones) module provides the returned
    /// [`WindingZones`] iterator and has further information.
    ///
    /// # Examples
    ///
    /// The number of winding zones is equal to the number of slots times the
    /// number of [`CoilLayout::layers`].
    ///
    /// ```
    /// use std::f64::consts::PI;
    /// use std::sync::Arc;
    ///
    /// use stem_core::prelude::*;
    ///
    /// let slot: SemiTrapezoidSlot = SemiTrapezoidWithoutSlopesBuilder {
    ///     bottom_width: Length::new::<millimeter>(9.0),
    ///     opening_width: Length::new::<millimeter>(2.0),
    ///     height: Length::new::<millimeter>(20.0),
    ///     opening_height: Length::new::<millimeter>(2.0),
    ///     slot_angle: 10.0 * PI / 180.0,
    ///     bottom_radius: Length::new::<millimeter>(2.0),
    ///     top_radius: Length::new::<millimeter>(1.0),
    ///     opening_radius: Length::new::<millimeter>(0.0),
    ///     consider_tooth_tip_leakage: true,
    /// }
    /// .try_into()
    /// .unwrap();
    ///
    /// let air_gap_slotted = SlottedAirGap::new(36.try_into().expect("not zero"), false, CarterFactorModel::Bin12, Arc::new(slot));
    ///
    /// let core: RotCore = RotCoreBuilder {
    ///     air_gap_radius: Length::new::<millimeter>(55.0),
    ///     yoke_radius: Length::new::<millimeter>(90.0),
    ///     axial_length: Length::new::<millimeter>(165.0),
    ///     axial_coil_overhang: Length::new::<millimeter>(0.0),
    ///     iron_fill_factor: 1.0,
    ///     material: Arc::new(Material::default()),
    ///     pole_pairs: 2.try_into().expect("not zero"),
    ///     skew_angle: 0.0,
    ///     air_gap: Box::new(air_gap_slotted),
    ///     flux_barrier: None,
    /// }
    /// .try_into()
    /// .unwrap();
    ///
    /// let coil_layout = CoilLayout::Quadruple;
    ///
    /// let zones: Vec<PositionedZoneContour> = core.winding_zones(&coil_layout).collect();
    /// assert_eq!(zones.len(), usize::from(coil_layout.layers().get()) * usize::from(core.slots()));
    /// assert_eq!(zones.len(), 4 * 36);
    /// ```
    fn winding_zones(&self, coil_layout: &CoilLayout) -> WindingZones {
        return self
            .air_gap()
            .winding_zones(self.as_core_ref(), coil_layout);
    }

    /// Returns the contour of the winding zone, if it exists.
    ///
    /// This method returns the [`nth`](WindingZones::nth) contour of the
    /// [`WindingZones`] iterator created by [`CoreExt::winding_zones`]. `n` is
    /// calculated as:
    ///
    /// `n = zone.slot * coil_layout.layers().get() + zone.layer`
    fn winding_zone_at(
        &self,
        coil_layout: &CoilLayout,
        zone: stem_slot::stem_types::Zone,
    ) -> Option<Contour> {
        let layers = coil_layout.layers().get();
        if zone.layer >= layers || zone.slot >= self.slots() {
            return None;
        }

        let n = zone.slot * layers + zone.layer;
        self.winding_zones(coil_layout)
            .nth(n.into())
            .map(|pc| pc.contour)
    }

    /// Returns an iterator over the surface
    /// [`PositionedMagnetShape`](crate::magnets::PositionedMagnetShape)s for
    /// the given `magnet_assembly`.
    ///
    /// This method takes the magnet out of the provided `magnet_assembly` and
    /// retrieves the magnet nort and south shapes if `split` is true or the
    /// full magnet shape otherwise (see [`Magnet::shape`] and
    /// [`Magnet::north_south_shapes`]) and positions them along the air gap
    /// relative to the [`CoreExt::shape`] of `self`. The number of magnets
    /// positioned next to each other on a single pole is defined via
    /// [`MagnetAssembly::num_tangential`]. This assembly is then repeated for
    /// each pole. The total number of elements returned by the iterator is
    /// therefore `magnet_assembly.num_tangential() * (1 + split) *
    /// self.poles()`. Since there is only one type of magnet assembly on the
    /// surface by definition,
    /// [`PositionedMagnetShape::magnet_type`](crate::magnets::PositionedMagnetShape::magnet_type)
    /// is always 0.
    ///
    /// The positioning itself is done by [`AirGap::surface_magnets`], using
    /// `self` as the second, `magnet_assembly` as the third and `split` as the
    /// fourth argument. The image below shows two examples: On the left a
    /// [`PlainAirGap`](crate::air_gap::PlainAirGap) and on the right a
    /// [`StraightIndentsAirGap`](crate::air_gap::StraightIndentsAirGap).
    #[doc = ""]
    #[cfg_attr(
        feature = "doc-images",
        doc = "![Surface magnets for a plain and an indent air gap][surface_magnets]"
    )]
    #[cfg_attr(
        feature = "doc-images",
        embed_doc_image::embed_doc_image("surface_magnets", "docs/img/surface_magnets.svg")
    )]
    #[cfg_attr(
        not(feature = "doc-images"),
        doc = "**Doc images not enabled**. Compile docs with
        `cargo doc --features 'doc-images'` and Rust version >= 1.54."
    )]
    /// _This image was produced with `examples/surface_magnets.rs`._
    ///
    /// # Examples
    ///
    /// The number of magnet shapes is equal to the number of poles times
    /// [`MagnetAssembly::num_tangential`] times (1 + split).
    ///
    /// ```
    /// use std::f64::consts::FRAC_PI_2;
    /// use std::sync::Arc;
    ///
    /// use stem_core::prelude::*;
    ///
    /// let core: RotCore = RotCoreBuilder {
    ///     air_gap_radius: Length::new::<millimeter>(55.0),
    ///     yoke_radius: Length::new::<millimeter>(90.0),
    ///     axial_length: Length::new::<millimeter>(165.0),
    ///     axial_coil_overhang: Length::new::<millimeter>(0.0),
    ///     iron_fill_factor: 1.0,
    ///     material: Arc::new(Material::default()),
    ///     pole_pairs: 2.try_into().expect("not zero"),
    ///     skew_angle: 0.0,
    ///     air_gap: Box::new(PlainAirGap::default()),
    ///     flux_barrier: None,
    /// }
    /// .try_into()
    /// .unwrap();
    ///
    /// let magnet = ArcParallelMagnet::with_const_thickness(
    ///    core.axial_length(),
    ///    core.air_gap_radius(),
    ///    SideHeightOrThickness::Thickness(Length::new::<millimeter>(4.0)),
    ///    AngleOrWidth::Angle(0.7 * FRAC_PI_2 / 2.0),
    ///    Arc::new(Material::default()),
    /// ).unwrap();
    /// let surface_magnets = MagnetAssembly::new(magnet, 1.try_into().unwrap(), 2.try_into().unwrap());
    ///
    /// let split = true;
    /// let magnets: Vec<PositionedMagnetShape> = core.surface_magnets(&surface_magnets, split).collect();
    /// assert_eq!(magnets.len(), (1 + usize::from(split)) * usize::from(core.poles().get()) * usize::from(surface_magnets.num_tangential().get()));
    /// assert_eq!(magnets.len(), 16);
    /// for m in magnets.iter() {
    ///     assert_eq!(m.magnet_type, 0);
    /// }
    ///
    /// let split = false;
    /// let magnets: Vec<PositionedMagnetShape> = core.surface_magnets(&surface_magnets, split).collect();
    /// assert_eq!(magnets.len(), (1 + usize::from(split)) * usize::from(core.poles().get()) * usize::from(surface_magnets.num_tangential().get()));
    /// assert_eq!(magnets.len(), 8);
    /// for m in magnets.iter() {
    ///     assert_eq!(m.magnet_type, 0);
    /// }
    /// ```
    fn surface_magnets(&self, magnet_assembly: &MagnetAssembly, split: bool) -> Magnets {
        return self
            .air_gap()
            .surface_magnets(self.as_core_ref(), magnet_assembly, split);
    }

    /// Returns the total number of surface magnets mounted on `self`.
    ///
    /// A `magnet_assembly` instance is mounted on each pole of `self`. Hence,
    /// the total number of magnets is `magnet_assembly.num_magnets() *
    /// self.poles()`.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::f64::consts::FRAC_PI_2;
    /// use std::sync::Arc;
    ///
    /// use stem_core::prelude::*;
    ///
    /// let core: RotCore = RotCoreBuilder {
    ///     air_gap_radius: Length::new::<millimeter>(55.0),
    ///     yoke_radius: Length::new::<millimeter>(90.0),
    ///     axial_length: Length::new::<millimeter>(165.0),
    ///     axial_coil_overhang: Length::new::<millimeter>(0.0),
    ///     iron_fill_factor: 1.0,
    ///     material: Arc::new(Material::default()),
    ///     pole_pairs: 2.try_into().expect("not zero"),
    ///     skew_angle: 0.0,
    ///     air_gap: Box::new(PlainAirGap::default()),
    ///     flux_barrier: None,
    /// }
    /// .try_into()
    /// .unwrap();
    ///
    /// let magnet = ArcParallelMagnet::with_const_thickness(
    ///    core.axial_length(),
    ///    core.air_gap_radius(),
    ///    SideHeightOrThickness::Thickness(Length::new::<millimeter>(4.0)),
    ///    AngleOrWidth::Angle(0.7 * FRAC_PI_2 / 2.0),
    ///    Arc::new(Material::default()),
    /// ).unwrap();
    /// let surface_magnets = MagnetAssembly::new(magnet, 3.try_into().unwrap(), 2.try_into().unwrap());
    ///
    /// assert_eq!(core.num_surface_magnets(&surface_magnets).get(), usize::from(core.poles().get()) * usize::from(surface_magnets.num_magnets().get()));
    /// assert_eq!(core.num_surface_magnets(&surface_magnets).get(), 24);
    /// ```
    fn num_surface_magnets(&self, magnet_assembly: &MagnetAssembly) -> NonZeroUsize {
        return NonZeroUsize::new(
            usize::from(self.poles().get()) * magnet_assembly.num_magnets().get(),
        )
        .expect("product of two nonzeros is nonzero");
    }

    /// Returns an iterator over the interior
    /// [`PositionedMagnetShape`](crate::magnets::PositionedMagnetShape)s within
    /// the flux barrier of `self`.
    ///
    /// If the core has a flux barrier ([`CoreExt::flux_barrier`] returns
    /// `Some`), it may also have interior magnets. The type(s), shape(s) and
    /// positioning of those magnets depend entirely on the [`FluxBarrier`]
    /// implementation, see [`FluxBarrier::magnet_assemblies`] and
    /// [`FluxBarrier::interior_magnets`] for details. Similar to
    /// [`CoreExt::surface_magnets`], the shapes returned by the [`Magnets`]
    /// iterator are already positioned relative to that returned by
    /// [`CoreExt::shape`]. The `split` argument is forwarded to
    /// [`FluxBarrier::interior_magnets`].
    ///
    /// The positioning itself is done by [`FluxBarrier::interior_magnets`],
    /// using `self` as the second and `split` as the third argument. The
    /// image below shows two examples: On the left a linear core
    /// and on the right a rotary core, both containing a
    /// [`Spoke1FluxBarrier`](crate::flux_barrier::Spoke1FluxBarrier).
    #[doc = ""]
    #[cfg_attr(
        feature = "doc-images",
        doc = "![Interior magnets for a linear and a rotary motor][lin_and_rot_core_interior_magnets]"
    )]
    #[cfg_attr(
        feature = "doc-images",
        embed_doc_image::embed_doc_image(
            "lin_and_rot_core_interior_magnets",
            "docs/img/lin_and_rot_core_interior_magnets.svg"
        )
    )]
    #[cfg_attr(
        not(feature = "doc-images"),
        doc = "**Doc images not enabled**. Compile docs with
        `cargo doc --features 'doc-images'` and Rust version >= 1.54."
    )]
    /// _This image was produced with `examples/lin_and_rot_core_plots.rs`._
    ///
    /// # Examples
    ///
    /// For the shown case of a linear core with a
    /// [`Spoke1FluxBarrier`](crate::flux_barrier::Spoke1FluxBarrier), the
    /// number of magnet shapes equals the number of poles times 1 plus
    /// `split`.
    ///
    /// ```
    /// use std::sync::Arc;
    ///
    /// use stem_core::prelude::*;
    ///
    /// let fb = Spoke1FluxBarrier {
    ///     air_gap_leakage_path_width: Length::new::<millimeter>(1.0),
    ///     yoke_leakage_path_width: Length::new::<millimeter>(1.0),
    ///     relief_path_air_gap_width: Length::new::<millimeter>(0.0),
    ///     magnet_space_width: Length::new::<millimeter>(10.0),
    ///     height_split: Spoke1HeightSplit::ReliefPathWidth(Length::new::<
    ///         millimeter,
    ///     >(0.0)),
    ///     glue_gap: Length::new::<millimeter>(0.5),
    ///     magnet_material: Some(Arc::new(Material::default())),
    ///     cache: None,
    /// };
    ///
    /// let core: LinCore = LinCoreBuilder {
    ///     height: Length::new::<millimeter>(20.0),
    ///     width: Length::new::<millimeter>(150.0),
    ///     axial_length: Length::new::<millimeter>(100.0),
    ///     axial_coil_overhang: Length::new::<millimeter>(0.0),
    ///     skew_angle: 0.0,
    ///     iron_fill_factor: 1.0,
    ///     material: Arc::new(Material::default()),
    ///     pole_pairs: 3.try_into().expect("not zero"),
    ///     air_gap: Box::new(PlainAirGap::default()),
    ///     flux_barrier: Some(Box::new(fb)),
    /// }
    /// .try_into().expect("valid inputs");
    ///
    /// let magnets_per_pole: usize = core.interior_magnet_assemblies().iter().map(|m|m.num_magnets().get()).sum();
    ///
    /// let split = true;
    /// let zones: Vec<PositionedMagnetShape> = core.interior_magnets(split).collect();
    /// assert_eq!(zones.len(), (1 + usize::from(split)) * magnets_per_pole * usize::from(core.poles().get()));
    /// assert_eq!(zones.len(), 12);
    ///
    /// let split = false;
    /// let zones: Vec<PositionedMagnetShape> = core.interior_magnets(split).collect();
    /// assert_eq!(zones.len(), (1 + usize::from(split)) * magnets_per_pole * usize::from(core.poles().get()));
    /// assert_eq!(zones.len(), 6);
    /// ```
    ///
    /// If the core has no flux barrier, the iterator is always empty.
    ///
    /// ```
    /// use std::sync::Arc;
    ///
    /// use stem_core::prelude::*;
    ///
    /// let core: LinCore = LinCoreBuilder {
    ///     height: Length::new::<millimeter>(20.0),
    ///     width: Length::new::<millimeter>(150.0),
    ///     axial_length: Length::new::<millimeter>(100.0),
    ///     axial_coil_overhang: Length::new::<millimeter>(0.0),
    ///     skew_angle: 0.0,
    ///     iron_fill_factor: 1.0,
    ///     material: Arc::new(Material::default()),
    ///     pole_pairs: 3.try_into().expect("not zero"),
    ///     air_gap: Box::new(PlainAirGap::default()),
    ///     flux_barrier: None,
    /// }
    /// .try_into().expect("valid inputs");
    ///
    /// let zones: Vec<PositionedMagnetShape> = core.interior_magnets(true).collect();
    /// assert!(zones.is_empty());
    /// ```
    fn interior_magnets(&self, split: bool) -> Magnets {
        match self.flux_barrier() {
            Some(fb) => fb.interior_magnets(self.as_core_ref(), split),
            None => {
                // Empty iterator
                Magnets::from_iter([].into_iter())
            }
        }
    }

    /// Returns all different magnet assemblies placed within the flux barrier,
    /// if the core has one.
    ///
    /// If [`CoreExt::flux_barrier`] returns a [`FluxBarrier`], this method
    /// forwards to [`FluxBarrier::magnet_assemblies`], see its docstring for
    /// details. Otherwise it just returns an empty slice.
    fn interior_magnet_assemblies(&self) -> &[MagnetAssembly] {
        match self.flux_barrier() {
            Some(fb) => fb.magnet_assemblies(self.as_core_ref()),
            None => &[],
        }
    }

    /// Returns the total mass of all surface magnets mounted on `self`.
    ///
    /// A `magnet_assembly` instance is mounted on each pole of `self`. Hence,
    /// the total magnet mass is `magnet_assembly.mass() * self.poles()`.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::f64::consts::FRAC_PI_2;
    /// use std::sync::Arc;
    ///
    /// use approxim::assert_abs_diff_eq;
    ///
    /// use stem_core::prelude::*;
    ///
    /// let core: RotCore = RotCoreBuilder {
    ///     air_gap_radius: Length::new::<millimeter>(55.0),
    ///     yoke_radius: Length::new::<millimeter>(90.0),
    ///     axial_length: Length::new::<millimeter>(165.0),
    ///     axial_coil_overhang: Length::new::<millimeter>(0.0),
    ///     iron_fill_factor: 1.0,
    ///     material: Arc::new(Material::default()),
    ///     pole_pairs: 2.try_into().expect("not zero"),
    ///     skew_angle: 0.0,
    ///     air_gap: Box::new(PlainAirGap::default()),
    ///     flux_barrier: None,
    /// }
    /// .try_into()
    /// .unwrap();
    ///
    /// let magnet = ArcParallelMagnet::with_const_thickness(
    ///    core.axial_length(),
    ///    core.air_gap_radius(),
    ///    SideHeightOrThickness::Thickness(Length::new::<millimeter>(4.0)),
    ///    AngleOrWidth::Angle(0.7 * FRAC_PI_2 / 2.0),
    ///    Arc::new(Material::default()),
    /// ).unwrap();
    /// let surface_magnets = MagnetAssembly::new(magnet, 3.try_into().unwrap(), 2.try_into().unwrap());
    ///
    /// assert_eq!(
    ///     core.mass_surface_magnets(&surface_magnets).eval(&[]),
    ///     core.poles().get() as f64 * surface_magnets.mass().eval(&[])
    /// );
    /// assert_abs_diff_eq!(core.mass_surface_magnets(&surface_magnets).eval(&[]).get::<kilogram>(), 0.478546, epsilon=1e-6);
    /// ```
    fn mass_surface_magnets(&self, magnet_assembly: &MagnetAssembly) -> VarQuantity<Mass> {
        return VarQuantity::from(f64::from(self.poles().get())) * magnet_assembly.mass();
    }

    /// Returns the total mass of all interior magnets mounted in the flux
    /// barrier of `self`.
    ///
    /// This method calculates the mass of all magnets within a single pole with
    /// `self.interior_magnet_assemblies().iter().map(|m| m.mass()).sum()`. The
    /// resulting number is then simply multiplied with [`CoreExt::poles`]. See
    /// [`CoreExt::interior_magnet_assemblies`] for details.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::f64::consts::FRAC_PI_2;
    /// use std::sync::Arc;
    ///
    /// use approxim::assert_abs_diff_eq;
    ///
    /// use stem_core::prelude::*;
    ///
    /// let fb = V1rFluxBarrier {
    ///     yoke_distance: Length::new::<millimeter>(4.5),
    ///     relief_path_air_gap_width: Length::new::<millimeter>(3.5),
    ///     relief_path_length: Length::new::<millimeter>(1.33),
    ///     relief_path_width: Length::new::<millimeter>(4.0),
    ///     opening_angle: FRAC_PI_2,
    ///     magnet_space_width: Length::new::<millimeter>(10.0),
    ///     magnet_space_height: Length::new::<millimeter>(20.0),
    ///     glue_gap: Length::new::<millimeter>(0.2),
    ///     leakage_path_width: Length::new::<millimeter>(1.0),
    ///     magnet_material: Some(Arc::new(Material::default())),
    ///     cache: None,
    /// };
    ///
    /// let core: RotCore = RotCoreBuilder {
    ///     air_gap_radius: Length::new::<millimeter>(55.0),
    ///     yoke_radius: Length::new::<millimeter>(18.0),
    ///     axial_length: Length::new::<millimeter>(165.0),
    ///     axial_coil_overhang: Length::new::<millimeter>(0.0),
    ///     iron_fill_factor: 1.0,
    ///     material: Arc::new(Material::default()),
    ///     pole_pairs: 2.try_into().expect("not zero"),
    ///     skew_angle: 0.0,
    ///     air_gap: Box::new(PlainAirGap::default()),
    ///     flux_barrier: Some(Box::new(fb)),
    /// }
    /// .try_into()
    /// .unwrap();
    ///
    /// assert_abs_diff_eq!(core.mass_interior_magnets().eval(&[]).get::<kilogram>(), 0.264, epsilon=1e-6);
    /// ```
    fn mass_interior_magnets(&self) -> VarQuantity<Mass> {
        let mass_per_pole: VarQuantity<Mass> = self
            .interior_magnet_assemblies()
            .iter()
            .map(|m| m.mass())
            .sum();
        return mass_per_pole * VarQuantity::from(f64::from(self.poles().get()));
    }

    /// Returns the number of "slots" for a winding.
    ///
    /// A "slot" in this context is a space for winding coils which contains one
    /// or more layers (see [`CoilLayout`]). This space can be an actual
    /// [`Slot`] (e.g., for a [`SlottedAirGap`](crate::air_gap::SlottedAirGap)),
    /// but doesn't necessarily need to be. For example, the "slots" for a
    /// [`PlainAirGap`](crate::air_gap::PlainAirGap) are the coil mounting
    /// points on the air gap surface. In this example image, both cores have
    /// 24 slots separated in two layers:
    #[doc = ""]
    #[cfg_attr(
        feature = "doc-images",
        doc = "![Winding zones for a slotted and a plain air gap][winding_zones]"
    )]
    #[cfg_attr(
        feature = "doc-images",
        embed_doc_image::embed_doc_image("winding_zones", "docs/img/winding_zones.svg")
    )]
    #[cfg_attr(
        not(feature = "doc-images"),
        doc = "**Doc images not enabled**. Compile docs with
        `cargo doc --features 'doc-images'` and Rust version >= 1.54."
    )]
    /// _This image was produced with `examples/winding_zones.rs`._
    ///
    /// This method forwards to [`AirGap::slots`], using `self` as the second
    /// argument.
    fn slots(&self) -> u16 {
        return self.air_gap().slots(self.as_core_ref());
    }

    /**
    Returns the slot opening factor for the harmonic with the specified
    `spatial_order`.

    Multiplying the absolute of this factor with the corresponding harmonic
    amplitude for the idealized case returns the actual harmonic amplitude.

    This method forwards to [`AirGap::slot_opening_factor`], using `self` as the
    second and `spatial_order` as the third argument. That method in turn is
    usually implemented with the
    [`slot_opening_factor`](crate::air_gap::slot_opening_factor) function. See
    its documentation for the physical background.

    # Examples

    ```
    use std::f64::consts::FRAC_PI_2;
    use std::sync::Arc;

    use approxim::assert_abs_diff_eq;

    use stem_core::prelude::*;

    // 80 % of a slot pitch is covered by coils
    let air_gap = PlainAirGap {
        num_segments: 0,
        air_gap_winding_height: Length::new::<millimeter>(1.0),
        winding_coverage: 0.8,
        starts_in_slot_middle: true,
        slots: 36,
    };
    let core: RotCore = RotCoreBuilder {
        air_gap_radius: Length::new::<millimeter>(55.0),
        yoke_radius: Length::new::<millimeter>(18.0),
        axial_length: Length::new::<millimeter>(165.0),
        axial_coil_overhang: Length::new::<millimeter>(0.0),
        iron_fill_factor: 1.0,
        material: Arc::new(Material::default()),
        pole_pairs: 2.try_into().expect("not zero"),
        skew_angle: 0.0,
        air_gap: Box::new(air_gap),
        flux_barrier: None,
    }
    .try_into()
    .unwrap();

    // Electrical fundamental / second mechanical spatial harmonic
    assert_abs_diff_eq!(
        core.slot_opening_factor(SpatialOrder::Mechanical(2)),
        0.996754,
        epsilon = 1e-6
    );

    // Electrical 5th and 7th harmonics
    assert_abs_diff_eq!(
        core.slot_opening_factor(SpatialOrder::Mechanical(10)),
        0.920725,
        epsilon = 1e-6
    );
    assert_abs_diff_eq!(
        core.slot_opening_factor(SpatialOrder::Mechanical(14)),
        0.848221,
        epsilon = 1e-6
    );
    ```
     */
    fn slot_opening_factor(&self, spatial_order: SpatialOrder) -> f64 {
        return self
            .air_gap()
            .slot_opening_factor(self.as_core_ref(), spatial_order);
    }

    /**
    Returns the curvature factor for the specified spatial order.

    The analytical analysis of the air gap field usually assumes a flat air gap.
    While this matches the actual conditions for a
    [`LinCore`](crate::core::LinCore), it will obviously result in incorrect
    values for a [`RotCore`](crate::core::RotCore), with the deviation becoming
    larger for smaller air gap radii (larger curvature) and larger air gaps.
    Multiplying the air gap field amplitude of the given spatial order by this
    factor corrects this difference. Usually, this is already done earlier in
    the analysis workflow by multiplying the winding factor with the curvature
    factor. Note that for an inner core, this value will be larger than 1, while
    it will be smaller than 1 for an outer core.

    For a [`LinCore`](crate::core::LinCore), this value is always 1. For a
    [`RotCore`](crate::core::RotCore), it is calculated using the
    [`air_gap_curvature_factor`](crate::core::air_gap_curvature_factor)
    function. The documentation of that function contains the mathematical
    details. The needed radii are derived from the
    [`RotCore::air_gap_radius`](crate::core::RotCore::air_gap_radius) and the
    provided `effective_air_gap`. The effective air gap results from the
    geometrical air gap by mulitplication with the [`CoreExt::carter_factor`].

    # Examples

    ```
    use std::sync::Arc;

    use approxim::assert_abs_diff_eq;

    use stem_core::prelude::*;

    // Outer core with larger radius
    let core: RotCore = RotCoreBuilder {
        air_gap_radius: Length::new::<millimeter>(50.0),
        yoke_radius: Length::new::<millimeter>(70.0),
        axial_length: Length::new::<millimeter>(165.0),
        axial_coil_overhang: Length::new::<millimeter>(0.0),
        iron_fill_factor: 1.0,
        material: Arc::new(Material::default()),
        pole_pairs: 2.try_into().expect("not zero"),
        skew_angle: 0.0,
        air_gap: Box::new(PlainAirGap::default()),
        flux_barrier: None,
    }
    .try_into()
    .unwrap();

    // Effect of the air gap on the electrical fundamental
    assert_abs_diff_eq!(
        core.air_gap_curvature_factor(Length::new::<millimeter>(1.0), SpatialOrder::Electrical(1)),
        0.990505,
        epsilon = 1e-6
    );
    assert_abs_diff_eq!(
        core.air_gap_curvature_factor(Length::new::<millimeter>(2.0), SpatialOrder::Electrical(1)),
        0.982040,
        epsilon = 1e-6
    );

    // Inner core with small radius
    let core: RotCore = RotCoreBuilder {
        air_gap_radius: Length::new::<millimeter>(20.0),
        yoke_radius: Length::new::<millimeter>(5.0),
        axial_length: Length::new::<millimeter>(165.0),
        axial_coil_overhang: Length::new::<millimeter>(0.0),
        iron_fill_factor: 1.0,
        material: Arc::new(Material::default()),
        pole_pairs: 2.try_into().expect("not zero"),
        skew_angle: 0.0,
        air_gap: Box::new(PlainAirGap::default()),
        flux_barrier: None,
    }
    .try_into()
    .unwrap();

    // Effect of the air gap on the electrical fundamental
    assert_abs_diff_eq!(
        core.air_gap_curvature_factor(Length::new::<millimeter>(1.0), SpatialOrder::Electrical(1)),
        1.028047,
        epsilon = 1e-6
    );
    assert_abs_diff_eq!(
        core.air_gap_curvature_factor(Length::new::<millimeter>(2.0), SpatialOrder::Electrical(1)),
        1.061883,
        epsilon = 1e-6
    );
    ```
     */
    fn air_gap_curvature_factor(
        &self,
        effective_air_gap: Length,
        spatial_order: SpatialOrder,
    ) -> f64;

    /// Returns the current displacement coefficients for a winding mounted on
    /// `self`.
    ///
    /// If a winding with massive conductors is mounted on the core, like for
    /// example a squirrel-cage winding, the resulting current displacement
    /// effects can lead to a notable increase in the effective coil resistance
    /// and to a decrease of the self-inductance. This effect is modelled via
    /// the [`CurrentDisplacementCalculator`] from the [stem_slot] crate. If the
    /// winding has distributed conductors, the current displacement effects can
    /// usually be neglected. This method assumes massive conductors and a
    /// single-layer winding and should not be used for other winding types.
    ///
    /// This method forwards to [`AirGap::current_displacement_coefficients`],
    /// using `self` as the second argument. If the
    /// [`air_gap`](CoreExt::air_gap) is a
    /// [`SlottedAirGap`](crate::air_gap::SlottedAirGap), the
    /// [`Slot::current_displacement_coefficients`] method gets invoked (for
    /// other air gap types, it depends on their respective implementation). See
    /// the docstring of [`Slot::current_displacement_coefficients`] for a
    /// general discussion on current displacement.
    fn current_displacement_coefficients(&self) -> CurrentDisplacementCalculator {
        return self
            .air_gap()
            .current_displacement_coefficients(self.as_core_ref());
    }

    /// Returns the slot type of the air gap.
    ///
    /// This method forwards to [`AirGap::slot`], using `self` as the second
    /// argument.
    fn slot(&self) -> Option<&dyn Slot> {
        return self.air_gap().slot(self.as_core_ref());
    }

    /// Returns the tooth height of the core.
    ///
    /// This method forwards to [`AirGap::tooth_height`] with `self` as the
    /// second argument. Usually, the returned value is the [`Slot::height`], as
    /// shown below, but the specific implementation may vary.
    #[doc = ""]
    #[cfg_attr(feature = "doc-images", doc = "![Yoke height][cad_yoke_tooth_height]")]
    #[cfg_attr(
        feature = "doc-images",
        embed_doc_image::embed_doc_image(
            "cad_yoke_tooth_height",
            "docs/img/cad_yoke_tooth_height.svg"
        )
    )]
    #[cfg_attr(
        not(feature = "doc-images"),
        doc = "**Doc images not enabled**. Compile docs with
        `cargo doc --features 'doc-images'` and Rust version >= 1.54."
    )]
    ///
    /// # Examples
    ///
    /// ```
    /// use std::f64::consts::PI;
    /// use std::sync::Arc;
    ///
    /// use approxim::assert_abs_diff_eq;
    ///
    /// use stem_core::prelude::*;
    ///
    /// let slot: SemiTrapezoidSlot = SemiTrapezoidWithoutSlopesBuilder {
    ///     bottom_width: Length::new::<millimeter>(9.0),
    ///     opening_width: Length::new::<millimeter>(2.0),
    ///     height: Length::new::<millimeter>(20.0),
    ///     opening_height: Length::new::<millimeter>(2.0),
    ///     slot_angle: 10.0 * PI / 180.0,
    ///     bottom_radius: Length::new::<millimeter>(2.0),
    ///     top_radius: Length::new::<millimeter>(1.0),
    ///     opening_radius: Length::new::<millimeter>(0.0),
    ///     consider_tooth_tip_leakage: true,
    /// }
    /// .try_into()
    /// .unwrap();
    ///
    /// let air_gap_slotted = SlottedAirGap::new(36.try_into().expect("not zero"), false, CarterFactorModel::Bin12, Arc::new(slot));
    ///
    /// let core: RotCore = RotCoreBuilder {
    ///     air_gap_radius: Length::new::<millimeter>(55.0),
    ///     yoke_radius: Length::new::<millimeter>(90.0),
    ///     axial_length: Length::new::<millimeter>(165.0),
    ///     axial_coil_overhang: Length::new::<millimeter>(0.0),
    ///     iron_fill_factor: 1.0,
    ///     material: Arc::new(Material::default()),
    ///     pole_pairs: 2.try_into().expect("not zero"),
    ///     skew_angle: 0.0,
    ///     air_gap: Box::new(air_gap_slotted),
    ///     flux_barrier: None,
    /// }
    /// .try_into()
    /// .unwrap();
    ///
    /// assert_abs_diff_eq!(core.tooth_height().get::<millimeter>(), 20.0, epsilon = 1e-6);
    /// ```
    fn tooth_height(&self) -> Length {
        return self.air_gap().tooth_height(self.as_core_ref());
    }

    /// Returns the tooth width at a specific height, measured from the air gap.
    ///
    /// This method forwards to [`AirGap::tooth_width_at`] with `self` as the
    /// second and `height` as the third argument. The coordinate system of
    /// `height` starts at the air gap and is perpendicular to it with positive
    /// values going inside the core. Essentially, it is the same coordinate
    /// system as that of a [`Slot`], just located in the tooth instead of in
    /// the slot middle.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::f64::consts::PI;
    /// use std::sync::Arc;
    ///
    /// use approxim::assert_abs_diff_eq;
    ///
    /// use stem_core::prelude::*;
    ///
    /// let slot: SemiTrapezoidSlot = SemiTrapezoidWithoutSlopesBuilder {
    ///     bottom_width: Length::new::<millimeter>(9.0),
    ///     opening_width: Length::new::<millimeter>(2.0),
    ///     height: Length::new::<millimeter>(20.0),
    ///     opening_height: Length::new::<millimeter>(2.0),
    ///     slot_angle: 10.0 * PI / 180.0,
    ///     bottom_radius: Length::new::<millimeter>(2.0),
    ///     top_radius: Length::new::<millimeter>(1.0),
    ///     opening_radius: Length::new::<millimeter>(0.0),
    ///     consider_tooth_tip_leakage: true,
    /// }
    /// .try_into()
    /// .unwrap();
    ///
    /// let air_gap_slotted = SlottedAirGap::new(36.try_into().expect("not zero"), false, CarterFactorModel::Bin12, Arc::new(slot));
    ///
    /// let core: RotCore = RotCoreBuilder {
    ///     air_gap_radius: Length::new::<millimeter>(55.0),
    ///     yoke_radius: Length::new::<millimeter>(90.0),
    ///     axial_length: Length::new::<millimeter>(165.0),
    ///     axial_coil_overhang: Length::new::<millimeter>(0.0),
    ///     iron_fill_factor: 1.0,
    ///     material: Arc::new(Material::default()),
    ///     pole_pairs: 2.try_into().expect("not zero"),
    ///     skew_angle: 0.0,
    ///     air_gap: Box::new(air_gap_slotted),
    ///     flux_barrier: None,
    /// }
    /// .try_into()
    /// .unwrap();
    ///
    /// assert_abs_diff_eq!(core.tooth_width_at(Length::new::<millimeter>(-1.0)).get::<millimeter>(), 0.0, epsilon = 1e-3);
    /// assert_abs_diff_eq!(core.tooth_width_at(Length::new::<millimeter>(1.0)).get::<millimeter>(), 7.767, epsilon = 1e-3);
    /// assert_abs_diff_eq!(core.tooth_width_at(Length::new::<millimeter>(5.0)).get::<millimeter>(), 4.106, epsilon = 1e-3);
    /// assert_abs_diff_eq!(core.tooth_width_at(Length::new::<millimeter>(30.0)).get::<millimeter>(), 14.815, epsilon = 1e-3);
    /// ```
    fn tooth_width_at(&self, height: Length) -> Length {
        return self.air_gap().tooth_width_at(self.as_core_ref(), height);
    }

    /// Returns whether a winding can be mounted on the core or not.
    ///
    /// A winding can be mounted if [`CoreExt::slots`] is not zero.
    fn is_windable(&self) -> bool {
        return self.slots() != 0;
    }

    /// Returns whether the core has slots.
    ///
    /// This method is implemented as `self.slot().is_some()`, i.e., the core is
    /// slotted if [`CoreExt::slot`] doesn't return `None`.
    fn slotted(&self) -> bool {
        return self.slot().is_some();
    }

    /// Returns the air gap surface area of the core.
    ///
    /// The air gap surface area is
    /// `self.axial_length() * self.air_gap_length()`, i.e., the area of the
    /// core body face which faces the air gap.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::sync::Arc;
    ///
    /// use approxim::assert_abs_diff_eq;
    ///
    /// use stem_core::prelude::*;
    ///
    /// let core: RotCore = RotCoreBuilder {
    ///     air_gap_radius: Length::new::<millimeter>(55.0),
    ///     yoke_radius: Length::new::<millimeter>(90.0),
    ///     axial_length: Length::new::<millimeter>(165.0),
    ///     axial_coil_overhang: Length::new::<millimeter>(0.0),
    ///     iron_fill_factor: 1.0,
    ///     material: Arc::new(Material::default()),
    ///     pole_pairs: 2.try_into().expect("not zero"),
    ///     skew_angle: 0.0,
    ///     air_gap: Box::new(PlainAirGap::default()),
    ///     flux_barrier: None
    /// }
    /// .try_into()
    /// .unwrap();
    ///
    /// assert_abs_diff_eq!(core.air_gap_area().get::<square_millimeter>(), 57019.906, epsilon = 1e-3);
    /// ```
    fn air_gap_area(&self) -> Area {
        return self.axial_length() * self.air_gap_length();
    }

    /**
    Returns [`CoreExt::shape`] wrapped in a [`DrawableCow`].

    This is a convenience function to simplify drawing the [`Shape`] of `self`.
     */
    #[cfg(feature = "cairo")]
    fn drawable(&self) -> planar_geo::draw::DrawableCow<'_> {
        let mut style = planar_geo::draw::Style::default();
        style.background_color = crate::GRAY;
        let shape = self.shape();
        return planar_geo::draw::DrawableCow::new(shape, style);
    }

    /// Returns the effective iron length of the core.
    ///
    /// This method returns the electromagnetically effective length of the core
    /// as the product of `self.iron_fill_factor()` and `self.axial_length()`.
    /// See [`CoreExt::iron_fill_factor`] for an explanation of the concept.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::sync::Arc;
    ///
    /// use approxim::assert_abs_diff_eq;
    ///
    /// use stem_core::prelude::*;
    ///
    /// let core: RotCore = RotCoreBuilder {
    ///     air_gap_radius: Length::new::<millimeter>(55.0),
    ///     yoke_radius: Length::new::<millimeter>(90.0),
    ///     axial_length: Length::new::<millimeter>(100.0),
    ///     axial_coil_overhang: Length::new::<millimeter>(0.0),
    ///     iron_fill_factor: 0.9,
    ///     material: Arc::new(Material::default()),
    ///     pole_pairs: 2.try_into().expect("not zero"),
    ///     skew_angle: 0.0,
    ///     air_gap: Box::new(PlainAirGap::default()),
    ///     flux_barrier: None
    /// }
    /// .try_into()
    /// .unwrap();
    ///
    /// // Iron fill factor of 90 % and axial length of 100 mm => iron length of 90 mm
    /// assert_abs_diff_eq!(core.iron_length().get::<millimeter>(), 90.0, epsilon = 1e-6);
    /// ```
    fn iron_length(&self) -> Length {
        return self.iron_fill_factor() * self.axial_length();
    }

    /// Returns the cross section area of the core.
    ///
    /// Since [`CoreExt::shape`] returns the cross section shape of `self`, this
    /// method simply calculates the area of that shape and wraps it in an
    /// [`Area`].
    ///
    /// # Examples
    ///
    /// ```
    /// use std::sync::Arc;
    ///
    /// use approxim::assert_abs_diff_eq;
    ///
    /// use stem_core::prelude::*;
    ///
    /// let core: RotCore = RotCoreBuilder {
    ///     air_gap_radius: Length::new::<millimeter>(55.0),
    ///     yoke_radius: Length::new::<millimeter>(90.0),
    ///     axial_length: Length::new::<millimeter>(100.0),
    ///     axial_coil_overhang: Length::new::<millimeter>(0.0),
    ///     iron_fill_factor: 0.9,
    ///     material: Arc::new(Material::default()),
    ///     pole_pairs: 2.try_into().expect("not zero"),
    ///     skew_angle: 0.0,
    ///     air_gap: Box::new(PlainAirGap::default()),
    ///     flux_barrier: None
    /// }
    /// .try_into()
    /// .unwrap();
    ///
    /// assert_abs_diff_eq!(core.cross_section_area().get::<square_millimeter>(), 15943.582, epsilon = 1e-3);
    /// ```
    fn cross_section_area(&self) -> Area {
        return Area::new::<square_meter>(self.shape().area());
    }

    /// Returns the volume of the core.
    ///
    /// For a radial flux machine, the cross section is constant along its
    /// axial length. Therefore, this value is the product of
    /// `self.cross_section_area()` and `self.axial_length()`.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::sync::Arc;
    ///
    /// use approxim::assert_abs_diff_eq;
    ///
    /// use stem_core::prelude::*;
    ///
    /// let core: RotCore = RotCoreBuilder {
    ///     air_gap_radius: Length::new::<millimeter>(55.0),
    ///     yoke_radius: Length::new::<millimeter>(90.0),
    ///     axial_length: Length::new::<millimeter>(100.0),
    ///     axial_coil_overhang: Length::new::<millimeter>(0.0),
    ///     iron_fill_factor: 0.9,
    ///     material: Arc::new(Material::default()),
    ///     pole_pairs: 2.try_into().expect("not zero"),
    ///     skew_angle: 0.0,
    ///     air_gap: Box::new(PlainAirGap::default()),
    ///     flux_barrier: None
    /// }
    /// .try_into()
    /// .unwrap();
    ///
    /// assert_abs_diff_eq!(core.volume().get::<cubic_millimeter>(), 1594358.271, epsilon = 1e-3);
    /// ```
    fn volume(&self) -> Volume {
        return self.cross_section_area() * self.axial_length();
    }

    /// Returns the mass of the core.
    ///
    /// The mass of the core is the product of the core material mass density,
    /// [`CoreExt::cross_section_area`] and [`CoreExt::iron_length`]. The mass
    /// of the insulation / glue is neglected, since the steel sheets of the
    /// lamination are much heavier.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::sync::Arc;
    ///
    /// use approxim::assert_abs_diff_eq;
    ///
    /// use stem_core::prelude::*;
    ///
    /// let core: RotCore = RotCoreBuilder {
    ///     air_gap_radius: Length::new::<millimeter>(55.0),
    ///     yoke_radius: Length::new::<millimeter>(90.0),
    ///     axial_length: Length::new::<millimeter>(100.0),
    ///     axial_coil_overhang: Length::new::<millimeter>(0.0),
    ///     iron_fill_factor: 0.9,
    ///     material: Arc::new(Material::default()),
    ///     pole_pairs: 2.try_into().expect("not zero"),
    ///     skew_angle: 0.0,
    ///     air_gap: Box::new(PlainAirGap::default()),
    ///     flux_barrier: None
    /// }
    /// .try_into()
    /// .unwrap();
    ///
    /// assert_abs_diff_eq!(core.mass().eval(&[]).get::<kilogram>(), 1.4349224, epsilon = 1e-6);
    /// ```
    fn mass(&self) -> VarQuantity<Mass> {
        VarQuantity::from(self.cross_section_area() * self.iron_length())
            * self.material().mass_density()
    }

    /// Returns the mass of all teeth.
    ///
    /// This function simply returns [`CoreExt::tooth_mass`] times
    /// [`CoreExt::slots`]. See the docstring of [`CoreExt::tooth_mass`] for
    /// details.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::f64::consts::PI;
    /// use std::sync::Arc;
    ///
    /// use approxim::assert_abs_diff_eq;
    ///
    /// use stem_core::prelude::*;
    ///
    /// let slot: SemiTrapezoidSlot = SemiTrapezoidWithoutSlopesBuilder {
    ///     bottom_width: Length::new::<millimeter>(9.0),
    ///     opening_width: Length::new::<millimeter>(2.0),
    ///     height: Length::new::<millimeter>(20.0),
    ///     opening_height: Length::new::<millimeter>(2.0),
    ///     slot_angle: 10.0 * PI / 180.0,
    ///     bottom_radius: Length::new::<millimeter>(2.0),
    ///     top_radius: Length::new::<millimeter>(1.0),
    ///     opening_radius: Length::new::<millimeter>(0.0),
    ///     consider_tooth_tip_leakage: true,
    /// }
    /// .try_into()
    /// .unwrap();
    ///
    /// let air_gap_slotted = SlottedAirGap::new(36.try_into().expect("not zero"), false, CarterFactorModel::Bin12, Arc::new(slot));
    ///
    /// let core: RotCore = RotCoreBuilder {
    ///     air_gap_radius: Length::new::<millimeter>(55.0),
    ///     yoke_radius: Length::new::<millimeter>(90.0),
    ///     axial_length: Length::new::<millimeter>(165.0),
    ///     axial_coil_overhang: Length::new::<millimeter>(0.0),
    ///     iron_fill_factor: 1.0,
    ///     material: Arc::new(Material::default()),
    ///     pole_pairs: 2.try_into().expect("not zero"),
    ///     skew_angle: 0.0,
    ///     air_gap: Box::new(air_gap_slotted),
    ///     flux_barrier: None,
    /// }
    /// .try_into()
    /// .unwrap();
    ///
    /// assert_abs_diff_eq!(core.teeth_mass().eval(&[]).get::<kilogram>(), core.tooth_mass().eval(&[]).get::<kilogram>() * core.slots() as f64, epsilon = 1e-3);
    /// assert_abs_diff_eq!(core.teeth_mass().eval(&[]).get::<kilogram>(), 0.5446, epsilon = 1e-3);
    /// ```
    fn teeth_mass(&self) -> VarQuantity<Mass> {
        return self.tooth_mass() * VarQuantity::from(self.slots() as f64);
    }

    /// Returns the mass of the yoke area.
    ///
    /// This is simply `self.mass() - self.teeth_mass()`.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::f64::consts::PI;
    /// use std::sync::Arc;
    ///
    /// use approxim::assert_abs_diff_eq;
    ///
    /// use stem_core::prelude::*;
    ///
    /// let slot: SemiTrapezoidSlot = SemiTrapezoidWithoutSlopesBuilder {
    ///     bottom_width: Length::new::<millimeter>(9.0),
    ///     opening_width: Length::new::<millimeter>(2.0),
    ///     height: Length::new::<millimeter>(20.0),
    ///     opening_height: Length::new::<millimeter>(2.0),
    ///     slot_angle: 10.0 * PI / 180.0,
    ///     bottom_radius: Length::new::<millimeter>(2.0),
    ///     top_radius: Length::new::<millimeter>(1.0),
    ///     opening_radius: Length::new::<millimeter>(0.0),
    ///     consider_tooth_tip_leakage: true,
    /// }
    /// .try_into()
    /// .unwrap();
    ///
    /// let air_gap_slotted = SlottedAirGap::new(36.try_into().expect("not zero"), false, CarterFactorModel::Bin12, Arc::new(slot));
    ///
    /// let core: RotCore = RotCoreBuilder {
    ///     air_gap_radius: Length::new::<millimeter>(55.0),
    ///     yoke_radius: Length::new::<millimeter>(90.0),
    ///     axial_length: Length::new::<millimeter>(165.0),
    ///     axial_coil_overhang: Length::new::<millimeter>(0.0),
    ///     iron_fill_factor: 1.0,
    ///     material: Arc::new(Material::default()),
    ///     pole_pairs: 2.try_into().expect("not zero"),
    ///     skew_angle: 0.0,
    ///     air_gap: Box::new(air_gap_slotted),
    ///     flux_barrier: None,
    /// }
    /// .try_into()
    /// .unwrap();
    ///
    /// assert_abs_diff_eq!(core.yoke_mass().eval(&[]).get::<kilogram>(), 1.283, epsilon = 1e-3);
    /// ```
    fn yoke_mass(&self) -> VarQuantity<Mass> {
        return self.mass() - VarQuantity::from(self.teeth_mass());
    }

    /// Returns the skew factor of the core for the given `spatial_order`.`
    ///
    /// This method forwards to the free function [`skew_factor`] with
    /// [`CoreExt::skew_angle`] and [`CoreExt::num_segments`] as the third and
    /// fourth argument. See the docstring of [`skew_factor`] for details and
    /// examples.
    fn skew_factor(&self, spatial_order: SpatialOrder) -> f64 {
        return skew_factor(
            self.skew_angle(),
            self.num_segments(),
            self.pole_pairs(),
            spatial_order,
        );
    }

    /**
    Returns the length of a half-coil turn inside the core.

    If the core is not skewed, this value is equal to the axial length of the
    core. If the core is skewed, the length of the half turn is increased due to
    the skewing. The corresponding formula is:
    `half_turn_length = axial_length / cos(skew_angle)`.

    # Examples

    ```
    use std::f64::consts::PI;
    use std::sync::Arc;

    use approxim::assert_abs_diff_eq;

    use stem_core::prelude::*;

    // Skewing by one slot pitch
    let air_gap = PlainAirGap::default();
    let core: RotCore = RotCoreBuilder {
        air_gap_radius: Length::new::<millimeter>(55.0),
        yoke_radius: Length::new::<millimeter>(18.0),
        axial_length: Length::new::<millimeter>(100.0),
        axial_coil_overhang: Length::new::<millimeter>(0.0),
        iron_fill_factor: 1.0,
        material: Arc::new(Material::default()),
        pole_pairs: 2.try_into().expect("not zero"),
        skew_angle: 10.0 / 180.0 * PI,
        air_gap: Box::new(air_gap),
        flux_barrier: None,
    }
    .try_into()
    .unwrap();

    assert_abs_diff_eq!(core.axial_coil_length().get::<millimeter>(), 101.543, epsilon = 1e-3);
    ```
     */
    fn axial_coil_length(&self) -> Length {
        return self.axial_length() / self.skew_angle().cos();
    }

    /**
    Returns the spatial order of the `k`-th slotting harmonic.

    When moving along the [`CoreExt::air_gap_length`] of a core, the slot openings
    cause a variation in the magnetic resistance / reluctance of the air gap.
    Plotting the air gap _permeance_ (inverse reluctance) over the air gap width
    will result in a straight line over the tooth heads interrupted by sudden drops
    in the slot opening area. This graph can be used to analytically assess the
    influence of the tooth head / slot opening geometry on phenomena such as cogging
    torque. To do that, the graph is disassembled into its harmonics via Fourier
    transformation.

    The orders are calculated by [\[1\]](#slotting_order_1), eq. (8):

    `o_mech = k * N`

    where `k = 1, 2, ...` and `N` is the number of slots.

    # Literature
    <a id="slotting_order_1">\[1\]</a>
    Huth, Gerhard: Nutrastung von permanenterregten AC-Servomotoren mit gestaffelter
    Rotoranordnung, Electrical Engineering 78 (1995), p. 391-397, Springer-Verlag
    */
    fn slotting_order(&self, k: NonZeroU32) -> SpatialOrder {
        return SpatialOrder::Mechanical(u32::from(self.slots()) * k.get());
    }

    /// Returns the offset of the first positive d-axis against the "start" of
    /// the core in electrical radians.
    ///
    /// The "start" of a linear core is its left edge when looking at the cross
    /// section; for a rotary core it is the x-axis. If there is no flux
    /// barrier, this value defaults to [`FRAC_PI_2`] (meaning that the
    /// start coincidences with a negative q-axis). If the core has a flux
    /// barrier, this method forwards to [`FluxBarrier::d_axis_offset`] and
    /// normalizes the returned value to be between 0 and 2 π.
    ///
    /// The following image shows why this factor is needed using the examples
    /// of a [`Spoke1FluxBarrier`](crate::flux_barrier::Spoke1FluxBarrier) and a
    /// [`V1rFluxBarrier`](crate::flux_barrier::V1rFluxBarrier): The former has
    /// an offset of 0 (for a linear core), because the magnet sits directly in
    /// the q-axis. Contrary, for the latter, the offset is [`FRAC_PI_2`] so
    /// the magnet assembly is not cut in half.
    #[doc = ""]
    #[cfg_attr(
        feature = "doc-images",
        doc = "![d-Axis offset from core start][d_axis_offset]"
    )]
    #[cfg_attr(
        feature = "doc-images",
        embed_doc_image::embed_doc_image("d_axis_offset", "docs/img/d_axis_offset.svg")
    )]
    #[cfg_attr(
        not(feature = "doc-images"),
        doc = "**Doc images not enabled**. Compile docs with
        `cargo doc --features 'doc-images'` and Rust version >= 1.54."
    )]
    ///
    /// `d_axis_offset` is even relevant when considering a rotary motor because
    /// it determines the position of the d-axis. This information is needed
    /// when placing surface magnets so they are located in the d-axes (as they
    /// should be).
    fn d_axis_offset(&self) -> f64 {
        match self.flux_barrier() {
            Some(fb) => fb
                .d_axis_offset(self.as_core_ref())
                .rem_euclid(std::f64::consts::TAU),
            None => FRAC_PI_2,
        }
    }
}

/**
Calculates the skew factor for a `spatial_order` for an either continuously
skewed or discretized core.

One way to suppress unwanted harmonics of the magnetic air gap field is to
"skew" or "stagger" a magnetic core. The docstring of [`CoreExt::skew_angle`]
contains background information.

This function calculates the "skew factor" for an harmonic with the specified
`spatial_order` where the core is skewed by the `skew_angle`. Multiplying
the skew factor with the amplitude of that harmonic calculated for the unskewed
core returns its resulting (actual) amplitude.

If `num_segments` is zero, the core is continuously twisted along its axial
length, otherwise it is composed of `num_segments` straight segments which are
shifted by `skew_angle / num_segments` against each other. In particular, this
means that for `num_segments`, the resulting skew factor is always 1 (as the
core is effectively unskewed). If the number of segments approach infinity, the
core is effectively continuously skewed and the resulting skew factor is
identical to that of `num_segments = 0`. These relations can be directly seen
from the formula for the staggered skew factor taken from
[\[1\]](#skew_factor_1), eq. (3) (`mech_order` is retrieved from `spatial_order`
with [`SpatialOrder::to_mechanical`]):

```text
skew_factor = sin(0.5 * mech_order * skew_angle) / (num_segments * sin(0.5 * mech_order * skew_angle / num_segments))
```

For `num_segments = 0`, the formula simplifies to [\[2\]](#skew_factor_2), eq.
(6.5-18):

```text
skew_factor = sin(0.5 * mech_order * skew_angle) / (0.5 * mech_order * skew_angle)
```

# Literature
<a id="skew_factor_1">\[1\]</a>
Huth, Gerhard: Nutrastung von permanenterregten AC-Servomotoren mit gestaffelter
Rotoranordnung, Electrical Engineering 78 (1995), p. 391-397, Springer-Verlag

<a id="skew_factor_2">\[2\]</a>
Binder, Andreas: Elektrische Maschinen und Antriebe (2012), Springer-Verlag,
Berlin Heidelberg

# Examples

## Continuous skewing

A core with 15 slots and 5 pole pairs produces cogging torque harmonics with
the mechanical orders 15, 30, 45 and so on due to the slotting. These can be
suppressed by skewing with a full slot pitch (360 / 15 = 24 degree)

```
use std::num::NonZeroU16;
use std::f64::consts::TAU;

use stem_core::core::skew_factor;
use stem_core::prelude::SpatialOrder;
use approxim::assert_abs_diff_eq;

let slots = 15;
let p = NonZeroU16::new(5).expect("not zero"); // pole pairs
let angle = TAU / slots as f64;
let num_segments = 0;

// All cogging harmonics are fully suppressed
for k in 1..100 {
    assert_abs_diff_eq!(skew_factor(angle, num_segments, p, SpatialOrder::Mechanical(slots * k)), 0.0, epsilon = 1e-5);
}

// Other harmonics like the first stator harmonic (which creates the torque)
// are reduced as well.
assert_abs_diff_eq!(skew_factor(angle, num_segments, p, SpatialOrder::Mechanical(p.get().into())), 0.82699, epsilon = 1e-5);
```

If especially the 30th order is problematic, it might be more sensible to
skew by 360 / 30 = 12 degree. This reduces the losses for the first harmonic
massively while still fully suppressing the 30th and its multiples.

```
use std::num::NonZeroU16;
use std::f64::consts::TAU;

use stem_core::core::skew_factor;
use stem_core::prelude::SpatialOrder;
use approxim::assert_abs_diff_eq;

let slots = 15;
let p = NonZeroU16::new(5).expect("not zero"); // pole pairs
let angle = 0.5 * TAU / slots as f64;
let num_segments = 0;

// Every second cogging harmonic is still fully suppressed
for k in 1..100 {
    assert_abs_diff_eq!(skew_factor(angle, num_segments, p, SpatialOrder::Mechanical(2 * slots * k)), 0.0, epsilon = 1e-5);
}

// Torque-creating harmonic is much less affected
assert_abs_diff_eq!(skew_factor(angle, num_segments, p, SpatialOrder::Mechanical(p.get().into())), 0.95493, epsilon = 1e-5);
```

## Staggering

As discussed above, having only one segment is equal to not skewing at all:

```
use std::num::NonZeroU16;
use std::f64::consts::TAU;

use stem_core::core::skew_factor;
use stem_core::prelude::SpatialOrder;
use approxim::assert_abs_diff_eq;

let slots = 15;
let p = NonZeroU16::new(5).expect("not zero"); // pole pairs
let angle = 0.5 * TAU / slots as f64;
let num_segments = 1;

// No suppression of any order
for k in 1..100 {
    assert_abs_diff_eq!(skew_factor(angle, num_segments, p, SpatialOrder::Mechanical(2 * slots * k)), 1.0, epsilon = 1e-5);
}
assert_abs_diff_eq!(skew_factor(angle, num_segments, p, SpatialOrder::Mechanical(p.get().into())), 1.0, epsilon = 1e-5);
```

With two segments, the 30th order can already be suppressed, but some of its
multiples aren't. By increasing the number of segments further, more and more
of these are suppressed as well. For a sufficiently high number of segments,
the staggered rotor behaves like the skewed one and suppresses all multiples.

```
use std::num::NonZeroU16;
use std::f64::consts::TAU;

use stem_core::core::skew_factor;
use stem_core::prelude::SpatialOrder;
use approxim::assert_abs_diff_eq;

let slots = 15;
let p = NonZeroU16::new(5).expect("not zero"); // pole pairs
let angle = 0.5 * TAU / slots as f64;

// Two segments
assert_abs_diff_eq!(skew_factor(angle, 2, p, SpatialOrder::Mechanical(2 * slots)), 0.0, epsilon = 1e-5);
assert_abs_diff_eq!(skew_factor(angle, 2, p, SpatialOrder::Mechanical(4 * slots)), -1.0, epsilon = 1e-5);
assert_abs_diff_eq!(skew_factor(angle, 2, p, SpatialOrder::Mechanical(6 * slots)), 0.0, epsilon = 1e-5);
assert_abs_diff_eq!(skew_factor(angle, 2, p, SpatialOrder::Mechanical(8 * slots)), 1.0, epsilon = 1e-5);
assert_abs_diff_eq!(skew_factor(angle, 2, p, SpatialOrder::Mechanical(p.get().into())), 0.96592, epsilon = 1e-5);

// Three segments
assert_abs_diff_eq!(skew_factor(angle, 3, p, SpatialOrder::Mechanical(2 * slots)), 0.0, epsilon = 1e-5);
assert_abs_diff_eq!(skew_factor(angle, 3, p, SpatialOrder::Mechanical(4 * slots)), 0.0, epsilon = 1e-5);
assert_abs_diff_eq!(skew_factor(angle, 3, p, SpatialOrder::Mechanical(6 * slots)), 1.0, epsilon = 1e-5);
assert_abs_diff_eq!(skew_factor(angle, 3, p, SpatialOrder::Mechanical(8 * slots)), 0.0, epsilon = 1e-5);
assert_abs_diff_eq!(skew_factor(angle, 3, p, SpatialOrder::Mechanical(p.get().into())), 0.95979, epsilon = 1e-5);

// Four segments
assert_abs_diff_eq!(skew_factor(angle, 4, p, SpatialOrder::Mechanical(2 * slots)), 0.0, epsilon = 1e-5);
assert_abs_diff_eq!(skew_factor(angle, 4, p, SpatialOrder::Mechanical(4 * slots)), 0.0, epsilon = 1e-5);
assert_abs_diff_eq!(skew_factor(angle, 4, p, SpatialOrder::Mechanical(6 * slots)), 0.0, epsilon = 1e-5);
assert_abs_diff_eq!(skew_factor(angle, 4, p, SpatialOrder::Mechanical(8 * slots)), -1.0, epsilon = 1e-5);
assert_abs_diff_eq!(skew_factor(angle, 4, p, SpatialOrder::Mechanical(p.get().into())), 0.95766, epsilon = 1e-5);

// 100 segments
assert_abs_diff_eq!(skew_factor(angle, 100, p, SpatialOrder::Mechanical(2 * slots)), 0.0, epsilon = 1e-5);
assert_abs_diff_eq!(skew_factor(angle, 100, p, SpatialOrder::Mechanical(4 * slots)), 0.0, epsilon = 1e-5);
assert_abs_diff_eq!(skew_factor(angle, 100, p, SpatialOrder::Mechanical(6 * slots)), 0.0, epsilon = 1e-5);
assert_abs_diff_eq!(skew_factor(angle, 100, p, SpatialOrder::Mechanical(8 * slots)), 0.0, epsilon = 1e-5);
assert_abs_diff_eq!(skew_factor(angle, 100, p, SpatialOrder::Mechanical(p.get().into())), 0.95493, epsilon = 1e-5);
```
 */
pub fn skew_factor(
    skew_angle: f64,
    num_segments: usize,
    pole_pairs: NonZeroU16,
    spatial_order: SpatialOrder,
) -> f64 {
    if skew_angle == 0.0 {
        return 1.0;
    } else {
        let arg = spatial_order.to_mechanical(pole_pairs) as f64 * skew_angle / 2.0;
        if num_segments == 0 {
            return arg.sin() / arg;
        } else {
            return arg.sin() / (num_segments as f64 * (arg / num_segments as f64).sin());
        }
    }
}

/**
Returns the staggering angle of a particular `segment`.

Each segment in a staggered laminated core has the same angular offset to its
neighbors:

`offset_angle = skew_angle / num_segments`.

The segment count starts at zero, the last segment of a staggered component has
therefore the index `num_segments-1`.


The angle is given relative to the reference axis, which intersects the
skew angle line at its middle. Therefore, the sum of all segment angles is
always zero.
*/
#[doc = ""]
#[cfg_attr(feature = "doc-images", doc = "![Staggering angle][segment_angle]")]
#[cfg_attr(
    feature = "doc-images",
    embed_doc_image::embed_doc_image("segment_angle", "docs/img/cad_segment_angle.svg")
)]
#[cfg_attr(
    not(feature = "doc-images"),
    doc = "**Doc images not enabled**. Compile docs with
        `cargo doc --features 'doc-images'` and Rust version >= 1.54."
)]
/**

This method implements [`CoreExt::segment_angle`].

# Examples

```
use std::num::NonZeroUsize;

use stem_core::core::segment_angle;
use approxim::assert_abs_diff_eq;

// Two segments
let num_segments = NonZeroUsize::new(2).expect("not zero");
assert_abs_diff_eq!(segment_angle(0, 6.0, num_segments), -1.5);
assert_abs_diff_eq!(segment_angle(1, 6.0, num_segments), 1.5);

// Three segments
let num_segments = NonZeroUsize::new(3).expect("not zero");
assert_abs_diff_eq!(segment_angle(0, 6.0, num_segments), -2.0);
assert_abs_diff_eq!(segment_angle(1, 6.0, num_segments), 0.0);
assert_abs_diff_eq!(segment_angle(2, 6.0, num_segments), 2.0);

// Segment indices are clamped
assert_abs_diff_eq!(segment_angle(3, 6.0, num_segments), 2.0);
assert_abs_diff_eq!(segment_angle(4, 6.0, num_segments), 2.0);
```
 */
pub fn segment_angle(segment: usize, skew_angle: f64, num_segments: NonZeroUsize) -> f64 {
    let beta = skew_angle / num_segments.get() as f64;
    return (0.5 + segment.clamp(0, num_segments.get() - 1) as f64) * beta - 0.5 * skew_angle;
}