alpha_g_detector 0.5.1

A Rust library to handle the raw output of the ALPHA-g detectors
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
use crate::padwing::{AfterId, BoardId, PadChannelId};
use lazy_static::lazy_static;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::f64::consts::PI;
use thiserror::Error;

/// Full length (in meters) of the detector along the Z axis.
pub const DETECTOR_LENGTH: f64 = 2.304;
/// Radius (in meters) of the position of the cathode pads.
pub const CATHODE_PADS_RADIUS: f64 = 0.190;
/// Number of pad columns in a Padwing board.
pub const PWB_PAD_COLUMNS: usize = 4;
/// Number of pad rows in a Padwing board.
pub const PWB_PAD_ROWS: usize = 72;
/// Number of PWB columns in the rTPC.
pub const TPC_PWB_COLUMNS: usize = 8;
/// Number of PWB rows in the rTPC.
pub const TPC_PWB_ROWS: usize = 8;
/// Number of pad columns in the rTPC.
pub const TPC_PAD_COLUMNS: usize = TPC_PWB_COLUMNS * PWB_PAD_COLUMNS;
/// Number of pad rows in the rTPC.
pub const TPC_PAD_ROWS: usize = TPC_PWB_ROWS * PWB_PAD_ROWS;
/// Number of pads in the rTPC.
pub const TPC_PADS: usize = TPC_PAD_COLUMNS * TPC_PAD_ROWS;
/// Distance (in meters) between the center of two adjacent pads in the Z
/// direction.
pub const PAD_PITCH_Z: f64 = DETECTOR_LENGTH / (TPC_PAD_ROWS as f64);
/// Angle (in radians) between the center of two adjacent pads in the
/// azimuthal direction.
pub const PAD_PITCH_PHI: f64 = 2.0 * PI / (TPC_PAD_COLUMNS as f64);

/// The error type returned when conversion from [`usize`] to Row or Column
/// fails.
#[derive(Debug, Error)]
#[error("unknown conversion from {input} to row or column")]
pub struct TryPositionFromIndexError {
    input: usize,
}

/// Column of a Padwing board in the rTPC.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct TpcPwbColumn(usize);
impl TryFrom<usize> for TpcPwbColumn {
    type Error = TryPositionFromIndexError;

    /// Convert from a `usize` (`0..=7`) to a [`TpcPwbColumn`].
    fn try_from(value: usize) -> Result<Self, Self::Error> {
        if value < TPC_PWB_COLUMNS {
            Ok(Self(value))
        } else {
            Err(TryPositionFromIndexError { input: value })
        }
    }
}

/// Row of a Padwing board in the rTPC.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct TpcPwbRow(usize);
impl TryFrom<usize> for TpcPwbRow {
    type Error = TryPositionFromIndexError;

    /// Convert from a `usize` (`0..=7`) to a [`TpcPwbRow`].
    fn try_from(value: usize) -> Result<Self, Self::Error> {
        if value < TPC_PWB_ROWS {
            Ok(Self(value))
        } else {
            Err(TryPositionFromIndexError { input: value })
        }
    }
}

// Map of all PWB boards as installed on the rTPC in run number X (included).
// First index is column, second index is row.
// The value is the board name.
//
// When you add a new map, remember to add the unit tests for it:
//     - Uniqueness of all &str.
//     - Validity of all &str.
//     - Test inverse map.
//
// Also remember to add the inverse (actually needed) map to the lazy_static
// below and update TpcPwbPosition::try_new.
const PADWING_BOARDS_4418: [[&str; TPC_PWB_ROWS]; TPC_PWB_COLUMNS] = [
    ["12", "13", "14", "02", "11", "17", "18", "19"],
    ["20", "21", "22", "23", "24", "25", "26", "27"],
    ["46", "29", "08", "77", "10", "33", "34", "35"],
    ["36", "37", "01", "39", "76", "41", "42", "40"],
    ["44", "49", "07", "78", "03", "04", "45", "15"],
    ["52", "53", "54", "55", "56", "57", "58", "05"],
    ["60", "00", "06", "63", "64", "65", "66", "67"],
    ["68", "69", "70", "71", "72", "73", "74", "75"],
];

