polarization 0.2.0

Simulate the polarization of a laser beam
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
//! An optical system that encapsulates a beam and the elements that it will pass
//! through.

use super::common::{Beam, ComplexMatrix, JonesError, JonesMatrix, JonesVector, Result};
use super::composite::CompositeElement;
use super::hwp::HalfWavePlate;
use super::identity::IdentityElement;
use super::polarizer::Polarizer;
use super::qwp::QuarterWavePlate;
use super::retarder::Retarder;
use super::rotator::PolarizationRotator;
#[cfg(test)]
use proptest::option;
#[cfg(test)]
use proptest::prelude::*;

/// A type that represents the various optical elements that may appear in the
/// optical system.
#[derive(Debug, Copy, Clone)]
pub enum OpticalElement {
    /// An ideal linear polarizer.
    Polarizer(Polarizer),
    /// An optical element that rotates the polarization of a beam.
    PolarizationRotator(PolarizationRotator),
    /// An optical retarder with an arbitrary phase delay.
    Retarder(Retarder),
    /// An ideal quarter-wave plate.
    QuarterWavePlate(QuarterWavePlate),
    /// An ideal half-wave plate.
    HalfWavePlate(HalfWavePlate),
    /// An element that passes a beam through untouched.
    Identity(IdentityElement),
    /// An element that represents the composition of several other elements.
    Composite(CompositeElement),
}

impl OpticalElement {
    pub fn matrix(&self) -> ComplexMatrix {
        match self {
            OpticalElement::Polarizer(pol) => pol.matrix(),
            OpticalElement::PolarizationRotator(rot) => rot.matrix(),
            OpticalElement::Retarder(ret) => ret.matrix(),
            OpticalElement::QuarterWavePlate(qwp) => qwp.matrix(),
            OpticalElement::HalfWavePlate(hwp) => hwp.matrix(),
            OpticalElement::Identity(id) => id.matrix(),
            OpticalElement::Composite(comp) => comp.matrix(),
        }
    }
}

#[cfg(test)]
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum OpticalElementType {
    Polarizer,
    PolarizationRotator,
    Retarder,
    QuarterWavePlate,
    HalfWavePlate,
    Identity,
    Composite,
    Any,
}

#[cfg(test)]
impl Default for OpticalElementType {
    fn default() -> Self {
        OpticalElementType::Any
    }
}

#[cfg(test)]
impl Arbitrary for OpticalElement {
    type Parameters = OpticalElementType;
    type Strategy = BoxedStrategy<Self>;

    fn arbitrary_with(args: Self::Parameters) -> Self::Strategy {
        match args {
            OpticalElementType::Polarizer => any::<Polarizer>()
                .prop_map(|x| OpticalElement::Polarizer(x))
                .boxed(),
            OpticalElementType::PolarizationRotator => any::<PolarizationRotator>()
                .prop_map(|x| OpticalElement::PolarizationRotator(x))
                .boxed(),
            OpticalElementType::Retarder => any::<Retarder>()
                .prop_map(|x| OpticalElement::Retarder(x))
                .boxed(),
            OpticalElementType::QuarterWavePlate => any::<QuarterWavePlate>()
                .prop_map(|x| OpticalElement::QuarterWavePlate(x))
                .boxed(),
            OpticalElementType::HalfWavePlate => any::<HalfWavePlate>()
                .prop_map(|x| OpticalElement::HalfWavePlate(x))
                .boxed(),
            OpticalElementType::Identity => any::<IdentityElement>()
                .prop_map(|x| OpticalElement::Identity(x))
                .boxed(),
            OpticalElementType::Composite => any::<CompositeElement>()
                .prop_map(|x| OpticalElement::Composite(x))
                .boxed(),
            OpticalElementType::Any => prop_oneof![
                any::<IdentityElement>().prop_map(|x| OpticalElement::Identity(x)),
                any::<Polarizer>().prop_map(|x| OpticalElement::Polarizer(x)),
                any::<PolarizationRotator>().prop_map(|x| OpticalElement::PolarizationRotator(x)),
                any::<QuarterWavePlate>().prop_map(|x| OpticalElement::QuarterWavePlate(x)),
                any::<HalfWavePlate>().prop_map(|x| OpticalElement::HalfWavePlate(x)),
                any::<Retarder>().prop_map(|x| OpticalElement::Retarder(x)),
                any::<CompositeElement>().prop_map(|x| OpticalElement::Composite(x)),
            ]
            .boxed(),
        }
        .boxed()
    }
}

