starfield 0.16.1

Astronomical data reduction toolkit with star catalogs, coordinate systems, and star finding algorithms (inspired by skyfield)
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
//! Chebyshev polynomial functionality for ephemeris interpolation
//!
//! Chebyshev polynomials are used in JPL ephemerides for interpolating
//! positions and velocities of celestial bodies from ephemeris data.

use super::errors::{JplephemError, Result};

/// Chebyshev polynomial representation and evaluation
///
/// Stores the coefficients of a Chebyshev polynomial expansion
/// and provides methods to evaluate the polynomial and its derivatives.
#[derive(Debug, Clone)]
pub struct ChebyshevPolynomial {
    coefficients: Vec<f64>,
}

impl ChebyshevPolynomial {
    /// Create a new Chebyshev polynomial with the given coefficients
    ///
    /// Coefficients are ordered from lowest to highest degree:
    /// `[c0, c1, c2, ..., cn]` where the polynomial is:
    /// `f(x) = c0*T0(x) + c1*T1(x) + c2*T2(x) + ... + cn*Tn(x)`
    pub fn new(coefficients: Vec<f64>) -> Self {
        Self { coefficients }
    }

    /// Evaluate the Chebyshev polynomial at point x in [-1, 1]
    ///
    /// Uses Clenshaw's recurrence for numerical stability.
    pub fn evaluate(&self, x: f64) -> f64 {
        if self.coefficients.is_empty() {
            return 0.0;
        }
        let n = self.coefficients.len();
        if n == 1 {
            return self.coefficients[0];
        }

        // Clenshaw recurrence: more stable than direct evaluation
        let mut b_k_plus_1 = 0.0;
        let mut b_k_plus_2 = 0.0;
        for i in (1..n).rev() {
            let b_k = 2.0 * x * b_k_plus_1 - b_k_plus_2 + self.coefficients[i];
            b_k_plus_2 = b_k_plus_1;
            b_k_plus_1 = b_k;
        }
        self.coefficients[0] + x * b_k_plus_1 - b_k_plus_2
    }

    /// Calculate the derivative of the Chebyshev polynomial at point x
    ///
    /// Uses the relation dT_n(x)/dx = n * U_{n-1}(x) where U is the
    /// Chebyshev polynomial of the second kind.
    pub fn derivative(&self, x: f64) -> f64 {
        if self.coefficients.len() <= 1 {
            return 0.0;
        }

        let mut result = 0.0;
        for i in 1..self.coefficients.len() {
            let n = i as f64;
            result += self.coefficients[i] * n * Self::chebyshev_u(i - 1, x);
        }
        result
    }

    /// Compute U_n(x), the Chebyshev polynomial of the second kind
    fn chebyshev_u(n: usize, x: f64) -> f64 {
        match n {
            0 => 1.0,
            1 => 2.0 * x,
            _ => {
                let mut u_prev2 = 1.0;
                let mut u_prev1 = 2.0 * x;
                let mut u_n = 0.0;
                for _ in 2..=n {
                    u_n = 2.0 * x * u_prev1 - u_prev2;
                    u_prev2 = u_prev1;
                    u_prev1 = u_n;
                }
                u_n
            }
        }
    }

    /// Get the degree of the polynomial
    pub fn degree(&self) -> usize {
        self.coefficients.len().saturating_sub(1)
    }

    /// Get a reference to the coefficients
    pub fn coefficients(&self) -> &[f64] {
        &self.coefficients
    }
}

/// Normalize a time value to [-1, 1] for Chebyshev evaluation
///
/// # Arguments
/// * `time` - The time to normalize
/// * `midpoint` - The midpoint of the time interval
/// * `radius` - The half-length of the time interval
pub fn normalize_time(time: f64, midpoint: f64, radius: f64) -> Result<f64> {
    if radius <= 0.0 {
        return Err(JplephemError::Other(
            "Invalid radius for time normalization: must be positive".to_string(),
        ));
    }

    let normalized = (time - midpoint) / radius;

    if !(-1.0 - 1e-9..=1.0 + 1e-9).contains(&normalized) {
        return Err(JplephemError::OutOfRangeError {
            jd: time,
            start_jd: midpoint - radius,
            end_jd: midpoint + radius,
        });
    }

    // Clamp to [-1, 1] to handle floating point edge cases
    Ok(normalized.clamp(-1.0, 1.0))
}

/// Rescale a derivative from normalized time to physical time
///
/// When evaluating derivatives of Chebyshev polynomials, we get the derivative
/// with respect to normalized time. This rescales to physical time units.
pub fn rescale_derivative(deriv_normalized: f64, radius: f64) -> Result<f64> {
    if radius <= 0.0 {
        return Err(JplephemError::Other(
            "Invalid radius for derivative rescaling: must be positive".to_string(),
        ));
    }
    Ok(deriv_normalized / radius)
}