const PADWING_BOARDS_10418: [[&str; TPC_PWB_ROWS]; TPC_PWB_COLUMNS] = [
    ["12", "13", "14", "02", "11", "17", "18", "19"],
    ["20", "21", "22", "23", "24", "25", "26", "27"],
    ["90", "29", "08", "85", "10", "33", "34", "35"],
    ["36", "37", "01", "39", "76", "41", "42", "40"],
    ["89", "49", "07", "87", "03", "04", "84", "91"],
    ["52", "53", "54", "55", "56", "57", "58", "81"],
    ["60", "00", "44", "63", "64", "65", "66", "67"],
    ["68", "69", "70", "71", "72", "73", "74", "75"],
];

fn inverse_pwb_map(
    map: [[&str; TPC_PWB_ROWS]; TPC_PWB_COLUMNS],
) -> HashMap<BoardId, TpcPwbPosition> {
    let mut inverse = HashMap::new();
    for (column, row) in map.iter().enumerate() {
        for (row, name) in row.iter().enumerate() {
            inverse.insert(
                // Safe to unwrap. Unit tests should validate that this cant fail.
                BoardId::try_from(*name).unwrap(),
                TpcPwbPosition {
                    column: TpcPwbColumn::try_from(column).unwrap(),
                    row: TpcPwbRow::try_from(row).unwrap(),
                },
            );
        }
    }
    inverse
}

lazy_static! {
    // Whenever a new map is added, just add it to this list.
    static ref INV_PADWING_BOARDS_4418: HashMap<BoardId, TpcPwbPosition> =
        inverse_pwb_map(PADWING_BOARDS_4418);
    static ref INV_PADWING_BOARDS_10418: HashMap<BoardId, TpcPwbPosition> =
        inverse_pwb_map(PADWING_BOARDS_10418);
}

/// The error type returned when mapping a [`BoardId`] to a [`TpcPwbPosition`]
/// fails.
#[derive(Debug, Error)]
pub enum MapTpcPwbPositionError {
    /// There is no mapping available for the given `run_number`.
    #[error("no rTPC PWB mapping available for run number {run_number}")]
    MissingMap { run_number: u32 },
    /// The given [`BoardId`] is not in the map for the given `run_number`.
    #[error("pwb `{}` not found in map for run number {run_number}", board_id.name())]
    BoardIdNotFound { run_number: u32, board_id: BoardId },
}

/// Position of a Padwing board in the rTPC.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct TpcPwbPosition {
    column: TpcPwbColumn,
    row: TpcPwbRow,
}
impl TpcPwbPosition {
    /// Create a new [`TpcPwbPosition`] from a [`TpcPwbColumn`] and a
    /// [`TpcPwbRow`].
    ///
    /// # Examples
    ///
    /// ```
    /// use alpha_g_detector::padwing::map::{TpcPwbColumn, TpcPwbPosition, TpcPwbRow};
    ///
    /// let column = TpcPwbColumn::try_from(0).unwrap();
    /// let row = TpcPwbRow::try_from(0).unwrap();
    ///
    /// let position = TpcPwbPosition::new(column, row);
    /// ```
    pub fn new(column: TpcPwbColumn, row: TpcPwbRow) -> Self {
        Self { column, row }
    }
    /// Map a [`BoardId`] to a [`TpcPwbPosition`] for a given `run_number`.
    /// Returns an error if there is no map available for the given `run_number`
    /// or if the given [`BoardId`] is not installed in the rTPC for that
    /// `run_number`.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// use alpha_g_detector::padwing::map::TpcPwbPosition;
    /// use alpha_g_detector::padwing::BoardId;
    ///
    /// let run_number = 5000;
    /// let board_id = BoardId::try_from("26")?;
    ///
    /// let position = TpcPwbPosition::try_new(run_number, board_id)?;
    /// # Ok(())
    /// # }
    pub fn try_new(run_number: u32, board_id: BoardId) -> Result<Self, MapTpcPwbPositionError> {
        let position_map = match run_number {
            // u32::MAX corresponds to a simulation run. The simulation mapping
            // was done to match the mapping of run number 5000.
            u32::MAX => &*INV_PADWING_BOARDS_4418,
            10418.. => &*INV_PADWING_BOARDS_10418,
            4418.. => &*INV_PADWING_BOARDS_4418,
            _ => return Err(MapTpcPwbPositionError::MissingMap { run_number }),
        };

        position_map
            .get(&board_id)
            .copied()
            .ok_or(MapTpcPwbPositionError::BoardIdNotFound {
                run_number,
                board_id,
            })
    }
    /// Return the column of the Padwing board within the rTPC.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// use alpha_g_detector::padwing::map::{TpcPwbPosition, TpcPwbColumn};
    /// use alpha_g_detector::padwing::BoardId;
    ///
    /// let run_number = 5000;
    /// let board_id = BoardId::try_from("26")?;
    /// let position = TpcPwbPosition::try_new(run_number, board_id)?;
    ///
    /// assert_eq!(position.column(), TpcPwbColumn::try_from(1)?);
    /// # Ok(())
    /// # }
    pub fn column(&self) -> TpcPwbColumn {
        self.column
    }
    /// Return the row of the Padwing board within the rTPC.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// use alpha_g_detector::padwing::map::{TpcPwbPosition, TpcPwbRow};
    /// use alpha_g_detector::padwing::BoardId;
    ///
    /// let run_number = 5000;
    /// let board_id = BoardId::try_from("26")?;
    /// let position = TpcPwbPosition::try_new(run_number, board_id)?;
    ///
    /// assert_eq!(position.row(), TpcPwbRow::try_from(6)?);
    /// # Ok(())
    /// # }
    /// ```
    pub fn row(&self) -> TpcPwbRow {
        self.row
    }
}

