solvastro 0.1.1

A Rust blind plate solver
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
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
use az::{Az, Cast};

use log::*;

use std::error::Error;
use std::f64::consts::FRAC_1_SQRT_2;
use std::fs::File;
use std::io::Write;
use std::num::NonZero;
use std::path::Path;
use kiddo_v6::{Manhattan, SquaredEuclidean};
use crate::dynamic_index::star_index_container::{DistanceMetric, KdTree};
use crate::structs_f64::{
    quad::{PotentialQuad, Quad, QuadCode},
    star::Star,
};
use crate::structs_generic::{Flt, Idx};
use memmap::MmapOptions;
use rkyv_08::{
    from_bytes_unchecked, rancor::Error as RkyvError, to_bytes, Archive, Deserialize, Serialize,
};

const MAX_AB_USE: usize = 10;
const MAX_TOTAL_REUSE: usize = 80; // 40;
const MAX_AB_SHRINK_FACTOR: f64 = FRAC_1_SQRT_2;
const MAX_AB2_MIN_AB2_RATIO: f64 = FRAC_1_SQRT_2;
const MIN_AC_MIN_AB_RATIO: f64 = 0.01f64;
const INITIAL_MAX_AB_DEGREES: f64 = 45f64;
const TERMINAL_MIN_AB_DEGREES: f64 = 3f64;

type SIDX = u32; // type used to index stars in the star kd-tree
type QIDX = u32; // type used to index quads in the quad kd-tree
type FLT = f64; // type used to represent a 3D point

pub type StarKdTree = kiddo_v6::ImmutableKdTree<FLT, 3>;
pub type QuadKdTree = kiddo_v6::ImmutableKdTree<FLT, 4>;

pub struct BestNeighbour<F: Flt, I: Idx> {
    pub distance: F,
    pub item: I,
}

pub struct NearestNeighbour<F: Flt, I: Idx> {
    pub distance: F,
    pub item: I,
}

impl<F: Flt + az::Cast<F2>, I: Idx + az::Cast<I2>, F2: Flt, I2: Idx>
    From<kiddo_v6::QueryResultItem<(), F, I>> for NearestNeighbour<F2, I2>
where
    F: Cast<I2>,
    F2: Cast<I2>,
    I: Cast<F2>
{
    fn from(nn: kiddo_v6::QueryResultItem<(), F, I>) -> Self {
        NearestNeighbour {
            item: nn.item.az::<I2>(),
            distance: nn.distance.az::<F2>(),
        }
    }
}

impl<F: Flt + az::Cast<F2>, I: Idx + az::Cast<I2>, F2: Flt, I2: Idx>
    From<kiddo_v6::QueryResultItem<(), F, I>> for BestNeighbour<F2, I2>
where
    F: Cast<I2>,
    F2: Cast<I2>,
    I: Cast<F2>
{
    fn from(bn: kiddo_v6::QueryResultItem<(), F, I>) -> Self {
        BestNeighbour {
            item: bn.item.az::<I2>(),
            distance: bn.distance.az::<F2>(),
        }
    }
}

pub trait StarIndexTrait<F: Flt> {
    fn best_n_stars_within(
        &self,
        query: [F; 3],
        radius: F,
        max_qty: NonZero<usize>,
    ) -> impl Iterator<Item = BestNeighbour<F, u32>>;

    fn get_star(&self, index: SIDX) -> &Star;

    fn get_quad(&self, index: QIDX) -> &Quad;

    fn stars_within_radius(&self, query: &[F; 3], radius: F) -> Vec<NearestNeighbour<F, SIDX>>;

    fn quad_codes_within_radius(&self, query: &[F; 4], radius: F)
        -> Vec<NearestNeighbour<F, SIDX>>;
}

impl StarIndexTrait<f64> for StarIndex {
    fn best_n_stars_within(
        &self,
        query: [f64; 3],
        radius: f64,
        max_qty: NonZero<usize>,
    ) -> impl Iterator<Item = BestNeighbour<f64, SIDX>> {
        self.kd_stars
            .query(&(f64::conv3::<f64, f64>(&query)))
            .best_n_within::<SquaredEuclidean<f64>>(
                radius.az::<f64>(),
                max_qty,
            )
            .execute()
            .into_iter()
            .map(|nn| BestNeighbour {
                distance: nn.distance.az::<f64>(),
                item: nn.item.az::<SIDX>(),
            })
    }