/// A type that contains a beam and the elements that it will pass through.
///
/// # Examples
/// An optical system is constructed using the builder pattern.
/// ```
/// # extern crate polarization;
/// use polarization::jones::*;
/// // A linearly polarized beam parallel to the x-axis
/// let beam = Beam::linear(Angle::Degrees(0.0));
/// // A linear polarizer at 45 degrees counter-clockwise from the x-axis
/// let pol = OpticalElement::Polarizer(Polarizer::new(Angle::Degrees(45.0)));
/// // The optical system
/// let system = OpticalSystem::new()
///     .add_beam(beam)
///     .add_element(pol);
/// ```
/// If you have several elements, you may also add them to the system using the
/// `add_elements` method.
///
/// The beam may be propagated through the elements in the system, returning a new beam.
/// ```
/// # use polarization::jones::*;
/// # let beam = Beam::linear(Angle::Degrees(0.0));
/// # let pol = OpticalElement::Polarizer(Polarizer::new(Angle::Degrees(45.0)));
/// # let system = OpticalSystem::new()
/// #     .add_beam(beam)
/// #     .add_element(pol);
/// let final_beam: Result<Beam> = system.propagate();
/// ```
/// This operation may fail because you're human and maybe you forgot to add a beam or
/// elements to your system before calling `propagate`.
///
/// The order in which you add elements to the system is the same order that the beam
/// will travel through the elements. For example, consider a horizontal beam, a
/// vertical polarizer, and a rotator that will rotate the beam by 90 degrees. If the
/// beam passes through the polarizer first, the intensity after the polarizer will be
/// zero since the polarization of the beam is perpendicular to the axis of the
/// polarizer.
/// ```
/// # use polarization::jones::*;
/// let beam = Beam::linear(Angle::Degrees(0.0));
/// let pol = OpticalElement::Polarizer(
///     Polarizer::new(Angle::Degrees(90.0))
/// );
/// let rot = OpticalElement::PolarizationRotator(
///     PolarizationRotator::new(Angle::Degrees(90.0))
/// );
/// let system = OpticalSystem::new()
///     .add_beam(beam.clone())
///     .add_element(pol.clone())  // this kills the beam!
///     .add_element(rot.clone());  // this does nothing now
/// let beam_after = system.propagate().unwrap();
/// assert!(beam_after.intensity().unwrap() < 1e-6);
/// ```
/// However, if the beam passes through the rotator first, the beam after the
/// rotator will be parallel to the polarizer, and will pass through unaffected.
/// ```
/// # use polarization::jones::*;
/// # let beam = Beam::linear(Angle::Degrees(0.0));
/// # let pol = OpticalElement::Polarizer(
/// #     Polarizer::new(Angle::Degrees(90.0))
/// # );
/// # let rot = OpticalElement::PolarizationRotator(
/// #     PolarizationRotator::new(Angle::Degrees(90.0))
/// # );
/// let system = OpticalSystem::new()
///     .add_beam(beam.clone())
///     .add_element(rot.clone())  // beam and polarizer are now parallel
///     .add_element(pol.clone());
/// let beam_after = system.propagate().unwrap();
/// assert!(beam_after.intensity().unwrap() > 0.99);
/// ```
#[derive(Debug, Clone)]
pub struct OpticalSystem {
    pub beam: Option<Beam>,
    pub elements: Option<Vec<OpticalElement>>,
}

impl OpticalSystem {
    /// Constructs a new optical system.
    ///
    /// The optical system constructed by this method does not contain a beam, and does not
    /// contain any optical elements. A beam and elements are both necessary for doing a
    /// polarization simulation.
    pub fn new() -> Self {
        OpticalSystem {
            beam: None,
            elements: None,
        }
    }

    /// Add a beam to the optical system, consuming the current system.
    ///
    /// Calling this method more than once will overwrite the previously added beam.
    pub fn add_beam(self, beam: Beam) -> Self {
        OpticalSystem {
            beam: Some(beam),
            elements: self.elements,
        }
    }