/// A run of equally spaced Chebyshev records, the coefficient layout shared by
/// SPK types 2 and 3 and by binary PCK type 2.
///
/// A segment of any of those types is an array of `n_records` fixed-size
/// records followed by four trailing numbers: the epoch of the first record,
/// the length of each record, the record size and the record count. Each
/// record holds its own midpoint and radius (in TDB seconds since J2000) and
/// then `component_count` blocks of `n_coeffs` Chebyshev coefficients: three
/// position components for SPK type 2, position and velocity for type 3, and
/// three Euler angles for binary PCK type 2.
#[derive(Debug, Clone)]
pub struct ChebyshevRecords {
    init: f64,
    intlen: f64,
    record_size: usize,
    n_records: usize,
    n_coeffs: usize,
    component_count: usize,
    coefficients: Vec<f64>,
}

impl ChebyshevRecords {
    /// Parse a segment array of the given number of components per record.
    ///
    /// # Errors
    ///
    /// Returns [`JplephemError::InvalidFormat`] if the array is too short, if
    /// the record size cannot hold at least one coefficient per component, or
    /// if the record count and record size disagree with the array length.
    pub fn load(array: &[f64], component_count: usize) -> Result<Self> {
        if array.len() < 4 {
            return Err(JplephemError::InvalidFormat(
                "Segment data too small for a Chebyshev record array".to_string(),
            ));
        }

        let n = array.len();
        let init = array[n - 4];
        let intlen = array[n - 3];
        let record_size = array[n - 2] as usize;
        let n_records = array[n - 1] as usize;

        if record_size < 2 + component_count {
            return Err(JplephemError::InvalidFormat(format!(
                "Invalid record size for {component_count} components: {record_size}"
            )));
        }

        let expected_size = n_records * record_size + 4;
        if n != expected_size {
            return Err(JplephemError::InvalidFormat(format!(
                "Inconsistent array size: expected {expected_size}, got {n}"
            )));
        }

        Ok(Self {
            init,
            intlen,
            record_size,
            n_records,
            n_coeffs: (record_size - 2) / component_count,
            component_count,
            coefficients: array[0..n - 4].to_vec(),
        })
    }

    /// Epoch of the start of the first record, in TDB seconds since J2000.
    pub fn init(&self) -> f64 {
        self.init
    }

    /// Length of each record, in seconds.
    pub fn interval_length(&self) -> f64 {
        self.intlen
    }

    /// Number of records in the segment.
    pub fn len(&self) -> usize {
        self.n_records
    }

    /// Whether the segment holds no records at all.
    pub fn is_empty(&self) -> bool {
        self.n_records == 0
    }

    /// Number of Chebyshev coefficients per component.
    pub fn coefficient_count(&self) -> usize {
        self.n_coeffs
    }

    /// Number of components stored in each record.
    pub fn component_count(&self) -> usize {
        self.component_count
    }

    /// Index of the record covering `et`, in TDB seconds since J2000.
    ///
    /// An epoch exactly at the end of the last record is clamped onto it.
    ///
    /// # Errors
    ///
    /// Returns [`JplephemError::OutOfRangeError`] if `et` falls outside the
    /// span of the records.
    pub fn record_index(&self, et: f64) -> Result<usize> {
        let out_of_range = || JplephemError::OutOfRangeError {
            jd: super::spk::seconds_to_jd(et),
            start_jd: super::spk::seconds_to_jd(self.init),
            end_jd: super::spk::seconds_to_jd(self.init + self.intlen * self.n_records as f64),
        };

        let elapsed = et - self.init;
        if elapsed < 0.0 || self.n_records == 0 {
            return Err(out_of_range());
        }
        let index = (elapsed / self.intlen).floor() as usize;
        match index.cmp(&self.n_records) {
            std::cmp::Ordering::Less => Ok(index),
            std::cmp::Ordering::Equal => Ok(self.n_records - 1),
            std::cmp::Ordering::Greater => Err(out_of_range()),
        }
    }

    /// Borrow one record by index.
    ///
    /// # Errors
    ///
    /// Returns [`JplephemError::InvalidFormat`] if the index is past the end
    /// of the coefficient array.
    pub fn record(&self, index: usize) -> Result<ChebyshevRecord<'_>> {
        let start = index * self.record_size;
        if index >= self.n_records || start + self.record_size > self.coefficients.len() {
            return Err(JplephemError::InvalidFormat(
                "Record index out of bounds".to_string(),
            ));
        }
        Ok(ChebyshevRecord {
            midpoint: self.coefficients[start],
            radius: self.coefficients[start + 1],
            coefficients: &self.coefficients[start + 2..start + self.record_size],
            n_coeffs: self.n_coeffs,
            component_count: self.component_count,
        })
    }

    /// Borrow the record covering `et`, in TDB seconds since J2000.
    ///
    /// # Errors
    ///
    /// Returns the errors of [`record_index`](Self::record_index) and
    /// [`record`](Self::record).
    pub fn record_at(&self, et: f64) -> Result<ChebyshevRecord<'_>> {
        self.record(self.record_index(et)?)
    }
}

