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
/*!
This module provides iterators for positioning winding zones inside or on magnetic
cores.

A winding [`Zone`] is the space where one coil of a winding is located. A "slot"
is a group of zones layered next to each other as defined by a [`CoilLayout`].
If a core is [slotted](crate::air_gap::SlottedAirGap), this group is located
inside an actual [`Slot`], whereas e.g., for an
[air gap winding](crate::air_gap::PlainAirGap), the coils are located on top of
the air gap surface of the core:

 */
#![cfg_attr(feature = "doc-images", doc = "")]
#![cfg_attr(
    feature = "doc-images",
    doc = "![Winding zone positioning (plain air gap and slotted air gap)][winding_zones_with_zone_pos.svg]"
)]
#![cfg_attr(feature = "doc-images",
cfg_attr(all(),
doc = ::embed_doc_image::embed_image!("winding_zones_with_zone_pos.svg", "docs/img/winding_zones_with_zone_pos.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_zone_plots.rs`._

The winding-zone contours are positioned relative to the core via the
[`WindingZones`] iterator, which in turn is created by
[`CoreExt::winding_zones`](crate::core::CoreExt::winding_zones). The positioning
depends on the [`AirGap`](crate::air_gap::AirGap) of the core, see
[`AirGap::winding_zones`](crate::air_gap::AirGap::winding_zones).
[`WindingZones`] returns an [`PositionedZoneContour`] struct, which contains the
positioned contour as well as the [`Zone`] indices shown in the image above.
[`PositionedZoneContour`] therefore provides the geometrical constraints for a
winding: For example, it tells how much space is available for the lower layer
in slot 23 of a double-layer winding.

[`WindingZones`] itself is a wrapper around iterators such as
[`WindingZonesPeriodic`] which implement `Iterator<Item = PositionedZoneContour>`.
It is possible to wrap custom iterators via [`WindingZones::from_iter`], which
allows using any iterator returning [`PositionedZoneContour`]s for implementing
[`AirGap::winding_zones`](crate::air_gap::AirGap::winding_zones).

`examples/winding_zone_plots.rs` demonstrates how to utilize the
[`WindingZones`] iterator for creating the above image:

```ignore
// "cr" is a cairo::Context
for w in core.winding_zones(&CoilLayout::DoubleVertical) {
    w.as_drawable().draw(cr)?;
    let slot_text = Text {
        text: format!("Slot: {}", w.zone.slot),
        anchor: Anchor::Center,
        fixed_anchor_offset: [0.0, -7.0],
        scaled_anchor_offset: w.contour.centroid(),
        color: Color {
            r: 0.0,
            g: 0.0,
            b: 0.0,
            a: 1.0,
        },
        font_size: 12.0,
        angle: 0.0,
    };
    slot_text.draw(cr)?;

    let layer_text = Text {
        text: format!("Layer: {}", w.zone.layer),
        anchor: Anchor::Center,
        fixed_anchor_offset: [0.0, 7.0],
        scaled_anchor_offset: w.contour.centroid(),
        color: Color {
            r: 0.0,
            g: 0.0,
            b: 0.0,
            a: 1.0,
        },
        font_size: 12.0,
        angle: 0.0,
    };
    layer_text.draw(cr)?;
}
```
 */

use crate::planar_geo;
use planar_geo::DEFAULT_EPSILON;
use planar_geo::prelude::{Polysegment, ToBoundingBox};
use planar_geo::segment::ArcSegment;
use planar_geo::{Transformation, contour::Contour};
use std::f64::consts::{FRAC_1_SQRT_2, FRAC_PI_2, TAU};
use std::num::NonZeroU16;
use stem_slot::prelude::*;
use stem_slot::{slot::Slot, stem_types::CoilLayout};

#[cfg(feature = "cairo")]
use stem_slot::planar_geo::draw::{Drawable, DrawableRef};

/// A positioned [`Contour`] and its winding [`Zone`] index.
///
/// This struct is returned by the [`WindingZones`] iterator and contains the
/// [`Contour`] of the zone positioned relative to the magnetic core which
/// created [`WindingZones`] via
/// [`CoreExt::winding_zones`](crate::core::CoreExt::winding_zones). In
/// addition, it also provides the [`Zone`] index.
///
/// This struct implements the [`Transformation`] trait. The trait methods are
/// applied to [`PositionedZoneContour::contour`] using the implementation
/// of that trait for [`Contour`].
///
/// See the [module documentation](crate::winding_zones) for examples.
#[derive(Debug, Clone)]
pub struct PositionedZoneContour {
    /// Positioned contour of the zone.
    pub contour: Contour,
    /// Index of the zone.
    pub zone: Zone,
}

impl PositionedZoneContour {
    /// Converts [`PositionedZoneContour::contour`] into a [`Drawable`] using
    /// the default [`stem_slot::SLOT_STYLE`].
    #[cfg(feature = "cairo")]
    pub fn into_drawable(self) -> Drawable {
        Drawable::new(self.contour, stem_slot::SLOT_STYLE)
    }

    /// Converts [`PositionedZoneContour::contour`] into a [`Drawable`] using
    /// the provided `style`.
    #[cfg(feature = "cairo")]
    pub fn into_drawable_with_style(self, style: planar_geo::draw::Style) -> Drawable {
        Drawable::new(self.contour, style)
    }

    /// Wraps [`PositionedZoneContour::contour`] into a [`DrawableRef`] using
    /// the default [`stem_slot::SLOT_STYLE`].
    #[cfg(feature = "cairo")]
    pub fn as_drawable<'a>(&'a self) -> DrawableRef<'a> {
        return DrawableRef::new(&self.contour, stem_slot::SLOT_STYLE);
    }

    /// Wraps [`PositionedZoneContour::contour`] into a [`DrawableRef`] using
    /// the provided `style`.
    #[cfg(feature = "cairo")]
    pub fn as_drawable_with_style<'a>(&'a self, style: planar_geo::draw::Style) -> DrawableRef<'a> {
        return DrawableRef::new(&self.contour, style);
    }
}