/// Column of a pad in a Padwing Board.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct PwbPadColumn(usize);
impl TryFrom<usize> for PwbPadColumn {
    type Error = TryPositionFromIndexError;

    /// Convert from a `usize` (`0..=3`) to a [`PwbPadColumn`].
    fn try_from(value: usize) -> Result<Self, Self::Error> {
        if value < PWB_PAD_COLUMNS {
            Ok(Self(value))
        } else {
            Err(TryPositionFromIndexError { input: value })
        }
    }
}

/// Row of a pad in a Padwing Board.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct PwbPadRow(usize);
impl TryFrom<usize> for PwbPadRow {
    type Error = TryPositionFromIndexError;

    /// Convert from a `usize` (`0..=71`) to a [`PwbPadRow`].
    fn try_from(value: usize) -> Result<Self, Self::Error> {
        if value < PWB_PAD_ROWS {
            Ok(Self(value))
        } else {
            Err(TryPositionFromIndexError { input: value })
        }
    }
}

// I don't see the following mapping between (AFTER, channel) -> Position
// changing or being updated any time soon. It would imply an excessive amount
// of hardware work. Nonetheless, I am leaving this mapping as a function of
// `run_number` to be consistent with the anode wire mapping. If it changes at
// some point, just do the same as the above PWB mapping or the anode wire
// mapping.
lazy_static! {
    // Map copied directly from agana/Feam.hh written by K.O.
    static ref INV_PADS_0: HashMap<(AfterId, PadChannelId), PwbPadPosition> = {
        let mut inverse = HashMap::new();
        for after in 0..=3u8 {
            let offset = (after % 2) * 36;
            for channel in 1..=72u8 {
                let mut col: u8;
                let mut row: u8;
                match channel {
                    0..=18 => {
                        col = 1;
                        row = channel - 1 + offset;
                    },
                    19..=36 => {
                        col = 0;
                        row = 36 - channel + offset;
                    },
                    37..=54 => {
                        col = 0;
                        row = 72 - channel + offset;
                    },
                    55..=72 => {
                        col = 1;
                        row = channel - 37 + offset;
                    }
                    _ => unreachable!(),
                }
                if after > 1 {
                    col = 3 - col;
                    row = 71 - row;
                }
                inverse.insert(
                    (
                        AfterId::try_from(after).unwrap(),
                        PadChannelId::try_from(u16::from(channel)).unwrap(),
                    ),
                    PwbPadPosition {
                        column: PwbPadColumn::try_from(usize::from(col)).unwrap(),
                        row: PwbPadRow::try_from(usize::from(row)).unwrap(),
                    },
                );
            }
        }
        inverse
    };
}

