1use nereids_core::types::Isotope;
5use nereids_endf::resonance::ResonanceData;
6use nereids_endf::retrieval::EndfLibrary;
7use nereids_fitting::lm::FlatMatrix;
8use nereids_fitting::poisson::Prior;
9use nereids_fitting::statistics::{Consistency, agreement};
10use nereids_physics::lattice_doppler::PhononSpectrum;
11use nereids_physics::resolution::TOF_FACTOR;
12use nereids_physics::transmission::resonance_center_energies;
13use serde::{Deserialize, Serialize};
14
15use crate::counts_fit::TEMPERATURE_BOUNDS_K;
16use crate::counts_fit::{
17 CountsFit, ExcludedRange, Material, Measurement, Region, Value, fit_counts, quantities,
18};
19use crate::error::PipelineError;
20use crate::open_beam::{Calibration, PULSE_NUMBERS, Pulse};
21
22#[derive(Debug, Clone)]
26pub struct PulsePrior {
27 pub(crate) numbers: Vec<usize>,
28 pub(crate) mean: Vec<f64>,
29 pub(crate) covariance: FlatMatrix,
30}
31
32impl Pulse {
33 pub(crate) fn uncalibrated_line(
34 &self,
35 isotopes: &[(ResonanceData, Value)],
36 time_edges_us: &[f64],
37 t0_us: f64,
38 flight_path_m: f64,
39 ) -> Option<f64> {
40 let (low, high) = self.line_span_ev?;
41 let present = isotopes
42 .iter()
43 .filter(|(_, density)| *density != Value::Known(0.0))
44 .map(|(isotope, _)| isotope);
45 lines_in_window(present, time_edges_us, t0_us, flight_path_m)
46 .into_iter()
47 .find(|e| !(low..=high).contains(e))
48 }
49}
50
51const FORMAT_VERSION: u32 = 6;
52
53const PULSE_MODEL: &str = "Ikeda–Carpenter pulse with α = α₀·E^p_α + α₁ and β = β₀·E^p_β + β₁ in \
54 1/µs, E in eV, a storage fraction R, constant or linear in √E to R_high across the energy span, \
55 folded with the proton pulse's triangle of FWHM h and, when present, a detector tail of \
56 fraction f and decay τ_D";
57
58const NUMBERS: [(&str, &str); 11] = [
59 ("alpha0", "1/(µs·eV^alpha_exponent)"),
60 ("alpha1", "1/µs"),
61 ("beta0", "1/(µs·eV^beta_exponent)"),
62 ("beta1", "1/µs"),
63 ("r", "1"),
64 ("fwhm_squared", "µs²"),
65 ("r_high", "1"),
66 ("tail_fraction", "1"),
67 ("tail_decay", "µs"),
68 ("alpha_exponent", "1"),
69 ("beta_exponent", "1"),
70];
71
72#[derive(Debug, Clone, PartialEq, Eq)]
76pub struct Provenance {
77 pub foil: String,
78 pub open: String,
79 pub sample: String,
80}
81
82#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
83#[serde(rename_all = "snake_case")]
84enum Status {
85 Fitted,
86 Known,
87 Absent,
88}
89
90#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
91#[serde(deny_unknown_fields)]
92struct Stated {
93 value: f64,
94 #[serde(deserialize_with = "Option::deserialize")]
95 sd: Option<f64>,
96}
97
98#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
99#[serde(deny_unknown_fields)]
100struct FoilIsotope {
101 #[serde(with = "nuclide")]
102 isotope: Isotope,
103 density: Stated,
104}
105
106mod nuclide {
107 use nereids_core::types::Isotope;
108 use serde::{Deserialize, Deserializer, Serialize, Serializer};
109
110 #[derive(Serialize, Deserialize)]
111 #[serde(deny_unknown_fields)]
112 struct Nuclide {
113 z: u32,
114 a: u32,
115 }
116
117 pub(super) fn serialize<S: Serializer>(isotope: &Isotope, s: S) -> Result<S::Ok, S::Error> {
118 Nuclide {
119 z: isotope.z(),
120 a: isotope.a(),
121 }
122 .serialize(s)
123 }
124
125 pub(super) fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Isotope, D::Error> {
126 let nuclide = Nuclide::deserialize(d)?;
127 Isotope::new(nuclide.z, nuclide.a).map_err(serde::de::Error::custom)
128 }
129}
130
131#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
132#[serde(deny_unknown_fields)]
133struct Lattice {
134 step_ev: f64,
135 density: Vec<f64>,
136}
137
138#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
139#[serde(deny_unknown_fields)]
140struct Foil {
141 isotopes: Vec<FoilIsotope>,
142 temperature_k: Stated,
143 #[serde(deserialize_with = "Option::deserialize")]
144 lattice: Option<Lattice>,
145 library: EndfLibrary,
146 #[serde(default, skip_serializing_if = "Vec::is_empty")]
147 excluded_ranges: Vec<ExcludedRange>,
148}
149
150#[derive(Debug, Clone)]
166pub struct PulseCalibration {
167 numbers: [f64; 11],
168 status: [Status; 11],
169 prior: Option<PulsePrior>,
170 t0_us: f64,
171 flight_path_m: f64,
172 energy_span_ev: (f64, f64),
173 n_tau: usize,
174 line_span_ev: Option<(f64, f64)>,
175 foil: Foil,
176 provenance: Provenance,
177 sample_overdispersion: Option<f64>,
178 transfer: Option<TransferRecord>,
179}
180
181impl PulseCalibration {
182 pub fn new(
210 measurement: &Measurement,
211 calibration: &Calibration,
212 provenance: Provenance,
213 ) -> Result<(Self, CountsFit), PipelineError> {
214 let foil = foil(measurement)?;
215 check_provenance(&provenance)?;
216 let pulse = &calibration.pulse;
217 let measured = pulse
218 .numbers()
219 .iter()
220 .any(|value| matches!(value, Value::Measured { .. } | Value::Within { .. }));
221 if pulse.prior.is_some() || measured {
222 return Err(PipelineError::InvalidParameter(
223 "a calibration foil is calibrated alone, its pulse numbers fitted over their \
224 physical ranges or known, with no pulse prior"
225 .into(),
226 ));
227 }
228 let fit = fit_counts(measurement, calibration)?;
229 let pulse = Self::from_fit(measurement, calibration, foil, provenance, &fit)?;
230 Ok((pulse, fit))
231 }
232
233 fn from_fit(
234 measurement: &Measurement,
235 calibration: &Calibration,
236 foil: Foil,
237 provenance: Provenance,
238 fit: &CountsFit,
239 ) -> Result<Self, PipelineError> {
240 let invalid = |message: String| Err(PipelineError::InvalidParameter(message));
241 if !fit.converged {
242 let rule = fit
243 .unconverged
244 .as_ref()
245 .map_or(String::new(), |rule| format!(": {rule}"));
246 return invalid(format!("a pulse calibration needs a converged fit{rule}"));
247 }
248 let fitted: Vec<bool> = quantities(measurement, calibration)
249 .map(|(_, value)| !matches!(value, Value::Known(_)))
250 .collect();
251 let first_number = fitted.len() - PULSE_NUMBERS.len();
252 let mut status = [Status::Known; 11];
253 let mut covered = Vec::with_capacity(11);
254 for (number, name) in PULSE_NUMBERS.into_iter().enumerate() {
255 let quantity = first_number + number;
256 let i = fitted[..quantity].iter().filter(|&&f| f).count();
257 if !fitted[quantity] {
258 continue;
259 }
260 let Some(unbounded) = fit.unbounded.as_ref() else {
261 return invalid(
262 "the calibration's fit gives no Gaussian without its bounds, as when a bin \
263 predicted zero pulls a quantity on its bound"
264 .into(),
265 );
266 };
267 let variance = unbounded.covariance.get(i, i);
268 if !(variance.is_finite() && variance > 0.0) {
269 return invalid(format!(
270 "the calibration fitted {name} without determining it: its variance is \
271 {variance}"
272 ));
273 }
274 status[number] = Status::Fitted;
275 covered.push((number, i));
276 }
277 if fit.r_high.is_none() {
278 status[6] = Status::Absent;
279 }
280 if fit.detector_tail.is_none() {
281 status[7..9].fill(Status::Absent);
282 }
283 let tail = fit.detector_tail.unwrap_or([0.0; 2]);
284 let numbers = [
285 fit.alpha[0],
286 fit.alpha[1],
287 fit.beta[0],
288 fit.beta[1],
289 fit.r,
290 fit.fwhm_squared_us2,
291 fit.r_high.unwrap_or(0.0),
292 tail[0],
293 tail[1],
294 fit.exponents[0],
295 fit.exponents[1],
296 ];
297 let line_span_ev = if fitted[first_number..].contains(&true) {
298 let present = foil_material(measurement)?
299 .isotopes
300 .iter()
301 .zip(&fit.regions[0].densities)
302 .filter(|(_, density)| **density > 0.0)
303 .map(|((isotope, _), _)| isotope);
304 let lines = lines_in_window(
305 present,
306 &measurement.time_edges_us,
307 fit.t0_us + fit.regions[0].timing_offset_us,
308 fit.flight_path_m,
309 );
310 if lines.is_empty() {
311 return invalid(
312 "the calibration foil has no resonance in its window to bound the energies \
313 its pulse holds over"
314 .into(),
315 );
316 }
317 Some(
318 lines
319 .iter()
320 .fold((f64::INFINITY, f64::NEG_INFINITY), |(low, high), &e| {
321 (low.min(e), high.max(e))
322 }),
323 )
324 } else {
325 None
326 };
327 let prior = if let Some(unbounded) = fit.unbounded.as_ref().filter(|_| !covered.is_empty())
328 {
329 let n = covered.len();
330 let covariance = &unbounded.covariance;
331 let mut block = FlatMatrix::zeros(n, n);
332 for (a, &(_, i)) in covered.iter().enumerate() {
333 for (b, &(_, j)) in covered.iter().enumerate() {
334 *block.get_mut(a, b) = 0.5 * (covariance.get(i, j) + covariance.get(j, i));
335 }
336 }
337 let numbers: Vec<usize> = covered.iter().map(|&(number, _)| number).collect();
338 let mean: Vec<f64> = covered.iter().map(|&(_, i)| unbounded.mean[i]).collect();
339 Prior::correlated(&numbers, &mean, &block)?;
340 Some(PulsePrior {
341 numbers,
342 mean,
343 covariance: block,
344 })
345 } else {
346 None
347 };
348 Ok(Self {
349 numbers,
350 status,
351 prior,
352 t0_us: fit.t0_us,
353 flight_path_m: fit.flight_path_m,
354 energy_span_ev: calibration.pulse.energy_span_ev,
355 n_tau: calibration.pulse.n_tau,
356 line_span_ev,
357 foil,
358 provenance,
359 sample_overdispersion: fit.regions[0].overdispersion[1],
360 transfer: None,
361 })
362 }
363
364 pub fn transfer(&self, other: &PulseCalibration) -> Result<Transfer, PipelineError> {
384 let invalid = |message: String| Err(PipelineError::InvalidParameter(message));
385 if !separate(&self.provenance, &other.provenance) {
386 return invalid(format!(
387 "a transfer is to a physically different foil that shares no run but the \
388 open-beam run; got {:?} and {:?}",
389 self.provenance, other.provenance
390 ));
391 }
392 for (n, name) in PULSE_NUMBERS.into_iter().enumerate() {
393 let (a, b) = (self.status[n], other.status[n]);
394 if a != b || (a == Status::Known && self.numbers[n] != other.numbers[n]) {
395 return invalid(format!(
396 "the two calibrations hold {name} differently, {a:?} at {} and {b:?} at {}, \
397 so they describe different pulse models",
398 self.numbers[n], other.numbers[n]
399 ));
400 }
401 }
402 let (Some(this), Some(that)) = (&self.prior, &other.prior) else {
403 return invalid("the two calibrations fit no pulse number".into());
404 };
405 let prior = |p: &PulsePrior| Prior::correlated(&p.numbers, &p.mean, &p.covariance);
406 let result = agreement(&prior(this)?, &prior(that)?)?;
407 Ok(Transfer {
408 record: TransferRecord {
409 foil: other.foil.clone(),
410 provenance: FileProvenance::from(&other.provenance),
411 sample_overdispersion: other.sample_overdispersion,
412 d2: result.q,
413 dof: result.dof,
414 p: result.p,
415 },
416 })
417 }
418
419 pub fn record_transfer(mut self, other: &PulseCalibration) -> Result<Self, PipelineError> {
428 let record = self.transfer(other)?.record;
429 if record.p <= TRANSFER_P {
430 return Err(PipelineError::InvalidParameter(format!(
431 "the pulse does not transfer: d² = {} on {} degrees of freedom gives p = {}, at \
432 most {TRANSFER_P}; the calibration is not written",
433 record.d2, record.dof, record.p
434 )));
435 }
436 self.transfer = Some(record);
437 Ok(self)
438 }
439
440 pub fn calibration(&self) -> Calibration {
444 let value = |number: usize| match self.status[number] {
445 Status::Fitted => Value::Fitted(self.numbers[number]),
446 Status::Known | Status::Absent => Value::Known(self.numbers[number]),
447 };
448 let present = |number: usize| self.status[number] != Status::Absent;
449 Calibration {
450 t0_us: Value::Fitted(self.t0_us),
451 flight_path_m: Value::Fitted(self.flight_path_m),
452 pulse: Pulse {
453 alpha: [value(0), value(1)],
454 beta: [value(2), value(3)],
455 exponents: [value(9), value(10)],
456 r: value(4),
457 fwhm_squared_us2: value(5),
458 r_high: present(6).then(|| value(6)),
459 detector_tail: present(7).then(|| [value(7), value(8)]),
460 energy_span_ev: self.energy_span_ev,
461 n_tau: self.n_tau,
462 line_span_ev: self.line_span_ev,
463 prior: self.prior.clone(),
464 },
465 }
466 }
467
468 pub fn to_json(&self) -> String {
482 let covariance = self.prior.as_ref().map_or_else(Vec::new, |prior| {
483 let k = prior.numbers.len();
484 (0..k)
485 .map(|a| (0..k).map(|b| prior.covariance.get(a, b)).collect())
486 .collect()
487 });
488 let mean = self
489 .prior
490 .as_ref()
491 .map_or_else(Vec::new, |prior| prior.mean.clone());
492 let file = File {
493 format_version: FORMAT_VERSION,
494 pulse_model: PULSE_MODEL.into(),
495 numbers: NUMBERS
496 .iter()
497 .zip(self.numbers)
498 .zip(self.status)
499 .map(|((&(name, unit), value), status)| Number {
500 name: name.into(),
501 unit: unit.into(),
502 value,
503 status,
504 })
505 .collect(),
506 mean,
507 rank: covariance.len(),
508 covariance,
509 t0_us: self.t0_us,
510 flight_path_m: self.flight_path_m,
511 energy_span_ev: self.energy_span_ev,
512 n_tau: self.n_tau,
513 line_span_ev: self.line_span_ev,
514 foil: self.foil.clone(),
515 provenance: FileProvenance::from(&self.provenance),
516 sample_overdispersion: self.sample_overdispersion,
517 transfer: self
518 .transfer
519 .clone()
520 .map_or(FileTransfer::Unchecked(Unchecked::Unchecked), |record| {
521 FileTransfer::Checked(Box::new(record))
522 }),
523 };
524 serde_json::to_string_pretty(&file).expect("these field types always serialize")
525 }
526
527 pub fn from_json(text: &str) -> Result<Self, PipelineError> {
552 let invalid = |message: String| Err(PipelineError::InvalidParameter(message));
553 let header: Header = match serde_json::from_str(text) {
554 Ok(header) => header,
555 Err(e) => return invalid(format!("not a pulse calibration file: {e}")),
556 };
557 if header.format_version != FORMAT_VERSION || header.pulse_model != PULSE_MODEL {
558 return invalid(format!(
559 "a pulse calibration file of format version {FORMAT_VERSION} and the pulse model \
560 {PULSE_MODEL:?} is read; got version {} and the model {:?}",
561 header.format_version, header.pulse_model
562 ));
563 }
564 let file: File = match serde_json::from_str(text) {
565 Ok(file) => file,
566 Err(e) => return invalid(format!("not a pulse calibration file: {e}")),
567 };
568 if file.numbers.len() != NUMBERS.len()
569 || NUMBERS
570 .iter()
571 .zip(&file.numbers)
572 .any(|(&(name, unit), number)| number.name != name || number.unit != unit)
573 {
574 return invalid(format!(
575 "the pulse numbers are (name, unit) {NUMBERS:?}, in that order"
576 ));
577 }
578 let numbers: [f64; 11] = std::array::from_fn(|n| file.numbers[n].value);
579 let status: [Status; 11] = std::array::from_fn(|n| file.numbers[n].status);
580 let absent = |n: usize| status[n] == Status::Absent;
581 if (0..6).chain(9..11).any(absent) || absent(7) != absent(8) {
582 return invalid(format!(
583 "only R_high or both of the detector tail's numbers are absent; got {status:?}"
584 ));
585 }
586 if let Some(n) = (6..9).find(|&n| absent(n) && numbers[n] != 0.0) {
587 return invalid(format!(
588 "an absent pulse number has the value 0; got {} for {}",
589 numbers[n], NUMBERS[n].0
590 ));
591 }
592 let covered: Vec<usize> = (0..11).filter(|&n| status[n] == Status::Fitted).collect();
593 let k = covered.len();
594 if file.rank != k
595 || file.mean.len() != k
596 || file.covariance.len() != k
597 || file.covariance.iter().any(|row| row.len() != k)
598 {
599 return invalid(format!(
600 "the mean has {k} entries and the covariance is {k}×{k}, of rank {k}, over the {k} \
601 fitted numbers; got rank {}, {} entries and {} rows",
602 file.rank,
603 file.mean.len(),
604 file.covariance.len()
605 ));
606 }
607 let fitted = k > 0;
608 let (first, last) = file.energy_span_ev;
609 let span_holds = match file.line_span_ev {
610 Some((low, high)) => fitted && first <= low && low <= high && high <= last,
611 None => !fitted,
612 };
613 if !span_holds {
614 return invalid(format!(
615 "the line span is present, within the energy span {:?}, exactly when a pulse \
616 number was fitted; got {:?}",
617 file.energy_span_ev, file.line_span_ev
618 ));
619 }
620 let provenance = Provenance::from(file.provenance);
621 check_provenance(&provenance)?;
622 if file
623 .sample_overdispersion
624 .is_some_and(|phi| !(phi.is_finite() && phi >= 1.0))
625 {
626 return invalid(format!(
627 "the overdispersion is 1 or more; got {:?}",
628 file.sample_overdispersion
629 ));
630 }
631 check_foil(&file.foil)?;
632 let prior = if fitted {
633 let mut covariance = FlatMatrix::zeros(k, k);
634 for (a, row) in file.covariance.iter().enumerate() {
635 for (b, &entry) in row.iter().enumerate() {
636 *covariance.get_mut(a, b) = entry;
637 }
638 }
639 Prior::correlated(&covered, &file.mean, &covariance)?;
640 Some(PulsePrior {
641 numbers: covered,
642 mean: file.mean,
643 covariance,
644 })
645 } else {
646 None
647 };
648 let transfer = match file.transfer {
649 FileTransfer::Unchecked(_) => None,
650 FileTransfer::Checked(record) => {
651 check_record(&record, &provenance, k)?;
652 Some(*record)
653 }
654 };
655 let pulse = Self {
656 numbers,
657 status,
658 prior,
659 t0_us: file.t0_us,
660 flight_path_m: file.flight_path_m,
661 energy_span_ev: file.energy_span_ev,
662 n_tau: file.n_tau,
663 line_span_ev: file.line_span_ev,
664 foil: file.foil,
665 provenance,
666 sample_overdispersion: file.sample_overdispersion,
667 transfer,
668 };
669 let experiment = pulse.calibration();
670 let start: Vec<f64> = experiment
671 .instrument()?
672 .iter()
673 .map(|parameter| parameter.value)
674 .collect();
675 experiment.pulse.at(&start[2..])?;
676 Ok(pulse)
677 }
678}
679
680const TRANSFER_P: f64 = 0.01;
681
682#[derive(Debug, Clone, PartialEq)]
685pub struct Transfer {
686 record: TransferRecord,
687}
688
689impl Transfer {
690 pub fn agreement(&self) -> Consistency {
692 Consistency {
693 q: self.record.d2,
694 dof: self.record.dof,
695 p: self.record.p,
696 }
697 }
698}
699
700#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
701#[serde(untagged)]
702enum FileTransfer {
703 Unchecked(Unchecked),
704 Checked(Box<TransferRecord>),
705}
706
707#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
708#[serde(rename_all = "snake_case")]
709enum Unchecked {
710 Unchecked,
711}
712
713#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
714#[serde(deny_unknown_fields)]
715struct TransferRecord {
716 foil: Foil,
717 provenance: FileProvenance,
718 #[serde(deserialize_with = "Option::deserialize")]
719 sample_overdispersion: Option<f64>,
720 d2: f64,
721 dof: usize,
722 p: f64,
723}
724
725#[derive(Deserialize)]
726struct Header {
727 format_version: u32,
728 pulse_model: String,
729}
730
731#[derive(Serialize, Deserialize)]
732#[serde(deny_unknown_fields)]
733struct File {
734 format_version: u32,
735 pulse_model: String,
736 numbers: Vec<Number>,
737 mean: Vec<f64>,
738 covariance: Vec<Vec<f64>>,
739 rank: usize,
740 t0_us: f64,
741 flight_path_m: f64,
742 energy_span_ev: (f64, f64),
743 n_tau: usize,
744 #[serde(deserialize_with = "Option::deserialize")]
745 line_span_ev: Option<(f64, f64)>,
746 foil: Foil,
747 provenance: FileProvenance,
748 #[serde(deserialize_with = "Option::deserialize")]
749 sample_overdispersion: Option<f64>,
750 transfer: FileTransfer,
751}
752
753#[derive(Serialize, Deserialize)]
754#[serde(deny_unknown_fields)]
755struct Number {
756 name: String,
757 unit: String,
758 value: f64,
759 status: Status,
760}
761
762#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
763#[serde(deny_unknown_fields)]
764struct FileProvenance {
765 foil: String,
766 open: String,
767 sample: String,
768}
769
770impl From<&Provenance> for FileProvenance {
771 fn from(provenance: &Provenance) -> Self {
772 Self {
773 foil: provenance.foil.clone(),
774 open: provenance.open.clone(),
775 sample: provenance.sample.clone(),
776 }
777 }
778}
779
780impl From<FileProvenance> for Provenance {
781 fn from(file: FileProvenance) -> Self {
782 Self {
783 foil: file.foil,
784 open: file.open,
785 sample: file.sample,
786 }
787 }
788}
789
790fn check_record(
791 record: &TransferRecord,
792 provenance: &Provenance,
793 rank: usize,
794) -> Result<(), PipelineError> {
795 let other = Provenance::from(record.provenance.clone());
796 check_provenance(&other)?;
797 check_foil(&record.foil)?;
798 let statistic = record.dof == rank
799 && Consistency::new(record.d2, record.dof)
800 .is_ok_and(|test| (record.p / test.p - 1.0).abs() <= 1e-12)
801 && record.p > TRANSFER_P;
802 if !separate(provenance, &other)
803 || record
804 .sample_overdispersion
805 .is_some_and(|phi| !(phi.is_finite() && phi >= 1.0))
806 || !statistic
807 {
808 return Err(PipelineError::InvalidParameter(format!(
809 "a recorded transfer is to another foil sharing no run but the open-beam run, on as \
810 many degrees of freedom as numbers fitted, with d² of 0 or more and p its χ² \
811 survival and above {TRANSFER_P}; got {record:?}"
812 )));
813 }
814 Ok(())
815}
816
817fn separate(a: &Provenance, b: &Provenance) -> bool {
818 a.foil != b.foil && a.sample != b.sample && a.sample != b.open && a.open != b.sample
819}
820
821fn check_provenance(provenance: &Provenance) -> Result<(), PipelineError> {
822 if provenance.foil.is_empty()
823 || provenance.open.is_empty()
824 || provenance.sample.is_empty()
825 || provenance.open == provenance.sample
826 {
827 return Err(PipelineError::InvalidParameter(format!(
828 "a calibration names its foil and its open-beam and sample runs, the two runs \
829 different; got {provenance:?}"
830 )));
831 }
832 Ok(())
833}
834
835fn foil_material(measurement: &Measurement) -> Result<&Material, PipelineError> {
836 let [
837 Region {
838 material: Some(material),
839 ..
840 },
841 ] = measurement.regions.as_slice()
842 else {
843 return Err(PipelineError::InvalidParameter(
844 "a pulse calibration fits the foil alone, as one region holding it".into(),
845 ));
846 };
847 Ok(material)
848}
849
850fn foil(measurement: &Measurement) -> Result<Foil, PipelineError> {
851 let material = foil_material(measurement)?;
852 let unmeasured = |what: &str, value: &Value| {
853 Err(PipelineError::InvalidParameter(format!(
854 "a calibration foil's {what} is measured, with its stated uncertainty; got {value:?}"
855 )))
856 };
857 let mut isotopes = Vec::with_capacity(material.isotopes.len());
858 for (data, density) in &material.isotopes {
859 let density = match *density {
860 Value::Measured { value, sd } => Stated {
861 value,
862 sd: Some(sd),
863 },
864 Value::Known(value) if value == 0.0 => Stated { value, sd: None },
865 other => return unmeasured(&format!("density of {}", data.isotope), &other),
866 };
867 isotopes.push(FoilIsotope {
868 isotope: data.isotope,
869 density,
870 });
871 }
872 let Value::Measured { value, sd } = material.temperature_k else {
873 return unmeasured("temperature", &material.temperature_k);
874 };
875 Ok(Foil {
876 isotopes,
877 temperature_k: Stated {
878 value,
879 sd: Some(sd),
880 },
881 lattice: material.lattice.as_ref().map(|spectrum| Lattice {
882 step_ev: spectrum.step_ev(),
883 density: spectrum.density().to_vec(),
884 }),
885 library: material.library,
886 excluded_ranges: material.excluded_ranges.clone(),
887 })
888}
889
890fn check_foil(foil: &Foil) -> Result<(), PipelineError> {
891 let value = |stated: Stated| match stated.sd {
892 Some(sd) => Value::Measured {
893 value: stated.value,
894 sd,
895 },
896 None => Value::Known(stated.value),
897 };
898 let isotopes = &foil.isotopes;
899 if isotopes.is_empty()
900 || isotopes
901 .iter()
902 .any(|isotope| isotope.density.sd.is_none() && isotope.density.value != 0.0)
903 || (0..isotopes.len()).any(|i| {
904 isotopes[..i]
905 .iter()
906 .any(|other| other.isotope == isotopes[i].isotope)
907 })
908 || foil.temperature_k.sd.is_none()
909 {
910 return Err(PipelineError::InvalidParameter(format!(
911 "a calibration foil has distinct isotopes, each measured or known to be absent, and \
912 a measured temperature; got {foil:?}"
913 )));
914 }
915 for isotope in &foil.isotopes {
916 value(isotope.density).parameter("density", 0.0..=f64::INFINITY, "0 or more")?;
917 }
918 let (low, high) = TEMPERATURE_BOUNDS_K;
919 value(foil.temperature_k).parameter(
920 "temperature",
921 low..=high,
922 &format!("within {low}–{high} K"),
923 )?;
924 if let Some(lattice) = &foil.lattice {
925 PhononSpectrum::new(lattice.step_ev, lattice.density.clone()).map_err(|e| {
926 PipelineError::InvalidParameter(format!("a calibration foil's lattice has an {e}"))
927 })?;
928 }
929 foil.excluded_ranges
930 .iter()
931 .try_for_each(ExcludedRange::check)
932}
933
934fn lines_in_window<'a>(
935 isotopes: impl Iterator<Item = &'a ResonanceData>,
936 time_edges_us: &[f64],
937 t0_us: f64,
938 flight_path_m: f64,
939) -> Vec<f64> {
940 let energy = |t: f64| (TOF_FACTOR * flight_path_m / (t - t0_us).max(0.0)).powi(2);
941 let window = energy(time_edges_us[time_edges_us.len() - 1])..=energy(time_edges_us[0]);
942 isotopes
943 .flat_map(|isotope| resonance_center_energies(&[isotope]))
944 .filter(|e| window.contains(e))
945 .collect()
946}
947
948#[cfg(test)]
949mod tests {
950 use nereids_endf::resonance::test_support::{synthetic_isotope, synthetic_isotope_multi};
951
952 use nereids_fitting::poisson::Unbounded;
953
954 use super::*;
955 use crate::beam::BeamSpline;
956 use crate::counts_fit::{NO_TIME_BACKGROUND, RegionFit};
957
958 type Edit = (&'static str, fn(&mut serde_json::Value));
959
960 fn measurement(absent: Option<f64>) -> Measurement {
961 let lines = [(10.0, 0.05, 0.06), (25.0, 0.005, 0.06), (50.0, 0.01, 0.06)];
962 let foil = (
963 synthetic_isotope_multi(73, 181, &lines),
964 Value::Measured {
965 value: 2e-3,
966 sd: 2e-5,
967 },
968 );
969 let impurity = absent.map(|energy| {
970 (
971 synthetic_isotope(74, 184, energy, 0.01, 0.06),
972 Value::Known(0.0),
973 )
974 });
975 let edges: Vec<f64> = (0..=45).map(|i| 240.0 + 8.0 * f64::from(i)).collect();
976 let bins = edges.len() - 1;
977 Measurement {
978 time_edges_us: edges,
979 charge_ratio: 1.0,
980 normalization: Value::Known(1.0),
981 time_background: NO_TIME_BACKGROUND,
982 room_background: None,
983 spread: None,
984 environment_scatter: None,
985 filter: None,
986 regions: vec![Region {
987 open_counts: vec![100.0; bins],
988 sample_counts: vec![100.0; bins],
989 open_live: None,
990 sample_live: None,
991 background: [Value::Known(0.0); 5],
992 pixels: 1.0,
993 gamma_transmission: Value::Known(1.0),
994 capture_gammas: Value::Known(0.0),
995 in_scatter: Value::Known(0.0),
996 timing_offset_us: Value::Known(0.0),
997 material: Some(Material {
998 covariances: Vec::new(),
999 library: EndfLibrary::EndfB8_0,
1000 excluded_ranges: Vec::new(),
1001 isotopes: std::iter::once(foil).chain(impurity).collect(),
1002 temperature_k: Value::Measured {
1003 value: 300.0,
1004 sd: 10.0,
1005 },
1006 thickness_variance: Value::Known(0.0),
1007 lattice: None,
1008 }),
1009 }],
1010 }
1011 }
1012
1013 fn material(m: &mut Measurement) -> &mut Material {
1014 m.regions[0].material.as_mut().expect("the foil")
1015 }
1016
1017 fn provenance() -> Provenance {
1018 Provenance {
1019 foil: "foil-a".into(),
1020 open: "open-1".into(),
1021 sample: "sample-1".into(),
1022 }
1023 }
1024
1025 fn calibrated(
1026 m: &Measurement,
1027 c: &Calibration,
1028 fit: CountsFit,
1029 ) -> Result<PulseCalibration, PipelineError> {
1030 PulseCalibration::from_fit(m, c, foil(m)?, provenance(), &fit)
1031 }
1032
1033 fn calibration(beta1: Value) -> Calibration {
1034 Calibration {
1035 t0_us: Value::Fitted(3.0),
1036 flight_path_m: Value::Fitted(25.0),
1037 pulse: Pulse {
1038 alpha: [Value::Known(0.5), Value::Fitted(1.0)],
1039 beta: [Value::Fitted(0.08), beta1],
1040 exponents: [Value::Known(0.5); 2],
1041 r: Value::Fitted(0.2),
1042 fwhm_squared_us2: Value::Fitted(0.1),
1043 r_high: None,
1044 detector_tail: None,
1045 energy_span_ev: (1.0, 200.0),
1046 n_tau: 256,
1047 line_span_ev: None,
1048 prior: None,
1049 },
1050 }
1051 }
1052
1053 fn fit(free: usize) -> CountsFit {
1054 let mut covariance = FlatMatrix::zeros(free, free);
1055 for i in 0..free {
1056 *covariance.get_mut(i, i) = 0.01 * (i + 1) as f64;
1057 }
1058 let (r, h) = (free - 2, free - 1);
1059 let pairs = [(4, r, 0.01), (4, h, -0.005), (r, h, 0.02), (2, 4, 0.003)];
1060 for (i, j, c) in pairs.into_iter().filter(|&(i, j, _)| i.max(j) < free) {
1061 *covariance.get_mut(i, j) = c;
1062 *covariance.get_mut(j, i) = c;
1063 }
1064 let unbounded = Unbounded {
1065 mean: (0..free).map(|i| -0.002 * (i + 1) as f64).collect(),
1066 covariance: FlatMatrix {
1067 data: covariance.data.iter().map(|c| 2.0 * c).collect(),
1068 ..covariance.clone()
1069 },
1070 };
1071 CountsFit {
1072 regions: vec![RegionFit {
1073 excluded_bins: Vec::new(),
1074 densities: vec![2e-3],
1075 temperature_k: Some(300.0),
1076 thickness_variance: Some(0.0),
1077 background: [0.0; 5],
1078 gamma_transmission: 1.0,
1079 capture_gammas: 0.0,
1080 in_scatter: 0.0,
1081 timing_offset_us: 0.0,
1082 beam: BeamSpline::constant(200.0, 600.0, 1.0),
1083 beam_at_limit: false,
1084 predicted: [Vec::new(), Vec::new()],
1085 overdispersion: [None; 2],
1086 }],
1087 normalization: 1.0,
1088 t0_us: 3.0,
1089 flight_path_m: 25.0,
1090 alpha: [0.5, 1.1],
1091 beta: [0.0, 0.01],
1092 exponents: [0.5; 2],
1093 r: 0.21,
1094 fwhm_squared_us2: 0.12,
1095 r_high: None,
1096 detector_tail: None,
1097 time_background: [0.0, 0.0, 1.0, 0.0],
1098 room_background: 0.0,
1099 spread_share: 0.0,
1100 scatter_fraction: 0.0,
1101 filter_density: 0.0,
1102 covariance: Some(covariance),
1103 unbounded: Some(unbounded),
1104 on_bound: vec![false; free],
1105 deviance: 0.0,
1106 converged: true,
1107 unconverged: None,
1108 measured_pulls: None,
1109 pulse_consistency: None,
1110 step_us: 0.1,
1111 points: 10,
1112 halvings: 0,
1113 }
1114 }
1115
1116 #[test]
1117 fn a_calibration_keeps_every_fitted_number_with_its_unbounded_uncertainty() {
1118 let (m, c) = (measurement(Some(55.0)), calibration(Value::Known(0.01)));
1119 let mut with_impurity = fit(8);
1120 with_impurity.regions[0].densities = vec![2e-3, 0.0];
1121 let experiment = calibrated(&m, &c, with_impurity).unwrap().calibration();
1122 let pulse = &experiment.pulse;
1123 assert_eq!(pulse.alpha, [Value::Known(0.5), Value::Fitted(1.1)]);
1124 assert_eq!(pulse.beta, [Value::Fitted(0.0), Value::Known(0.01)]);
1125 assert_eq!(
1126 [pulse.r, pulse.fwhm_squared_us2],
1127 [Value::Fitted(0.21), Value::Fitted(0.12)]
1128 );
1129 assert_eq!(
1130 [experiment.t0_us, experiment.flight_path_m],
1131 [Value::Fitted(3.0), Value::Fitted(25.0)]
1132 );
1133 let prior = pulse.prior.as_ref().expect("prior");
1134 assert_eq!(prior.numbers, [1, 2, 4, 5]);
1135 let unbounded = fit(8).unbounded.expect("unbounded");
1136 let at = [4, 5, 6, 7];
1137 assert_eq!(prior.mean, at.map(|i| unbounded.mean[i]));
1138 for (a, i) in at.into_iter().enumerate() {
1139 for (b, j) in at.into_iter().enumerate() {
1140 assert_eq!(prior.covariance.get(a, b), unbounded.covariance.get(i, j));
1141 }
1142 }
1143 assert_eq!(pulse.line_span_ev, Some((10.0, 50.0)));
1144
1145 let mut undetermined = fit(8);
1146 let mut withheld = fit(8);
1147 let covariance = &mut undetermined
1148 .unbounded
1149 .as_mut()
1150 .expect("unbounded")
1151 .covariance;
1152 for i in 0..8 {
1153 *covariance.get_mut(5, i) = f64::NAN;
1154 *covariance.get_mut(i, 5) = f64::NAN;
1155 }
1156 withheld
1157 .unbounded
1158 .as_mut()
1159 .expect("unbounded")
1160 .covariance
1161 .data
1162 .fill(f64::NAN);
1163 for (refused, refusal) in [
1164 (undetermined, "without determining it"),
1165 (withheld, "without determining it"),
1166 (
1167 CountsFit {
1168 converged: false,
1169 ..fit(8)
1170 },
1171 "converged fit",
1172 ),
1173 (
1174 CountsFit {
1175 unbounded: None,
1176 ..fit(8)
1177 },
1178 "no Gaussian without its bounds",
1179 ),
1180 ] {
1181 match calibrated(&m, &c, refused) {
1182 Err(PipelineError::InvalidParameter(message)) => {
1183 assert!(message.contains(refusal), "{message}")
1184 }
1185 other => panic!("{other:?}"),
1186 }
1187 }
1188 }
1189
1190 #[test]
1191 fn a_calibration_without_lines_or_with_a_singular_block_is_refused() {
1192 let c = calibration(Value::Known(0.01));
1193 let mut beyond = measurement(None);
1194 material(&mut beyond).isotopes[0].0 = synthetic_isotope(73, 181, 100.0, 0.05, 0.06);
1195 assert!(matches!(
1196 calibrated(&beyond, &c, fit(8)),
1197 Err(PipelineError::InvalidParameter(_))
1198 ));
1199 let mut singular = fit(8);
1200 let covariance = &mut singular.unbounded.as_mut().expect("unbounded").covariance;
1201 let (a, b) = (covariance.get(4, 4), covariance.get(6, 6));
1202 *covariance.get_mut(4, 6) = (a * b).sqrt();
1203 *covariance.get_mut(6, 4) = (a * b).sqrt();
1204 assert!(matches!(
1205 calibrated(&measurement(None), &c, singular),
1206 Err(PipelineError::Fitting(_))
1207 ));
1208 }
1209
1210 #[test]
1211 fn an_unconverged_fit_is_refused_with_the_rule_that_ended_it() {
1212 let stopped = CountsFit {
1213 converged: false,
1214 unconverged: Some("no step of the fitter lowers the objective".into()),
1215 ..fit(8)
1216 };
1217 let Err(PipelineError::InvalidParameter(message)) = calibrated(
1218 &measurement(None),
1219 &calibration(Value::Known(0.01)),
1220 stopped,
1221 ) else {
1222 panic!("an unconverged fit is refused");
1223 };
1224 assert_eq!(
1225 message,
1226 "a pulse calibration needs a converged fit: no step of the fitter lowers the objective"
1227 );
1228 }
1229
1230 #[test]
1231 fn only_isotopes_that_may_be_present_must_lie_within_the_calibrated_lines() {
1232 let pulse = Pulse {
1233 line_span_ev: Some((10.0, 50.0)),
1234 ..calibration(Value::Known(0.01)).pulse
1235 };
1236 let mut m = measurement(Some(55.0));
1237 let line = |m: &Measurement| {
1238 let isotopes = &foil_material(m).expect("the foil").isotopes;
1239 pulse.uncalibrated_line(isotopes, &m.time_edges_us, 3.0, 25.0)
1240 };
1241 assert_eq!(line(&m), None);
1242 material(&mut m).isotopes[1].1 = Value::Fitted(1e-4);
1243 assert_eq!(line(&m), Some(55.0));
1244 }
1245
1246 #[test]
1247 fn a_calibration_carries_its_line_span_exactly_when_it_fits_a_number() {
1248 let c = calibration(Value::Known(0.01));
1249 let moderated = CountsFit {
1250 beta: [0.08, 0.01],
1251 ..fit(8)
1252 };
1253 let fitted = calibrated(&measurement(None), &c, moderated.clone())
1254 .unwrap()
1255 .calibration();
1256 assert_eq!(fitted.pulse.line_span_ev, Some((10.0, 50.0)));
1257 let mut earlier = moderated;
1258 earlier.regions[0].timing_offset_us = -20.0;
1259 let earlier = calibrated(&measurement(None), &c, earlier)
1260 .unwrap()
1261 .calibration();
1262 assert_eq!(earlier.pulse.line_span_ev, Some((10.0, 25.0)));
1263 let mut wider = measurement(Some(55.0));
1264 material(&mut wider).isotopes[1].1 = Value::Fitted(1e-4);
1265 match fit_counts(&wider, &fitted) {
1266 Err(PipelineError::InvalidParameter(message)) => {
1267 assert!(message.contains("55 eV, outside the"), "{message}")
1268 }
1269 other => panic!("{other:?}"),
1270 }
1271
1272 let mut known = c;
1273 let pulse = &mut known.pulse;
1274 pulse.alpha[1] = Value::Known(1.0);
1275 pulse.beta[0] = Value::Known(0.08);
1276 pulse.r = Value::Known(0.2);
1277 pulse.fwhm_squared_us2 = Value::Known(0.1);
1278 let without = CountsFit {
1279 unbounded: None,
1280 ..fit(4)
1281 };
1282 let unfitted = calibrated(&measurement(None), &known, without)
1283 .unwrap()
1284 .calibration();
1285 assert_eq!(unfitted.pulse.line_span_ev, None);
1286 }
1287
1288 fn original() -> PulseCalibration {
1289 let mut fit = CountsFit {
1290 r: 0.012_537_345_881_063_615,
1291 ..fit(8)
1292 };
1293 fit.regions[0].overdispersion = [Some(1.25), Some(1.5)];
1294 calibrated(
1295 &measurement(Some(55.0)),
1296 &calibration(Value::Known(0.01)),
1297 fit,
1298 )
1299 .unwrap()
1300 }
1301
1302 fn file() -> String {
1303 original().to_json()
1304 }
1305
1306 #[test]
1307 fn a_calibration_file_records_the_ranges_its_foil_left_out() {
1308 let mut m = measurement(Some(55.0));
1309 material(&mut m).excluded_ranges = vec![ExcludedRange {
1310 energy_ev: (13.6, 14.2),
1311 reason: "the evaluation misplaces the line".into(),
1312 }];
1313 let text = calibrated(&m, &calibration(Value::Known(0.01)), fit(8))
1314 .unwrap()
1315 .to_json();
1316 let recorded: serde_json::Value = serde_json::from_str(&text).unwrap();
1317 assert_eq!(
1318 recorded["foil"]["excluded_ranges"][0],
1319 serde_json::json!({
1320 "energy_ev": [13.6, 14.2],
1321 "reason": "the evaluation misplaces the line"
1322 })
1323 );
1324 let read = PulseCalibration::from_json(&text).unwrap();
1325 assert_eq!(read.to_json(), text);
1326 assert!(!file().contains("excluded_ranges"));
1327 }
1328
1329 #[test]
1330 fn a_calibration_reads_back_from_its_file_bit_for_bit() {
1331 let original = original();
1332 let text = original.to_json();
1333 let read = PulseCalibration::from_json(&text).unwrap();
1334 assert_eq!(format!("{read:?}"), format!("{original:?}"));
1335 assert_eq!(read.to_json(), text);
1336 assert_eq!(
1337 read.numbers[4].to_bits(),
1338 0.012_537_345_881_063_615_f64.to_bits()
1339 );
1340 for expected in [
1341 "\"format_version\": 6",
1342 "\"name\": \"alpha0\"",
1343 "\"unit\": \"1/(µs·eV^alpha_exponent)\"",
1344 "\"status\": \"fitted\"",
1345 "\"rank\": 4",
1346 "\"lattice\": null",
1347 "\"sample_overdispersion\": 1.5",
1348 "\"transfer\": \"unchecked\"",
1349 ] {
1350 assert!(text.contains(expected), "{expected} in {text}");
1351 }
1352 let mut crystal = measurement(Some(55.0));
1353 let spectrum = PhononSpectrum::debye(240.0, 4).expect("Debye");
1354 material(&mut crystal).lattice = Some(spectrum.clone());
1355 let bound = calibrated(&crystal, &calibration(Value::Known(0.01)), fit(8)).unwrap();
1356 let text = bound.to_json();
1357 let read = PulseCalibration::from_json(&text).unwrap();
1358 assert_eq!(read.to_json(), text);
1359 let lattice = read.foil.lattice.expect("the spectrum");
1360 assert_eq!(lattice.step_ev.to_bits(), spectrum.step_ev().to_bits());
1361 assert_eq!(lattice.density, spectrum.density());
1362 }
1363
1364 #[test]
1365 fn files_that_are_not_such_a_calibration_are_refused() {
1366 let original: serde_json::Value = serde_json::from_str(&file()).unwrap();
1367 let edits: [Edit; 28] = [
1368 ("version", |v| v["format_version"] = 1.into()),
1369 ("absent", |v| v["numbers"][4]["status"] = "absent".into()),
1370 ("absent value", |v| v["numbers"][6]["value"] = 0.5.into()),
1371 ("half a tail", |v| {
1372 v["numbers"][8]["status"] = "known".into()
1373 }),
1374 ("mean", |v| {
1375 v["mean"].as_array_mut().unwrap().pop();
1376 }),
1377 ("model", |v| v["pulse_model"] = "Gaussian".into()),
1378 ("transfer", |v| v["transfer"] = "checked".into()),
1379 ("unknown field", |v| v["comment"] = "added".into()),
1380 ("name", |v| v["numbers"][1]["name"] = "alpha2".into()),
1381 ("unit", |v| v["numbers"][2]["unit"] = "1/µs".into()),
1382 ("rank", |v| v["rank"] = 2.into()),
1383 ("row", |v| {
1384 v["covariance"].as_array_mut().unwrap().pop();
1385 }),
1386 ("span missing", |v| {
1387 v["line_span_ev"] = serde_json::Value::Null
1388 }),
1389 ("span reversed", |v| {
1390 v["line_span_ev"] = serde_json::json!([50.0, 10.0])
1391 }),
1392 ("runs", |v| v["provenance"]["sample"] = "open-1".into()),
1393 ("overdispersion", |v| {
1394 v["sample_overdispersion"] = 0.5.into()
1395 }),
1396 ("negative rate", |v| {
1397 v["numbers"][0]["value"] = (-0.01).into()
1398 }),
1399 ("missing key", |v| {
1400 v.as_object_mut().unwrap().remove("sample_overdispersion");
1401 }),
1402 ("nuclide key", |v| {
1403 v["foil"]["isotopes"][0]["isotope"]["n"] = 1.into();
1404 }),
1405 ("same isotope", |v| {
1406 let isotope = v["foil"]["isotopes"][0].clone();
1407 v["foil"]["isotopes"].as_array_mut().unwrap().push(isotope);
1408 }),
1409 ("unknown library", |v| {
1410 v["foil"]["library"] = "ENDF/B-IX".into()
1411 }),
1412 ("excluded range out of order", |v| {
1413 v["foil"]["excluded_ranges"] =
1414 serde_json::json!([{"energy_ev": [14.2, 13.6], "reason": "misplaced"}]);
1415 }),
1416 ("temperature sd", |v| {
1417 v["foil"]["temperature_k"]["sd"] = serde_json::Value::Null;
1418 }),
1419 ("lattice missing", |v| {
1420 v["foil"].as_object_mut().unwrap().remove("lattice");
1421 }),
1422 ("phonon spectrum", |v| {
1423 v["foil"]["lattice"] = serde_json::json!({"step_ev": 0.0, "density": [0.0, 1.0]});
1424 }),
1425 ("span beyond the pulse", |v| {
1426 v["line_span_ev"] = serde_json::json!([10.0, 300.0]);
1427 }),
1428 ("singular covariance", |v| {
1429 let c = &v["covariance"];
1430 let r = (c[0][0].as_f64().unwrap() * c[1][1].as_f64().unwrap()).sqrt();
1431 v["covariance"][0][1] = r.into();
1432 v["covariance"][1][0] = r.into();
1433 }),
1434 ("n_tau", |v| v["n_tau"] = 4.into()),
1435 ];
1436 for (what, edit) in edits {
1437 let mut value = original.clone();
1438 edit(&mut value);
1439 assert!(
1440 PulseCalibration::from_json(&value.to_string()).is_err(),
1441 "{what}"
1442 );
1443 }
1444 assert!(PulseCalibration::from_json(&original.to_string()).is_ok());
1445 let mut known = calibration(Value::Known(0.01));
1446 let pulse = &mut known.pulse;
1447 pulse.alpha[1] = Value::Known(1.1);
1448 pulse.beta[0] = Value::Known(0.0);
1449 pulse.r = Value::Known(0.21);
1450 pulse.fwhm_squared_us2 = Value::Known(0.12);
1451 let unfitted = calibrated(&measurement(None), &known, fit(4)).unwrap();
1452 let mut stray: serde_json::Value = serde_json::from_str(&unfitted.to_json()).unwrap();
1453 assert!(PulseCalibration::from_json(&stray.to_string()).is_ok());
1454 stray["mean"] = serde_json::json!([1.0]);
1455 assert!(PulseCalibration::from_json(&stray.to_string()).is_err());
1456 match PulseCalibration::from_json(r#"{"format_version": 1, "pulse_model": "", "runs": {}}"#)
1457 {
1458 Err(PipelineError::InvalidParameter(message)) => {
1459 assert!(message.contains("got version 1"), "{message}")
1460 }
1461 other => panic!("{other:?}"),
1462 }
1463 }
1464
1465 #[test]
1466 fn a_foil_whose_density_or_temperature_is_not_measured_is_refused() {
1467 let c = calibration(Value::Known(0.01));
1468 let mut fitted = measurement(None);
1469 material(&mut fitted).isotopes[0].1 = Value::Fitted(2e-3);
1470 let mut warm = measurement(None);
1471 material(&mut warm).temperature_k = Value::Fitted(300.0);
1472 for m in [fitted, warm] {
1473 match PulseCalibration::new(&m, &c, provenance()) {
1474 Err(PipelineError::InvalidParameter(message)) => {
1475 assert!(message.contains("is measured"), "{message}")
1476 }
1477 other => panic!("{other:?}"),
1478 }
1479 }
1480 let mut two = measurement(None);
1481 two.regions.push(two.regions[0].clone());
1482 let mut empty = measurement(None);
1483 empty.regions[0].material = None;
1484 for m in [two, empty] {
1485 match PulseCalibration::new(&m, &c, provenance()) {
1486 Err(PipelineError::InvalidParameter(message)) => {
1487 assert!(message.contains("the foil alone"), "{message}")
1488 }
1489 other => panic!("{other:?}"),
1490 }
1491 }
1492 let same = Provenance {
1493 open: "sample-1".into(),
1494 ..provenance()
1495 };
1496 let unnamed = Provenance {
1497 foil: String::new(),
1498 ..provenance()
1499 };
1500 let mut measured = c.clone();
1501 measured.pulse.r = Value::Measured {
1502 value: 0.2,
1503 sd: 0.01,
1504 };
1505 let mut boxed = c.clone();
1506 boxed.pulse.r = Value::Within {
1507 start: 0.2,
1508 lower: 0.15,
1509 upper: 0.25,
1510 };
1511 for (c, provenance, refusal) in [
1512 (&c, same, "names its foil"),
1513 (&c, unnamed, "names its foil"),
1514 (&original().calibration(), provenance(), "calibrated alone"),
1515 (&measured, provenance(), "calibrated alone"),
1516 (&boxed, provenance(), "calibrated alone"),
1517 ] {
1518 match PulseCalibration::new(&measurement(None), c, provenance) {
1519 Err(PipelineError::InvalidParameter(message)) => {
1520 assert!(message.contains(refusal), "{message}")
1521 }
1522 other => panic!("{other:?}"),
1523 }
1524 }
1525 }
1526
1527 const VERSION_6: &str = r#"{
1528 "format_version": 6,
1529 "pulse_model": "Ikeda–Carpenter pulse with α = α₀·E^p_α + α₁ and β = β₀·E^p_β + β₁ in 1/µs, E in eV, a storage fraction R, constant or linear in √E to R_high across the energy span, folded with the proton pulse's triangle of FWHM h and, when present, a detector tail of fraction f and decay τ_D",
1530 "numbers": [
1531 {
1532 "name": "alpha0",
1533 "unit": "1/(µs·eV^alpha_exponent)",
1534 "value": 0.5,
1535 "status": "known"
1536 },
1537 {
1538 "name": "alpha1",
1539 "unit": "1/µs",
1540 "value": 1.1,
1541 "status": "fitted"
1542 },
1543 {
1544 "name": "beta0",
1545 "unit": "1/(µs·eV^beta_exponent)",
1546 "value": 0.0,
1547 "status": "fitted"
1548 },
1549 {
1550 "name": "beta1",
1551 "unit": "1/µs",
1552 "value": 0.01,
1553 "status": "known"
1554 },
1555 {
1556 "name": "r",
1557 "unit": "1",
1558 "value": 0.012537345881063615,
1559 "status": "fitted"
1560 },
1561 {
1562 "name": "fwhm_squared",
1563 "unit": "µs²",
1564 "value": 0.12,
1565 "status": "fitted"
1566 },
1567 {
1568 "name": "r_high",
1569 "unit": "1",
1570 "value": 0.0,
1571 "status": "absent"
1572 },
1573 {
1574 "name": "tail_fraction",
1575 "unit": "1",
1576 "value": 0.0,
1577 "status": "absent"
1578 },
1579 {
1580 "name": "tail_decay",
1581 "unit": "µs",
1582 "value": 0.0,
1583 "status": "absent"
1584 },
1585 {
1586 "name": "alpha_exponent",
1587 "unit": "1",
1588 "value": 0.5,
1589 "status": "known"
1590 },
1591 {
1592 "name": "beta_exponent",
1593 "unit": "1",
1594 "value": 0.5,
1595 "status": "known"
1596 }
1597 ],
1598 "mean": [
1599 -0.01,
1600 -0.012,
1601 -0.014,
1602 -0.016
1603 ],
1604 "covariance": [
1605 [
1606 0.1,
1607 0.0,
1608 0.02,
1609 -0.01
1610 ],
1611 [
1612 0.0,
1613 0.12,
1614 0.0,
1615 0.0
1616 ],
1617 [
1618 0.02,
1619 0.0,
1620 0.14,
1621 0.04
1622 ],
1623 [
1624 -0.01,
1625 0.0,
1626 0.04,
1627 0.16
1628 ]
1629 ],
1630 "rank": 4,
1631 "t0_us": 3.0,
1632 "flight_path_m": 25.0,
1633 "energy_span_ev": [
1634 1.0,
1635 200.0
1636 ],
1637 "n_tau": 256,
1638 "line_span_ev": [
1639 10.0,
1640 50.0
1641 ],
1642 "foil": {
1643 "isotopes": [
1644 {
1645 "isotope": {
1646 "z": 73,
1647 "a": 181
1648 },
1649 "density": {
1650 "value": 0.002,
1651 "sd": 0.00002
1652 }
1653 },
1654 {
1655 "isotope": {
1656 "z": 74,
1657 "a": 184
1658 },
1659 "density": {
1660 "value": 0.0,
1661 "sd": null
1662 }
1663 }
1664 ],
1665 "temperature_k": {
1666 "value": 300.0,
1667 "sd": 10.0
1668 },
1669 "lattice": null,
1670 "library": "ENDF/B-VIII.0"
1671 },
1672 "provenance": {
1673 "foil": "foil-a",
1674 "open": "open-1",
1675 "sample": "sample-1"
1676 },
1677 "sample_overdispersion": 1.5,
1678 "transfer": "unchecked"
1679}"#;
1680
1681 #[test]
1682 fn a_calibration_carries_a_fitted_r_high_and_detector_tail() {
1683 let mut c = calibration(Value::Known(0.01));
1684 c.pulse.r_high = Some(Value::Fitted(0.3));
1685 c.pulse.detector_tail = Some([Value::Fitted(0.1), Value::Known(2.0)]);
1686 let fit = CountsFit {
1687 r_high: Some(0.35),
1688 detector_tail: Some([0.12, 2.0]),
1689 ..fit(10)
1690 };
1691 let calibration = calibrated(&measurement(Some(55.0)), &c, fit).unwrap();
1692 let read = PulseCalibration::from_json(&calibration.to_json()).unwrap();
1693 let pulse = read.calibration().pulse;
1694 assert_eq!(pulse.r_high, Some(Value::Fitted(0.35)));
1695 assert_eq!(
1696 pulse.detector_tail,
1697 Some([Value::Fitted(0.12), Value::Known(2.0)])
1698 );
1699 assert_eq!(pulse.prior.expect("prior").numbers, [1, 2, 4, 5, 6, 7]);
1700 }
1701
1702 #[test]
1703 fn the_file_is_format_version_6_byte_for_byte() {
1704 let original = original();
1705 assert_eq!(original.to_json(), VERSION_6);
1706 let read = PulseCalibration::from_json(VERSION_6).unwrap();
1707 assert_eq!(format!("{read:?}"), format!("{original:?}"));
1708 }
1709
1710 fn other_foil(density: f64) -> Measurement {
1711 let mut m = measurement(None);
1712 material(&mut m).isotopes[0].1 = Value::Measured {
1713 value: density,
1714 sd: 0.01 * density,
1715 };
1716 m
1717 }
1718
1719 fn other_provenance() -> Provenance {
1720 Provenance {
1721 foil: "foil-b".into(),
1722 open: "open-2".into(),
1723 sample: "sample-2".into(),
1724 }
1725 }
1726
1727 fn other(alpha1: f64, alpha0: f64) -> PulseCalibration {
1728 let m = other_foil(3e-3);
1729 let mut fit = CountsFit {
1730 alpha: [alpha0, alpha1],
1731 beta: [0.004, 0.01],
1732 r: 0.205,
1733 fwhm_squared_us2: 0.11,
1734 ..fit(8)
1735 };
1736 let unbounded = fit.unbounded.as_mut().expect("unbounded");
1737 unbounded.mean[4] += alpha1 - 1.1;
1738 for (i, j, c) in [(4, 5, 0.02), (5, 6, 0.015)] {
1739 *unbounded.covariance.get_mut(i, j) = c;
1740 *unbounded.covariance.get_mut(j, i) = c;
1741 }
1742 let c = calibration(Value::Known(0.01));
1743 PulseCalibration::from_fit(&m, &c, foil(&m).unwrap(), other_provenance(), &fit).unwrap()
1744 }
1745
1746 fn solve(mut m: Vec<Vec<f64>>, mut v: Vec<f64>) -> Vec<f64> {
1747 let k = v.len();
1748 for i in 0..k {
1749 let pivot = m[i].clone();
1750 for r in i + 1..k {
1751 let factor = m[r][i] / pivot[i];
1752 for (entry, above) in m[r].iter_mut().zip(&pivot).skip(i) {
1753 *entry -= factor * above;
1754 }
1755 v[r] -= factor * v[i];
1756 }
1757 }
1758 for i in (0..k).rev() {
1759 v[i] = (v[i] - (i + 1..k).map(|c| m[i][c] * v[c]).sum::<f64>()) / m[i][i];
1760 }
1761 v
1762 }
1763
1764 #[test]
1765 fn a_transfer_compares_every_number_both_foils_fitted() {
1766 let (a, b) = (original(), other(1.15, 0.5));
1767 let result = a.transfer(&b).unwrap().agreement();
1768 let (pa, pb) = (a.prior.as_ref().unwrap(), b.prior.as_ref().unwrap());
1769 let k = pa.numbers.len();
1770 let d: Vec<f64> = (0..k).map(|i| pa.mean[i] - pb.mean[i]).collect();
1771 let sum = (0..k)
1772 .map(|i| {
1773 (0..k)
1774 .map(|j| pa.covariance.get(i, j) + pb.covariance.get(i, j))
1775 .collect()
1776 })
1777 .collect();
1778 let q: f64 = d
1779 .iter()
1780 .zip(solve(sum, d.clone()))
1781 .map(|(x, y)| x * y)
1782 .sum();
1783 assert!(q > 0.0);
1784 assert_eq!(result.dof, 4);
1785 assert!((result.q / q - 1.0).abs() <= 1e-12, "{} vs {q}", result.q);
1786 assert_eq!(result, Consistency::new(result.q, 4).unwrap());
1787 }
1788
1789 #[test]
1790 fn a_transfer_needs_another_foil_with_the_same_pulse_model() {
1791 let a = original();
1792 let mut same_foil = other(1.15, 0.5);
1793 same_foil.provenance.foil = "foil-a".into();
1794 let mut shared = other(1.15, 0.5);
1795 shared.provenance.sample = "sample-1".into();
1796 let mut open_as_sample = other(1.15, 0.5);
1797 open_as_sample.provenance.sample = "open-1".into();
1798 let mut sample_as_open = other(1.15, 0.5);
1799 sample_as_open.provenance.open = "sample-1".into();
1800 let m = other_foil(3e-3);
1801 let calibrated_other = |c: &Calibration, fit: CountsFit| {
1802 PulseCalibration::from_fit(&m, c, foil(&m).unwrap(), other_provenance(), &fit).unwrap()
1803 };
1804 let mut known_r = calibration(Value::Known(0.01));
1805 known_r.pulse.r = Value::Known(0.21);
1806 let mut known = known_r.clone();
1807 let pulse = &mut known.pulse;
1808 pulse.alpha[1] = Value::Known(1.1);
1809 pulse.beta[0] = Value::Known(0.0);
1810 pulse.fwhm_squared_us2 = Value::Known(0.12);
1811 let unfitted = calibrated(&measurement(None), &known, fit(4)).unwrap();
1812 for (a, b, refusal) in [
1813 (&a, same_foil, "physically different foil"),
1814 (&a, shared, "physically different foil"),
1815 (&a, open_as_sample, "physically different foil"),
1816 (&a, sample_as_open, "physically different foil"),
1817 (&a, other(1.15, 0.6), "different pulse models"),
1818 (
1819 &a,
1820 calibrated_other(&known_r, fit(7)),
1821 "different pulse models",
1822 ),
1823 (
1824 &unfitted,
1825 calibrated_other(&known, fit(4)),
1826 "fit no pulse number",
1827 ),
1828 ] {
1829 match a.transfer(&b) {
1830 Err(PipelineError::InvalidParameter(message)) => {
1831 assert!(message.contains(refusal), "{message}")
1832 }
1833 other => panic!("{other:?}"),
1834 }
1835 }
1836 }
1837
1838 #[test]
1839 fn only_a_transfer_that_passes_is_recorded_and_read_back() {
1840 let failing = other(3.0, 0.5);
1841 assert!(original().transfer(&failing).unwrap().agreement().p <= 0.01);
1842 match original().record_transfer(&failing) {
1843 Err(PipelineError::InvalidParameter(message)) => {
1844 assert!(message.contains("does not transfer"), "{message}")
1845 }
1846 other => panic!("{other:?}"),
1847 }
1848
1849 let b = other(1.15, 0.5);
1850 let a = original().record_transfer(&b).unwrap();
1851 assert_eq!(a.transfer, Some(original().transfer(&b).unwrap().record));
1852 let text = a.to_json();
1853 let read = PulseCalibration::from_json(&text).unwrap();
1854 assert_eq!(format!("{read:?}"), format!("{a:?}"));
1855 assert_eq!(read.to_json(), text);
1856
1857 let original: serde_json::Value = serde_json::from_str(&text).unwrap();
1858 let mut rounded = original.clone();
1859 let p = rounded["transfer"]["p"].as_f64().unwrap();
1860 rounded["transfer"]["p"] = (p * (1.0 + 1e-13)).into();
1861 assert!(PulseCalibration::from_json(&rounded.to_string()).is_ok());
1862 let edits: [Edit; 10] = [
1863 ("p not its d2's", |v| v["transfer"]["p"] = 0.5.into()),
1864 ("failed", |v| {
1865 v["transfer"]["d2"] = 50.0.into();
1866 v["transfer"]["p"] = Consistency::new(50.0, 4).unwrap().p.into();
1867 }),
1868 ("dof not the numbers fitted", |v| {
1869 let d2 = v["transfer"]["d2"].as_f64().unwrap();
1870 v["transfer"]["dof"] = 3.into();
1871 v["transfer"]["p"] = Consistency::new(d2, 3).unwrap().p.into();
1872 }),
1873 ("same foil", |v| {
1874 v["transfer"]["provenance"]["foil"] = v["provenance"]["foil"].clone();
1875 }),
1876 ("same sample run", |v| {
1877 v["transfer"]["provenance"]["sample"] = v["provenance"]["sample"].clone();
1878 }),
1879 ("this open run as the other's sample", |v| {
1880 v["transfer"]["provenance"]["sample"] = v["provenance"]["open"].clone();
1881 }),
1882 ("this sample run as the other's open", |v| {
1883 v["transfer"]["provenance"]["open"] = v["provenance"]["sample"].clone();
1884 }),
1885 ("other overdispersion", |v| {
1886 v["transfer"]["sample_overdispersion"] = 0.5.into();
1887 }),
1888 ("other runs the same", |v| {
1889 v["transfer"]["provenance"]["open"] = v["transfer"]["provenance"]["sample"].clone();
1890 }),
1891 ("other foil", |v| {
1892 v["transfer"]["foil"]["isotopes"] = serde_json::json!([]);
1893 }),
1894 ];
1895 for (what, edit) in edits {
1896 let mut value = original.clone();
1897 edit(&mut value);
1898 assert!(
1899 PulseCalibration::from_json(&value.to_string()).is_err(),
1900 "{what}"
1901 );
1902 }
1903 }
1904}