impl From<PositionedZoneContour> for Contour {
    fn from(value: PositionedZoneContour) -> Self {
        value.contour
    }
}

impl From<(Contour, Zone)> for PositionedZoneContour {
    fn from(value: (Contour, Zone)) -> Self {
        Self {
            contour: value.0,
            zone: value.1,
        }
    }
}

#[cfg(feature = "cairo")]
impl From<PositionedZoneContour> for Drawable {
    fn from(value: PositionedZoneContour) -> Self {
        value.into_drawable()
    }
}

impl Transformation for PositionedZoneContour {
    fn translate(&mut self, shift: [f64; 2]) {
        self.contour.translate(shift);
    }

    fn rotate(&mut self, center: [f64; 2], angle: f64) {
        self.contour.rotate(center, angle);
    }

    fn scale(&mut self, factor: f64) {
        self.contour.scale(factor);
    }

    fn line_reflection(&mut self, start: [f64; 2], stop: [f64; 2]) -> () {
        self.contour.line_reflection(start, stop);
    }
}

impl ToBoundingBox for PositionedZoneContour {
    fn bounding_box(&self) -> planar_geo::prelude::BoundingBox {
        self.contour.bounding_box()
    }
}

/**
An iterator which periodically repeats the [`PositionedZoneContour`]s of a
[`CoilLayout`] over all slots.

This struct is essentially a builder for a [`WindingZones`] iterator which
groups the zone contours of the same slot together and ensures an equidistant
distribution of the slots over the air gap surface. It can be used for both
linear (`LIN = true`) and rotary cores (`LIN = false`) and provides a bunch of
constructors for either defining it from scratch or for particular
[`AirGap`](crate::air_gap::AirGap) types. It implements `Into<WindingZones>`.

The following image demonstrates how the iterator works using the example of a
linear and a rotary core with three slots with an
[air gap winding](crate::air_gap::PlainAirGap) on the left side and a
[slotted air gap](crate::air_gap::SlottedAirGap) on the right side. The
[`WindingZonesPeriodic::new`] constructor receives a "prototype" `zones`
argument consisting of the zone contours (shown together with their coordinate
system in red). These zones are then copied into new coordinate systems which
are distributed evenly along the air gap surface, starting from the left. In
case the core begins and ends in the middle of a slot, the layers are
distributed accordingly as shown for the right-side core.
*/
#[doc = ""]
#[cfg_attr(
    feature = "doc-images",
    doc = "![How WindingZonesPeriodic distributes the winding zones][cad_winding_zones_periodic]"
)]
#[cfg_attr(
    feature = "doc-images",
    embed_doc_image::embed_doc_image(
        "cad_winding_zones_periodic",
        "docs/img/cad_winding_zones_periodic.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 stem_core::prelude::*;
use planar_geo::prelude::*;

// Dummy contours defining the lower and the upper layer of a winding.
let lower = Contour::new(Polysegment::new());
let upper = Contour::new(Polysegment::new());

let mut wz = WindingZonesPeriodic::<Contour, true>::new(
    Length::new::<millimeter>(100.0),
    vec![lower, upper],
    12,
    false
);

// Two layers and twelve slots -> Total number of elements should be 24.
assert_eq!(wz.slots() * wz.layers(), 24);
assert_eq!(wz.count(), 24);
```
 */
#[derive(Debug, Clone)]
pub struct WindingZonesPeriodic<T: Transformation + Clone, const LIN: bool> {
    slots: u16,
    air_gap_length: Length,
    zones: Vec<T>,
    starts_in_slot_middle: bool,
    index: usize,
}

impl<T: Transformation + Clone, const LIN: bool> WindingZonesPeriodic<T, LIN> {
    /// Creates a new [`WindingZonesPeriodic`].
    ///
    /// This is the "raw" constructor for a [`WindingZonesPeriodic`] which can
    /// be used if the constructors with an higher abstraction level such as
    /// [`WindingZonesPeriodic::from_slot`] and
    /// [`WindingZonesPeriodic::from_air_gap_winding`] are not applicable. These
    /// constructors usually create `zones` and then call
    /// [`WindingZonesPeriodic::new`]. See the
    /// [struct-level](WindingZonesPeriodic) documentation for details.
    ///
    /// - `air_gap_length`: The cross-section length of the air gap surface
    ///   along which the zones will be distributed. See
    ///   [`CoreExt::air_gap_length`](crate::core::CoreExt::air_gap_length).
    /// - `zones`: The geometric entities to be distributed. Each element is
    ///   interpreted as a layer, i.e., `zones.len() == self.layers()`.
    /// - `slots`: Number of slots along the air gap. The `zones` will be
    ///   distributed `slots` times along the `air_gap_length`.
    /// - `starts_in_slot_middle`: If true, the first slot starts at the
    ///   reference point of the core (which is the left side for a
    ///   [`LinCore`](crate::core::LinCore) and the x-axis for a
    ///   [`RotCore`](crate::core::RotCore). If false, it starts at an offset of
    ///   `air_gap_length / (2*slots)`.
    ///
    /// In the following example, `slots` is 3 for both the left side showing
    /// an [air gap winding](crate::air_gap::PlainAirGap) and for the right side
    /// representing a [slotted air gap](crate::air_gap::SlottedAirGap). The
    /// `zones` argument is a vector of two contours as shown in the image. The
    /// `air_gap_length` is identical for both and `starts_in_slot_middle` is
    /// false for the left and true for the right side.
    #[doc = ""]
    #[cfg_attr(
        feature = "doc-images",
        doc = "![How WindingZonesPeriodic distributes the winding zones][cad_winding_zones_periodic]"
    )]
    #[cfg_attr(
        feature = "doc-images",
        embed_doc_image::embed_doc_image(
            "cad_winding_zones_periodic",
            "docs/img/cad_winding_zones_periodic.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 stem_core::prelude::*;
    /// use planar_geo::prelude::*;
    ///
    /// // Dummy contours defining the lower and the upper layer of a winding.
    /// let lower = Contour::new(Polysegment::new());
    /// let upper = Contour::new(Polysegment::new());
    ///
    /// // Left side
    /// let mut left = WindingZonesPeriodic::<Contour, true>::new(
    ///     Length::new::<millimeter>(100.0),
    ///     vec![lower.clone(), upper.clone()],
    ///     3,
    ///     false
    /// );
    ///
    /// // Two layers and three slots -> Total number of elements should be 6.
    /// assert_eq!(left.slots() * left.layers(), 6);
    /// assert_eq!(left.count(), 6);
    ///
    /// // Right side
    /// let mut right = WindingZonesPeriodic::<Contour, true>::new(
    ///     Length::new::<millimeter>(100.0),
    ///     vec![lower, upper],
    ///     3,
    ///     true
    /// );
    ///
    /// // Two layers and three slots -> Total number of elements should be 6.
    /// assert_eq!(right.slots() * right.layers(), 6);
    /// assert_eq!(right.count(), 6);
    /// ```
    pub fn new(
        air_gap_length: Length,
        zones: Vec<T>,
        slots: u16,
        starts_in_slot_middle: bool,
    ) -> Self {
        return Self {
            slots,
            air_gap_length,
            zones,
            starts_in_slot_middle,
            index: 0,
        };
    }

    /// Returns a "dummy" iterator which will only yield `None`.
    ///
    /// This constructor is useful for creating an "empty" iterator (e.g., for
    /// implementing
    /// [`CoreExt::winding_zones`](crate::core::CoreExt::winding_zones) for a
    /// non-windable air gap). It calls [`WindingZonesPeriodic::new`] with
    /// `slots` being zero and `zones` being an empty vector.
    ///
    /// # Examples
    ///
    /// ```
    /// use stem_core::prelude::*;
    /// use planar_geo::prelude::*;
    ///
    /// let mut wz = WindingZonesPeriodic::<Contour, true>::no_slots();
    /// assert!(wz.next().is_none());
    /// ```
    pub fn no_slots() -> Self {
        return Self {
            slots: 0,
            air_gap_length: Length::new::<meter>(0.0),
            zones: Vec::new(),
            starts_in_slot_middle: true,
            index: 0,
        };
    }

    /// Returns the number of layers within a single slot.
    ///
    /// When iterated over, `self` will return `self.layers() * self.slots()`
    /// items.
    pub fn layers(&self) -> usize {
        return self.zones.len();
    }

    /// Returns the number of slots.
    ///
    /// When iterated over, `self` will return `self.layers() * self.slots()`
    /// items.
    pub fn slots(&self) -> usize {
        return self.slots.into();
    }

    /// Resets the iterator.
    ///
    /// After "resetting" the iterator, the next yielded item is again the first
    /// zone (`Zone {slot: 0, layer: 0}`).
    ///
    /// # Examples
    ///
    /// ```
    /// use stem_core::prelude::*;
    /// use planar_geo::prelude::*;
    ///
    /// // Dummy contours defining the lower and the upper layer of a winding.
    /// let lower = Contour::new(Polysegment::new());
    /// let upper = Contour::new(Polysegment::new());
    ///
    /// let mut wz = WindingZonesPeriodic::<Contour, true>::new(
    ///     Length::new::<millimeter>(100.0),
    ///     vec![lower, upper],
    ///     12,
    ///     false
    /// );
    ///
    /// // Start iterating
    /// assert_eq!(wz.next().unwrap().zone, Zone {slot: 0, layer: 0});
    /// assert_eq!(wz.next().unwrap().zone, Zone {slot: 0, layer: 1});
    /// assert_eq!(wz.next().unwrap().zone, Zone {slot: 1, layer: 0});
    /// // ...
    ///
    /// // Now reset the iterator
    /// wz.reset();
    /// assert_eq!(wz.next().unwrap().zone, Zone {slot: 0, layer: 0});
    /// ```
    pub fn reset(&mut self) {
        self.index = 0;
    }
}