/// The error type returned when mapping an [`AfterId`] and [`PadChannelId`] to a
/// [`PwbPadPosition`] fails.
#[derive(Debug, Error)]
#[error("no PWB pad mapping available for run number {run_number}")]
pub struct MapPwbPadPositionError {
    run_number: u32,
}

/// Position of a pad in a Padwing Board.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct PwbPadPosition {
    column: PwbPadColumn,
    row: PwbPadRow,
}
impl PwbPadPosition {
    /// Create a new [`PwbPadPosition`] from a [`PwbPadColumn`] and a
    /// [`PwbPadRow`].
    ///
    /// # Examples
    ///
    /// ```
    /// use alpha_g_detector::padwing::map::{PwbPadPosition, PwbPadColumn, PwbPadRow};
    ///
    /// let column = PwbPadColumn::try_from(0).unwrap();
    /// let row = PwbPadRow::try_from(0).unwrap();
    ///
    /// let position = PwbPadPosition::new(column, row);
    /// ```
    pub fn new(column: PwbPadColumn, row: PwbPadRow) -> Self {
        Self { column, row }
    }
    /// Map an [`AfterId`] and [`PadChannelId`] to a [`PwbPadPosition`] for a
    /// given `run_number`. Returns an error if there is no map available for
    /// that `run_number`.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// use alpha_g_detector::padwing::map::PwbPadPosition;
    /// use alpha_g_detector::padwing::{AfterId, PadChannelId};
    ///
    /// let run_number = 5000;
    /// let after_id = AfterId::try_from('A')?;
    /// let pad_channel_id = PadChannelId::try_from(1)?;
    ///
    /// let position = PwbPadPosition::try_new(run_number, after_id, pad_channel_id)?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn try_new(
        _run_number: u32,
        after_id: AfterId,
        pad_channel_id: PadChannelId,
    ) -> Result<PwbPadPosition, MapPwbPadPositionError> {
        // If this ever changes (and becomes a function of run number), recall
        // that simulation (run number u32::MAX) was written to match the map
        // from run number 5000.
        let position_map = &INV_PADS_0;
        Ok(*position_map.get(&(after_id, pad_channel_id)).unwrap())
    }
    /// Return the column of the pad within the Padwing Board.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// use alpha_g_detector::padwing::map::{PwbPadPosition, PwbPadColumn};
    /// use alpha_g_detector::padwing::{AfterId, PadChannelId};
    ///
    /// let run_number = 5000;
    /// let after_id = AfterId::try_from('A')?;
    /// let pad_channel_id = PadChannelId::try_from(1)?;
    ///
    /// let position = PwbPadPosition::try_new(run_number, after_id, pad_channel_id)?;
    ///
    /// assert_eq!(position.column(), PwbPadColumn::try_from(1)?);
    /// # Ok(())
    /// # }
    /// ```
    pub fn column(&self) -> PwbPadColumn {
        self.column
    }
    /// Return the row of the pad within the Padwing Board.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// use alpha_g_detector::padwing::map::{PwbPadPosition, PwbPadRow};
    /// use alpha_g_detector::padwing::{AfterId, PadChannelId};
    ///
    /// let run_number = 5000;
    /// let after_id = AfterId::try_from('A')?;
    /// let pad_channel_id = PadChannelId::try_from(1)?;
    ///
    /// let position = PwbPadPosition::try_new(run_number, after_id, pad_channel_id)?;
    ///
    /// assert_eq!(position.row(), PwbPadRow::try_from(0)?);
    /// # Ok(())
    /// # }
    /// ```
    pub fn row(&self) -> PwbPadRow {
        self.row
    }
}

/// Column of a pad in the rTPC.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
// These are needed because otherwise it would be possible to deserialize some
// invalid values (e.g. handwritten columns greater than 31).
#[serde(try_from = "usize", into = "usize")]
pub struct TpcPadColumn(usize);
impl TryFrom<usize> for TpcPadColumn {
    type Error = TryPositionFromIndexError;

