psrutils 0.2.7

A crate with a few utilities to facilitate pulsar science projects in rust.
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
//! Proveds a RW interface for `.par` files.
//!
//! # Examples
//!
//! ```
//! # use psrutils::parfile::Parfile;
//! # use psrutils::parfile::FittedParameterValue;
//! # use psrutils::data_types::J2000Ra;
//! # fn test() -> Result<(), psrutils::error::PsruError> {
//! let par_text = "
//!     PSR    J0000-9999\n\
//!     RA     23:59:59.999\n\
//!     DEC    45:59:59.999\n\
//!     PEPOCH 55000\n\
//!     F0     9001 1 0.0001\n\
//!     DM     1001.1
//! ".as_bytes();
//!
//! let par = Parfile::read(std::io::BufReader::new(par_text))?;
//!
//! // This is the name
//! let name_par = &par.texts[0];
//!
//! assert_eq!(name_par.name(), "PSR");
//! assert_eq!(name_par.value(), "J0000-9999");
//!
//! // This is the right ascension
//! let ra = J2000Ra::new(23, 59, 59.999).unwrap();
//! let fpv = FittedParameterValue::JustValue(ra);
//! assert_eq!(&fpv, par.ra.value());
//!
//! // This is the fundamental frequency
//! let f0_par = &par.parameters[1];
//! let fpv = FittedParameterValue::FitInfo{
//!     value: 9001.0,
//!     fit: true,
//!     error: 0.0001,
//! };
//! assert_eq!(f0_par.name(), "F0");
//! assert_eq!(f0_par.value(), &fpv);
//!
//! # Ok(())
//! }
//! ```

use std::io::{BufRead, BufWriter, Write};

pub use glitch::Glitch;
pub use jump::Jump;
use parameters::{
    COORDS, FittedParameter, J2000Fit, parse_coord, parse_count, parse_fitted,
    parse_flag, parse_text,
};
pub use parameters::{FittedParameterValue, Parameter};

use crate::{
    data_types::{DECCoordType, RACoordType},
    error::PsruError,
};

mod glitch;
mod jump;
mod parameters;
mod tests;

/// Time ephemeris used.
#[allow(missing_docs)]
#[derive(Debug, Default, PartialEq, Eq)]
pub enum TimeEphemeris {
    #[default]
    Unstated,

    IF99,
    FB90,
}
/// Binary model used.
#[allow(missing_docs)]
#[derive(Debug, Default, PartialEq, Eq)]
pub enum BinaryModel {
    #[default]
    Unstated,

    BT,
    ELL1,
    DD,
    MSS,
}
/// T2C method used.
#[allow(missing_docs)]
#[derive(Debug, Default, PartialEq, Eq)]
pub enum T2CMethod {
    #[default]
    Unstated,

    IAU2000B,
    TEMPO,
}
/// Error mode used.
#[allow(missing_docs)]
#[derive(Debug, Default, PartialEq, Eq)]
pub enum ErrorMode {
    #[default]
    Unstated,

    Mode0,
    Mode1,
}
/// Units used.
#[allow(missing_docs)]
#[derive(Debug, Default, PartialEq, Eq)]
pub enum Units {
    #[default]
    Unstated,

    SI,
    TCB,
    TDB,
}

/// Complete representation of a loaded .par file.
///
/// It follows the loose standards of TEMPO2, and as such is guaranteed to have
/// values for `PSR`, `F0`, `PEPOCH`, and `DM`. Some particular parameters
/// (e.g. `units`) are _not_ given default values when absent from a loaded
/// file, rather, they are set to `Unstated`.
///
/// Glitches and jumps are stored in vectors. Since glitches are multi-line
/// parameters, they are kept track of with indices (e.g. `GLEP_1`) and
/// disjunct ranges are considered erroneous.
///
/// All fields are public, since it is essentially just a datafile. There is,
/// however, a check of all values performed before writing. A failure in this
/// results in an error and no write.
#[derive(Debug, Default)]
pub struct Parfile {
    /// J2000 right ascension (hh:mm:ss.sss)
    pub ra: Parameter<J2000Fit<RACoordType>>,
    /// J2000 declination (dd:mm:ss.sss)
    pub dec: Parameter<J2000Fit<DECCoordType>>,