impl<T: Transformation + Clone + ToBoundingBox, const LIN: bool> WindingZonesPeriodic<T, LIN> {
    fn next_priv(&mut self) -> Option<(T, Zone)> {
        let result = self.nth_priv(self.index);
        self.index = self.index + 1;
        result
    }

    fn nth_priv(&mut self, n: usize) -> Option<(T, Zone)> {
        let layers = self.layers();
        if n >= (self.slots as usize) * layers {
            return None;
        }
        let layer = n.rem_euclid(layers);
        let slot = n / layers;

        // Cannot panic, because the index is the remainder of a division by the
        // total number of layers and therefore is always in bounds
        let mut geom = self.zones[layer].clone();

        if LIN {
            // If all vertices of the contour are negative, shift it to the
            // end of the core. This can only happen for the first slot in
            // case the slot starts in the tooth middle
            let factor = if slot == 0
                && self.starts_in_slot_middle
                && geom.bounding_box().xmax() <= DEFAULT_EPSILON
            {
                1.0
            } else {
                1.0 / f64::from(self.slots)
                    * (slot as f64 + 0.5 * (!self.starts_in_slot_middle) as u32 as f64)
            };
            geom.translate([self.air_gap_length.get::<meter>() * factor, 0.0]);
        } else {
            geom.translate([0.0, self.air_gap_length.get::<meter>() / TAU]);
            let angle = -TAU
                * (slot as f64 + 0.5 * (!self.starts_in_slot_middle) as u32 as f64) as f64
                / self.slots as f64
                + FRAC_PI_2;
            geom.rotate([0.0, 0.0], angle);
        }
        return Some((
            geom,
            Zone {
                slot: slot as u16,
                layer: layer as u16,
            },
        ));
    }
}