    /// Convert from a `usize` (`0..=31`) to a [`TpcPadColumn`]. Do not assume
    /// angular position of a pad column based on this index; the
    /// [`TpcPadColumn::phi()`] method should be used instead.
    fn try_from(value: usize) -> Result<Self, Self::Error> {
        if value < TPC_PAD_COLUMNS {
            Ok(TpcPadColumn(value))
        } else {
            Err(TryPositionFromIndexError { input: value })
        }
    }
}
// I would rather not have this implementation, but it is needed for the
// serialization of the TpcPadColumn to be consistent with the
// deserialization.
// In theory this should not be used by the user explicitly.
impl From<TpcPadColumn> for usize {
    /// Convert to the `u: usize` such that
    /// `TpcPadColumn::try_from(u).unwrap() == self`. Do not assume angular
    /// position of a pad column based on this index; the
    /// [`TpcPadColumn::phi()`] method should always be used instead.
    ///
    /// If you are explicitly using this conversion, you are probably doing
    /// something wrong.
    fn from(pad_column: TpcPadColumn) -> Self {
        pad_column.0
    }
}
impl TpcPadColumn {
    /// Return the `phi` coordinate (in radians) of the pad column.
    pub fn phi(&self) -> f64 {
        let column = self.0;
        (column as f64 + 0.5) * PAD_PITCH_PHI
    }
}

/// Row of a pad in the rTPC.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
// These are needed because otherwise it would be possible to deserialize some
// invalid values (e.g. handwritten rows greater than 575).
#[serde(try_from = "usize", into = "usize")]
pub struct TpcPadRow(usize);
impl TryFrom<usize> for TpcPadRow {
    type Error = TryPositionFromIndexError;

    /// Convert from a `usize` (`0..=575`) to a [`TpcPadRow`]. Do not assume a
    /// `z` position of a pad row based on this index; the
    /// [`TpcPadRow::z()`] method should be used instead.
    fn try_from(value: usize) -> Result<Self, Self::Error> {
        if value < TPC_PAD_ROWS {
            Ok(TpcPadRow(value))
        } else {
            Err(TryPositionFromIndexError { input: value })
        }
    }
}
// I would rather not have this implementation, but it is needed for the
// serialization of the TpcPadRow to be consistent with the deserialization.
// In theory this should not be used by the user explicitly.
impl From<TpcPadRow> for usize {
    /// Convert to the `u: usize` such that
    /// `TpcPadRow::try_from(u).unwrap() == self`. Do not assume `z` position of
    /// a pad row based on this index; the [`TpcPadRow::z()`] method should
    /// always be used instead.
    ///
    /// If you are explicitly using this conversion, you are probably doing
    /// something wrong.
    fn from(pad_row: TpcPadRow) -> Self {
        pad_row.0
    }
}
impl TpcPadRow {
    /// Return the `z` coordinate (in meters) of the pad row. The `z` coordinate
    /// is measured from the center of the rTPC (positive upward).
    pub fn z(&self) -> f64 {
        let row = self.0;
        const DETECTOR_HALF_LENGTH: f64 = 0.5 * DETECTOR_LENGTH;
        (row as f64 + 0.5) * PAD_PITCH_Z - DETECTOR_HALF_LENGTH
    }
}