    /// All double precision parameters, and optional data on whether to fit
    /// them, with errors. See `FittedParameter` for more info.
    pub parameters: Vec<FittedParameter>,
    /// All integer parameters.
    pub counts: Vec<Parameter<u32>>,
    /// All text parameters.
    pub texts: Vec<Parameter<String>>,
    /// All boolean flags.
    pub flags: Vec<Parameter<bool>>,

    /// Glitches, if any
    pub glitches: Vec<Glitch>,
    /// Jumps, if any
    pub jumps: Vec<Jump>,

    /// Which time ephemeris to use
    pub time_eph: TimeEphemeris,
    /// Binary model
    pub binary_model: BinaryModel,
    /// Method for transforming from terrestrial to celestial frame
    pub t2c_method: T2CMethod,

    /// What units to use.
    pub units: Units,
    /// Which error mode to use.
    pub error_mode: ErrorMode,
}

impl Parfile {
    /// Reads a `BufReader` as a .par file.
    ///
    /// # Errors
    /// Returns errors for malformed entries,
    /// duplicate entries, missing mandatory parameters, and some
    /// out-of-bounds values.
    ///
    /// # Notes
    /// Most parameters are `f64` values, but some are `String`, a couple are
    /// `u32`, and a few have their own enums to avoid excessive `String`
    /// usage.
    pub fn read(reader: impl BufRead) -> Result<Self, PsruError> {
        let mut par = Self::default();

        for result in reader.lines() {
            let line = result?;
            if line.is_empty() {
                continue;
            }
            par.parse_line(&line)?;
        }

        par.check()?;

        Ok(par)
    }

    /// Writes itself to a stream.
    ///
    /// Note that the order of parameters and whitespace may differ from any
    /// input file used to construct it, but the contents will be consistent.
    ///
    /// # Errors
    /// Most opportunities for erros come from calls to `write_all`, but it
    /// will also throw an error if your .par file is missing a `name`
    /// parameter.
    pub fn write(&self, writer: &mut impl Write) -> Result<(), PsruError> {
        self.check()?;
        let mut writer = BufWriter::new(writer);

        // It's nice to put the name up top, even though it is a regular text
        // parameter... so we extract it here.
        let name_index = self
            .texts
            .iter()
            .position(|t| t.name() == "PSR")
            .ok_or(PsruError::ParNoName)?;

        let mut texts = self.texts.iter().collect::<Vec<_>>();

        let name = texts.remove(name_index);

        // The special fields
        let intro =
            format!("PSR {}\n{}\n{}\n", name.value(), self.ra, self.dec,);
        writer.write_all(intro.as_bytes())?;

        // Double params
        for parameter in &self.parameters {
            writer.write_all(format!("{parameter}\n").as_bytes())?;
        }

        // Integer params
        for parameter in &self.counts {
            let line = format!("{} {}\n", parameter.name(), parameter.value());
            writer.write_all(line.as_bytes())?;
        }

        // String params
        for parameter in texts {
            let line = format!("{} {}\n", parameter.name(), parameter.value());
            writer.write_all(line.as_bytes())?;
        }

        // Flags
        for parameter in &self.flags {
            let line = format!(
                "{} {}",
                parameter.name(),
                match parameter.value() {
                    true => "Y\n",
                    false => "N\n",
                }
            );
            writer.write_all(line.as_bytes())?;
        }

        // Oddballs
        if self.time_eph != TimeEphemeris::Unstated {
            let line = format!("TIMEEPH {:?}\n", self.time_eph);
            writer.write_all(line.as_bytes())?;
        }
        if self.binary_model != BinaryModel::Unstated {
            let line = format!("MODEL {:?}\n", self.binary_model);
            writer.write_all(line.as_bytes())?;
        }
        if self.units != Units::Unstated {
            let line = format!("UNITS {:?}\n", self.units);
            writer.write_all(line.as_bytes())?;
        }
        if self.t2c_method != T2CMethod::Unstated {
            let line = format!("T2CMETHOD {:?}\n", self.t2c_method);
            writer.write_all(line.as_bytes())?;
        }
        match self.error_mode {
            ErrorMode::Unstated => {}
            ErrorMode::Mode0 => writer.write_all(b"MODE 0\n")?,
            ErrorMode::Mode1 => writer.write_all(b"MODE 1\n")?,
        }

        // Glitches
        for glitch in &self.glitches {
            let lines = glitch.write();
            writer.write_all(lines.as_bytes())?;
        }

        // Jumps
        for jump in &self.jumps {
            let line = jump.write();
            writer.write_all(line.as_bytes())?;
        }

        writer.flush()?;

        Ok(())
    }