impl<const LIN: bool> WindingZonesPeriodic<Polysegment, LIN> {
    /// Returns an iterator over the [`Slot::outline`]s distributed evenly along
    /// the `air_gap_length`.
    ///
    /// This constructor is specifically used for creating the
    /// [`SlottedAirGap`](crate::air_gap::SlottedAirGap) shape. It uses the
    /// `slot` to get the [`Slot::outline`], flips it vertically for an inner
    /// rotary core and then forwards the resulting [`Polysegment`] into the
    /// `zones` argument of [`WindingZonesPeriodic::new`] along with the
    /// other arguments. See [`WindingZonesPeriodic::new`] for more details
    /// and examples.
    pub fn from_slot<S: Slot + ?Sized>(
        air_gap_length: Length,
        slots: NonZeroU16,
        slot: &S,
        starts_in_slot_middle: bool,
        outer_core: bool,
    ) -> Self {
        let air_gap_length = if LIN {
            air_gap_length
        } else {
            use stem_material::uom::typenum::P2;
            let air_gap_radius = air_gap_length / TAU;

            let mod_radius = 0.5
                * (4.0 * air_gap_radius.powi(P2::new()) - slot.opening_width().powi(P2::new()))
                    .sqrt();
            mod_radius * TAU
        };

        let mut slot_outline: Polysegment = slot.outline().into_owned();

        if !LIN && !outer_core {
            slot_outline.line_reflection([0.0, 0.0], [1.0, 0.0])
        };

        return Self {
            slots: slots.get(),
            air_gap_length,
            zones: vec![slot_outline],
            starts_in_slot_middle,
            index: 0,
        };
    }
}

