target-match 0.3.3

Given a telescope pointing and field of view, rank which catalogued sky objects fall on the frame. Matches by sky position; holds no catalogue data and does no I/O.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
//! Plate scale and field-of-view geometry.
//!
//! A [`Field`] is the angular extent of a frame, built from full [`Optics`], from
//! a directly supplied pixel scale, or from a directly supplied field of view. It
//! is binning-aware (effective pixel = pixel size × binning, per axis) and
//! axis-independent (x and y are handled separately). A [`RadiusPolicy`] turns a
//! field into a search radius.

use skymath::Angle;

use crate::error::{Error, Result};

/// Exact number of arcseconds in one radian (supersedes the rounded `206.265`).
pub const ARCSEC_PER_RADIAN: f64 = skymath::ARCSEC_PER_RADIAN;
/// Arcseconds per degree.
pub const ARCSEC_PER_DEGREE: f64 = 3600.0;
/// Fallback search radius when a field of view cannot be derived (5°).
pub const DEFAULT_FALLBACK_RADIUS: Angle = Angle::from_radians(5.0 * core::f64::consts::PI / 180.0);

/// Full optical train: focal length, per-axis pixel size, per-axis binning, and
/// sensor pixel counts.
///
/// Pass to [`Field::from_optics`] to derive a [`Field`].
///
/// # Example
///
/// ```
/// use target_match::{Field, Optics};
///
/// let field = Field::from_optics(Optics {
///     focal_mm: 800.0,
///     pixel_um: (3.76, 3.76),
///     binning: (1, 1),
///     pixels: (6248, 4176),
/// })
/// .unwrap();
/// assert!((field.width().degrees() - 1.683).abs() < 1e-2);
/// ```
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Optics {
    /// Focal length, millimetres.
    pub focal_mm: f64,
    /// Pixel size in micrometres, `(x, y)`.
    pub pixel_um: (f64, f64),
    /// Binning factor, `(x, y)` (1 = unbinned).
    pub binning: (u32, u32),
    /// Sensor pixel counts, `(naxis1, naxis2)`.
    pub pixels: (u32, u32),
}

/// How a search radius is derived from a [`Field`].
///
/// Passed to [`Field::radius`], or embedded in a [`Constraint`](crate::Constraint)
/// via [`Constraint::within`](crate::Constraint::within).
///
/// # Example
///
/// ```
/// use skymath::Angle;
/// use target_match::{Field, RadiusPolicy};
///
/// let field = Field::from_fov(Angle::from_degrees(2.0), Angle::from_degrees(1.0)).unwrap();
/// let circumscribed = field.radius(RadiusPolicy::Circumscribed);
/// let inscribed = field.radius(RadiusPolicy::Inscribed);
/// assert!(circumscribed.degrees() > inscribed.degrees(), "circumscribed bounds the whole frame");
/// ```
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum RadiusPolicy {
    /// Half the diagonal — the circle that circumscribes the whole frame (default).
    Circumscribed,
    /// Half the shorter side — the circle inscribed within the frame.
    Inscribed,
    /// A multiplier applied to the circumscribed radius.
    Multiplier(f64),
    /// An explicit radius, ignoring the field extent.
    Explicit(Angle),
}

/// The angular extent of a frame.
///
/// Feed a `Field` to [`Constraint::within`](crate::Constraint::within) (circular
/// membership sized by a [`RadiusPolicy`]) or
/// [`Constraint::frame`](crate::Constraint::frame) (rectangular membership) to
/// build a search [`Constraint`](crate::Constraint).
///
/// # Example
///
/// ```
/// use target_match::{Field, Optics, RadiusPolicy};
///
/// let field = Field::from_optics(Optics {
///     focal_mm: 800.0,
///     pixel_um: (3.76, 3.76),
///     binning: (1, 1),
///     pixels: (6248, 4176),
/// })
/// .unwrap();
///
/// assert!(field.width().degrees() > 0.0);
/// assert!(field.height().degrees() > 0.0);
/// assert!(field.diagonal().degrees() > field.width().degrees());
/// assert!(field.pixel_scale().is_some(), "derived from optics, so plate scale is known");
/// let _radius = field.radius(RadiusPolicy::Circumscribed);
/// ```
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Field {
    fov: (Angle, Angle),
    pixel_scale: Option<(f64, f64)>, // arcsec/px, per axis; None for a direct-FOV field
}