    /// Add an optical element to the system.
    ///
    /// The beam will pass through the elements in the order that they are added.
    pub fn add_element(self, elem: OpticalElement) -> Self {
        let elements = match self.elements {
            Some(elements) => {
                let mut new_elements = elements.clone();
                new_elements.push(elem);
                new_elements
            }
            None => vec![elem],
        };
        OpticalSystem {
            beam: self.beam,
            elements: Some(elements),
        }
    }

    /// Add several optical elements to the system at once.
    ///
    /// If elements have already been added to the system, these elements will be added after
    /// the existing elements.
    pub fn add_elements(self, elems: Vec<OpticalElement>) -> Self {
        if self.elements.is_none() {
            let system = OpticalSystem {
                beam: self.beam,
                elements: Some(elems),
            };
            return system;
        }
        let mut elements = self.elements.clone().unwrap();
        elements.extend(elems);
        OpticalSystem {
            beam: self.beam,
            elements: Some(elements),
        }
    }

    /// Add a beam to a system in-place.
    ///
    /// If the system already contains a beam, it will be discarded.
    pub fn add_beam_mut(&mut self, beam: Beam) {
        self.beam = Some(beam);
    }

    /// Clear the beam from the system.
    pub fn clear_beam(&mut self) {
        self.beam = None;
    }

    /// Add an element to a system in-place.
    ///
    /// The beam will travel the elements in the order in which they are added to the system.
    pub fn add_element_mut(&mut self, elem: OpticalElement) {
        let elems = self.elements.take();
        match elems {
            Some(mut elems) => {
                elems.push(elem);
                self.elements = Some(elems);
            },
            None => {
                self.elements = Some(vec![elem]);
            }
        }
    }

    /// Add multiple elements to the system at once, modifying it in-place.
    ///
    /// The beam will travel through elements in the order in which they are added to the system.
    pub fn add_elements_mut(&mut self, elems: Vec<OpticalElement>) {
        let existing = self.elements.take();
        match existing {
            Some(mut existing) => {
                existing.extend(elems);
                self.elements = Some(existing);
            },
            None => {
                self.elements = Some(elems);
            }
        }
    }

    /// Clear all of the elements from the system.
    pub fn clear_elements(&mut self) {
        self.elements = None;
    }

    /// Propagate the beam through the elements in the system, returning the final beam.
    /// Will return an error if there is no beam in the system, or if there are no elements in
    /// the system.
    pub fn propagate(&self) -> Result<Beam> {
        // Bring the variant names into scope just for convenience.
        if self.elements.is_none() {
            return Err(JonesError::NoElements);
        }
        if self.beam.is_none() {
            return Err(JonesError::NoBeam);
        }
        let composite = self.composed_elements().unwrap();
        Ok(self.beam.clone().unwrap().apply_element(composite))
    }

    #[allow(clippy::let_and_return)]
    pub fn composed_elements(&self) -> Result<CompositeElement> {
        // Bring the variant names into scope just for convenience.
        use self::OpticalElement::*;
        if self.elements.is_none() {
            return Err(JonesError::NoElements);
        }
        if self.beam.is_none() {
            return Err(JonesError::NoBeam);
        }
        // This will be the "accumulator" for the call to 'fold'
        let ident = IdentityElement::new();
        // You can combine the optical elements into a single element by multiplying
        // them all together. Then the new beam can be created with 'apply_element'
        let composite_mat =
            self.elements
                .clone()
                .unwrap()
                .iter()
                .fold(ident.matrix(), |acc, elem| {
                    let mat = match *elem {
                        Polarizer(pol) => pol.matrix(),
                        PolarizationRotator(rot) => rot.matrix(),
                        Retarder(ret) => ret.matrix(),
                        QuarterWavePlate(qwp) => qwp.matrix(),
                        HalfWavePlate(hwp) => hwp.matrix(),
                        Identity(id) => id.matrix(),
                        Composite(comp) => comp.matrix(),
                    };
                    // Binding to "new" isn't strictly necessary, but it makes debugging easier
                    // since you can directly observe the value of "new".
                    let new = mat * acc;
                    new
                });
        Ok(CompositeElement::from_matrix(composite_mat))
    }
}

#[cfg(test)]
impl Arbitrary for OpticalSystem {
    type Parameters = ();
    type Strategy = BoxedStrategy<Self>;