    fn get_star(&self, index: SIDX) -> &Star {
        &self.stars[index as usize]
    }

    fn get_quad(&self, index: QIDX) -> &Quad {
        &self.quads[index as usize]
    }

    fn stars_within_radius(
        &self,
        query: &[f64; 3],
        radius: f64,
    ) -> Vec<NearestNeighbour<f64, SIDX>> {
        self.kd_stars
            .query(&(f64::conv3::<f64, f64>(query)))
            .within::<SquaredEuclidean<f64>>(radius.az::<f64>())
            .execute()
            .into_iter()
            .map(|nn| NearestNeighbour {
                distance: nn.distance.az::<f64>(),
                item: nn.item.az::<SIDX>(),
            })
            .collect()
    }

    fn quad_codes_within_radius(
        &self,
        query: &[f64; 4],
        radius: f64,
    ) -> Vec<NearestNeighbour<f64, SIDX>> {
        self.kd_codes
            .query(&(f64::conv4::<f64, f64>(query)))
            .within::<Manhattan<f64>>(radius.az::<f64>())
            .execute()
            .into_iter()
            .map(|nn| NearestNeighbour {
                distance: nn.distance.az::<f64>(),
                item: nn.item.az::<SIDX>(),
            })
            .collect()
    }
}

pub struct DynStarIndex {
    stars: Vec<Star>,
    kd_stars: Box<dyn KdTree<3>>,
    quads: Vec<Quad>,
    kd_codes: Box<dyn KdTree<4>>,
}

impl StarIndexTrait<f64> for DynStarIndex {
    fn best_n_stars_within(
        &self,
        query: [f64; 3],
        radius: f64,
        max_qty: NonZero<usize>,
    ) -> impl Iterator<Item = BestNeighbour<f64, u32>> {
        Box::new(
            self.kd_stars
                .best_n_within_radius(&query, radius, max_qty, DistanceMetric::SquaredEuclidean)
                .map(|nn| BestNeighbour {
                    distance: nn.distance.az::<f64>(),
                    item: nn.item.az::<SIDX>(),
                }),
        )
    }

    fn get_star(&self, index: SIDX) -> &Star {
        &self.stars[index as usize]
    }

    fn get_quad(&self, index: QIDX) -> &Quad {
        &self.quads[index as usize]
    }

    fn stars_within_radius(
        &self,
        query: &[f64; 3],
        radius: f64,
    ) -> Vec<NearestNeighbour<f64, SIDX>> {
        self.kd_stars
            .within_radius(query, radius.az::<f64>(), DistanceMetric::SquaredEuclidean)
            .into_iter()
            .map(|nn| NearestNeighbour {
                distance: nn.distance.az::<f64>(),
                item: nn.item.az::<SIDX>(),
            })
            .collect()
    }

    fn quad_codes_within_radius(
        &self,
        query: &[f64; 4],
        radius: f64,
    ) -> Vec<NearestNeighbour<f64, SIDX>> {
        self.kd_codes
            .within_radius(query, radius.az::<f64>(), DistanceMetric::Manhattan)
            .into_iter()
            .map(|nn| NearestNeighbour {
                distance: nn.distance.az::<f64>(),
                item: nn.item.az::<SIDX>(),
            })
            .collect()
    }
}

#[derive(Debug, Archive, Serialize, Deserialize)]
#[rkyv(crate=rkyv_08)]
pub struct StarIndex {
    pub stars: Vec<Star>,
    pub(crate) kd_stars: StarKdTree,
    pub quads: Vec<Quad>,
    kd_codes: QuadKdTree,
}

impl StarIndex {
    pub fn new(
        stars: Vec<Star>,
        kd_stars: StarKdTree,
        quads: Vec<Quad>,
        kd_codes: QuadKdTree,
    ) -> StarIndex {
        StarIndex {
            stars,
            kd_stars,
            quads,
            kd_codes,
        }
    }

    pub fn from_stars(stars: Vec<Star>) -> StarIndex {
        let kd_stars = StarIndex::build_star_kdtree(&stars);
        let quads: Vec<Quad> = StarIndex::generate_quad_list(&stars);
        let kd_codes = StarIndex::build_code_kdtree(&quads, &stars);

        StarIndex::new(stars, kd_stars, quads, kd_codes)
    }