    fn parse_line(&mut self, line: &str) -> Result<(), PsruError> {
        let parts = line.split_whitespace().collect::<Vec<_>>();
        if parts.len() < 2 {
            return Err(PsruError::ParMissingValue(parts[0].to_string()));
        }

        if Glitch::parse(&parts, &mut self.glitches)? {
            return Ok(());
        }
        if Jump::parse(&parts, &mut self.jumps)? {
            return Ok(());
        }
        if self.parse_special(&parts)? {
            return Ok(());
        }

        if let Some(flag) = parse_flag(&parts)? {
            self.flags.push(flag);
            return Ok(());
        }
        if let Some(param) = parse_fitted(&parts)? {
            self.parameters.push(param);
            return Ok(());
        }
        if let Some(param) = parse_count(&parts)? {
            self.counts.push(param);
            return Ok(());
        }
        if let Some(param) = parse_text(&parts)? {
            self.texts.push(param);
            return Ok(());
        }

        Ok(())
    }

    fn parse_special(&mut self, parts: &[&str]) -> Result<bool, PsruError> {
        let key = parts[0];
        let value = parts[1];

        // Coords
        if COORDS[0].1.contains(&key) {
            if *self.ra.value() != FittedParameterValue::Missing {
                return Err(PsruError::ParRepeatParam(COORDS[0].0.to_string()));
            }

            self.ra = Parameter::new(
                &COORDS[0],
                parse_coord::<RACoordType>(value, parts)?,
            );

            return Ok(true);
        }
        if COORDS[1].1.contains(&key) {
            if *self.dec.value() != FittedParameterValue::Missing {
                return Err(PsruError::ParRepeatParam(COORDS[1].0.to_string()));
            }

            self.dec = Parameter::new(
                &COORDS[1],
                parse_coord::<DECCoordType>(value, parts)?,
            );

            return Ok(true);
        }

        // Which time ephemeris to use (IF99/FB90)
        if "TIMEEPH" == key {
            if self.time_eph != TimeEphemeris::Unstated {
                return Err(PsruError::ParRepeatParam(String::from("TIMEEPH")));
            }
            self.time_eph = match value {
                "IF99" => TimeEphemeris::IF99,
                "FB90" => TimeEphemeris::FB90,
                other => {
                    return Err(PsruError::UnknownTimeEphemeris(
                        other.to_string(),
                    ));
                }
            };
            return Ok(true);
        }

        // Binary model
        if "MODEL" == key {
            if self.binary_model != BinaryModel::Unstated {
                return Err(PsruError::ParRepeatParam(String::from("MODEL")));
            }
            self.binary_model = match value {
                "BT" => BinaryModel::BT,
                "DD" => BinaryModel::DD,
                "ELL1" => BinaryModel::ELL1,
                "MSS" => BinaryModel::MSS,
                other => {
                    return Err(PsruError::UnknownBinaryModel(
                        other.to_string(),
                    ));
                }
            };
            return Ok(true);
        }

        // Method for transforming from terrestrial to celestial frame
        if "T2CMETHOD" == key {
            if self.t2c_method != T2CMethod::Unstated {
                return Err(PsruError::ParRepeatParam(String::from(
                    "T2CMETHOD",
                )));
            }
            self.t2c_method = match value {
                "TEMPO" => T2CMethod::TEMPO,
                "IAU2000B" => T2CMethod::IAU2000B,
                other => {
                    return Err(PsruError::UnknownT2CMethod(other.to_string()));
                }
            };
            return Ok(true);
        }

        // Units
        if "UNITS" == key {
            if self.units != Units::Unstated {
                return Err(PsruError::ParRepeatParam(String::from("UNITS")));
            }
            self.units = match value {
                "SI" => Units::SI,
                "TCB" => Units::TCB,
                "TDB" => Units::TDB,
                other => {
                    return Err(PsruError::UnknownUnits(other.to_string()));
                }
            };
            return Ok(true);
        }

        if "MODE" == key {
            if self.error_mode != ErrorMode::Unstated {
                return Err(PsruError::ParRepeatParam(String::from("MODE")));
            }
            self.error_mode = match value {
                "0" => ErrorMode::Mode0,
                "1" => ErrorMode::Mode1,
                other => {
                    return Err(PsruError::UnknownErrorMode(other.to_string()));
                }
            };
            return Ok(true);
        }

        Ok(false)
    }

