1#[cfg(feature = "debug-pipeline")]
4pub mod background;
5#[cfg(not(feature = "debug-pipeline"))]
6mod background;
7
8#[cfg(feature = "debug-pipeline")]
9pub mod convolution;
10#[cfg(not(feature = "debug-pipeline"))]
11mod convolution;
12
13#[cfg(feature = "debug-pipeline")]
14pub mod detection;
15#[cfg(not(feature = "debug-pipeline"))]
16mod detection;
17
18#[cfg(feature = "debug-pipeline")]
19pub mod fitting;
20#[cfg(not(feature = "debug-pipeline"))]
21mod fitting;
22
23#[cfg(feature = "debug-pipeline")]
24pub mod metrics;
25#[cfg(not(feature = "debug-pipeline"))]
26mod metrics;
27
28#[cfg(feature = "debug-pipeline")]
29pub mod snr;
30#[cfg(not(feature = "debug-pipeline"))]
31mod snr;
32
33#[cfg(feature = "debug-pipeline")]
34pub mod render;
35
36use std::path::Path;
37use std::sync::Arc;
38
39use anyhow::{Context, Result};
40
41use crate::formats;
42use crate::processing::color::u16_to_f32;
43use crate::processing::debayer;
44use crate::processing::stretch::find_median;
45use crate::types::{BayerPattern, ImageMetadata, PixelData};
46
47use detection::DetectionParams;
48
49#[derive(Debug, Clone, Copy, PartialEq)]
51pub enum FitMethod {
52 FreeMoffat,
54 FixedMoffat,
56 Gaussian,
58 Moments,
60}
61
62pub struct StarMetrics {
64 pub x: f32,
66 pub y: f32,
68 pub peak: f32,
70 pub flux: f32,
72 pub fwhm_x: f32,
74 pub fwhm_y: f32,
76 pub fwhm: f32,
78 pub eccentricity: f32,
80 pub snr: f32,
82 pub hfr: f32,
84 pub theta: f32,
88 pub beta: Option<f32>,
90 pub fit_method: FitMethod,
92 pub fit_residual: f32,
95}
96
97pub struct AnalysisResult {
99 pub width: usize,
101 pub height: usize,
103 pub source_channels: usize,
105 pub background: f32,
107 pub noise: f32,
109 pub detection_threshold: f32,
111 pub stars_detected: usize,
113 pub stars: Vec<StarMetrics>,
115 pub median_fwhm: f32,
117 pub median_eccentricity: f32,
119 pub median_snr: f32,
121 pub median_hfr: f32,
123 pub snr_weight: f32,
125 pub psf_signal: f32,
127 pub frame_snr: f32,
130 pub trail_r_squared: f32,
135 pub possibly_trailed: bool,
140 pub measured_fwhm_kernel: f32,
144 pub median_beta: Option<f32>,
147}
148
149pub struct AnalysisConfig {
151 detection_sigma: f32,
152 min_star_area: usize,
153 max_star_area: usize,
154 saturation_fraction: f32,
155 max_stars: usize,
156 apply_debayer: bool,
157 trail_r_squared_threshold: f32,
158 noise_layers: usize,
160 measure_cap: usize,
162 fit_max_iter: usize,
164 fit_tolerance: f64,
166 fit_max_rejects: usize,
168}
169
170pub struct ImageAnalyzer {
172 config: AnalysisConfig,
173 thread_pool: Option<Arc<rayon::ThreadPool>>,
174}
175
176impl ImageAnalyzer {
177 pub fn new() -> Self {
178 ImageAnalyzer {
179 config: AnalysisConfig {
180 detection_sigma: 5.0,
181 min_star_area: 5,
182 max_star_area: 2000,
183 saturation_fraction: 0.95,
184 max_stars: 200,
185 apply_debayer: true,
186 trail_r_squared_threshold: 0.5,
187 noise_layers: 0,
188 measure_cap: 500,
189 fit_max_iter: 25,
190 fit_tolerance: 1e-4,
191 fit_max_rejects: 5,
192 },
193 thread_pool: None,
194 }
195 }
196
197 pub fn with_detection_sigma(mut self, sigma: f32) -> Self {
199 self.config.detection_sigma = sigma.max(1.0);
200 self
201 }
202
203 pub fn with_min_star_area(mut self, area: usize) -> Self {
205 self.config.min_star_area = area.max(1);
206 self
207 }
208
209 pub fn with_max_star_area(mut self, area: usize) -> Self {
211 self.config.max_star_area = area;
212 self
213 }
214
215 pub fn with_saturation_fraction(mut self, frac: f32) -> Self {
217 self.config.saturation_fraction = frac.clamp(0.5, 1.0);
218 self
219 }
220
221 pub fn with_max_stars(mut self, n: usize) -> Self {
223 self.config.max_stars = n.max(1);
224 self
225 }
226
227 pub fn without_debayer(mut self) -> Self {
229 self.config.apply_debayer = false;
230 self
231 }
232
233 pub fn with_trail_threshold(mut self, threshold: f32) -> Self {
237 self.config.trail_r_squared_threshold = threshold.clamp(0.0, 1.0);
238 self
239 }
240
241 pub fn with_mrs_layers(mut self, layers: usize) -> Self {
246 self.config.noise_layers = layers;
247 self
248 }
249
250 pub fn with_measure_cap(mut self, n: usize) -> Self {
254 self.config.measure_cap = n;
255 self
256 }
257
258 pub fn with_fit_max_iter(mut self, n: usize) -> Self {
261 self.config.fit_max_iter = n.max(1);
262 self
263 }
264
265 pub fn with_fit_tolerance(mut self, tol: f64) -> Self {
268 self.config.fit_tolerance = tol;
269 self
270 }
271
272 pub fn with_fit_max_rejects(mut self, n: usize) -> Self {
274 self.config.fit_max_rejects = n.max(1);
275 self
276 }
277
278 pub fn with_thread_pool(mut self, pool: Arc<rayon::ThreadPool>) -> Self {
280 self.thread_pool = Some(pool);
281 self
282 }
283
284 pub fn analyze<P: AsRef<Path>>(&self, path: P) -> Result<AnalysisResult> {
286 let path = path.as_ref();
287 match &self.thread_pool {
288 Some(pool) => pool.install(|| self.analyze_impl(path)),
289 None => self.analyze_impl(path),
290 }
291 }
292
293 pub fn analyze_data(
300 &self,
301 data: &[f32],
302 width: usize,
303 height: usize,
304 channels: usize,
305 ) -> Result<AnalysisResult> {
306 match &self.thread_pool {
307 Some(pool) => pool.install(|| {
308 self.run_analysis(data, width, height, channels)
309 }),
310 None => self.run_analysis(data, width, height, channels),
311 }
312 }
313
314 pub fn analyze_raw(
319 &self,
320 meta: &ImageMetadata,
321 pixels: &PixelData,
322 ) -> Result<AnalysisResult> {
323 match &self.thread_pool {
324 Some(pool) => pool.install(|| self.analyze_raw_impl(meta, pixels)),
325 None => self.analyze_raw_impl(meta, pixels),
326 }
327 }
328
329 fn analyze_raw_impl(
330 &self,
331 meta: &ImageMetadata,
332 pixels: &PixelData,
333 ) -> Result<AnalysisResult> {
334 let f32_data = match pixels {
335 PixelData::Float32(d) => std::borrow::Cow::Borrowed(d.as_slice()),
336 PixelData::Uint16(d) => std::borrow::Cow::Owned(u16_to_f32(d)),
337 };
338
339 let mut data = f32_data.into_owned();
340 let width = meta.width;
341 let height = meta.height;
342 let channels = meta.channels;
343
344 if self.config.apply_debayer
347 && meta.bayer_pattern != BayerPattern::None
348 && channels == 1
349 {
350 data = debayer::interpolate_green_f32(&data, width, height, meta.bayer_pattern);
351 }
352
353 self.run_analysis(&data, width, height, channels)
354 }
355
356 fn analyze_impl(&self, path: &Path) -> Result<AnalysisResult> {
357 let (meta, pixel_data) =
358 formats::read_image(path).context("Failed to read image for analysis")?;
359
360 let f32_data = match pixel_data {
362 PixelData::Float32(d) => d,
363 PixelData::Uint16(d) => u16_to_f32(&d),
364 };
365
366 let mut data = f32_data;
367 let width = meta.width;
368 let height = meta.height;
369 let channels = meta.channels;
370
371 if self.config.apply_debayer
373 && meta.bayer_pattern != BayerPattern::None
374 && channels == 1
375 {
376 data = debayer::interpolate_green_f32(&data, width, height, meta.bayer_pattern);
377 }
378
379 self.run_analysis(&data, width, height, channels)
380 }
381
382 fn run_analysis(
383 &self,
384 data: &[f32],
385 width: usize,
386 height: usize,
387 channels: usize,
388 ) -> Result<AnalysisResult> {
389 let lum = if channels == 3 {
391 extract_luminance(data, width, height)
392 } else {
393 data[..width * height].to_vec()
394 };
395
396 let det_params = DetectionParams {
397 detection_sigma: self.config.detection_sigma,
398 min_star_area: self.config.min_star_area,
399 max_star_area: self.config.max_star_area,
400 saturation_limit: self.config.saturation_fraction * 65535.0,
401 };
402
403 let cell_size = background::auto_cell_size(width, height);
405 let mut bg_result = background::estimate_background_mesh(&lum, width, height, cell_size);
406 if self.config.noise_layers > 0 {
407 bg_result.noise = background::estimate_noise_mrs(
409 &lum, width, height, self.config.noise_layers.max(1),
410 ).max(0.001);
411 }
412 let initial_fwhm = 3.0_f32;
416 let pass1_stars = {
417 let bg_map = bg_result.background_map.as_deref();
418 let noise_map = bg_result.noise_map.as_deref();
419 detection::detect_stars(
420 &lum, width, height,
421 bg_result.background, bg_result.noise,
422 bg_map, noise_map, &det_params, initial_fwhm,
423 None,
424 )
425 };
426
427 let calibration_stars: Vec<&detection::DetectedStar> = pass1_stars
429 .iter()
430 .filter(|s| s.eccentricity < 0.5 && s.area >= 5)
431 .take(100)
432 .collect();
433
434 let field_beta: Option<f64>;
436 let field_fwhm: f32;
437 if calibration_stars.len() >= 3 {
438 let cal_owned: Vec<detection::DetectedStar> = calibration_stars
439 .iter()
440 .map(|s| detection::DetectedStar {
441 x: s.x, y: s.y, peak: s.peak, flux: s.flux,
442 area: s.area, theta: s.theta, eccentricity: s.eccentricity,
443 })
444 .collect();
445 let cal_measured = metrics::measure_stars(
446 &lum, width, height, &cal_owned,
447 bg_result.background,
448 bg_result.background_map.as_deref(),
449 None, None, 50, 1e-6, 5, None, false, );
455
456 let mut beta_vals: Vec<f32> = cal_measured.iter().filter_map(|s| s.beta).collect();
457 let mut fwhm_vals: Vec<f32> = cal_measured.iter().map(|s| s.fwhm).collect();
458
459 if beta_vals.len() >= 3 {
460 field_beta = Some(sigma_clipped_median(&beta_vals) as f64);
461 } else if !beta_vals.is_empty() {
462 field_beta = Some(find_median(&mut beta_vals) as f64);
463 } else {
464 field_beta = None;
465 }
466
467 if fwhm_vals.len() >= 3 {
468 field_fwhm = sigma_clipped_median(&fwhm_vals);
469 } else if !fwhm_vals.is_empty() {
470 field_fwhm = find_median(&mut fwhm_vals);
471 } else {
472 field_fwhm = estimate_fwhm_from_stars(
473 &lum, width, height, &pass1_stars,
474 bg_result.background, bg_result.background_map.as_deref(),
475 );
476 }
477 } else {
478 field_beta = None;
480 field_fwhm = estimate_fwhm_from_stars(
481 &lum, width, height, &pass1_stars,
482 bg_result.background, bg_result.background_map.as_deref(),
483 );
484 }
485
486 let clamped_fwhm = field_fwhm.max(2.0);
496 let final_fwhm = if clamped_fwhm > 1.0
497 && ((clamped_fwhm - initial_fwhm) / initial_fwhm).abs() > 0.30
498 {
499 clamped_fwhm.min(initial_fwhm * 2.0)
500 } else {
501 initial_fwhm
502 };
503
504 let detected = {
505 let bg_map = bg_result.background_map.as_deref();
506 let noise_map = bg_result.noise_map.as_deref();
507 detection::detect_stars(
508 &lum, width, height,
509 bg_result.background, bg_result.noise,
510 bg_map, noise_map, &det_params, final_fwhm,
511 Some(clamped_fwhm),
512 )
513 };
514
515 let bg_map_ref = bg_result.background_map.as_deref();
516 let detection_threshold = self.config.detection_sigma * bg_result.noise;
517
518 let (trail_r_squared, possibly_trailed) = if detected.len() >= 20 {
522 let n = detected.len();
523 let (sum_cos, sum_sin) =
524 detected.iter().fold((0.0f64, 0.0f64), |(sc, ss), s| {
525 let a = 2.0 * s.theta as f64;
526 (sc + a.cos(), ss + a.sin())
527 });
528 let r_sq = (sum_cos * sum_cos + sum_sin * sum_sin) / (n as f64 * n as f64);
529 let p = (-(n as f64) * r_sq).exp();
530 let mut eccs: Vec<f32> = detected.iter().map(|s| s.eccentricity).collect();
531 eccs.sort_unstable_by(|a, b| a.total_cmp(b));
532 let median_ecc = if eccs.len() % 2 == 1 {
533 eccs[eccs.len() / 2]
534 } else {
535 (eccs[eccs.len() / 2 - 1] + eccs[eccs.len() / 2]) * 0.5
536 };
537 let threshold = self.config.trail_r_squared_threshold as f64;
538 let trailed = (r_sq > threshold && p < 0.01) || (r_sq > 0.05 && median_ecc > 0.6 && p < 0.05); (r_sq as f32, trailed)
541 } else {
542 (0.0, false)
543 };
544
545 let snr_weight = snr::compute_snr_weight(&lum, bg_result.background, bg_result.noise);
546 let frame_snr = if bg_result.noise > 0.0 { bg_result.background / bg_result.noise } else { 0.0 };
547
548 let make_zero_result = |stars_detected: usize| {
549 Ok(AnalysisResult {
550 width, height, source_channels: channels,
551 background: bg_result.background, noise: bg_result.noise,
552 detection_threshold, stars_detected,
553 stars: Vec::new(),
554 median_fwhm: 0.0, median_eccentricity: 0.0,
555 median_snr: 0.0, median_hfr: 0.0,
556 snr_weight, psf_signal: 0.0, frame_snr,
557 trail_r_squared, possibly_trailed,
558 measured_fwhm_kernel: final_fwhm,
559 median_beta: field_beta.map(|b| b as f32),
560 })
561 };
562
563 if detected.is_empty() {
564 return make_zero_result(0);
565 }
566
567 let stars_detected = detected.len();
569
570 let effective_cap = if self.config.measure_cap == 0 {
574 detected.len()
575 } else {
576 self.config.measure_cap
577 };
578
579 let to_measure: Vec<detection::DetectedStar> = if detected.len() <= effective_cap {
580 detected.clone()
581 } else {
582 debug_assert!(
583 detected.windows(2).all(|w| w[0].flux >= w[1].flux),
584 "detected stars must be sorted by flux descending"
585 );
586 const GRID_N: usize = 4;
587 let cell_w = width as f32 / GRID_N as f32;
588 let cell_h = height as f32 / GRID_N as f32;
589 let mut buckets: Vec<Vec<&detection::DetectedStar>> =
590 vec![Vec::new(); GRID_N * GRID_N];
591
592 for star in &detected {
593 let gx = ((star.x / cell_w) as usize).min(GRID_N - 1);
594 let gy = ((star.y / cell_h) as usize).min(GRID_N - 1);
595 buckets[gy * GRID_N + gx].push(star);
596 }
597
598 let mut selected: Vec<detection::DetectedStar> = Vec::with_capacity(effective_cap);
599 let mut idx = vec![0usize; GRID_N * GRID_N];
600 loop {
601 let mut added_any = false;
602 for cell in 0..(GRID_N * GRID_N) {
603 if selected.len() >= effective_cap { break; }
604 if idx[cell] < buckets[cell].len() {
605 selected.push(buckets[cell][idx[cell]].clone());
606 idx[cell] += 1;
607 added_any = true;
608 }
609 }
610 if !added_any || selected.len() >= effective_cap { break; }
611 }
612 selected
613 };
614
615 let mut measured = metrics::measure_stars(
616 &lum, width, height, &to_measure,
617 bg_result.background, bg_map_ref,
618 None, field_beta, self.config.fit_max_iter,
620 self.config.fit_tolerance,
621 self.config.fit_max_rejects,
622 Some(field_fwhm), possibly_trailed, );
625
626 if measured.is_empty() {
627 return make_zero_result(stars_detected);
628 }
629
630 const FWHM_ECC_MAX: f32 = 0.8;
639 let fwhm_filtered: Vec<&metrics::MeasuredStar> = if possibly_trailed {
640 measured.iter().collect()
641 } else {
642 let round: Vec<&metrics::MeasuredStar> = measured.iter()
643 .filter(|s| s.eccentricity <= FWHM_ECC_MAX)
644 .collect();
645 if round.len() >= 3 { round } else { measured.iter().collect() }
646 };
647 let (fwhm_vals, hfr_vals, shape_weights) = (
648 fwhm_filtered.iter().map(|s| s.fwhm).collect::<Vec<f32>>(),
649 fwhm_filtered.iter().map(|s| s.hfr).collect::<Vec<f32>>(),
650 fwhm_filtered.iter().map(|s| 1.0 / (1.0 + s.fit_residual)).collect::<Vec<f32>>(),
651 );
652 let median_fwhm = sigma_clipped_weighted_median(&fwhm_vals, &shape_weights);
653
654 let ecc_use_all = possibly_trailed;
658 let ecc_filtered: Vec<&metrics::MeasuredStar> = if ecc_use_all {
659 measured.iter().collect()
660 } else {
661 let filtered: Vec<&metrics::MeasuredStar> = measured.iter()
662 .filter(|s| s.eccentricity <= FWHM_ECC_MAX)
663 .collect();
664 if filtered.len() >= 3 { filtered } else { measured.iter().collect() }
665 };
666 let ecc_vals: Vec<f32> = ecc_filtered.iter().map(|s| s.eccentricity).collect();
667 let ecc_weights: Vec<f32> = ecc_filtered.iter()
668 .map(|s| 1.0 / (1.0 + s.fit_residual))
669 .collect();
670
671 snr::compute_star_snr(&lum, width, height, &mut measured, median_fwhm);
672
673 let mut snr_vals: Vec<f32> = measured.iter().map(|s| s.snr).collect();
674
675 let median_eccentricity = sigma_clipped_weighted_median(&ecc_vals, &ecc_weights);
676 let median_snr = find_median(&mut snr_vals);
677 let median_hfr = sigma_clipped_weighted_median(&hfr_vals, &shape_weights);
678 let psf_signal = snr::compute_psf_signal(&measured, bg_result.noise);
679
680 let median_beta = if let Some(fb) = field_beta {
682 Some(fb as f32)
683 } else {
684 let mut beta_vals: Vec<f32> = measured.iter().filter_map(|s| s.beta).collect();
685 if beta_vals.is_empty() { None } else { Some(find_median(&mut beta_vals)) }
686 };
687
688 measured.truncate(self.config.max_stars);
690
691 let stars: Vec<StarMetrics> = measured
692 .into_iter()
693 .map(|m| StarMetrics {
694 x: m.x, y: m.y, peak: m.peak, flux: m.flux,
695 fwhm_x: m.fwhm_x, fwhm_y: m.fwhm_y, fwhm: m.fwhm,
696 eccentricity: m.eccentricity, snr: m.snr, hfr: m.hfr,
697 theta: m.theta, beta: m.beta, fit_method: m.fit_method,
698 fit_residual: m.fit_residual,
699 })
700 .collect();
701
702 Ok(AnalysisResult {
703 width, height, source_channels: channels,
704 background: bg_result.background, noise: bg_result.noise,
705 detection_threshold, stars_detected, stars,
706 median_fwhm, median_eccentricity, median_snr, median_hfr,
707 snr_weight, psf_signal, frame_snr,
708 trail_r_squared, possibly_trailed,
709 measured_fwhm_kernel: final_fwhm,
710 median_beta,
711 })
712 }
713}
714
715impl Default for ImageAnalyzer {
716 fn default() -> Self {
717 Self::new()
718 }
719}
720
721pub fn sigma_clipped_median(values: &[f32]) -> f32 {
730 if values.is_empty() {
731 return 0.0;
732 }
733 let mut v: Vec<f32> = values.to_vec();
734 for _ in 0..2 {
735 if v.len() < 3 {
736 break;
737 }
738 let med = find_median(&mut v);
739 let mut abs_devs: Vec<f32> = v.iter().map(|&x| (x - med).abs()).collect();
740 let mad = find_median(&mut abs_devs);
741 let sigma_mad = 1.4826 * mad;
742 if sigma_mad < 1e-10 {
743 break; }
745 let clip = 3.0 * sigma_mad;
746 v.retain(|&x| (x - med).abs() <= clip);
747 }
748 if v.is_empty() {
749 return find_median(&mut values.to_vec());
750 }
751 find_median(&mut v)
752}
753
754pub fn weighted_median(values: &[f32], weights: &[f32]) -> f32 {
758 if values.is_empty() || values.len() != weights.len() {
759 return 0.0;
760 }
761 let mut pairs: Vec<(f32, f32)> = values.iter().copied()
762 .zip(weights.iter().copied())
763 .filter(|(_, w)| *w > 0.0)
764 .collect();
765 if pairs.is_empty() {
766 return 0.0;
767 }
768 pairs.sort_by(|a, b| a.0.total_cmp(&b.0));
769 let total: f32 = pairs.iter().map(|(_, w)| w).sum();
770 if total <= 0.0 {
771 return 0.0;
772 }
773 let half = total * 0.5;
774 let mut cumulative = 0.0_f32;
775 for &(val, w) in &pairs {
776 cumulative += w;
777 if cumulative >= half {
778 return val;
779 }
780 }
781 pairs.last().unwrap().0
782}
783
784pub fn sigma_clipped_weighted_median(values: &[f32], weights: &[f32]) -> f32 {
789 if values.is_empty() || values.len() != weights.len() {
790 return 0.0;
791 }
792 let mut v: Vec<f32> = values.to_vec();
793 let mut w: Vec<f32> = weights.to_vec();
794 for _ in 0..2 {
795 if v.len() < 3 {
796 break;
797 }
798 let med = weighted_median(&v, &w);
799 let abs_devs: Vec<f32> = v.iter().map(|&x| (x - med).abs()).collect();
800 let mut sorted_devs = abs_devs.clone();
802 sorted_devs.sort_by(|a, b| a.total_cmp(b));
803 let mad = sorted_devs[sorted_devs.len() / 2];
804 let sigma_mad = 1.4826 * mad;
805 if sigma_mad < 1e-10 {
806 break;
807 }
808 let clip = 3.0 * sigma_mad;
809 let mut new_v = Vec::with_capacity(v.len());
810 let mut new_w = Vec::with_capacity(w.len());
811 for (val, wt) in v.iter().zip(w.iter()) {
812 if (*val - med).abs() <= clip {
813 new_v.push(*val);
814 new_w.push(*wt);
815 }
816 }
817 v = new_v;
818 w = new_w;
819 }
820 if v.is_empty() {
821 return weighted_median(values, weights);
822 }
823 weighted_median(&v, &w)
824}
825
826pub fn estimate_fwhm_from_stars(
830 lum: &[f32],
831 width: usize,
832 height: usize,
833 stars: &[detection::DetectedStar],
834 background: f32,
835 bg_map: Option<&[f32]>,
836) -> f32 {
837 let scan_n = stars.len().min(50);
841 if scan_n < 3 {
842 return 0.0;
843 }
844
845 let round_stars: Vec<&detection::DetectedStar> = stars[..scan_n]
846 .iter()
847 .filter(|s| s.eccentricity <= 0.7)
848 .take(20)
849 .collect();
850 if round_stars.len() < 3 {
851 return 0.0;
852 }
853
854 let mut fwhm_vals = Vec::with_capacity(round_stars.len());
855 for star in &round_stars {
856 let stamp_radius = 12_usize; let cx = star.x.round() as i32;
858 let cy = star.y.round() as i32;
859 let sr = stamp_radius as i32;
860 if cx - sr <= 0 || cy - sr <= 0
861 || cx + sr >= width as i32 - 1
862 || cy + sr >= height as i32 - 1
863 {
864 continue;
865 }
866 let x0 = (cx - sr) as usize;
867 let y0 = (cy - sr) as usize;
868 let x1 = (cx + sr) as usize;
869 let y1 = (cy + sr) as usize;
870 let stamp_w = x1 - x0 + 1;
871 let mut stamp = Vec::with_capacity(stamp_w * (y1 - y0 + 1));
872 for sy in y0..=y1 {
873 for sx in x0..=x1 {
874 let bg = bg_map.map_or(background, |m| m[sy * width + sx]);
875 stamp.push(lum[sy * width + sx] - bg);
876 }
877 }
878 let rel_cx = star.x - x0 as f32;
879 let rel_cy = star.y - y0 as f32;
880 let sigma = metrics::estimate_sigma_halfmax(&stamp, stamp_w, rel_cx, rel_cy);
881 let fwhm = sigma * 2.3548;
882 if fwhm > 1.0 && fwhm < 20.0 {
883 fwhm_vals.push(fwhm);
884 }
885 }
886
887 if fwhm_vals.len() < 3 {
888 return 0.0;
889 }
890 find_median(&mut fwhm_vals)
891}
892
893fn build_green_mask(width: usize, height: usize, pattern: BayerPattern) -> Vec<bool> {
899 let green_at_even = matches!(pattern, BayerPattern::Gbrg | BayerPattern::Grbg);
900 (0..height)
901 .flat_map(|y| {
902 (0..width).map(move |x| {
903 let parity = (x + y) & 1;
904 if green_at_even { parity == 0 } else { parity == 1 }
905 })
906 })
907 .collect()
908}
909
910pub fn extract_luminance(data: &[f32], width: usize, height: usize) -> Vec<f32> {
912 use rayon::prelude::*;
913
914 let plane_size = width * height;
915 let r = &data[..plane_size];
916 let g = &data[plane_size..2 * plane_size];
917 let b = &data[2 * plane_size..3 * plane_size];
918
919 let mut lum = vec![0.0_f32; plane_size];
920 const CHUNK: usize = 8192;
921 lum.par_chunks_mut(CHUNK)
922 .enumerate()
923 .for_each(|(ci, chunk)| {
924 let off = ci * CHUNK;
925 for (i, dst) in chunk.iter_mut().enumerate() {
926 let idx = off + i;
927 *dst = 0.2126 * r[idx] + 0.7152 * g[idx] + 0.0722 * b[idx];
928 }
929 });
930 lum
931}
932
933#[cfg(feature = "debug-pipeline")]
939pub fn prepare_luminance(
940 meta: &crate::types::ImageMetadata,
941 pixels: &crate::types::PixelData,
942 apply_debayer: bool,
943) -> (Vec<f32>, usize, usize, usize, Option<Vec<bool>>) {
944 use crate::processing::color::u16_to_f32;
945 use crate::processing::debayer;
946
947 let f32_data = match pixels {
948 PixelData::Float32(d) => std::borrow::Cow::Borrowed(d.as_slice()),
949 PixelData::Uint16(d) => std::borrow::Cow::Owned(u16_to_f32(d)),
950 };
951
952 let mut data = f32_data.into_owned();
953 let width = meta.width;
954 let height = meta.height;
955 let channels = meta.channels;
956
957 if apply_debayer
960 && meta.bayer_pattern != BayerPattern::None
961 && channels == 1
962 {
963 data = debayer::interpolate_green_f32(&data, width, height, meta.bayer_pattern);
964 }
965 let green_mask: Option<Vec<bool>> = None;
966
967 let lum = if channels == 3 {
968 extract_luminance(&data, width, height)
969 } else {
970 data[..width * height].to_vec()
971 };
972
973 (lum, width, height, channels, green_mask)
974}
975
976#[cfg(test)]
977mod tests {
978 use super::*;
979
980 #[test]
981 fn test_weighted_median_equal_weights() {
982 let vals = [1.0_f32, 3.0, 5.0, 7.0, 9.0];
984 let wts = [1.0_f32; 5];
985 let wm = weighted_median(&vals, &wts);
986 assert!((wm - 5.0).abs() < 0.01, "Equal-weight median should be 5, got {}", wm);
987 }
988
989 #[test]
990 fn test_weighted_median_skewed_weights() {
991 let vals = [1.0_f32, 10.0];
993 let wts = [9.0_f32, 1.0]; let wm = weighted_median(&vals, &wts);
995 assert!((wm - 1.0).abs() < 0.01, "Skewed-weight median should be 1, got {}", wm);
996 }
997
998 #[test]
999 fn test_weighted_median_empty() {
1000 let wm = weighted_median(&[], &[]);
1001 assert_eq!(wm, 0.0);
1002 }
1003
1004 #[test]
1005 fn test_weighted_median_single() {
1006 let wm = weighted_median(&[42.0], &[1.0]);
1007 assert!((wm - 42.0).abs() < 0.01);
1008 }
1009
1010 #[test]
1011 fn test_sigma_clipped_weighted_median_basic() {
1012 let vals = [3.0_f32, 3.1, 3.0, 3.2, 3.0, 100.0]; let wts = [1.0_f32; 6];
1015 let scwm = sigma_clipped_weighted_median(&vals, &wts);
1016 assert!(scwm < 4.0, "Outlier should be clipped, got {}", scwm);
1017 }
1018}