    pub fn from_stars_and_quads(stars: Vec<Star>, quads: Vec<Quad>) -> StarIndex {
        let kd_stars = StarIndex::build_star_kdtree(&stars);
        let kd_codes = StarIndex::build_code_kdtree(&quads, &stars);

        StarIndex::new(stars, kd_stars, quads, kd_codes)
    }

    pub fn from_stars_and_quads_and_codes(
        stars: Vec<Star>,
        quads: Vec<Quad>,
        codes: Vec<QuadCode>,
    ) -> StarIndex {
        let kd_stars = StarIndex::build_star_kdtree(&stars);
        let kd_codes = StarIndex::build_code_kdtree_from_codes(&codes);

        StarIndex::new(stars, kd_stars, quads, kd_codes)
    }

    fn build_star_kdtree(stars: &[Star]) -> StarKdTree {
        let points = stars
            .iter()
            .map(|star| star.spherical_array())
            .collect::<Vec<_>>();

        let kd_stars = StarKdTree::new_from_slice(&points).expect("Failed to create KDTree");

        info!("Stars added to kd-tree: {:?}", kd_stars.size());
        kd_stars
    }

    // fn build_star_kdtree(stars: &[Star]) -> StarKdTree {
    //     let points: Vec<_> = stars.iter().map(|star|[
    //         star.spherical_array()[0],
    //         star.spherical_array()[1],
    //         star.spherical_array()[2],
    //     ]).collect();
    //
    //     let mut kd_stars: StarKdTree = ImmutableKdTree::new_from_slice(&points);
    //
    //     info!("Stars added to kd-tree: {:?}", kd_stars.size());
    //     kd_stars
    // }

    fn build_code_kdtree(quads: &[Quad], stars: &[Star]) -> QuadKdTree {
        let codes = quads
            .iter()
            .map(|quad| quad.calc_code(&stars).unwrap())
            .collect::<Vec<_>>();

        let kdt = QuadKdTree::new_from_slice(&codes).expect("Failed to create KDTree");

        info!("Quads added to kd-tree: {:?}", kdt.size());
        kdt
    }

    fn build_code_kdtree_from_codes(codes: &[QuadCode]) -> QuadKdTree {
        QuadKdTree::new_from_slice(&codes).expect("Failed to create KDTree")
    }