impl Field {
    /// Derive a field from full optics.
    ///
    /// Effective pixel size = pixel size × binning (per axis); pixel scale
    /// (arcsec/px) = effective pixel size (mm) / focal length (mm) × arcsec/radian;
    /// field extent = pixel scale × pixel count.
    ///
    /// # Example
    ///
    /// ```
    /// use target_match::{Field, Optics};
    ///
    /// let field = Field::from_optics(Optics {
    ///     focal_mm: 800.0,
    ///     pixel_um: (3.76, 3.76),
    ///     binning: (1, 1),
    ///     pixels: (6248, 4176),
    /// })
    /// .unwrap();
    /// let (sx, _) = field.pixel_scale().unwrap();
    /// assert!((sx - 0.969).abs() < 1e-2, "≈0.969 arcsec/px");
    /// ```
    ///
    /// # Errors
    /// [`Error::InvalidOptics`] if any input is non-positive or non-finite.
    pub fn from_optics(o: Optics) -> Result<Self> {
        let focal = finite_positive(o.focal_mm, "focal length")?;
        let (px, py) = (
            finite_positive(o.pixel_um.0, "pixel size x")?,
            finite_positive(o.pixel_um.1, "pixel size y")?,
        );
        let (bx, by) = (
            positive_count(o.binning.0, "binning x")?,
            positive_count(o.binning.1, "binning y")?,
        );
        let (nx, ny) = (
            positive_count(o.pixels.0, "naxis1")?,
            positive_count(o.pixels.1, "naxis2")?,
        );
        // arcsec/px = eff_pixel_um / 1000 (→ mm) / focal_mm × arcsec/radian
        let scale_x = (px * bx) / 1000.0 / focal * ARCSEC_PER_RADIAN;
        let scale_y = (py * by) / 1000.0 / focal * ARCSEC_PER_RADIAN;
        Ok(Self {
            fov: (
                Angle::from_arcseconds(scale_x * nx),
                Angle::from_arcseconds(scale_y * ny),
            ),
            pixel_scale: Some((scale_x, scale_y)),
        })
    }

    /// Build a field from a directly supplied pixel scale (arcsec/px, per axis)
    /// and sensor pixel counts.
    ///
    /// # Example
    ///
    /// ```
    /// use target_match::Field;
    ///
    /// let field = Field::from_pixel_scale((0.9694, 0.9694), (6248, 4176)).unwrap();
    /// assert_eq!(field.pixel_scale(), Some((0.9694, 0.9694)));
    /// assert!((field.width().degrees() - 1.683).abs() < 1e-2);
    /// ```
    ///
    /// # Errors
    /// [`Error::InvalidOptics`] if any input is non-positive or non-finite.
    pub fn from_pixel_scale(scale_arcsec_px: (f64, f64), pixels: (u32, u32)) -> Result<Self> {
        let sx = finite_positive(scale_arcsec_px.0, "pixel scale x")?;
        let sy = finite_positive(scale_arcsec_px.1, "pixel scale y")?;
        let nx = positive_count(pixels.0, "naxis1")?;
        let ny = positive_count(pixels.1, "naxis2")?;
        Ok(Self {
            fov: (
                Angle::from_arcseconds(sx * nx),
                Angle::from_arcseconds(sy * ny),
            ),
            pixel_scale: Some((sx, sy)),
        })
    }

    /// Build a field directly from its angular width and height (no optics; pixel
    /// scale is unknown).
    ///
    /// # Example
    ///
    /// ```
    /// use skymath::Angle;
    /// use target_match::Field;
    ///
    /// let field = Field::from_fov(Angle::from_degrees(2.0), Angle::from_degrees(1.0)).unwrap();
    /// assert_eq!(field.width().degrees(), 2.0);
    /// assert!(field.pixel_scale().is_none(), "no optics, so no plate scale");
    /// ```
    ///
    /// # Errors
    /// [`Error::InvalidOptics`] if width or height is non-positive or non-finite.
    pub fn from_fov(width: Angle, height: Angle) -> Result<Self> {
        finite_positive(width.degrees(), "field width")?;
        finite_positive(height.degrees(), "field height")?;
        Ok(Self {
            fov: (width, height),
            pixel_scale: None,
        })
    }