impl<const LIN: bool> WindingZonesPeriodic<Contour, LIN> {
    /// Returns an iterator over the [`Slot::layer_contours`]s distributed
    /// evenly along the `air_gap_length`.
    ///
    /// This constructor creates the `zones` argument of
    /// [`WindingZonesPeriodic::new`] with `slot.layer_contours(coil_layout)`,
    /// flips it vertically for an inner rotary core and and then forwards the
    /// resulting [`Vec<Contour>`] into the `zones` argument of
    /// [`WindingZonesPeriodic::new`] along with the other arguments. See
    /// [`WindingZonesPeriodic::new`] for more details and examples.
    pub fn from_slot<S: Slot + ?Sized>(
        air_gap_length: Length,
        slots: u16,
        slot: &S,
        coil_layout: &CoilLayout,
        starts_in_slot_middle: bool,
        outer_core: bool,
    ) -> Self {
        let mut zones = slot.layer_contours(coil_layout);

        let air_gap_length = if LIN {
            air_gap_length
        } else {
            use stem_material::uom::typenum::P2;
            let air_gap_radius = air_gap_length / TAU;

            if slot.is_open() && coil_layout == &CoilLayout::SingleFilled {
                // Won't panic, since the zones vector will always have
                // one entry if coil_layout == &CoilLayout::Single
                let mut contour = Contour::new(Polysegment::new());
                std::mem::swap(&mut contour, &mut zones[0]);

                // Last element of the contour is the straight slot opening
                // segment => replace it with an arc
                let mut slot_seg = Polysegment::from(contour);
                if let Some(opening_seg) = slot_seg.pop_back() {
                    if let Ok(a) = ArcSegment::from_start_stop_radius(
                        opening_seg.start(),
                        opening_seg.stop(),
                        air_gap_radius.get::<meter>(),
                        outer_core,
                        false,
                    ) {
                        slot_seg.push_back(a.into());
                    } else {
                        slot_seg.push_back(opening_seg.into());
                    }
                }
                let mut contour = Contour::new(slot_seg);
                std::mem::swap(&mut contour, &mut zones[0]);
            }

            let mod_radius = 0.5
                * (4.0 * air_gap_radius.powi(P2::new()) - slot.opening_width().powi(P2::new()))
                    .sqrt();
            mod_radius * TAU
        };
        if !LIN && !outer_core {
            zones
                .iter_mut()
                .for_each(|c| c.line_reflection([0.0, 0.0], [1.0, 0.0]));
        };

        return Self {
            slots,
            air_gap_length,
            zones,
            starts_in_slot_middle,
            index: 0,
        };
    }