/// One record of a [`ChebyshevRecords`] array.
#[derive(Debug, Clone, Copy)]
pub struct ChebyshevRecord<'a> {
    midpoint: f64,
    radius: f64,
    coefficients: &'a [f64],
    n_coeffs: usize,
    component_count: usize,
}

impl ChebyshevRecord<'_> {
    /// Midpoint of the record, in TDB seconds since J2000.
    pub fn midpoint(&self) -> f64 {
        self.midpoint
    }

    /// Half-length of the record, in seconds.
    pub fn radius(&self) -> f64 {
        self.radius
    }

    /// The Chebyshev polynomial of component `index`.
    ///
    /// # Errors
    ///
    /// Returns [`JplephemError::InvalidFormat`] if the component does not
    /// exist in this record.
    pub fn polynomial(&self, index: usize) -> Result<ChebyshevPolynomial> {
        if index >= self.component_count {
            return Err(JplephemError::InvalidFormat(format!(
                "Component {index} out of range for a record of {} components",
                self.component_count
            )));
        }
        let start = index * self.n_coeffs;
        Ok(ChebyshevPolynomial::new(
            self.coefficients[start..start + self.n_coeffs].to_vec(),
        ))
    }

    /// Map `et`, in TDB seconds since J2000, onto the polynomial's `[-1, 1]`.
    ///
    /// # Errors
    ///
    /// Returns the errors of [`normalize_time`].
    pub fn normalized_time(&self, et: f64) -> Result<f64> {
        normalize_time(et, self.midpoint, self.radius)
    }
}

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

    #[test]
    fn test_chebyshev_constant() {
        let poly = ChebyshevPolynomial::new(vec![5.0]);
        assert_eq!(poly.evaluate(-1.0), 5.0);
        assert_eq!(poly.evaluate(0.0), 5.0);
        assert_eq!(poly.evaluate(1.0), 5.0);
        assert_eq!(poly.derivative(0.0), 0.0);
    }

    #[test]
    fn test_chebyshev_linear() {
        // f(x) = 3 + 2x
        let poly = ChebyshevPolynomial::new(vec![3.0, 2.0]);
        assert!((poly.evaluate(-1.0) - 1.0).abs() < 1e-12);
        assert!((poly.evaluate(0.0) - 3.0).abs() < 1e-12);
        assert!((poly.evaluate(1.0) - 5.0).abs() < 1e-12);
        assert!((poly.derivative(0.0) - 2.0).abs() < 1e-12);
    }

    #[test]
    fn test_chebyshev_quadratic() {
        // T2(x) = 2x² - 1, so f(x) = 3 + 2x + (2x² - 1) = 2 + 2x + 2x²
        let poly = ChebyshevPolynomial::new(vec![3.0, 2.0, 1.0]);
        assert!((poly.evaluate(-1.0) - 2.0).abs() < 1e-12);
        assert!((poly.evaluate(0.0) - 2.0).abs() < 1e-12);
        assert!((poly.evaluate(1.0) - 6.0).abs() < 1e-12);
        // f'(x) = 2 + 4x
        assert!((poly.derivative(-1.0) - (-2.0)).abs() < 1e-12);
        assert!((poly.derivative(0.0) - 2.0).abs() < 1e-12);
        assert!((poly.derivative(1.0) - 6.0).abs() < 1e-12);
    }

    #[test]
    fn test_x_squared_approximation() {
        // x^2 = (T2(x) + 1)/2, coefficients [0.5, 0, 0.5]
        let poly = ChebyshevPolynomial::new(vec![0.5, 0.0, 0.5]);
        for i in 0..=10 {
            let x = -1.0 + i as f64 * 0.2;
            let expected = x * x;
            assert!(
                (expected - poly.evaluate(x)).abs() < 1e-12,
                "Bad approximation at x={x}"
            );
        }
    }

    #[test]
    fn test_time_normalization() {
        let mid = 100.0;
        let rad = 10.0;
        assert_eq!(normalize_time(100.0, mid, rad).unwrap(), 0.0);
        assert_eq!(normalize_time(90.0, mid, rad).unwrap(), -1.0);
        assert_eq!(normalize_time(110.0, mid, rad).unwrap(), 1.0);
        assert_eq!(normalize_time(95.0, mid, rad).unwrap(), -0.5);
        assert!(normalize_time(79.0, mid, rad).is_err());
        assert!(normalize_time(121.0, mid, rad).is_err());
        assert!(normalize_time(100.0, mid, 0.0).is_err());
    }

    #[test]
    fn test_derivative_rescaling() {
        assert_eq!(rescale_derivative(5.0, 10.0).unwrap(), 0.5);
        assert!(rescale_derivative(5.0, 0.0).is_err());
    }
}