    fn arbitrary_with(_: Self::Parameters) -> Self::Strategy {
        (
            option::of(any::<Beam>()),
            option::of(any::<Vec<OpticalElement>>()),
        )
            .prop_map(|(beam, elements)| OpticalSystem { beam, elements })
            .boxed()
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use jones::common::{are_rel_eq, Angle};
    use na::Matrix2;
    use num::complex::Complex;

    #[test]
    fn test_elements_are_applied_in_order() {
        // Pass a horizontal beam through a vertical polarizer and then a polarization
        // rotator. If applied in the correct order, the polarizer will kill the beam
        // since the beam and the polarizer axis are perpendicular. The polarization
        // rotator will have no effect in this case. If the elements are applied in the
        // wrong order, then the polarization rotator will rotate the beam to be
        // parallel to the polarizer and the final beam will have a non-zero intensity.
        let beam = Beam::linear(Angle::Degrees(0.0));
        let zero_beam = Beam::new(Complex::new(0_f64, 0_f64), Complex::new(0_f64, 0_f64));
        let pol = Polarizer::new(Angle::Degrees(90.0));
        let rot = PolarizationRotator::new(Angle::Degrees(90.0));
        let system = OpticalSystem::new()
            .add_beam(beam)
            .add_element(OpticalElement::Polarizer(pol))
            .add_element(OpticalElement::PolarizationRotator(rot));
        let beam_after = system.propagate();
        assert!(beam_after.is_ok());
        assert_beam_approx_eq!(beam_after.unwrap(), zero_beam);
    }

    #[test]
    fn test_element_is_added_to_system() {
        let ident = IdentityElement::new();
        let mut system = OpticalSystem::new().add_element(OpticalElement::Identity(ident));
        assert_eq!(system.elements.clone().unwrap().len(), 1);
        system = system.add_element(OpticalElement::Identity(ident));
        assert_eq!(system.elements.clone().unwrap().len(), 2);
    }

    proptest!{
        #[test]
        fn test_element_is_added_in_place(mut sys: OpticalSystem, elem: OpticalElement) {
            let len_before = match sys.elements.clone() {
                Some(elems) => {
                    elems.len()
                },
                None => 0
            };
            let len_expected = len_before + 1;
            sys.add_element_mut(elem);
            let len_after = sys.elements.clone().unwrap().len();
            prop_assert_eq!(len_after, len_expected);
        }

        #[test]
        fn test_elements_are_added_in_place(mut sys: OpticalSystem, elems: Vec<OpticalElement>) {
            let len_before = match sys.elements.clone() {
                Some(existing) => {
                    existing.len()
                },
                None => 0
            };
            let len_to_add = elems.len();
            let len_expected = len_before + len_to_add;
            sys.add_elements_mut(elems);
            let len_after = sys.elements.clone().unwrap().len();
            prop_assert_eq!(len_after, len_expected);
        }

        #[test]
        fn test_beam_is_added_in_place(mut sys: OpticalSystem, beam: Beam) {
            let beam_clone = beam.clone();
            sys.add_beam_mut(beam);
            let in_system = sys.beam.take().unwrap();
            prop_assert_beam_approx_eq!(in_system, beam_clone);
        }

        #[test]
        fn test_beam_is_cleared(mut sys: OpticalSystem) {
            prop_assume!(sys.beam.is_some());
            sys.clear_beam();
            prop_assert!(sys.beam.is_none());
        }

        #[test]
        fn test_elements_are_cleared(mut sys: OpticalSystem) {
            prop_assume!(sys.elements.is_some());
            sys.clear_elements();
            prop_assert!(sys.elements.is_none());
        }

        #[test]
        fn test_elements_are_added_to_system_during_construction(elems: Vec<OpticalElement>) {
            let num_elems = elems.len();
            let system = OpticalSystem::new().add_elements(elems);
            let num_elems_in_system = system.elements.clone().unwrap().len();
            prop_assert_eq!(num_elems, num_elems_in_system);
        }

        #[test]
        fn test_additional_elements_are_added_to_system(elems1: Vec<OpticalElement>, elems2: Vec<OpticalElement>) {
            let len1 = elems1.len();
            let len2 = elems2.len();
            let mut system = OpticalSystem::new().add_elements(elems1);
            let len_after_elems1 = system.elements.clone().unwrap().len();
            prop_assert_eq!(len_after_elems1, len1);
            system = system.add_elements(elems2);
            let len_after_elems2 = system.elements.clone().unwrap().len();
            let expected_len = len1 + len2;
            prop_assert_eq!(len_after_elems2, expected_len);
        }

        #[test]
        fn test_beam_passes_through(beam: Beam) {
            let ident = IdentityElement::new();
            let element = OpticalElement::Identity(ident);
            let system = OpticalSystem::new()
                .add_beam(beam.clone())
                .add_element(element);
            let beam_after = system.propagate();
            assert!(beam_after.is_ok());
            assert_beam_approx_eq!(beam_after.unwrap(), beam);
        }

        #[test]
        fn test_single_composed_element_is_returned_untouched(beam: Beam, elem: OpticalElement) {
            let system = OpticalSystem::new()
                .add_beam(beam)
                .add_element(elem.clone());
            let composed = system.composed_elements().unwrap().matrix();
            let original = elem.matrix();
            prop_assert_matrix_approx_eq!(composed, original);
        }

        #[test]
        fn test_composed_identity_looks_like_identity(beam: Beam) {
            let ident = IdentityElement::new();
            let system = OpticalSystem::new()
                .add_beam(beam)
                .add_element(OpticalElement::Identity(ident.clone()))
                .add_element(OpticalElement::Identity(ident.clone()))
                .add_element(OpticalElement::Identity(ident.clone()));
            let composed = system.composed_elements().unwrap().matrix();
            prop_assert_matrix_approx_eq!(composed, ident.matrix());
        }

        #[test]
        fn test_mat_composed_with_identity_is_untouched(beam: Beam, elem: CompositeElement) {
            let ident = IdentityElement::new();
            let system = OpticalSystem::new()
                .add_beam(beam)
                .add_element(OpticalElement::Identity(ident))
                .add_element(OpticalElement::Composite(elem.clone()));
            let composed = system.composed_elements().unwrap().matrix();
            prop_assert_matrix_approx_eq!(composed, elem.matrix());
        }

        #[test]
        fn test_system_propagates_as_if_elements_applied_individually(beam: Beam, elements: Vec<OpticalElement>) {
            let system = OpticalSystem::new()
                .add_beam(beam.clone())
                .add_elements(elements.clone());
            let by_propagation = system.propagate();
            prop_assume!(by_propagation.is_ok());
            let by_propagation = by_propagation.unwrap();
            let mut by_application = beam;
            for elem in elements {
                match elem {
                    OpticalElement::Identity(inner) => by_application = by_application.apply_element(inner),
                    OpticalElement::Composite(inner) => by_application = by_application.apply_element(inner),
                    OpticalElement::PolarizationRotator(inner) => by_application = by_application.apply_element(inner),
                    OpticalElement::Polarizer(inner) => by_application = by_application.apply_element(inner),
                    OpticalElement::QuarterWavePlate(inner) => by_application = by_application.apply_element(inner),
                    OpticalElement::HalfWavePlate(inner) => by_application = by_application.apply_element(inner),
                    OpticalElement::Retarder(inner) => by_application = by_application.apply_element(inner),
                }
            }
            prop_assert_beam_approx_eq!(by_propagation, by_application);
        }

        #[test]
        fn test_composed_matrix_looks_like_multiplied_individuals(beam: Beam, elements: Vec<OpticalElement>) {
            let system = OpticalSystem::new()
                .add_beam(beam.clone())
                .add_elements(elements.clone());
            let composed = system.composed_elements().unwrap().matrix();
            let mut multiplied: Matrix2<Complex<f64>> = Matrix2::identity();
            for elem in elements {
                match elem {
                    // Remember, the element that the beam encounters first must correspond to the
                    // matrix that appears on the right!
                    OpticalElement::Identity(inner) => multiplied = inner.matrix() * multiplied,
                    OpticalElement::Composite(inner) => multiplied = inner.matrix() * multiplied,
                    OpticalElement::PolarizationRotator(inner) => multiplied = inner.matrix() * multiplied,
                    OpticalElement::Polarizer(inner) => multiplied = inner.matrix() * multiplied,
                    OpticalElement::QuarterWavePlate(inner) => multiplied = inner.matrix() * multiplied,
                    OpticalElement::HalfWavePlate(inner) => multiplied = inner.matrix() * multiplied,
                    OpticalElement::Retarder(inner) => multiplied = inner.matrix() * multiplied,
                }
            }
            prop_assert_matrix_approx_eq!(composed, multiplied);
        }
    }
}