    /// Returns an iterator over the [`PositionedZoneContour`]s of an air gap
    /// winding distributed evenly along the `air_gap_length`.
    ///
    /// This method creates the air gap winding zone [`Contour`]s from the
    /// `air_gap_winding_height`, `winding_coverage` and `coil_layout` as shown
    /// in the image below (for a rotary core, the zones are curved instead):
    #[doc = ""]
    #[cfg_attr(
        feature = "doc-images",
        doc = "![Air gap winding dimensions][cad_plain_air_gap_winding]"
    )]
    #[cfg_attr(
        feature = "doc-images",
        embed_doc_image::embed_doc_image(
            "cad_plain_air_gap_winding",
            "docs/img/cad_plain_air_gap_winding.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."
    )]
    ///
    /// The origin of the created segments is at the air gap surface. If
    /// `outer_core` is true, they are flipped.
    ///
    /// The resulting [`Vec<Contour>`] is then provided as `zones` argument to
    /// [`WindingZonesPeriodic::new`] along with the other arguments. See
    /// [`WindingZonesPeriodic::new`] for more details and examples.
    ///
    /// # Examples
    ///
    /// ```
    /// use stem_core::prelude::*;
    /// use planar_geo::prelude::*;
    ///
    /// let coil_layout = CoilLayout::DoubleVertical;
    /// let slots = 12;
    ///
    /// let wz = WindingZonesPeriodic::<Contour, true>::from_air_gap_winding(
    ///     Length::new::<millimeter>(100.0),
    ///     slots,
    ///     Length::new::<millimeter>(6.0),
    ///     0.8,
    ///     &coil_layout,
    ///     false,
    ///     true,
    /// );
    ///
    /// // Two layers and three slots -> Total number of elements should be 24.
    /// let num_contours = wz.count();
    /// assert_eq!(num_contours, usize::from(slots * coil_layout.layers().get()));
    /// assert_eq!(num_contours, 24);
    /// ```
    pub fn from_air_gap_winding(
        air_gap_length: Length,
        slots: u16,
        air_gap_winding_height: Length,
        winding_coverage: f64,
        coil_layout: &CoilLayout,
        starts_in_slot_middle: bool,
        outer_core: bool,
    ) -> Self {
        let mut zones = Vec::with_capacity(coil_layout.layers().get() as usize);
        let ag_height = if outer_core {
            -air_gap_winding_height.get::<meter>()
        } else {
            air_gap_winding_height.get::<meter>()
        };

        if LIN {
            let half_slot_width =
                winding_coverage.clamp(0.0, 1.0) * 0.5 * air_gap_length.get::<meter>()
                    / slots as f64;
            match coil_layout {
                CoilLayout::Single | CoilLayout::SingleFilled => zones.push(Contour::rectangle(
                    [-half_slot_width, 0.0],
                    [half_slot_width, ag_height],
                )),
                CoilLayout::DoubleVertical => {
                    zones.push(Contour::rectangle(
                        [-half_slot_width, 0.0],
                        [half_slot_width, 0.5 * ag_height],
                    ));
                    zones.push(Contour::rectangle(
                        [-half_slot_width, 0.5 * ag_height],
                        [half_slot_width, ag_height],
                    ));
                }
                CoilLayout::DoubleHorizontal => {
                    zones.push(Contour::rectangle(
                        [-half_slot_width, 0.0],
                        [0.0, ag_height],
                    ));
                    zones.push(Contour::rectangle([0.0, 0.0], [half_slot_width, ag_height]));
                }
                CoilLayout::Quadruple => {
                    zones.push(Contour::rectangle(
                        [-half_slot_width, 0.0],
                        [0.0, 0.5 * ag_height],
                    ));
                    zones.push(Contour::rectangle(
                        [-half_slot_width, 0.5 * ag_height],
                        [0.0, ag_height],
                    ));
                    zones.push(Contour::rectangle(
                        [0.0, 0.5 * ag_height],
                        [half_slot_width, ag_height],
                    ));
                    zones.push(Contour::rectangle(
                        [0.0, 0.0],
                        [half_slot_width, 0.5 * ag_height],
                    ));
                }
                CoilLayout::MultiVertical(layers) => {
                    let layers = layers.get();
                    let layer_height = ag_height / (layers) as f64;
                    for layer in 0..(layers) {
                        zones.push(Contour::rectangle(
                            [-half_slot_width, layer as f64 * layer_height],
                            [half_slot_width, (layer + 1) as f64 * layer_height],
                        ));
                    }
                }
            }
        } else {
            let angle = winding_coverage.clamp(0.0, 1.0) * TAU / slots as f64;
            let agr = air_gap_length.get::<meter>() / TAU;
            match coil_layout {
                CoilLayout::Single | CoilLayout::SingleFilled => {
                    let mut ps = Polysegment::with_capacity(4);
                    if let Ok(arc) = ArcSegment::from_center_radius_start_sweep_angle(
                        [0.0, 0.0],
                        agr,
                        -0.5 * angle + FRAC_PI_2,
                        angle,
                    ) {
                        ps.push_back(arc.into());
                    }
                    if let Ok(arc) = ArcSegment::from_center_radius_start_sweep_angle(
                        [0.0, 0.0],
                        agr + ag_height,
                        0.5 * angle + FRAC_PI_2,
                        -angle,
                    ) {
                        ps.push_back(arc.into());
                    }
                    zones.push(ps.into());
                }
                CoilLayout::DoubleVertical => {
                    let radicand = (agr + ag_height).powi(2) + agr.powi(2);
                    let mean_radius = radicand.signum() * FRAC_1_SQRT_2 * radicand.sqrt();

                    // Lower layer
                    let mut ps = Polysegment::with_capacity(4);
                    if let Ok(arc) = ArcSegment::from_center_radius_start_sweep_angle(
                        [0.0, 0.0],
                        agr,
                        -0.5 * angle + FRAC_PI_2,
                        angle,
                    ) {
                        ps.push_back(arc.into());
                    }
                    if let Ok(arc) = ArcSegment::from_center_radius_start_sweep_angle(
                        [0.0, 0.0],
                        mean_radius,
                        0.5 * angle + FRAC_PI_2,
                        -angle,
                    ) {
                        ps.push_back(arc.into());
                    }
                    zones.push(ps.into());

                    // Upper layer
                    let mut ps = Polysegment::with_capacity(4);
                    if let Ok(arc) = ArcSegment::from_center_radius_start_sweep_angle(
                        [0.0, 0.0],
                        mean_radius,
                        -0.5 * angle + FRAC_PI_2,
                        angle,
                    ) {
                        ps.push_back(arc.into());
                    }
                    if let Ok(arc) = ArcSegment::from_center_radius_start_sweep_angle(
                        [0.0, 0.0],
                        agr + ag_height,
                        0.5 * angle + FRAC_PI_2,
                        -angle,
                    ) {
                        ps.push_back(arc.into());
                    }
                    zones.push(ps.into());
                }
                CoilLayout::DoubleHorizontal => {
                    // Right layer
                    let mut ps = Polysegment::with_capacity(4);
                    if let Ok(arc) = ArcSegment::from_center_radius_start_sweep_angle(
                        [0.0, 0.0],
                        agr,
                        FRAC_PI_2,
                        0.5 * angle,
                    ) {
                        ps.push_back(arc.into());
                    }
                    if let Ok(arc) = ArcSegment::from_center_radius_start_sweep_angle(
                        [0.0, 0.0],
                        agr + ag_height,
                        FRAC_PI_2 + 0.5 * angle,
                        -0.5 * angle,
                    ) {
                        ps.push_back(arc.into());
                    }
                    zones.push(ps.into());

                    // Left layer
                    let mut ps = Polysegment::with_capacity(4);
                    if let Ok(arc) = ArcSegment::from_center_radius_start_sweep_angle(
                        [0.0, 0.0],
                        agr,
                        -0.5 * angle + FRAC_PI_2,
                        0.5 * angle,
                    ) {
                        ps.push_back(arc.into());
                    }
                    if let Ok(arc) = ArcSegment::from_center_radius_start_sweep_angle(
                        [0.0, 0.0],
                        agr + ag_height,
                        FRAC_PI_2,
                        -0.5 * angle,
                    ) {
                        ps.push_back(arc.into());
                    }
                    zones.push(ps.into());
                }
                CoilLayout::Quadruple => {
                    let radicand = (agr + ag_height).powi(2) + agr.powi(2);
                    let mean_radius = radicand.signum() * FRAC_1_SQRT_2 * radicand.sqrt();

                    // First layer
                    let mut ps = Polysegment::with_capacity(4);
                    if let Ok(arc) = ArcSegment::from_center_radius_start_sweep_angle(
                        [0.0, 0.0],
                        agr,
                        FRAC_PI_2,
                        0.5 * angle,
                    ) {
                        ps.push_back(arc.into());
                    }
                    if let Ok(arc) = ArcSegment::from_center_radius_start_sweep_angle(
                        [0.0, 0.0],
                        mean_radius,
                        0.5 * angle + FRAC_PI_2,
                        -0.5 * angle,
                    ) {
                        ps.push_back(arc.into());
                    }
                    zones.push(ps.into());

                    // Second layer
                    let mut ps = Polysegment::with_capacity(4);
                    if let Ok(arc) = ArcSegment::from_center_radius_start_sweep_angle(
                        [0.0, 0.0],
                        mean_radius,
                        FRAC_PI_2,
                        0.5 * angle,
                    ) {
                        ps.push_back(arc.into());
                    }
                    if let Ok(arc) = ArcSegment::from_center_radius_start_sweep_angle(
                        [0.0, 0.0],
                        agr + ag_height,
                        0.5 * angle + FRAC_PI_2,
                        -0.5 * angle,
                    ) {
                        ps.push_back(arc.into());
                    }
                    zones.push(ps.into());

                    // Third layer
                    let mut ps = Polysegment::with_capacity(4);
                    if let Ok(arc) = ArcSegment::from_center_radius_start_sweep_angle(
                        [0.0, 0.0],
                        mean_radius,
                        -0.5 * angle + FRAC_PI_2,
                        0.5 * angle,
                    ) {
                        ps.push_back(arc.into());
                    }
                    if let Ok(arc) = ArcSegment::from_center_radius_start_sweep_angle(
                        [0.0, 0.0],
                        agr + ag_height,
                        FRAC_PI_2,
                        -0.5 * angle,
                    ) {
                        ps.push_back(arc.into());
                    }
                    zones.push(ps.into());

                    // Fourth layer
                    let mut ps = Polysegment::with_capacity(4);
                    if let Ok(arc) = ArcSegment::from_center_radius_start_sweep_angle(
                        [0.0, 0.0],
                        agr,
                        -0.5 * angle + FRAC_PI_2,
                        0.5 * angle,
                    ) {
                        ps.push_back(arc.into());
                    }
                    if let Ok(arc) = ArcSegment::from_center_radius_start_sweep_angle(
                        [0.0, 0.0],
                        mean_radius,
                        FRAC_PI_2,
                        -0.5 * angle,
                    ) {
                        ps.push_back(arc.into());
                    }
                    zones.push(ps.into());
                }
                CoilLayout::MultiVertical(layers) => {
                    let layers = layers.get();
                    let layer_height = ag_height / (layers) as f64;
                    for layer in 0..(layers) {
                        let first_radius = agr + layer as f64 * layer_height;
                        let second_radius = agr + (layer + 1) as f64 * layer_height;

                        let mut ps = Polysegment::with_capacity(4);
                        if let Ok(arc) = ArcSegment::from_center_radius_start_sweep_angle(
                            [0.0, 0.0],
                            first_radius,
                            -0.5 * angle + FRAC_PI_2,
                            angle,
                        ) {
                            ps.push_back(arc.into());
                        }
                        if let Ok(arc) = ArcSegment::from_center_radius_start_sweep_angle(
                            [0.0, 0.0],
                            second_radius,
                            0.5 * angle + FRAC_PI_2,
                            -angle,
                        ) {
                            ps.push_back(arc.into());
                        }
                        zones.push(ps.into());
                    }
                }
            }
            zones.iter_mut().for_each(|c| c.translate([0.0, -agr]));
        }

        return Self {
            slots,
            air_gap_length,
            zones,
            starts_in_slot_middle,
            index: 0,
        };
    }
}

