1use std::ops::RangeInclusive;
5use std::sync::Arc;
6
7use nereids_fitting::error::FittingError;
8use nereids_fitting::lm::{FitModel, FlatMatrix};
9use nereids_fitting::parameters::{FitParameter, ParameterSet};
10use nereids_fitting::poisson::{PoissonConfig, PoissonResult, Prior, Rejected, Stop, poisson_fit};
11use nereids_physics::flight_time_grid::{FlightTimeGrid, FlightTimeGridError};
12use nereids_physics::ikeda_carpenter::{
13 DETECTOR_TAIL_DECAY_US, DetectorPulse, DetectorTail, EnergyLaw, IkedaCarpenterParams,
14};
15
16use crate::beam::BeamSpline;
17use crate::counts_fit::{Filter, NEGLIGIBLE_PREDICTION, Value};
18use crate::error::PipelineError;
19use crate::pulse_calibration::PulsePrior;
20
21pub const BOUND: f64 = 0.01;
25
26pub(crate) const PULSE_NUMBERS: [&str; 11] = [
27 "α₀", "α₁", "β₀", "β₁", "R", "h²", "R_high", "f", "τ_D", "p_α", "p_β",
28];
29
30const NO_TAIL: [Value; 2] = [Value::Known(0.0), Value::Known(1.0)];
31
32const RATE: (RangeInclusive<f64>, &str) = (0.0..=f64::INFINITY, "0 or more");
33
34const FRACTION: (RangeInclusive<f64>, &str) = (0.0..=1.0, "within 0–1");
35
36const CONSTANT: Value = Value::Known(0.0);
37
38#[derive(Debug, Clone)]
44pub struct Calibration {
45 pub t0_us: Value,
46 pub flight_path_m: Value,
47 pub pulse: Pulse,
48}
49
50impl Calibration {
51 pub(crate) fn instrument(&self) -> Result<Vec<FitParameter>, PipelineError> {
52 let pulse = &self.pulse;
53 let ranges = [
54 RATE,
55 RATE,
56 RATE,
57 RATE,
58 FRACTION,
59 RATE,
60 FRACTION,
61 FRACTION,
62 (DETECTOR_TAIL_DECAY_US, "from 1e-9 to 1e9"),
63 FRACTION,
64 FRACTION,
65 ];
66 let mut parameters = vec![
67 self.t0_us
68 .parameter("t0", f64::NEG_INFINITY..=f64::INFINITY, "any real number")?,
69 self.flight_path_m.parameter(
70 "flight path",
71 f64::MIN_POSITIVE..=f64::INFINITY,
72 "positive",
73 )?,
74 ];
75 for ((name, value), (range, allowed)) in
76 PULSE_NUMBERS.into_iter().zip(pulse.numbers()).zip(ranges)
77 {
78 parameters.push(value.parameter(name, range, allowed)?);
79 }
80 Ok(parameters)
81 }
82}
83
84#[derive(Debug, Clone)]
92pub struct Pulse {
93 pub alpha: [Value; 2],
95 pub beta: [Value; 2],
97 pub exponents: [Value; 2],
99 pub r: Value,
102 pub fwhm_squared_us2: Value,
104 pub r_high: Option<Value>,
107 pub detector_tail: Option<[Value; 2]>,
112 pub energy_span_ev: (f64, f64),
115 pub n_tau: usize,
118 pub line_span_ev: Option<(f64, f64)>,
127 pub prior: Option<PulsePrior>,
132}
133
134impl Pulse {
135 pub(crate) fn numbers(&self) -> [&Value; 11] {
139 let [f, decay] = self.detector_tail.as_ref().unwrap_or(&NO_TAIL);
140 [
141 &self.alpha[0],
142 &self.alpha[1],
143 &self.beta[0],
144 &self.beta[1],
145 &self.r,
146 &self.fwhm_squared_us2,
147 self.r_high.as_ref().unwrap_or(&CONSTANT),
148 f,
149 decay,
150 &self.exponents[0],
151 &self.exponents[1],
152 ]
153 }
154
155 pub(crate) fn storage_span(&self) -> Option<(f64, f64)> {
158 self.r_high.map(|_| self.energy_span_ev)
159 }
160
161 pub(crate) fn at(&self, numbers: &[f64]) -> Result<DetectorPulse, PipelineError> {
162 DetectorPulse::new(
163 laws(numbers, self.storage_span()),
164 self.energy_span_ev,
165 self.n_tau,
166 )
167 .map_err(|e| PipelineError::InvalidParameter(e.to_string()))
168 }
169}
170
171pub(crate) fn laws(numbers: &[f64], storage_span: Option<(f64, f64)>) -> IkedaCarpenterParams {
174 IkedaCarpenterParams {
175 alpha: EnergyLaw::PowerE {
176 a0: numbers[0],
177 a1: numbers[1],
178 exponent: numbers[9],
179 },
180 beta: EnergyLaw::PowerE {
181 a0: numbers[2],
182 a1: numbers[3],
183 exponent: numbers[10],
184 },
185 r: storage_span.map_or(EnergyLaw::Const(numbers[4]), |span_ev| {
186 EnergyLaw::SqrtEBetween {
187 low: numbers[4],
188 high: numbers[6],
189 span_ev,
190 }
191 }),
192 burst_sigma_us: None,
193 channel_fwhm_us: Some(numbers[5].sqrt()),
194 detector_tail: Some(DetectorTail {
195 fraction: numbers[7],
196 decay_us: numbers[8],
197 }),
198 }
199}
200
201#[derive(Debug, Clone)]
203pub struct OpenBeamFit {
204 pub beam: BeamSpline,
208 pub deviance: f64,
210 pub converged: bool,
213 pub covariance: Option<FlatMatrix>,
218 pub overdispersion: Option<f64>,
229 pub at_limit: bool,
233 pub step_us: f64,
236 pub points: usize,
238 pub halvings: usize,
240}
241
242pub fn fit_open_beam(
294 time_edges_us: &[f64],
295 open_counts: &[f64],
296 calibration: &Calibration,
297 open_live: Option<&[f64]>,
298 known: Option<&[f64]>,
299) -> Result<OpenBeamFit, PipelineError> {
300 open_beam_with_intervals(
301 time_edges_us,
302 open_counts,
303 calibration,
304 open_live,
305 known,
306 None,
307 None,
308 )
309}
310
311pub(crate) fn open_beam_with_intervals(
314 time_edges_us: &[f64],
315 open_counts: &[f64],
316 calibration: &Calibration,
317 open_live: Option<&[f64]>,
318 known: Option<&[f64]>,
319 intervals: Option<usize>,
320 filter: Option<(&Filter, f64)>,
321) -> Result<OpenBeamFit, PipelineError> {
322 let start: Vec<f64> = calibration
323 .instrument()?
324 .iter()
325 .map(|parameter| parameter.value)
326 .collect();
327 let t0_us = start[0];
328 let grid = Arc::new(FlightTimeGrid::new(
329 time_edges_us,
330 t0_us,
331 start[1],
332 &calibration.pulse.at(&start[2..])?,
333 )?);
334 validate_counts("open-beam", open_counts, time_edges_us.len() - 1)?;
335 let live = validate_live("open-beam", open_live, time_edges_us.len() - 1)?;
336 let known = validate_known(known, time_edges_us.len() - 1)?;
337
338 let coefficients = |intervals: usize| intervals + 3;
339 let admits = |intervals: usize| {
340 2 * coefficients(intervals) <= open_counts.len()
341 && spans_two_bins(time_edges_us, t0_us, intervals)
342 };
343 if !admits(1) {
344 return Err(PipelineError::InvalidParameter(format!(
345 "the open-beam fit needs at least {} time bins, one interval's {} coefficients \
346 and as many again to measure the noise; got {}",
347 2 * coefficients(1),
348 coefficients(1),
349 open_counts.len()
350 )));
351 }
352
353 let u_first = time_edges_us[0] - t0_us;
354 let u_last = time_edges_us[time_edges_us.len() - 1] - t0_us;
355 let constant = BeamSpline::constant(u_first, u_last, 1.0);
356 let unit = OpenBeamModel::new(&grid, &constant, &[]).filtered(filter)?;
357 let per_unit_beam = grid.predict(&unit.beam(constant.coefficients()))?;
358 let recorded: f64 = per_unit_beam.iter().zip(&live).map(|(c, l)| l * c).sum();
359 let per_us = open_counts.iter().sum::<f64>() / recorded;
360 let negligible = (NEGLIGIBLE_PREDICTION / recorded).ln();
362 let ladder_start = BeamSpline::constant(u_first, u_last, per_us).above(negligible);
363 let fit_beam = |start: &BeamSpline| fit_beam(&grid, start, open_counts, &live, &known, filter);
364 let mut ladder = vec![fit_beam(&ladder_start)?];
365 while let Some(start) = ladder
366 .last()
367 .filter(|candidate| candidate.fit.converged && admits(2 * candidate.beam.intervals()))
368 .map(|candidate| candidate.beam.refined())
369 {
370 match fit_beam(&start) {
371 Ok(candidate) if candidate.fit.converged => ladder.push(candidate),
372 Ok(_)
373 | Err(PipelineError::FlightTimeGrid(FlightTimeGridError::TooManyPoints { .. })) => {
374 break;
375 }
376 Err(error) => return Err(error),
377 }
378 }
379
380 let richest = &ladder[ladder.len() - 1].fit;
381 let overdispersion = overdispersion(
382 open_counts,
383 richest,
384 &counted(richest, 0..open_counts.len()),
385 0.0,
386 );
387 let scale = overdispersion.unwrap_or(1.0);
388 let criterion = |candidate: &Candidate| {
389 2.0 * candidate.fit.result.deviance / scale
390 + 2.0 * candidate.beam.coefficients().len() as f64
391 };
392 let (chosen, _) =
393 ladder
394 .iter()
395 .map(criterion)
396 .enumerate()
397 .fold(
398 (0, f64::INFINITY),
399 |best, (i, q)| {
400 if q < best.1 { (i, q) } else { best }
401 },
402 );
403 let chosen = match intervals {
404 None => chosen,
405 Some(k) => ladder
406 .iter()
407 .position(|candidate| candidate.beam.intervals() == k)
408 .ok_or_else(|| {
409 FittingError::EvaluationFailed(format!(
410 "the open-beam fit does not converge with {k} intervals"
411 ))
412 })?,
413 };
414 let at_limit = chosen + 1 == ladder.len();
415 let Candidate { beam, fit } = ladder.swap_remove(chosen);
416 Ok(OpenBeamFit {
417 beam,
418 deviance: fit.result.deviance,
419 converged: fit.converged,
420 covariance: fit
421 .result
422 .covariance
423 .filter(|_| fit.converged)
424 .map(|mut covariance| {
425 covariance.data.iter_mut().for_each(|v| *v *= scale);
426 covariance
427 }),
428 overdispersion,
429 at_limit,
430 step_us: fit.step_us,
431 points: fit.points,
432 halvings: fit.halvings,
433 })
434}
435
436fn spans_two_bins(time_edges_us: &[f64], t0_us: f64, intervals: usize) -> bool {
438 let last = time_edges_us.len() - 1;
439 let (low, high) = (time_edges_us[0] - t0_us, time_edges_us[last] - t0_us);
440 let bins_before = |knot: usize| {
441 if knot == intervals {
442 return last as f64;
443 }
444 let t = t0_us + low * (high / low).powf(knot as f64 / intervals as f64);
445 let bin = time_edges_us
446 .partition_point(|edge| *edge <= t)
447 .clamp(1, last)
448 - 1;
449 bin as f64 + (t - time_edges_us[bin]) / (time_edges_us[bin + 1] - time_edges_us[bin])
450 };
451 (0..intervals).all(|k| bins_before(k + 1) - bins_before(k) >= 2.0 - 1e-9)
453}
454
455pub(crate) fn validate_counts(run: &str, counts: &[f64], bins: usize) -> Result<(), PipelineError> {
456 if counts.len() != bins {
457 return Err(PipelineError::ShapeMismatch(format!(
458 "{} {run} counts for {bins} time bins",
459 counts.len()
460 )));
461 }
462 if let Some((bin, count)) = counts.iter().enumerate().find(|(_, c)| !whole(**c)) {
463 return Err(PipelineError::InvalidParameter(format!(
464 "{run} counts must be whole non-negative numbers, got {count} in bin {bin}"
465 )));
466 }
467 if counts.iter().all(|&c| c == 0.0) {
468 return Err(PipelineError::InvalidParameter(format!(
469 "the {run} run has no counts"
470 )));
471 }
472 Ok(())
473}
474
475pub(crate) fn whole(count: f64) -> bool {
476 count.is_finite() && count >= 0.0 && count.fract() == 0.0
477}
478
479pub(crate) fn validate_live(
480 run: &str,
481 live: Option<&[f64]>,
482 bins: usize,
483) -> Result<Vec<f64>, PipelineError> {
484 let live = live.map_or_else(|| vec![1.0; bins], <[f64]>::to_vec);
485 if live.len() != bins {
486 return Err(PipelineError::ShapeMismatch(format!(
487 "{} {run} live fractions for {bins} time bins",
488 live.len()
489 )));
490 }
491 if let Some((bin, fraction)) = live
492 .iter()
493 .enumerate()
494 .find(|(_, l)| !(**l > 0.0 && **l <= 1.0))
495 {
496 return Err(PipelineError::InvalidParameter(format!(
497 "{run} live fractions must be in (0, 1], got {fraction} in bin {bin}"
498 )));
499 }
500 Ok(live)
501}
502
503fn validate_known(known: Option<&[f64]>, bins: usize) -> Result<Vec<f64>, PipelineError> {
504 let known = known.map_or_else(|| vec![0.0; bins], <[f64]>::to_vec);
505 if known.len() != bins {
506 return Err(PipelineError::ShapeMismatch(format!(
507 "{} known open-beam counts for {bins} time bins",
508 known.len()
509 )));
510 }
511 if let Some((bin, count)) = known
512 .iter()
513 .enumerate()
514 .find(|(_, g)| !(g.is_finite() && **g >= 0.0))
515 {
516 return Err(PipelineError::InvalidParameter(format!(
517 "known open-beam counts must be finite and 0 or more, got {count} in bin {bin}"
518 )));
519 }
520 Ok(known)
521}
522
523pub(crate) const COUNTS_TO_MEASURE_NOISE: f64 = 1.0;
524
525pub(crate) fn counted(fit: &GridFit, bins: std::ops::Range<usize>) -> Vec<usize> {
526 bins.filter(|&k| fit.predicted[k] >= COUNTS_TO_MEASURE_NOISE)
527 .collect()
528}
529
530pub(crate) fn overdispersion(
531 observed: &[f64],
532 fit: &GridFit,
533 counted: &[usize],
534 shared_leverage: f64,
535) -> Option<f64> {
536 let leverage = fit.result.leverage.as_ref().filter(|_| fit.converged)?;
537 let (pearson, skew, freedom) =
538 counted
539 .iter()
540 .fold((0.0, 0.0, 0.0), |(pearson, skew, freedom), &k| {
541 let (y, mu) = (observed[k], fit.predicted[k]);
542 (
543 pearson + (y - mu).powi(2) / mu,
544 skew + (y - mu) / mu,
545 freedom + 1.0 - leverage[k],
546 )
547 });
548 let fletcher = 1.0 + skew / counted.len() as f64;
549 let freedom = freedom - shared_leverage;
550 (freedom >= 1.0)
551 .then(|| (pearson / freedom / fletcher).clamp(1.0, f64::INFINITY))
552 .filter(|phi| phi.is_finite())
553}
554
555struct Candidate {
556 beam: BeamSpline,
557 fit: GridFit,
558}
559
560fn fit_beam(
561 first_grid: &Arc<FlightTimeGrid>,
562 start: &BeamSpline,
563 open_counts: &[f64],
564 live: &[f64],
565 known: &[f64],
566 filter: Option<(&Filter, f64)>,
567) -> Result<Candidate, PipelineError> {
568 let mut parameters = ParameterSet::new(
569 start
570 .coefficients()
571 .iter()
572 .enumerate()
573 .map(|(i, &c)| FitParameter {
574 lower: start.floor(),
575 ..FitParameter::unbounded(format!("beam {i}"), c)
576 })
577 .collect(),
578 );
579 let dispersion = vec![1.0; open_counts.len()];
580 let fit = fit_on_halved_grids(
581 first_grid,
582 &mut parameters,
583 open_counts,
584 &dispersion,
585 &[],
586 |grid| {
587 Ok(Recorded {
588 model: OpenBeamModel::new(grid, start, known).filtered(filter)?,
589 live,
590 })
591 },
592 |spread, _, _| Ok(spread <= BOUND),
593 )?;
594 Ok(Candidate {
595 beam: start.with_coefficients(&fit.result.params),
596 fit,
597 })
598}
599
600pub(crate) struct GridFit {
601 pub(crate) result: PoissonResult,
602 pub(crate) converged: bool,
603 pub(crate) unconverged: Option<String>,
604 pub(crate) predicted: Vec<f64>,
605 pub(crate) coarse: Arc<FlightTimeGrid>,
606 pub(crate) fine: Arc<FlightTimeGrid>,
607 pub(crate) step_us: f64,
608 pub(crate) points: usize,
609 pub(crate) halvings: usize,
610}
611
612pub(crate) fn fit_on_halved_grids<M: FitModel>(
613 first_grid: &Arc<FlightTimeGrid>,
614 parameters: &mut ParameterSet,
615 observed: &[f64],
616 dispersion: &[f64],
617 priors: &[Prior],
618 model_on: impl Fn(&Arc<FlightTimeGrid>) -> Result<M, PipelineError>,
619 done: impl Fn(f64, &FlightTimeGrid, &[f64]) -> Result<bool, PipelineError>,
620) -> Result<GridFit, PipelineError> {
621 let dispersed: Vec<f64> = observed
622 .iter()
623 .zip(dispersion)
624 .map(|(y, d)| y / d)
625 .collect();
626 let mut grid = Arc::clone(first_grid);
627 let mut coarse = model_on(&grid)?;
628 let mut halvings = 0;
629 loop {
630 let finer = Arc::new(grid.halved()?);
631 let fine = model_on(&finer)?;
632 let result = poisson_fit(
633 &Dispersed {
634 model: &fine,
635 dispersion,
636 },
637 &dispersed,
638 priors,
639 parameters,
640 &PoissonConfig::default(),
641 )?;
642 let unconverged = match result.stop {
643 Stop::Minimum if result.params.iter().all(|p| p.is_finite()) => None,
644 Stop::Minimum => Some("a fitted number is not finite".to_string()),
645 stop => {
646 let free = parameters.free_indices();
647 let names: Vec<&str> = (result.moving.iter())
648 .map(|&j| &*parameters.params[free[j]].name)
649 .collect();
650 let mut rule = stop.to_string();
651 if let (false, Some(left), Some((alone, own))) =
652 (names.is_empty(), result.decrement, result.own)
653 {
654 let (names, alone) = (names.join(", "), ¶meters.params[free[alone]].name);
655 rule += &format!(
656 ", still moving {names} with a further decrease of {left:.2e} predicted, \
657 {own:.2e} at most by {alone} with the others held"
658 );
659 }
660 let Rejected {
661 refused,
662 impossible,
663 reason,
664 tested,
665 alone,
666 again,
667 around,
668 most,
669 ..
670 } = &result.rejected;
671 if let Some((predicted, rise)) = tested {
672 rule += &format!(
673 "; the last trial step that could lower the objective raised it by \
674 {rise:.2e} where a decrease of {predicted:.2e} was predicted"
675 );
676 }
677 if let Some((alone, moved, rise)) = *alone {
678 let name = ¶meters.params[free[alone]].name;
679 rule += &format!(
680 ", and its change of {name} by {moved:.2e} alone raised it by {rise:.2e}"
681 );
682 }
683 if let Some([half, opposite]) = around {
684 rule += &format!(
685 "; half that change raised it by {half:.2e} and the opposite change by \
686 {opposite:.2e}"
687 );
688 }
689 if let Some((k, before, after, changed)) = *most {
690 let edges = grid.time_edges_us();
691 let (block, bin) = (k / (edges.len() - 1), k % (edges.len() - 1));
692 let run = ["open-beam", "sample"][block % 2];
693 let scale = Some(dispersion[k]).filter(|d| d.is_finite()).unwrap_or(1.0);
694 let raw = |count: f64| if count < 0.0 { count } else { scale * count };
696 rule += &format!(
697 "; it changed {changed} predicted counts by more than 1e-6 of themselves, \
698 most the {run} count of region {} from {:.3} to {:.3} µs, from {:.6e} to \
699 {:.6e}",
700 block / 2,
701 edges[bin],
702 edges[bin + 1],
703 raw(before),
704 raw(after)
705 );
706 }
707 if let Some(again) = again.filter(|again| *again != 0.0) {
708 rule += &format!(
709 "; evaluated again at the same quantities the objective differs by \
710 {again:.2e}"
711 );
712 }
713 if refused + impossible > 0 {
714 rule += &format!(
715 "; {impossible} of its rejected trial steps predicted a negative count, \
716 or zero where something was counted, and the model refused {refused}"
717 );
718 if let Some(reason) = reason {
719 rule += &format!(": {reason}");
720 }
721 }
722 Some(rule)
723 }
724 };
725 let converged = unconverged.is_none();
726 let predicted = fine.evaluate(&result.params)?;
727 let spread: f64 = predicted
728 .iter()
729 .zip(coarse.evaluate(&result.params)?)
730 .filter(|(fine, _)| **fine > 0.0)
731 .map(|(fine, coarse)| (fine - coarse).powi(2) / fine)
732 .sum();
733 let coarse_grid = std::mem::replace(&mut grid, finer);
734 coarse = fine;
735 halvings += 1;
736 if !converged || done(spread, &coarse_grid, &result.params)? {
737 return Ok(GridFit {
738 result,
739 converged,
740 unconverged,
741 predicted,
742 coarse: coarse_grid,
743 fine: Arc::clone(&grid),
744 step_us: grid.step_us(),
745 points: grid.flight_times_us().len(),
746 halvings,
747 });
748 }
749 }
750}
751
752struct Dispersed<'a, M> {
753 model: &'a M,
754 dispersion: &'a [f64],
755}
756
757impl<M: FitModel> FitModel for Dispersed<'_, M> {
758 fn evaluate(&self, params: &[f64]) -> Result<Vec<f64>, FittingError> {
759 let counts = self.model.evaluate(params)?;
760 Ok(counts
761 .iter()
762 .zip(self.dispersion)
763 .map(|(&c, d)| if c < 0.0 { c } else { c / d })
764 .collect())
765 }
766
767 fn analytical_jacobian(
768 &self,
769 params: &[f64],
770 free_param_indices: &[usize],
771 y_current: &[f64],
772 ) -> Option<FlatMatrix> {
773 let mut jacobian = self
774 .model
775 .analytical_jacobian(params, free_param_indices, y_current)?;
776 for (row, d) in self.dispersion.iter().enumerate() {
777 for col in 0..free_param_indices.len() {
778 *jacobian.get_mut(row, col) /= d;
779 }
780 }
781 Some(jacobian)
782 }
783}
784
785pub(crate) struct Recorded<'a, M> {
786 pub(crate) model: M,
787 pub(crate) live: &'a [f64],
788}
789
790impl<M: FitModel> FitModel for Recorded<'_, M> {
791 fn evaluate(&self, params: &[f64]) -> Result<Vec<f64>, FittingError> {
792 let counts = self.model.evaluate(params)?;
793 Ok(counts.iter().zip(self.live).map(|(c, l)| l * c).collect())
794 }
795
796 fn analytical_jacobian(
797 &self,
798 params: &[f64],
799 free_param_indices: &[usize],
800 y_current: &[f64],
801 ) -> Option<FlatMatrix> {
802 let mut jacobian = self
803 .model
804 .analytical_jacobian(params, free_param_indices, y_current)?;
805 for (row, l) in self.live.iter().enumerate() {
806 for col in 0..free_param_indices.len() {
807 *jacobian.get_mut(row, col) *= l;
808 }
809 }
810 Some(jacobian)
811 }
812}
813
814pub(crate) fn combined(basis: &[[(usize, f64); 5]], coefficients: &[f64]) -> Vec<f64> {
815 basis
816 .iter()
817 .map(|pairs| pairs.iter().map(|&(i, w)| w * coefficients[i]).sum())
818 .collect()
819}
820
821pub(crate) fn weights_of(basis: &[[(usize, f64); 5]], index: usize) -> Vec<f64> {
822 basis
823 .iter()
824 .map(|pairs| {
825 pairs
826 .iter()
827 .filter(|&&(i, _)| i == index)
828 .map(|&(_, w)| w)
829 .sum()
830 })
831 .collect()
832}
833
834pub(crate) struct OpenBeamModel {
835 grid: Arc<FlightTimeGrid>,
836 basis: Vec<[(usize, f64); 5]>,
837 known: Vec<f64>,
838 transmission: Option<Vec<f64>>,
839}
840
841impl OpenBeamModel {
842 pub(crate) fn new(grid: &Arc<FlightTimeGrid>, beam: &BeamSpline, known: &[f64]) -> Self {
843 Self {
844 grid: Arc::clone(grid),
845 basis: grid
846 .flight_times_us()
847 .iter()
848 .map(|&u| beam.basis(u))
849 .collect(),
850 known: known.to_vec(),
851 transmission: None,
852 }
853 }
854
855 pub(crate) fn filtered(
857 mut self,
858 filter: Option<(&Filter, f64)>,
859 ) -> Result<Self, PipelineError> {
860 self.transmission = filter
861 .map(|(filter, density)| {
862 let sigma = filter.on_grid(&self.grid)?;
863 Ok::<_, PipelineError>(sigma.iter().map(|s| (-density * s).exp()).collect())
864 })
865 .transpose()?;
866 Ok(self)
867 }
868
869 pub(crate) fn beam(&self, coefficients: &[f64]) -> Vec<f64> {
870 let beam = combined(&self.basis, coefficients)
871 .into_iter()
872 .map(f64::exp);
873 match &self.transmission {
874 Some(transmission) => beam.zip(transmission).map(|(phi, t)| phi * t).collect(),
875 None => beam.collect(),
876 }
877 }
878
879 pub(crate) fn log_slope(&self, index: usize) -> Vec<f64> {
880 weights_of(&self.basis, index)
881 }
882
883 pub(crate) fn counts(&self, values: &[f64]) -> Result<Vec<f64>, FittingError> {
884 self.grid
885 .predict(values)
886 .map_err(|e| FittingError::EvaluationFailed(e.to_string()))
887 }
888}
889
890impl FitModel for OpenBeamModel {
891 fn evaluate(&self, params: &[f64]) -> Result<Vec<f64>, FittingError> {
892 let mut counts = self.counts(&self.beam(params))?;
893 for (c, g) in counts.iter_mut().zip(&self.known) {
894 *c += g;
895 }
896 Ok(counts)
897 }
898
899 fn analytical_jacobian(
900 &self,
901 params: &[f64],
902 free_param_indices: &[usize],
903 y_current: &[f64],
904 ) -> Option<FlatMatrix> {
905 let beam = self.beam(params);
906 let mut jacobian = FlatMatrix::zeros(y_current.len(), free_param_indices.len());
907 for (col, &index) in free_param_indices.iter().enumerate() {
908 let values: Vec<f64> = self
909 .log_slope(index)
910 .iter()
911 .zip(&beam)
912 .map(|(slope, phi)| slope * phi)
913 .collect();
914 for (row, value) in self.counts(&values).ok()?.into_iter().enumerate() {
915 *jacobian.get_mut(row, col) = value;
916 }
917 }
918 Some(jacobian)
919 }
920}
921
922#[cfg(test)]
923pub(crate) mod tests {
924 use nereids_physics::ikeda_carpenter::{IkedaCarpenter, SynthesisGrid};
925
926 use super::*;
927
928 pub(crate) const FLIGHT_PATH_M: f64 = 25.0;
929 pub(crate) const T0_US: f64 = 3.0;
930 pub(crate) const EDGES_US: std::ops::RangeInclusive<u32> = 350..=470;
931 pub(crate) const ALPHA: EnergyLaw = EnergyLaw::SqrtE { a0: 0.35, a1: 0.05 };
932 pub(crate) const BETA: EnergyLaw = EnergyLaw::Const(0.25);
933 pub(crate) const R: EnergyLaw = EnergyLaw::Const(0.15);
934
935 pub(crate) fn grid(channel_fwhm_us: Option<f64>) -> Arc<FlightTimeGrid> {
936 let pulse = IkedaCarpenter::new(
937 IkedaCarpenterParams {
938 alpha: ALPHA,
939 beta: BETA,
940 r: R,
941 burst_sigma_us: None,
942 channel_fwhm_us,
943 detector_tail: None,
944 },
945 FLIGHT_PATH_M,
946 &SynthesisGrid {
947 e_min_ev: 1.0,
948 e_max_ev: 200.0,
949 n_energies: 32,
950 n_tau: 256,
951 },
952 )
953 .expect("valid IC model");
954 let edges: Vec<f64> = EDGES_US.map(f64::from).collect();
955 Arc::new(
956 FlightTimeGrid::new(&edges, T0_US, FLIGHT_PATH_M, &pulse.detector_pulse())
957 .expect("grid"),
958 )
959 }
960
961 #[test]
962 fn a_beam_interval_spans_two_bins_or_more() {
963 let fine: Vec<f64> = (0..=3262).map(|i| 127.84 + 0.16 * f64::from(i)).collect();
965 assert!(spans_two_bins(&fine, 0.0, 512) && !spans_two_bins(&fine, 0.0, 1024));
966 let even: Vec<f64> = (0..=64).map(|i| 3.0 + 100.0 * 1.02_f64.powi(i)).collect();
968 assert!(spans_two_bins(&even, 3.0, 32) && !spans_two_bins(&even, 3.0, 64));
969 let (low, high) = (347.21427154527134_f64, 460.0701208068366_f64);
971 assert!(low * (high / low) < high);
972 assert!(spans_two_bins(
973 &[low, f64::from_bits(high.to_bits() - 1), high],
974 0.0,
975 1
976 ));
977 }
978
979 struct Backwards;
980
981 impl FitModel for Backwards {
982 fn evaluate(&self, params: &[f64]) -> Result<Vec<f64>, FittingError> {
983 Ok(vec![params[0]; 4])
984 }
985
986 fn analytical_jacobian(&self, _: &[f64], free: &[usize], _: &[f64]) -> Option<FlatMatrix> {
987 let mut slopes = FlatMatrix::zeros(4, free.len());
988 for row in 0..4 {
989 *slopes.get_mut(row, 0) = -1.0;
990 }
991 Some(slopes)
992 }
993 }
994
995 #[test]
996 fn a_grid_fit_names_the_rule_that_ended_the_fitter() {
997 let mut level = ParameterSet::new(vec![FitParameter::unbounded("level", 50.0)]);
998 let fit = fit_on_halved_grids(
999 &grid(None),
1000 &mut level,
1001 &[100.0; 4],
1002 &[1.0; 4],
1003 &[],
1004 |_| Ok(Backwards),
1005 |_, _, _| Ok(true),
1006 )
1007 .expect("fit");
1008 assert!(!fit.converged);
1009 let rule = fit.unconverged.expect("rule");
1010 let (stall, trial) = rule.split_once("; ").expect("two clauses");
1011 assert_eq!(
1012 stall,
1013 "no step of the fitter lowers the objective, still moving level with a further \
1014 decrease of 1.00e2 predicted, 1.00e2 at most by level with the others held"
1015 );
1016 assert!(
1017 trial.starts_with("the last trial step that could lower the objective raised it by "),
1018 "{trial}"
1019 );
1020 }
1021
1022 #[test]
1023 fn the_jacobian_is_the_slope_of_the_counts() {
1024 for channel_fwhm_us in [None, Some(2.0)] {
1025 let grid = grid(channel_fwhm_us);
1026 let (_, u_hi) = grid.range_us();
1027 for beam in [
1028 BeamSpline::constant(347.0, u_hi, 1.0e4),
1029 BeamSpline::constant(347.0, u_hi, 1.0e4).refined().refined(),
1030 ] {
1031 let model = OpenBeamModel::new(&grid, &beam, &[]);
1032 let coefficients: Vec<f64> = (0..beam.coefficients().len())
1033 .map(|i| 9.0 + 0.3 * (i as f64).sin())
1034 .collect();
1035 let counts = model.evaluate(&coefficients).expect("counts");
1036 let indices: Vec<usize> = (0..coefficients.len()).collect();
1037 let jacobian = model
1038 .analytical_jacobian(&coefficients, &indices, &counts)
1039 .expect("jacobian");
1040 for index in indices {
1041 let h = 1e-4;
1042 let shifted = |d: f64| {
1043 let mut c = coefficients.clone();
1044 c[index] += d;
1045 model.evaluate(&c).expect("counts")
1046 };
1047 let (up, down) = (shifted(h), shifted(-h));
1048 let slopes: Vec<f64> = up
1049 .iter()
1050 .zip(&down)
1051 .map(|(u, d)| (u - d) / (2.0 * h))
1052 .collect();
1053 let column = slopes.iter().fold(0.0_f64, |m, s| m.max(s.abs()));
1054 for (row, &slope) in slopes.iter().enumerate() {
1055 let analytic = jacobian.get(row, index);
1056 assert!(
1057 (analytic - slope).abs() <= 1e-6 * column,
1058 "{channel_fwhm_us:?} {} {index} {row}: {analytic} vs {slope}",
1059 beam.intervals()
1060 );
1061 }
1062 }
1063 }
1064 }
1065 }
1066}