    /// Performs a little check to see everything's ok.
    fn check(&self) -> Result<(), PsruError> {
        // Check mandatory params
        if !self.texts.iter().any(|t| t.name() == "PSR") {
            return Err(PsruError::ParNoName);
        }
        self.parameters
            .iter()
            .find(|t| t.name() == "PEPOCH")
            .map_or_else(
                || Err(PsruError::ParNoPEpoch),
                |p| {
                    if match *p.value() {
                        FittedParameterValue::Missing => false,
                        FittedParameterValue::JustValue(value)
                        | FittedParameterValue::FitInfo { value, .. } => {
                            value > 0.0
                        }
                    } {
                        Ok(())
                    } else {
                        Err(PsruError::ParBadPEpoch)
                    }
                },
            )?;

        self.parameters
            .iter()
            .find(|t| t.name() == "F0")
            .map_or_else(
                || Err(PsruError::ParNoFrequency),
                |p| {
                    if match *p.value() {
                        FittedParameterValue::Missing => false,
                        FittedParameterValue::JustValue(value)
                        | FittedParameterValue::FitInfo { value, .. } => {
                            value > 0.0
                        }
                    } {
                        Ok(())
                    } else {
                        Err(PsruError::ParBadFrequency)
                    }
                },
            )?;

        if !self.parameters.iter().any(|t| t.name() == "DM") {
            return Err(PsruError::ParNoDispersion);
        }

        // Check for duplicates
        let p64dupes = find_duplicates(&self.parameters);
        if !p64dupes.is_empty() {
            return Err(PsruError::ParDuplicateParameters(
                p64dupes
                    .into_iter()
                    .map(|(i, j)| {
                        (
                            self.parameters[i].to_string(),
                            self.parameters[j].to_string(),
                        )
                    })
                    .collect(),
            ));
        }
        let ptdupes = find_duplicates(&self.texts);
        if !ptdupes.is_empty() {
            return Err(PsruError::ParDuplicateParameters(
                ptdupes
                    .into_iter()
                    .map(|(i, j)| {
                        (
                            self.parameters[i].to_string(),
                            self.parameters[j].to_string(),
                        )
                    })
                    .collect(),
            ));
        }
        let fdupes = find_duplicates(&self.flags);
        if !fdupes.is_empty() {
            return Err(PsruError::ParDuplicateParameters(
                fdupes
                    .into_iter()
                    .map(|(i, j)| {
                        (
                            self.parameters[i].name().to_string(),
                            self.parameters[j].name().to_string(),
                        )
                    })
                    .collect(),
            ));
        }

        // Check glitches
        for glitch in &self.glitches {
            glitch.check()?;
        }

        Ok(())
    }
}

fn find_duplicates<T>(params: &[Parameter<T>]) -> Vec<(usize, usize)> {
    params
        .iter()
        .enumerate()
        .filter_map(|(i, p1)| {
            params[i + 1..]
                .iter()
                .enumerate()
                .find(|(_, p2)| p1.name() == p2.name())
                .map(|(j, _)| (i, j))
        })
        .collect()
}