    /// Field width (x extent). See also [`height`](Field::height) and
    /// [`diagonal`](Field::diagonal).
    ///
    /// # Example
    ///
    /// ```
    /// use skymath::Angle;
    /// use target_match::Field;
    ///
    /// let field = Field::from_fov(Angle::from_degrees(2.0), Angle::from_degrees(1.0)).unwrap();
    /// assert_eq!(field.width().degrees(), 2.0);
    /// ```
    #[must_use]
    pub fn width(self) -> Angle {
        self.fov.0
    }
    /// Field height (y extent). See also [`width`](Field::width) and
    /// [`diagonal`](Field::diagonal).
    ///
    /// # Example
    ///
    /// ```
    /// use skymath::Angle;
    /// use target_match::Field;
    ///
    /// let field = Field::from_fov(Angle::from_degrees(2.0), Angle::from_degrees(1.0)).unwrap();
    /// assert_eq!(field.height().degrees(), 1.0);
    /// ```
    #[must_use]
    pub fn height(self) -> Angle {
        self.fov.1
    }
    /// Diagonal field of view — `hypot(`[`width`](Field::width)`,`
    /// [`height`](Field::height)`)`. Halved, this is the
    /// [`RadiusPolicy::Circumscribed`] search radius.
    ///
    /// # Example
    ///
    /// ```
    /// use skymath::Angle;
    /// use target_match::Field;
    ///
    /// let field = Field::from_fov(Angle::from_degrees(2.0), Angle::from_degrees(1.0)).unwrap();
    /// assert!((field.diagonal().degrees() - 2.0_f64.hypot(1.0)).abs() < 1e-9);
    /// ```
    #[must_use]
    pub fn diagonal(self) -> Angle {
        Angle::from_degrees(self.fov.0.degrees().hypot(self.fov.1.degrees()))
    }
    /// Per-axis pixel scale (arcsec/px), if this field was built with a scale
    /// (via [`from_optics`](Field::from_optics) or
    /// [`from_pixel_scale`](Field::from_pixel_scale)) — `None` for
    /// [`from_fov`](Field::from_fov).
    ///
    /// # Example
    ///
    /// ```
    /// use target_match::{Field, Optics};
    ///
    /// let field = Field::from_optics(Optics {
    ///     focal_mm: 800.0, pixel_um: (3.76, 3.76), binning: (1, 1), pixels: (6248, 4176),
    /// })
    /// .unwrap();
    /// let (sx, sy) = field.pixel_scale().unwrap();
    /// assert!((sx - 0.969).abs() < 1e-2);
    /// assert_eq!(sx, sy);
    /// ```
    #[must_use]
    pub fn pixel_scale(self) -> Option<(f64, f64)> {
        self.pixel_scale
    }

    /// Compute a search radius from this field under `policy`. Feeds
    /// [`Constraint::within`](crate::Constraint::within), which calls this
    /// internally.
    ///
    /// # Example
    ///
    /// ```
    /// use skymath::Angle;
    /// use target_match::{Field, RadiusPolicy};
    ///
    /// let field = Field::from_fov(Angle::from_degrees(2.0), Angle::from_degrees(1.0)).unwrap();
    /// let r = field.radius(RadiusPolicy::Explicit(Angle::from_degrees(3.0)));
    /// assert!((r.degrees() - 3.0).abs() < 1e-9);
    /// ```
    #[must_use]
    pub fn radius(self, policy: RadiusPolicy) -> Angle {
        match policy {
            RadiusPolicy::Circumscribed => Angle::from_degrees(self.diagonal().degrees() / 2.0),
            RadiusPolicy::Inscribed => {
                Angle::from_degrees(self.fov.0.degrees().min(self.fov.1.degrees()) / 2.0)
            }
            RadiusPolicy::Multiplier(m) => Angle::from_degrees(self.diagonal().degrees() / 2.0 * m),
            RadiusPolicy::Explicit(a) => a,
        }
    }
}

fn finite_positive(v: f64, what: &str) -> Result<f64> {
    if v.is_finite() && v > 0.0 {
        Ok(v)
    } else {
        Err(Error::InvalidOptics(format!(
            "{what} must be finite and > 0, got {v}"
        )))
    }
}