impl<const LIN: bool> Iterator for WindingZonesPeriodic<Polysegment, LIN> {
    type Item = Polysegment;

    fn next(&mut self) -> Option<Self::Item> {
        self.next_priv().map(|t| t.0)
    }

    fn nth(&mut self, n: usize) -> Option<Self::Item> {
        self.nth_priv(n).map(|t| t.0)
    }
}

impl<const LIN: bool> Iterator for WindingZonesPeriodic<Contour, LIN> {
    type Item = PositionedZoneContour;

    fn next(&mut self) -> Option<Self::Item> {
        self.next_priv().map(From::from)
    }

    fn nth(&mut self, n: usize) -> Option<Self::Item> {
        self.nth_priv(n).map(From::from)
    }
}

/**
An iterator over the [`PositionedZoneContour`]s of a magnetic core.

If a magnetic core provides space for the coils of a winding ("zones"), this
iterator returns the [`Contour`]s describing that space for each [`Zone`] of the
winding. The [`Zone`]s are strictly increasing:

```
use std::sync::Arc;
use stem_core::prelude::*;

let core: LinCore = LinCoreBuilder {
    height: Length::new::<millimeter>(15.0),
    width: Length::new::<millimeter>(50.0),
    axial_length: Length::new::<millimeter>(1.0),
    axial_coil_overhang: Length::new::<millimeter>(0.0),
    skew_angle: 0.0,
    iron_fill_factor: 1.0,
    material: Arc::new(Default::default()),
    pole_pairs: 1.try_into().expect("not zero"),
    air_gap: Box::new(PlainAirGap {
        num_segments: 0,
        air_gap_winding_height: Length::new::<millimeter>(8.0),
        winding_coverage: 0.7,
        starts_in_slot_middle: false,
        slots: 3,
    }),
    flux_barrier: None,
}
.try_into().expect("valid dimensions");

// Single-layer winding
let mut wz_single = core.winding_zones(&CoilLayout::Single);
assert_eq!(wz_single.next().unwrap().zone, Zone {slot: 0, layer: 0});
assert_eq!(wz_single.next().unwrap().zone, Zone {slot: 1, layer: 0});
assert_eq!(wz_single.next().unwrap().zone, Zone {slot: 2, layer: 0});
assert!(wz_single.next().is_none());

// Double-layer winding
let mut wz_double = core.winding_zones(&CoilLayout::DoubleVertical);
assert_eq!(wz_double.next().unwrap().zone, Zone {slot: 0, layer: 0});
assert_eq!(wz_double.next().unwrap().zone, Zone {slot: 0, layer: 1});
assert_eq!(wz_double.next().unwrap().zone, Zone {slot: 1, layer: 0});
assert_eq!(wz_double.next().unwrap().zone, Zone {slot: 1, layer: 1});
assert_eq!(wz_double.next().unwrap().zone, Zone {slot: 2, layer: 0});
assert_eq!(wz_double.next().unwrap().zone, Zone {slot: 2, layer: 1});
assert!(wz_double.next().is_none());
```

All predefined specialized iterators (such as [`WindingZonesPeriodic`]) can be
converted into [`WindingZones`] via its [`From`] implementations. The
[`Iterator::nth`] method, which is used in
[`CoreExt::winding_zone_at`](crate::core::CoreExt::winding_zone_at)
implementation of [`WindingZones`] dispatches to that of the underlying
iterator, so it is recommended to implement that method if possible.

When implementing
[`AirGap::winding_zones`](crate::air_gap::AirGap::winding_zones) (which drives
[`CoreExt::winding_zones`](crate::core::CoreExt::winding_zones)), the
[`WindingZones::from_iter`] method can be used for wrapping a custom
iterator. The custom iterator should provide the zones in the same ascending
order as shown in the example (i.e., the zone of the `(n+1)`th item
should be greater than the `n`th [`PositionedZoneContour::zone`] according to
the [`Ord`] implementation for [`Zone`]). See [`Zone`] for details.
 */
