Skip to main content

astroimage/analysis/
mod.rs

1/// Image analysis: FWHM, eccentricity, SNR, PSF signal.
2
3#[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/// Method used to measure this star's PSF.
50#[derive(Debug, Clone, Copy, PartialEq)]
51pub enum FitMethod {
52    /// Free-beta Moffat (8 params) — highest accuracy.
53    FreeMoffat,
54    /// Fixed-beta Moffat (7 params) — field median beta.
55    FixedMoffat,
56    /// Gaussian fallback (7 params).
57    Gaussian,
58    /// Windowed moments — lowest accuracy, flagged unreliable.
59    Moments,
60}
61
62/// Quantitative metrics for a single detected star.
63pub struct StarMetrics {
64    /// Subpixel centroid X.
65    pub x: f32,
66    /// Subpixel centroid Y.
67    pub y: f32,
68    /// Background-subtracted peak value (ADU).
69    pub peak: f32,
70    /// Total background-subtracted flux (ADU).
71    pub flux: f32,
72    /// FWHM along major axis (pixels).
73    pub fwhm_x: f32,
74    /// FWHM along minor axis (pixels).
75    pub fwhm_y: f32,
76    /// Geometric mean FWHM (pixels).
77    pub fwhm: f32,
78    /// Eccentricity: 0 = round, approaching 1 = elongated.
79    pub eccentricity: f32,
80    /// Per-star aperture photometry SNR.
81    pub snr: f32,
82    /// Half-flux radius (pixels).
83    pub hfr: f32,
84    /// PSF position angle in radians, counter-clockwise from +X axis.
85    /// Orientation of the major axis (fwhm_x direction).
86    /// 0.0 when Gaussian fit is disabled and star is nearly round.
87    pub theta: f32,
88    /// Moffat β parameter (None if Gaussian/moments fit was used).
89    pub beta: Option<f32>,
90    /// Which PSF fitting method produced this measurement.
91    pub fit_method: FitMethod,
92    /// Normalized fit residual (quality weight: w = 1/(1+r)).
93    /// Lower = better fit. 1.0 for moments fallback.
94    pub fit_residual: f32,
95}
96
97/// Full analysis result for an image.
98pub struct AnalysisResult {
99    /// Image width (after debayer if applicable).
100    pub width: usize,
101    /// Image height (after debayer if applicable).
102    pub height: usize,
103    /// Number of source channels: 1 = mono, 3 = color (after debayer).
104    pub source_channels: usize,
105    /// Global background level (ADU).
106    pub background: f32,
107    /// Background noise sigma (ADU).
108    pub noise: f32,
109    /// Actual detection threshold used (ADU above background).
110    pub detection_threshold: f32,
111    /// Total stars detected (raw detection count, before measure cap).
112    pub stars_detected: usize,
113    /// Per-star metrics, sorted by flux descending, capped at max_stars.
114    pub stars: Vec<StarMetrics>,
115    /// Median FWHM across all measured stars (pixels).
116    pub median_fwhm: f32,
117    /// Median eccentricity across all measured stars.
118    pub median_eccentricity: f32,
119    /// Median per-star SNR.
120    pub median_snr: f32,
121    /// Median half-flux radius (pixels).
122    pub median_hfr: f32,
123    /// SNR weight for frame ranking: (MeanDev / noise)².
124    pub snr_weight: f32,
125    /// PSF signal: median(star_peaks) / noise.
126    pub psf_signal: f32,
127    /// Per-frame SNR: background / noise (linear ratio).
128    /// Use for stacking prediction: stacked_snr = sqrt(sum(frame_snr_i²)).
129    pub frame_snr: f32,
130    /// Rayleigh R̄² (squared mean resultant length) for directional coherence
131    /// of star position angles. Uses 2θ doubling for axial orientation data.
132    /// 0.0 = uniform (no trail), 1.0 = all stars aligned (strong trail).
133    /// A threshold of 0.5 corresponds to R̄ ≈ 0.71 (strong coherence).
134    pub trail_r_squared: f32,
135    /// True if the image is likely trailed, based on the Rayleigh test.
136    /// Fires when R̄² > threshold with significant p-value, or when R̄² > 0.05
137    /// with high median eccentricity (catches non-coherent guiding issues).
138    /// Requires ≥20 detected stars for statistical reliability.
139    pub possibly_trailed: bool,
140    /// Measured FWHM from adaptive two-pass detection (pixels).
141    /// This is the FWHM used for the final matched filter kernel.
142    /// If the first-pass FWHM was within 30% of 3.0, this equals 3.0.
143    pub measured_fwhm_kernel: f32,
144    /// Median Moffat β across all stars (None if Moffat fitting not used).
145    /// Typical range: 2.0-5.0 for real optics. Lower = broader wings.
146    pub median_beta: Option<f32>,
147}
148
149/// Builder configuration for analysis (internal).
150pub 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    /// MRS wavelet noise layers (default 4).
159    noise_layers: usize,
160    /// Max stars to PSF-fit for statistics. 0 = measure all.
161    measure_cap: usize,
162    /// LM max iterations for pass-2 measurement fits.
163    fit_max_iter: usize,
164    /// LM convergence tolerance for pass-2 measurement fits.
165    fit_tolerance: f64,
166    /// Consecutive LM step rejects before early bailout.
167    fit_max_rejects: usize,
168}
169
170/// Image analyzer with builder pattern.
171pub 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: 4,
188                measure_cap: 2000,
189                fit_max_iter: 25,
190                fit_tolerance: 1e-4,
191                fit_max_rejects: 5,
192            },
193            thread_pool: None,
194        }
195    }
196
197    /// Star detection threshold in σ above background.
198    pub fn with_detection_sigma(mut self, sigma: f32) -> Self {
199        self.config.detection_sigma = sigma.max(1.0);
200        self
201    }
202
203    /// Reject connected components with fewer pixels than this (filters hot pixels).
204    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    /// Reject connected components with more pixels than this (filters galaxies/nebulae).
210    pub fn with_max_star_area(mut self, area: usize) -> Self {
211        self.config.max_star_area = area;
212        self
213    }
214
215    /// Reject stars with peak > fraction × 65535 (saturated).
216    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    /// Keep only the brightest N stars in the returned result.
222    pub fn with_max_stars(mut self, n: usize) -> Self {
223        self.config.max_stars = n.max(1);
224        self
225    }
226
227    /// Skip debayering for OSC images (less accurate but faster).
228    pub fn without_debayer(mut self) -> Self {
229        self.config.apply_debayer = false;
230        self
231    }
232
233    /// Set the R² threshold for trail detection.
234    /// Images with Rayleigh R² above this are flagged as possibly trailed.
235    /// Default: 0.5. Lower values are more aggressive (more false positives).
236    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    /// Set MRS wavelet noise layers.
242    /// Uses à trous B3-spline wavelet to isolate noise from nebulosity/gradients.
243    /// Default: 4.
244    pub fn with_mrs_layers(mut self, layers: usize) -> Self {
245        self.config.noise_layers = layers.max(1);
246        self
247    }
248
249    /// Max stars to PSF-fit for statistics. Default 2000.
250    /// Stars are sorted by flux (brightest first) before capping.
251    /// Set to 0 to measure all detected stars (catalog export mode).
252    pub fn with_measure_cap(mut self, n: usize) -> Self {
253        self.config.measure_cap = n;
254        self
255    }
256
257    /// LM max iterations for pass-2 measurement fits. Default 25.
258    /// Calibration pass always uses 50 iterations.
259    pub fn with_fit_max_iter(mut self, n: usize) -> Self {
260        self.config.fit_max_iter = n.max(1);
261        self
262    }
263
264    /// LM convergence tolerance for pass-2 measurement fits. Default 1e-4.
265    /// Calibration pass always uses 1e-6.
266    pub fn with_fit_tolerance(mut self, tol: f64) -> Self {
267        self.config.fit_tolerance = tol;
268        self
269    }
270
271    /// Consecutive LM step rejects before early bailout. Default 5.
272    pub fn with_fit_max_rejects(mut self, n: usize) -> Self {
273        self.config.fit_max_rejects = n.max(1);
274        self
275    }
276
277    /// Use a custom rayon thread pool.
278    pub fn with_thread_pool(mut self, pool: Arc<rayon::ThreadPool>) -> Self {
279        self.thread_pool = Some(pool);
280        self
281    }
282
283    /// Analyze a FITS or XISF image file.
284    pub fn analyze<P: AsRef<Path>>(&self, path: P) -> Result<AnalysisResult> {
285        let path = path.as_ref();
286        match &self.thread_pool {
287            Some(pool) => pool.install(|| self.analyze_impl(path)),
288            None => self.analyze_impl(path),
289        }
290    }
291
292    /// Analyze pre-loaded f32 pixel data.
293    ///
294    /// `data`: planar f32 pixel data (for 3-channel: RRRGGGBBB layout).
295    /// `width`: image width.
296    /// `height`: image height.
297    /// `channels`: 1 for mono, 3 for RGB.
298    pub fn analyze_data(
299        &self,
300        data: &[f32],
301        width: usize,
302        height: usize,
303        channels: usize,
304    ) -> Result<AnalysisResult> {
305        match &self.thread_pool {
306            Some(pool) => pool.install(|| {
307                self.run_analysis(data, width, height, channels, None)
308            }),
309            None => self.run_analysis(data, width, height, channels, None),
310        }
311    }
312
313    /// Analyze pre-read raw pixel data (skips file I/O).
314    ///
315    /// Accepts `ImageMetadata` and borrows `PixelData`, handling u16→f32
316    /// conversion and green-channel interpolation for OSC images internally.
317    pub fn analyze_raw(
318        &self,
319        meta: &ImageMetadata,
320        pixels: &PixelData,
321    ) -> Result<AnalysisResult> {
322        match &self.thread_pool {
323            Some(pool) => pool.install(|| self.analyze_raw_impl(meta, pixels)),
324            None => self.analyze_raw_impl(meta, pixels),
325        }
326    }
327
328    fn analyze_raw_impl(
329        &self,
330        meta: &ImageMetadata,
331        pixels: &PixelData,
332    ) -> Result<AnalysisResult> {
333        let f32_data = match pixels {
334            PixelData::Float32(d) => std::borrow::Cow::Borrowed(d.as_slice()),
335            PixelData::Uint16(d) => std::borrow::Cow::Owned(u16_to_f32(d)),
336        };
337
338        let mut data = f32_data.into_owned();
339        let width = meta.width;
340        let height = meta.height;
341        let channels = meta.channels;
342
343        let green_mask = if self.config.apply_debayer
344            && meta.bayer_pattern != BayerPattern::None
345            && channels == 1
346        {
347            data = debayer::interpolate_green_f32(&data, width, height, meta.bayer_pattern);
348            Some(build_green_mask(width, height, meta.bayer_pattern))
349        } else {
350            None
351        };
352
353        self.run_analysis(&data, width, height, channels, green_mask.as_deref())
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        // Convert to f32
361        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        // Green-channel interpolation for OSC: native-resolution mono green image
372        // (matches Siril's interpolate_nongreen — no PSF broadening from 2×2 binning)
373        let green_mask = if self.config.apply_debayer
374            && meta.bayer_pattern != BayerPattern::None
375            && channels == 1
376        {
377            data = debayer::interpolate_green_f32(&data, width, height, meta.bayer_pattern);
378            // width, height, channels unchanged — native resolution mono green
379            Some(build_green_mask(width, height, meta.bayer_pattern))
380        } else {
381            None
382        };
383
384        self.run_analysis(&data, width, height, channels, green_mask.as_deref())
385    }
386
387    fn run_analysis(
388        &self,
389        data: &[f32],
390        width: usize,
391        height: usize,
392        channels: usize,
393        green_mask: Option<&[bool]>,
394    ) -> Result<AnalysisResult> {
395        // Extract luminance if multi-channel
396        let lum = if channels == 3 {
397            extract_luminance(data, width, height)
398        } else {
399            data[..width * height].to_vec()
400        };
401
402        let det_params = DetectionParams {
403            detection_sigma: self.config.detection_sigma,
404            min_star_area: self.config.min_star_area,
405            max_star_area: self.config.max_star_area,
406            saturation_limit: self.config.saturation_fraction * 65535.0,
407        };
408
409        // ── Stage 1: Background & Noise ──────────────────────────────────
410        let cell_size = background::auto_cell_size(width, height);
411        let mut bg_result = background::estimate_background_mesh(&lum, width, height, cell_size);
412        bg_result.noise = background::estimate_noise_mrs(
413            &lum, width, height, self.config.noise_layers.max(1),
414        ).max(0.001);
415
416        // ── Stage 2, Pass 1: Discovery ───────────────────────────────────
417        let initial_fwhm = 3.0_f32;
418        let pass1_stars = {
419            let bg_map = bg_result.background_map.as_deref();
420            let noise_map = bg_result.noise_map.as_deref();
421            detection::detect_stars(
422                &lum, width, height,
423                bg_result.background, bg_result.noise,
424                bg_map, noise_map, &det_params, initial_fwhm,
425            )
426        };
427
428        // Select calibration stars: brightest, not saturated, not too elongated
429        let calibration_stars: Vec<&detection::DetectedStar> = pass1_stars
430            .iter()
431            .filter(|s| s.eccentricity < 0.5 && s.area >= 5)
432            .take(100)
433            .collect();
434
435        // Free-beta Moffat on calibration stars to discover field PSF model
436        let field_beta: Option<f64>;
437        let field_fwhm: f32;
438        if calibration_stars.len() >= 3 {
439            let cal_owned: Vec<detection::DetectedStar> = calibration_stars
440                .iter()
441                .map(|s| detection::DetectedStar {
442                    x: s.x, y: s.y, peak: s.peak, flux: s.flux,
443                    area: s.area, theta: s.theta, eccentricity: s.eccentricity,
444                })
445                .collect();
446            let cal_measured = metrics::measure_stars(
447                &lum, width, height, &cal_owned,
448                bg_result.background,
449                bg_result.background_map.as_deref(),
450                green_mask,
451                None, // free-beta Moffat
452                50, 1e-6, 5, // calibration always uses full precision
453            );
454
455            let mut beta_vals: Vec<f32> = cal_measured.iter().filter_map(|s| s.beta).collect();
456            let mut fwhm_vals: Vec<f32> = cal_measured.iter().map(|s| s.fwhm).collect();
457
458            if beta_vals.len() >= 3 {
459                field_beta = Some(sigma_clipped_median(&beta_vals) as f64);
460            } else if !beta_vals.is_empty() {
461                field_beta = Some(find_median(&mut beta_vals) as f64);
462            } else {
463                field_beta = None;
464            }
465
466            if fwhm_vals.len() >= 3 {
467                field_fwhm = sigma_clipped_median(&fwhm_vals);
468            } else if !fwhm_vals.is_empty() {
469                field_fwhm = find_median(&mut fwhm_vals);
470            } else {
471                field_fwhm = estimate_fwhm_from_stars(
472                    &lum, width, height, &pass1_stars,
473                    bg_result.background, bg_result.background_map.as_deref(),
474                );
475            }
476        } else {
477            // Too few calibration stars — fall back to halfmax estimate
478            field_beta = None;
479            field_fwhm = estimate_fwhm_from_stars(
480                &lum, width, height, &pass1_stars,
481                bg_result.background, bg_result.background_map.as_deref(),
482            );
483        }
484
485        // Source-mask background re-estimation
486        let mask_fwhm = if field_fwhm > 1.0 { field_fwhm } else { initial_fwhm };
487        if !pass1_stars.is_empty() {
488            let mask_radius = (2.5 * mask_fwhm).ceil() as i32;
489            let mask_r_sq = (mask_radius * mask_radius) as f32;
490            let mut source_mask = vec![false; width * height];
491            for star in &pass1_stars {
492                let cx = star.x.round() as i32;
493                let cy = star.y.round() as i32;
494                for dy in -mask_radius..=mask_radius {
495                    let py = cy + dy;
496                    if py < 0 || py >= height as i32 { continue; }
497                    for dx in -mask_radius..=mask_radius {
498                        let px = cx + dx;
499                        if px < 0 || px >= width as i32 { continue; }
500                        if (dx * dx + dy * dy) as f32 <= mask_r_sq {
501                            source_mask[py as usize * width + px as usize] = true;
502                        }
503                    }
504                }
505            }
506            bg_result = background::estimate_background_mesh_masked(
507                &lum, width, height, cell_size, &source_mask,
508            );
509            bg_result.noise = background::estimate_noise_mrs(
510                &lum, width, height, self.config.noise_layers.max(1),
511            ).max(0.001);
512        }
513
514        // ── Stage 2, Pass 2: Full detection with refined kernel ──────────
515        let final_fwhm = if field_fwhm > 1.0
516            && ((field_fwhm - initial_fwhm) / initial_fwhm).abs() > 0.30
517        {
518            field_fwhm.min(initial_fwhm * 2.0)
519        } else {
520            initial_fwhm
521        };
522
523        let detected = {
524            let bg_map = bg_result.background_map.as_deref();
525            let noise_map = bg_result.noise_map.as_deref();
526            detection::detect_stars(
527                &lum, width, height,
528                bg_result.background, bg_result.noise,
529                bg_map, noise_map, &det_params, final_fwhm,
530            )
531        };
532
533        let bg_map_ref = bg_result.background_map.as_deref();
534        let detection_threshold = self.config.detection_sigma * bg_result.noise;
535
536        // ── Trail detection (Rayleigh test on detection-stage moments) ────
537        // Uses 2θ doubling for axial orientation data. R̄² = squared mean
538        // resultant length; p ≈ exp(-n·R̄²) is the asymptotic Rayleigh p-value.
539        let (trail_r_squared, possibly_trailed) = if detected.len() >= 20 {
540            let n = detected.len();
541            let (sum_cos, sum_sin) =
542                detected.iter().fold((0.0f64, 0.0f64), |(sc, ss), s| {
543                    let a = 2.0 * s.theta as f64;
544                    (sc + a.cos(), ss + a.sin())
545                });
546            let r_sq = (sum_cos * sum_cos + sum_sin * sum_sin) / (n as f64 * n as f64);
547            let p = (-(n as f64) * r_sq).exp();
548            let mut eccs: Vec<f32> = detected.iter().map(|s| s.eccentricity).collect();
549            eccs.sort_unstable_by(|a, b| a.total_cmp(b));
550            let median_ecc = if eccs.len() % 2 == 1 {
551                eccs[eccs.len() / 2]
552            } else {
553                (eccs[eccs.len() / 2 - 1] + eccs[eccs.len() / 2]) * 0.5
554            };
555            let threshold = self.config.trail_r_squared_threshold as f64;
556            let trailed = (r_sq > threshold && p < 0.01)       // strong angle coherence
557                || (r_sq > 0.05 && median_ecc > 0.6 && p < 0.05); // moderate coherence + high ecc
558            (r_sq as f32, trailed)
559        } else {
560            (0.0, false)
561        };
562
563        let snr_weight = snr::compute_snr_weight(&lum, bg_result.background, bg_result.noise);
564        let frame_snr = if bg_result.noise > 0.0 { bg_result.background / bg_result.noise } else { 0.0 };
565
566        let make_zero_result = |stars_detected: usize| {
567            Ok(AnalysisResult {
568                width, height, source_channels: channels,
569                background: bg_result.background, noise: bg_result.noise,
570                detection_threshold, stars_detected,
571                stars: Vec::new(),
572                median_fwhm: 0.0, median_eccentricity: 0.0,
573                median_snr: 0.0, median_hfr: 0.0,
574                snr_weight, psf_signal: 0.0, frame_snr,
575                trail_r_squared, possibly_trailed,
576                measured_fwhm_kernel: final_fwhm,
577                median_beta: field_beta.map(|b| b as f32),
578            })
579        };
580
581        if detected.is_empty() {
582            return make_zero_result(0);
583        }
584
585        // ── Stage 3: PSF Measurement (with measure cap) ─────────────────
586        let stars_detected = detected.len();
587
588        // Apply measure cap: only fit the brightest N stars (already sorted by flux)
589        let effective_cap = if self.config.measure_cap == 0 {
590            detected.len()
591        } else {
592            self.config.measure_cap
593        };
594        let to_measure = &detected[..detected.len().min(effective_cap)];
595
596        let mut measured = metrics::measure_stars(
597            &lum, width, height, to_measure,
598            bg_result.background, bg_map_ref,
599            green_mask, field_beta,
600            self.config.fit_max_iter,
601            self.config.fit_tolerance,
602            self.config.fit_max_rejects,
603        );
604
605        if measured.is_empty() {
606            return make_zero_result(stars_detected);
607        }
608
609        // ── Stage 4: Metrics ─────────────────────────────────────────────
610
611        // Refine trail detection using accurate PSF-fit eccentricities.
612        // Detection-stage moments are noisy; PSF-fit ecc is reliable.
613        let possibly_trailed = possibly_trailed || {
614            let mut fit_eccs: Vec<f32> = measured.iter().map(|s| s.eccentricity).collect();
615            fit_eccs.sort_unstable_by(|a, b| a.total_cmp(b));
616            let med = if fit_eccs.len() % 2 == 1 {
617                fit_eccs[fit_eccs.len() / 2]
618            } else {
619                (fit_eccs[fit_eccs.len() / 2 - 1] + fit_eccs[fit_eccs.len() / 2]) * 0.5
620            };
621            med > 0.55
622        };
623
624        // FWHM & HFR: ecc ≤ 0.8 filter — elongated profiles inflate
625        // geometric-mean FWHM. On trailed frames bypass it.
626        const FWHM_ECC_MAX: f32 = 0.8;
627        let fwhm_filtered: Vec<&metrics::MeasuredStar> = if possibly_trailed {
628            measured.iter().collect()
629        } else {
630            let round: Vec<&metrics::MeasuredStar> = measured.iter()
631                .filter(|s| s.eccentricity <= FWHM_ECC_MAX)
632                .collect();
633            if round.len() >= 3 { round } else { measured.iter().collect() }
634        };
635        let (fwhm_vals, hfr_vals, shape_weights) = (
636            fwhm_filtered.iter().map(|s| s.fwhm).collect::<Vec<f32>>(),
637            fwhm_filtered.iter().map(|s| s.hfr).collect::<Vec<f32>>(),
638            fwhm_filtered.iter().map(|s| 1.0 / (1.0 + s.fit_residual)).collect::<Vec<f32>>(),
639        );
640        let median_fwhm = sigma_clipped_weighted_median(&fwhm_vals, &shape_weights);
641
642        // Eccentricity: on normal frames, ecc ≤ 0.8 cutoff removes noise from
643        // faint detections. On trailed frames, elongation IS the signal — bypass
644        // the cutoff so the reported ecc reflects actual frame quality.
645        let ecc_use_all = possibly_trailed;
646        let ecc_filtered: Vec<&metrics::MeasuredStar> = if ecc_use_all {
647            measured.iter().collect()
648        } else {
649            let filtered: Vec<&metrics::MeasuredStar> = measured.iter()
650                .filter(|s| s.eccentricity <= FWHM_ECC_MAX)
651                .collect();
652            if filtered.len() >= 3 { filtered } else { measured.iter().collect() }
653        };
654        let ecc_vals: Vec<f32> = ecc_filtered.iter().map(|s| s.eccentricity).collect();
655        let ecc_weights: Vec<f32> = ecc_filtered.iter()
656            .map(|s| 1.0 / (1.0 + s.fit_residual))
657            .collect();
658
659        snr::compute_star_snr(&lum, width, height, &mut measured, median_fwhm);
660
661        let mut snr_vals: Vec<f32> = measured.iter().map(|s| s.snr).collect();
662
663        let median_eccentricity = sigma_clipped_weighted_median(&ecc_vals, &ecc_weights);
664        let median_snr = find_median(&mut snr_vals);
665        let median_hfr = sigma_clipped_weighted_median(&hfr_vals, &shape_weights);
666        let psf_signal = snr::compute_psf_signal(&measured, bg_result.noise);
667
668        // Median beta: use field_beta from calibration, or compute from all stars
669        let median_beta = if let Some(fb) = field_beta {
670            Some(fb as f32)
671        } else {
672            let mut beta_vals: Vec<f32> = measured.iter().filter_map(|s| s.beta).collect();
673            if beta_vals.is_empty() { None } else { Some(find_median(&mut beta_vals)) }
674        };
675
676        // Late cap: truncate to max_stars AFTER all statistics are computed
677        measured.truncate(self.config.max_stars);
678
679        let stars: Vec<StarMetrics> = measured
680            .into_iter()
681            .map(|m| StarMetrics {
682                x: m.x, y: m.y, peak: m.peak, flux: m.flux,
683                fwhm_x: m.fwhm_x, fwhm_y: m.fwhm_y, fwhm: m.fwhm,
684                eccentricity: m.eccentricity, snr: m.snr, hfr: m.hfr,
685                theta: m.theta, beta: m.beta, fit_method: m.fit_method,
686                fit_residual: m.fit_residual,
687            })
688            .collect();
689
690        Ok(AnalysisResult {
691            width, height, source_channels: channels,
692            background: bg_result.background, noise: bg_result.noise,
693            detection_threshold, stars_detected, stars,
694            median_fwhm, median_eccentricity, median_snr, median_hfr,
695            snr_weight, psf_signal, frame_snr,
696            trail_r_squared, possibly_trailed,
697            measured_fwhm_kernel: final_fwhm,
698            median_beta,
699        })
700    }
701}
702
703impl Default for ImageAnalyzer {
704    fn default() -> Self {
705        Self::new()
706    }
707}
708
709/// Sigma-clipped median: 2-iteration, 3σ MAD-based clipping.
710///
711/// Standard in SExtractor/DAOPHOT for robust statistics:
712///   MAD = median(|x_i − median|)
713///   σ_MAD = 1.4826 × MAD
714///   reject: |x − median| > 3 × σ_MAD
715///
716/// Returns plain median if fewer than 3 values remain after clipping.
717pub fn sigma_clipped_median(values: &[f32]) -> f32 {
718    if values.is_empty() {
719        return 0.0;
720    }
721    let mut v: Vec<f32> = values.to_vec();
722    for _ in 0..2 {
723        if v.len() < 3 {
724            break;
725        }
726        let med = find_median(&mut v);
727        let mut abs_devs: Vec<f32> = v.iter().map(|&x| (x - med).abs()).collect();
728        let mad = find_median(&mut abs_devs);
729        let sigma_mad = 1.4826 * mad;
730        if sigma_mad < 1e-10 {
731            break; // all values identical
732        }
733        let clip = 3.0 * sigma_mad;
734        v.retain(|&x| (x - med).abs() <= clip);
735    }
736    if v.is_empty() {
737        return find_median(&mut values.to_vec());
738    }
739    find_median(&mut v)
740}
741
742/// Weighted median: walk sorted (value, weight) pairs until cumulative weight >= total/2.
743///
744/// Returns 0.0 if inputs are empty or total weight is zero.
745pub fn weighted_median(values: &[f32], weights: &[f32]) -> f32 {
746    if values.is_empty() || values.len() != weights.len() {
747        return 0.0;
748    }
749    let mut pairs: Vec<(f32, f32)> = values.iter().copied()
750        .zip(weights.iter().copied())
751        .filter(|(_, w)| *w > 0.0)
752        .collect();
753    if pairs.is_empty() {
754        return 0.0;
755    }
756    pairs.sort_by(|a, b| a.0.total_cmp(&b.0));
757    let total: f32 = pairs.iter().map(|(_, w)| w).sum();
758    if total <= 0.0 {
759        return 0.0;
760    }
761    let half = total * 0.5;
762    let mut cumulative = 0.0_f32;
763    for &(val, w) in &pairs {
764        cumulative += w;
765        if cumulative >= half {
766            return val;
767        }
768    }
769    pairs.last().unwrap().0
770}
771
772/// Sigma-clipped weighted median: 2-iteration 3σ MAD clipping, then weighted median.
773///
774/// Combines outlier rejection (via MAD) with continuous quality weighting.
775/// Falls back to plain weighted median if fewer than 3 values survive clipping.
776pub fn sigma_clipped_weighted_median(values: &[f32], weights: &[f32]) -> f32 {
777    if values.is_empty() || values.len() != weights.len() {
778        return 0.0;
779    }
780    let mut v: Vec<f32> = values.to_vec();
781    let mut w: Vec<f32> = weights.to_vec();
782    for _ in 0..2 {
783        if v.len() < 3 {
784            break;
785        }
786        let med = weighted_median(&v, &w);
787        let abs_devs: Vec<f32> = v.iter().map(|&x| (x - med).abs()).collect();
788        // Unweighted MAD for clipping threshold (weights affect median, not clip boundary)
789        let mut sorted_devs = abs_devs.clone();
790        sorted_devs.sort_by(|a, b| a.total_cmp(b));
791        let mad = sorted_devs[sorted_devs.len() / 2];
792        let sigma_mad = 1.4826 * mad;
793        if sigma_mad < 1e-10 {
794            break;
795        }
796        let clip = 3.0 * sigma_mad;
797        let mut new_v = Vec::with_capacity(v.len());
798        let mut new_w = Vec::with_capacity(w.len());
799        for (val, wt) in v.iter().zip(w.iter()) {
800            if (*val - med).abs() <= clip {
801                new_v.push(*val);
802                new_w.push(*wt);
803            }
804        }
805        v = new_v;
806        w = new_w;
807    }
808    if v.is_empty() {
809        return weighted_median(values, weights);
810    }
811    weighted_median(&v, &w)
812}
813
814/// Estimate FWHM from the brightest detected stars by extracting stamps
815/// and using `estimate_sigma_halfmax`. Returns median FWHM, or 0.0 if
816/// fewer than 3 stars yield valid measurements.
817pub fn estimate_fwhm_from_stars(
818    lum: &[f32],
819    width: usize,
820    height: usize,
821    stars: &[detection::DetectedStar],
822    background: f32,
823    bg_map: Option<&[f32]>,
824) -> f32 {
825    // Scan top 50 brightest (already sorted by flux descending), select up to 20
826    // with low eccentricity (≤ 0.7) to avoid elongated non-stellar objects
827    // poisoning the kernel estimate.
828    let scan_n = stars.len().min(50);
829    if scan_n < 3 {
830        return 0.0;
831    }
832
833    let round_stars: Vec<&detection::DetectedStar> = stars[..scan_n]
834        .iter()
835        .filter(|s| s.eccentricity <= 0.7)
836        .take(20)
837        .collect();
838    if round_stars.len() < 3 {
839        return 0.0;
840    }
841
842    let mut fwhm_vals = Vec::with_capacity(round_stars.len());
843    for star in &round_stars {
844        let stamp_radius = 12_usize; // enough for FWHM up to ~10px
845        let cx = star.x.round() as i32;
846        let cy = star.y.round() as i32;
847        let sr = stamp_radius as i32;
848        if cx - sr <= 0 || cy - sr <= 0
849            || cx + sr >= width as i32 - 1
850            || cy + sr >= height as i32 - 1
851        {
852            continue;
853        }
854        let x0 = (cx - sr) as usize;
855        let y0 = (cy - sr) as usize;
856        let x1 = (cx + sr) as usize;
857        let y1 = (cy + sr) as usize;
858        let stamp_w = x1 - x0 + 1;
859        let mut stamp = Vec::with_capacity(stamp_w * (y1 - y0 + 1));
860        for sy in y0..=y1 {
861            for sx in x0..=x1 {
862                let bg = bg_map.map_or(background, |m| m[sy * width + sx]);
863                stamp.push(lum[sy * width + sx] - bg);
864            }
865        }
866        let rel_cx = star.x - x0 as f32;
867        let rel_cy = star.y - y0 as f32;
868        let sigma = metrics::estimate_sigma_halfmax(&stamp, stamp_w, rel_cx, rel_cy);
869        let fwhm = sigma * 2.3548;
870        if fwhm > 1.0 && fwhm < 20.0 {
871            fwhm_vals.push(fwhm);
872        }
873    }
874
875    if fwhm_vals.len() < 3 {
876        return 0.0;
877    }
878    find_median(&mut fwhm_vals)
879}
880
881/// Build a boolean mask marking green CFA pixel positions.
882///
883/// Returns a `Vec<bool>` of length `width * height` where `true` marks pixels
884/// that are at green positions in the Bayer pattern. For GBRG/GRBG green is
885/// at (row + col) even; for RGGB/BGGR green is at (row + col) odd.
886fn build_green_mask(width: usize, height: usize, pattern: BayerPattern) -> Vec<bool> {
887    let green_at_even = matches!(pattern, BayerPattern::Gbrg | BayerPattern::Grbg);
888    (0..height)
889        .flat_map(|y| {
890            (0..width).map(move |x| {
891                let parity = (x + y) & 1;
892                if green_at_even { parity == 0 } else { parity == 1 }
893            })
894        })
895        .collect()
896}
897
898/// Extract luminance from planar RGB data: L = 0.2126R + 0.7152G + 0.0722B
899pub fn extract_luminance(data: &[f32], width: usize, height: usize) -> Vec<f32> {
900    use rayon::prelude::*;
901
902    let plane_size = width * height;
903    let r = &data[..plane_size];
904    let g = &data[plane_size..2 * plane_size];
905    let b = &data[2 * plane_size..3 * plane_size];
906
907    let mut lum = vec![0.0_f32; plane_size];
908    const CHUNK: usize = 8192;
909    lum.par_chunks_mut(CHUNK)
910        .enumerate()
911        .for_each(|(ci, chunk)| {
912            let off = ci * CHUNK;
913            for (i, dst) in chunk.iter_mut().enumerate() {
914                let idx = off + i;
915                *dst = 0.2126 * r[idx] + 0.7152 * g[idx] + 0.0722 * b[idx];
916            }
917        });
918    lum
919}
920
921/// Prepare luminance data from raw metadata + pixels.
922///
923/// Handles u16→f32 conversion, green-channel interpolation for OSC,
924/// and luminance extraction for multi-channel images.
925/// Returns `(luminance, width, height, channels, green_mask)`.
926#[cfg(feature = "debug-pipeline")]
927pub fn prepare_luminance(
928    meta: &crate::types::ImageMetadata,
929    pixels: &crate::types::PixelData,
930    apply_debayer: bool,
931) -> (Vec<f32>, usize, usize, usize, Option<Vec<bool>>) {
932    use crate::processing::color::u16_to_f32;
933    use crate::processing::debayer;
934
935    let f32_data = match pixels {
936        PixelData::Float32(d) => std::borrow::Cow::Borrowed(d.as_slice()),
937        PixelData::Uint16(d) => std::borrow::Cow::Owned(u16_to_f32(d)),
938    };
939
940    let mut data = f32_data.into_owned();
941    let width = meta.width;
942    let height = meta.height;
943    let channels = meta.channels;
944
945    let green_mask = if apply_debayer
946        && meta.bayer_pattern != BayerPattern::None
947        && channels == 1
948    {
949        data = debayer::interpolate_green_f32(&data, width, height, meta.bayer_pattern);
950        Some(build_green_mask(width, height, meta.bayer_pattern))
951    } else {
952        None
953    };
954
955    let lum = if channels == 3 {
956        extract_luminance(&data, width, height)
957    } else {
958        data[..width * height].to_vec()
959    };
960
961    (lum, width, height, channels, green_mask)
962}
963
964#[cfg(test)]
965mod tests {
966    use super::*;
967
968    #[test]
969    fn test_weighted_median_equal_weights() {
970        // Equal weights → same as unweighted median
971        let vals = [1.0_f32, 3.0, 5.0, 7.0, 9.0];
972        let wts = [1.0_f32; 5];
973        let wm = weighted_median(&vals, &wts);
974        assert!((wm - 5.0).abs() < 0.01, "Equal-weight median should be 5, got {}", wm);
975    }
976
977    #[test]
978    fn test_weighted_median_skewed_weights() {
979        // Heavy weight on low value should pull median down
980        let vals = [1.0_f32, 10.0];
981        let wts = [9.0_f32, 1.0]; // 90% weight on 1.0
982        let wm = weighted_median(&vals, &wts);
983        assert!((wm - 1.0).abs() < 0.01, "Skewed-weight median should be 1, got {}", wm);
984    }
985
986    #[test]
987    fn test_weighted_median_empty() {
988        let wm = weighted_median(&[], &[]);
989        assert_eq!(wm, 0.0);
990    }
991
992    #[test]
993    fn test_weighted_median_single() {
994        let wm = weighted_median(&[42.0], &[1.0]);
995        assert!((wm - 42.0).abs() < 0.01);
996    }
997
998    #[test]
999    fn test_sigma_clipped_weighted_median_basic() {
1000        // With an outlier, sigma clipping should reject it
1001        let vals = [3.0_f32, 3.1, 3.0, 3.2, 3.0, 100.0]; // 100.0 is outlier
1002        let wts = [1.0_f32; 6];
1003        let scwm = sigma_clipped_weighted_median(&vals, &wts);
1004        assert!(scwm < 4.0, "Outlier should be clipped, got {}", scwm);
1005    }
1006}