fn positive_count(v: u32, what: &str) -> Result<f64> {
    if v >= 1 {
        Ok(f64::from(v))
    } else {
        Err(Error::InvalidOptics(format!("{what} must be >= 1")))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn approx(a: f64, b: f64, eps: f64) -> bool {
        (a - b).abs() < eps
    }

    fn asi2600_800mm() -> Optics {
        Optics {
            focal_mm: 800.0,
            pixel_um: (3.76, 3.76),
            binning: (1, 1),
            pixels: (6248, 4176),
        }
    }

    #[test]
    fn from_optics_matches_hand_calc() {
        let f = Field::from_optics(asi2600_800mm()).unwrap();
        let (sx, sy) = f.pixel_scale().unwrap();
        assert!(approx(sx, 0.9694, 1e-3), "scale {sx}");
        assert!(approx(sy, 0.9694, 1e-3));
        assert!(
            approx(f.width().degrees(), 1.683, 5e-3),
            "w {}",
            f.width().degrees()
        );
        assert!(
            approx(f.height().degrees(), 1.125, 5e-3),
            "h {}",
            f.height().degrees()
        );
        // radius = circumscribed = half diagonal ≈ 1.012°
        assert!(approx(
            f.radius(RadiusPolicy::Circumscribed).degrees(),
            1.012,
            5e-3
        ));
    }

    #[test]
    fn binning_doubles_scale_and_fov() {
        let mut o = asi2600_800mm();
        o.binning = (2, 2);
        let f = Field::from_optics(o).unwrap();
        let (sx, _) = f.pixel_scale().unwrap();
        assert!(approx(sx, 2.0 * 0.9694, 2e-3), "binned scale {sx}");
        // Holding the (binned) pixel count, ×2 binning ⇒ ×2 scale ⇒ ×2 field (SC-009).
        assert!(
            approx(f.width().degrees(), 2.0 * 1.683, 1e-2),
            "w {}",
            f.width().degrees()
        );
    }

    #[test]
    fn binning_fov_doubles() {
        let base = Field::from_optics(asi2600_800mm()).unwrap();
        let mut o = asi2600_800mm();
        o.binning = (2, 2);
        let binned = Field::from_optics(o).unwrap();
        assert!(approx(
            binned.width().degrees(),
            2.0 * base.width().degrees(),
            1e-6
        ));
    }

    #[test]
    fn from_fov_and_pixel_scale_paths() {
        let direct =
            Field::from_fov(Angle::from_degrees(1.683), Angle::from_degrees(1.125)).unwrap();
        assert!(direct.pixel_scale().is_none());
        assert!(approx(
            direct.radius(RadiusPolicy::Circumscribed).degrees(),
            1.012,
            5e-3
        ));

        let by_scale = Field::from_pixel_scale((0.9694, 0.9694), (6248, 4176)).unwrap();
        assert!(approx(by_scale.width().degrees(), 1.683, 5e-3));
        assert_eq!(by_scale.pixel_scale(), Some((0.9694, 0.9694)));
    }

    #[test]
    fn radius_policies() {
        let f = Field::from_fov(Angle::from_degrees(2.0), Angle::from_degrees(1.0)).unwrap();
        assert!(approx(
            f.radius(RadiusPolicy::Inscribed).degrees(),
            0.5,
            1e-9
        )); // half min side
        let circ = f.radius(RadiusPolicy::Circumscribed).degrees();
        assert!(approx(circ, (2.0_f64.hypot(1.0)) / 2.0, 1e-9));
        assert!(approx(
            f.radius(RadiusPolicy::Multiplier(2.0)).degrees(),
            circ * 2.0,
            1e-9
        ));
        assert!(approx(
            f.radius(RadiusPolicy::Explicit(Angle::from_degrees(3.0)))
                .degrees(),
            3.0,
            1e-9
        ));
    }

    #[test]
    fn rejects_bad_optics() {
        let mut o = asi2600_800mm();
        o.focal_mm = 0.0;
        assert!(matches!(
            Field::from_optics(o).unwrap_err(),
            Error::InvalidOptics(_)
        ));
        let mut o2 = asi2600_800mm();
        o2.pixel_um = (-1.0, 3.76);
        assert!(matches!(
            Field::from_optics(o2).unwrap_err(),
            Error::InvalidOptics(_)
        ));
        let mut o3 = asi2600_800mm();
        o3.pixels = (0, 4176);
        assert!(matches!(
            Field::from_optics(o3).unwrap_err(),
            Error::InvalidOptics(_)
        ));
        assert!(matches!(
            Field::from_fov(Angle::from_degrees(0.0), Angle::from_degrees(1.0)).unwrap_err(),
            Error::InvalidOptics(_)
        ));
    }

    #[test]
    fn fallback_radius_is_five_degrees() {
        assert!(approx(DEFAULT_FALLBACK_RADIUS.degrees(), 5.0, 1e-9));
    }
}