    pub fn generate_quad_list(stars: &[Star]) -> Vec<Quad> {
        let mut quad_inbox: Vec<Quad> = Vec::with_capacity(stars.len() * 3);

        let mut filtered_star_indices: Vec<usize> = Vec::with_capacity(stars.len());
        filtered_star_indices.push(0);
        let mut i = 0;
        filtered_star_indices.resize_with(stars.len() - 1, || {
            i += 1;
            i
        });

        let mut max_ab: f64 = INITIAL_MAX_AB_DEGREES;
        let mut min_ab: f64 = max_ab * MAX_AB2_MIN_AB2_RATIO;
        let mut min_ac = min_ab * MIN_AC_MIN_AB_RATIO;

        while min_ab >= TERMINAL_MIN_AB_DEGREES {
            info!(
                "max_ab = {:}, min_ab = {:}, quads so far: {:}",
                max_ab,
                min_ab,
                quad_inbox.len()
            );
            let mut stars_times_used = vec![0; stars.len()];

            let max_ab2: f64 = max_ab.to_radians() * max_ab.to_radians();
            let min_ab2: f64 = min_ab.to_radians() * min_ab.to_radians();
            let min_ac2: f64 = min_ac.to_radians() * min_ac.to_radians();

            filtered_star_indices = filtered_star_indices
                .into_iter()
                .filter(|&index| stars_times_used[index] < MAX_TOTAL_REUSE)
                .collect();

            'b_loop: for (b_pos, &b_idx) in filtered_star_indices.iter().enumerate() {
                let b_times_used: usize = stars_times_used[b_idx];
                if b_times_used >= MAX_TOTAL_REUSE {
                    //println!("skip B (B overuse)");
                    continue;
                }
                if b_pos % 1000 == 0 {
                    debug!("b_pos: {:}", b_pos);
                }

                'a_loop: for (a_pos, &a_idx) in filtered_star_indices.iter().enumerate() {
                    if a_pos == b_pos {
                        break;
                    }

                    let a_times_used: usize = stars_times_used[a_idx];
                    if a_times_used >= MAX_TOTAL_REUSE {
                        //println!("skip A (A overuse)");
                        continue;
                    }

                    if !StarIndex::check_scale(&stars[a_idx], &stars[b_idx], min_ab2, max_ab2) {
                        continue;
                    }

                    let mut ab_used: usize = 0;
                    let pquad = PotentialQuad::new(a_idx, b_idx, stars);

                    // omit stars too close to A or B, to avoid having quads
                    // that have two vertices on both stars in a double
                    let interior_star_indices: Vec<usize> = filtered_star_indices
                        .iter()
                        .filter(|&&cd_idx: &&usize| {
                            a_idx != cd_idx
                                && b_idx != cd_idx
                                && pquad.can_contain(cd_idx, &stars)
                                && stars[a_idx].dist_sq_to(&stars[cd_idx]) > min_ac2
                                && stars[b_idx].dist_sq_to(&stars[cd_idx]) > min_ac2
                        })
                        .copied()
                        .collect();

                    'c_loop: for (c_pos, &c_idx) in interior_star_indices.iter().enumerate() {
                        for &d_idx in interior_star_indices.iter().skip(c_pos + 1) {
                            // skip if D is too close to C, to avoid having quads
                            // that have two vertices on both stars in a double
                            if stars[c_idx].dist_sq_to(&stars[d_idx]) < min_ac2 {
                                //println!("skip D (too close to C)");
                                continue;
                            }

                            if ab_used >= MAX_AB_USE {
                                //println!("skip B (AB overuse)");
                                continue 'a_loop;
                            }

                            let c_times_used: usize = stars_times_used[c_idx];
                            if c_times_used >= MAX_TOTAL_REUSE {
                                continue 'c_loop;
                            }

                            let d_times_used: usize = stars_times_used[d_idx];
                            if d_times_used >= MAX_TOTAL_REUSE {
                                continue;
                            }

                            let a_times_used: usize = stars_times_used[a_idx];
                            if a_times_used == MAX_TOTAL_REUSE {
                                continue 'a_loop;
                            }

                            let b_times_used: usize = stars_times_used[b_idx];
                            if b_times_used == MAX_TOTAL_REUSE {
                                continue 'b_loop;
                            }

                            stars_times_used[a_idx] = a_times_used + 1;
                            stars_times_used[b_idx] = b_times_used + 1;
                            stars_times_used[c_idx] = c_times_used + 1;
                            stars_times_used[d_idx] = d_times_used + 1;
                            ab_used += 1;

                            quad_inbox.push(pquad.to_quad(c_idx, d_idx));
                            //println!("Quad #{:?}: ({:?}, {:?}, {:?}, {:?})", quad_inbox.len(), a_idx, b_idx, c_idx, d_idx);
                        }
                    }
                }
            }

            debug!("CABD Phase");
            'c_loop2: for (c_pos, &c_idx) in filtered_star_indices.iter().enumerate() {
                let c_times_used: usize = stars_times_used[c_idx];
                if c_times_used >= MAX_TOTAL_REUSE {
                    debug!("skip B (B overuse)");
                    continue;
                }
                if c_pos % 1000 == 0 {
                    debug!("c_pos: {:}", c_pos);
                }

                'a_loop2: for (a_pos, &a_idx) in filtered_star_indices.iter().enumerate() {
                    if c_pos == 0 /* prevent panic from underflow by subtracting 1 from 0 */ || a_pos == c_pos - 1
                    {
                        break;
                    }

                    let a_times_used: usize = stars_times_used[a_idx];
                    if a_times_used >= MAX_TOTAL_REUSE {
                        // println!("skip A (A overuse)");
                        continue;
                    }

                    'b_loop2: for (b_pos, &b_idx) in
                        filtered_star_indices.iter().skip(a_pos + 1).enumerate()
                    {
                        if b_pos == c_pos - 1 {
                            break;
                        }

                        if !StarIndex::check_scale(&stars[a_idx], &stars[b_idx], min_ab2, max_ab2) {
                            continue;
                        }

                        let mut ab_used: usize = 0;
                        let pquad = PotentialQuad::new(a_idx, b_idx, stars);
                        if !pquad.can_contain(c_idx, &stars) {
                            continue;
                        }

                        // omit stars too close to A or B, to avoid having quads
                        // that have two vertices on both stars in a double
                        let interior_star_indices: Vec<usize> = filtered_star_indices
                            .iter()
                            .filter(|&&d_idx| {
                                d_idx != c_idx
                                    && b_idx != d_idx
                                    && a_idx != d_idx
                                    && pquad.can_contain(d_idx, &stars)
                                    && stars[a_idx].dist_sq_to(&stars[d_idx]) > min_ac2
                                    && stars[b_idx].dist_sq_to(&stars[d_idx]) > min_ac2
                            })
                            .copied()
                            .collect();

                        debug!(
                            "interior_star_indices length: {:?}",
                            interior_star_indices.len()
                        );

                        for &d_idx in interior_star_indices.iter().skip(c_pos + 1) {
                            // skip if D is too close to C, to avoid having quads
                            // that have two vertices on both stars in a double
                            if stars[c_idx].dist_sq_to(&stars[d_idx]) < min_ac2 {
                                debug!("skip D (too close to C)");
                                continue;
                            }

                            if ab_used >= MAX_AB_USE {
                                debug!("skip B (AB overuse)");
                                continue 'a_loop2;
                            }

                            let c_times_used: usize = stars_times_used[c_idx];
                            if c_times_used >= MAX_TOTAL_REUSE {
                                debug!("skip C (overuse)");
                                continue 'c_loop2;
                            }

                            let d_times_used: usize = stars_times_used[d_idx];
                            if d_times_used >= MAX_TOTAL_REUSE {
                                debug!("skip D (overuse)");
                                continue;
                            }

                            let a_times_used: usize = stars_times_used[a_idx];
                            if a_times_used == MAX_TOTAL_REUSE {
                                debug!("skip A (overuse)");
                                continue 'a_loop2;
                            }

                            let b_times_used: usize = stars_times_used[b_idx];
                            if b_times_used == MAX_TOTAL_REUSE {
                                debug!("skip B (overuse)");
                                continue 'b_loop2;
                            }

                            stars_times_used[a_idx] = a_times_used + 1;
                            stars_times_used[b_idx] = b_times_used + 1;
                            stars_times_used[c_idx] = c_times_used + 1;
                            stars_times_used[d_idx] = d_times_used + 1;
                            ab_used += 1;

                            quad_inbox.push(pquad.to_quad(c_idx, d_idx));
                            debug!(
                                "CABD Quad #{:?}: ({:?}, {:?}, {:?}, {:?})",
                                quad_inbox.len(),
                                a_idx,
                                b_idx,
                                c_idx,
                                d_idx
                            );
                        }
                    }
                }
            }

            // shrink the scale
            max_ab *= MAX_AB_SHRINK_FACTOR;
            min_ab = max_ab * MAX_AB2_MIN_AB2_RATIO;
            min_ac = min_ab * MIN_AC_MIN_AB_RATIO;
        }
        quad_inbox
        // TODO: maintain a list at each AB scale level that shows the
        //       total usages of each star, for statistical validation
        //       of the quad generation algo
    }

    fn check_scale(star_a: &Star, star_b: &Star, min_ab_sq: f64, max_ab_sq: f64) -> bool {
        let dist: f64 = star_a.dist_sq_to(star_b);
        dist >= min_ab_sq && dist <= max_ab_sq
    }

    pub fn write_to_rkyv(self, filename: &str) -> Result<(), Box<dyn Error>> {
        let mut file = File::create(filename)?;

        let buf = to_bytes::<RkyvError>(&self).expect("Could not serialize with rkyv");

        file.write(&buf)
            .expect("Could not write serialized rkyv to file");
        Ok(())
    }

    pub fn deserialize_from_rkyv_file(filename: &Path) -> Result<StarIndex, Box<dyn Error>> {
        let buf = unsafe { MmapOptions::new().map(&File::open(filename)?)? };
        let index = unsafe { from_bytes_unchecked::<StarIndex, RkyvError>(&buf) }?;

        let num_stars = index.stars.len();
        let num_quads = index.quads.len();
        info!(
            "index loaded (Stars: {:?}, Quads: {:?})",
            num_stars, num_quads
        );

        Ok(index)
    }
}