/// The error type returned when mapping a [`BoardId`], [`AfterId`], and
/// [`PadChannelId`] to a [`TpcPadPosition`] fails.
#[derive(Debug, Error)]
pub enum MapTpcPadPositionError {
    /// For the given `run_number`, it was not possible to map the [`BoardId`]
    /// to a [`TpcPwbPosition`].
    #[error("unable to map PWB in the rTPC")]
    BadTpcPwbPosition(#[from] MapTpcPwbPositionError),
    /// For the given `run_number`, it was not possible to map the [`AfterId`]
    /// and [`PadChannelId`] to a [`PwbPadPosition`].
    #[error("unable to map pad in the PWB")]
    BadPwbPadPosition(#[from] MapPwbPadPositionError),
}

/// Position of a pad in the rTPC.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct TpcPadPosition {
    pub column: TpcPadColumn,
    pub row: TpcPadRow,
}
impl TpcPadPosition {
    /// Map a [`TpcPwbPosition`] and [`PwbPadPosition`] to a [`TpcPadPosition`].
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// use alpha_g_detector::padwing::map::{TpcPadPosition, TpcPwbPosition, PwbPadPosition};
    /// use alpha_g_detector::padwing::{AfterId, PadChannelId, BoardId};
    ///
    /// let run_number = 5000;
    /// let board = BoardId::try_from("26")?;
    /// let board_pos = TpcPwbPosition::try_new(run_number, board)?;
    ///
    /// let after = AfterId::try_from('A')?;
    /// let pad_channel = PadChannelId::try_from(1)?;
    /// let pad_pos = PwbPadPosition::try_new(run_number, after, pad_channel)?;
    ///
    /// let tpc_pad_position = TpcPadPosition::new(board_pos, pad_pos);
    /// # Ok(())
    /// # }
    /// ```
    pub fn new(board_position: TpcPwbPosition, pad_position: PwbPadPosition) -> Self {
        let TpcPwbPosition { column, row } = board_position;
        let PwbPadPosition {
            column: pad_column,
            row: pad_row,
        } = pad_position;
        let column = TpcPadColumn::try_from(column.0 * PWB_PAD_COLUMNS + pad_column.0).unwrap();
        let row = TpcPadRow::try_from(row.0 * PWB_PAD_ROWS + pad_row.0).unwrap();
        TpcPadPosition { column, row }
    }
    /// Map a [`BoardId`], [`AfterId`], and [`PadChannelId`] to a
    /// [`TpcPadPosition`].
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// use alpha_g_detector::padwing::map::TpcPadPosition;
    /// use alpha_g_detector::padwing::{AfterId, PadChannelId, BoardId};
    ///
    /// let run_number = 5000;
    /// let board = BoardId::try_from("26")?;
    /// let after = AfterId::try_from('A')?;
    /// let pad_channel = PadChannelId::try_from(1)?;
    ///
    /// let tpc_pad_position = TpcPadPosition::try_new(run_number, board, after, pad_channel)?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn try_new(
        run_number: u32,
        board_id: BoardId,
        after_id: AfterId,
        pad_channel_id: PadChannelId,
    ) -> Result<Self, MapTpcPadPositionError> {
        let board_position = TpcPwbPosition::try_new(run_number, board_id)?;
        let pad_position = PwbPadPosition::try_new(run_number, after_id, pad_channel_id)?;
        Ok(TpcPadPosition::new(board_position, pad_position))
    }
    /// Return the `z` coordinate (in meters) of the pad center within the rTPC.
    /// The `z` coordinate is measured from the center of the rTPC (positive
    /// upward).
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// use alpha_g_detector::padwing::map::TpcPadPosition;
    /// use alpha_g_detector::padwing::{AfterId, PadChannelId, BoardId};
    ///
    /// let run_number = 5000;
    /// let board = BoardId::try_from("26")?;
    /// let after = AfterId::try_from('A')?;
    /// let pad_channel = PadChannelId::try_from(1)?;
    /// let tpc_pad_position = TpcPadPosition::try_new(run_number, board, after, pad_channel)?;
    ///
    /// let abs_difference = (tpc_pad_position.z() - 0.578).abs();
    /// assert!(abs_difference < 1e-10);
    /// # Ok(())
    /// # }
    /// ```
    pub fn z(&self) -> f64 {
        self.row.z()
    }
    /// Return the `phi` coordinate (in radians) of the pad center within the
    /// rTPC.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// use alpha_g_detector::padwing::map::TpcPadPosition;
    /// use alpha_g_detector::padwing::{AfterId, PadChannelId, BoardId};
    ///
    /// let run_number = 5000;
    /// let board = BoardId::try_from("26")?;
    /// let after = AfterId::try_from('A')?;
    /// let pad_channel = PadChannelId::try_from(1)?;
    /// let tpc_pad_position = TpcPadPosition::try_new(run_number, board, after, pad_channel)?;
    ///
    /// let abs_difference = (tpc_pad_position.phi() - 1.0799224746).abs();
    /// assert!(abs_difference < 1e-10);
    /// # Ok(())
    /// # }
    /// ```
    pub fn phi(&self) -> f64 {
        self.column.phi()
    }
}

#[cfg(test)]
mod tests;