pub struct WindingZones(WindingZonesInner);

impl WindingZones {
    /// Creates [`WindingZones`] from a custom iterator.
    ///
    /// The iterator must yield [`PositionedZoneContour`]s in strictly
    /// increasing [`Zone`] order. See the [`Zone`] documentation for
    /// details.
    pub fn from_iter<I>(iter: I) -> Self
    where
        I: Iterator<Item = PositionedZoneContour> + 'static,
    {
        Self(WindingZonesInner::Other(Box::new(iter)))
    }
}

enum WindingZonesInner {
    WindingZonesPeriodicLin(WindingZonesPeriodic<Contour, true>),
    WindingZonesPeriodicRot(WindingZonesPeriodic<Contour, false>),
    Other(Box<dyn Iterator<Item = PositionedZoneContour>>),
}

impl From<WindingZonesInner> for WindingZones {
    fn from(value: WindingZonesInner) -> Self {
        Self(value)
    }
}

impl Iterator for WindingZones {
    type Item = PositionedZoneContour;

    fn next(&mut self) -> Option<Self::Item> {
        match &mut self.0 {
            WindingZonesInner::WindingZonesPeriodicLin(i) => i.next(),
            WindingZonesInner::WindingZonesPeriodicRot(i) => i.next(),
            WindingZonesInner::Other(i) => i.next(),
        }
    }

    fn nth(&mut self, n: usize) -> Option<Self::Item> {
        match &mut self.0 {
            WindingZonesInner::WindingZonesPeriodicLin(i) => i.nth(n),
            WindingZonesInner::WindingZonesPeriodicRot(i) => i.nth(n),
            WindingZonesInner::Other(i) => i.nth(n),
        }
    }
}

impl From<WindingZonesPeriodic<Contour, true>> for WindingZones {
    fn from(value: WindingZonesPeriodic<Contour, true>) -> Self {
        WindingZonesInner::WindingZonesPeriodicLin(value).into()
    }
}

impl From<WindingZonesPeriodic<Contour, false>> for WindingZones {
    fn from(value: WindingZonesPeriodic<Contour, false>) -> Self {
        WindingZonesInner::WindingZonesPeriodicRot(value).into()
    }
}

impl From<Box<dyn Iterator<Item = PositionedZoneContour>>> for WindingZones {
    fn from(value: Box<dyn Iterator<Item = PositionedZoneContour>>) -> Self {
        WindingZonesInner::Other(value).into()
    }
}