LOST 0.0.1
LOST: Open-source Star Tracker
Loading...
Searching...
No Matches
io.cpp
Go to the documentation of this file.
1#include "io.hpp"
2
3#include <assert.h>
4#include <cairo/cairo.h>
5#include <dirent.h>
6#include <errno.h>
7#include <limits.h>
8#include <math.h>
9#include <stdio.h>
10#include <stdlib.h>
11#include <sys/stat.h>
12#include <unistd.h>
13
14#include <algorithm>
15#include <chrono>
16#include <cstring>
17#include <fstream>
18#include <iostream>
19#include <map>
20#include <memory>
21#include <random>
22#include <string>
23#include <utility>
24#include <vector>
25
27#include "attitude-utils.hpp"
28#include "databases.hpp"
29#include "decimal.hpp"
30#include "star-id.hpp"
31#include "star-utils.hpp"
32
33namespace lost {
34
36UserSpecifiedOutputStream::UserSpecifiedOutputStream(std::string filePath, bool isBinary) {
37 if (isBinary && isatty(fileno(stdout)) && (filePath == "stdout" || filePath == "-")) {
38 std::cerr << "WARNING: output contains binary contents. Not printed to terminal." << std::endl;
39 filePath = "/dev/null";
40 }
41
42 if (filePath == "stdout" || filePath == "-") {
43 stream = &std::cout;
44 isFstream = false;
45 } else {
46 std::fstream *fs = new std::fstream();
47 fs->open(filePath, std::fstream::out);
48 stream = fs;
49 isFstream = true;
50 }
51}
52
54 if (isFstream) {
55 delete stream;
56 }
57}
58
60std::vector<CatalogStar> BscParse(std::string tsvPath) {
61 std::vector<CatalogStar> result;
62 FILE* file;
63 decimal raj2000, dej2000;
64 decimal magnitude;
65 int name;
66 char weird;
67
68 file = fopen(tsvPath.c_str(), "r");
69
70 if (file == NULL) {
71 printf("Error opening file: %s\n", strerror(errno));
72 exit(1); // TODO: do we want any other error handling?
73 return result;
74 }
75
76#ifdef LOST_FLOAT_MODE
77 std::string format = "%f|%f|%d|%c|%f";
78#else
79 std::string format = "%lf|%lf|%d|%c|%lf";
80#endif
81
82 while (EOF != fscanf(file, format.c_str(), &raj2000, &dej2000, &name, &weird, &magnitude)) {
83 result.push_back(CatalogStar(DegToRad(raj2000), DegToRad(dej2000), magnitude, name));
84 }
85
86 fclose(file);
87 assert(result.size() > 9000); // basic sanity check
88 return result;
89}
90
91#ifndef DEFAULT_BSC_PATH
92#define DEFAULT_BSC_PATH "bright-star-catalog.tsv"
93#endif
94
97 static bool readYet = false;
98 static std::vector<CatalogStar> catalog;
99
100 if (!readYet) {
101 readYet = true;
102 char *tsvPath = getenv("LOST_BSC_PATH");
103 catalog = BscParse(tsvPath ? tsvPath : DEFAULT_BSC_PATH);
104 // perform essential narrowing
105 // remove all stars with exactly the same position as another, keeping the one with brighter magnitude
106 std::sort(catalog.begin(), catalog.end(), [](const CatalogStar &a, const CatalogStar &b) {
107 return a.spatial.x < b.spatial.x;
108 });
109 for (int i = catalog.size()-1; i > 0; i--) {
110 if ((catalog[i].spatial - catalog[i-1].spatial).Magnitude() < DECIMAL(5e-5)) { // 70 stars removed at this threshold.
111 if (catalog[i].magnitude > catalog[i-1].magnitude) {
112 catalog.erase(catalog.begin() + i);
113 } else {
114 catalog.erase(catalog.begin() + i - 1);
115 }
116 }
117 }
118 }
119 return catalog;
120}
121
124unsigned char *SurfaceToGrayscaleImage(cairo_surface_t *cairoSurface) {
125 int width, height;
126 unsigned char *result;
127 uint32_t *cairoImage, pixel;
128
129 if (cairo_image_surface_get_format(cairoSurface) != CAIRO_FORMAT_ARGB32 &&
130 cairo_image_surface_get_format(cairoSurface) != CAIRO_FORMAT_RGB24) {
131 puts("Can't convert weird image formats to grayscale.");
132 return NULL;
133 }
134
135 width = cairo_image_surface_get_width(cairoSurface);
136 height = cairo_image_surface_get_height(cairoSurface);
137
138 result = new unsigned char[width*height];
139 cairoImage = (uint32_t *)cairo_image_surface_get_data(cairoSurface);
140
141 for (int i = 0; i < height * width; i++) {
142 pixel = cairoImage[i];
143 // use "luminosity" method of grayscaling
144 result[i] = round(
145 (pixel>>16 &0xFF) *0.21 +
146 (pixel>>8 &0xFF) *0.71 +
147 (pixel &0xFF) *0.07);
148 }
149
150 return result;
151}
152
153cairo_surface_t *GrayscaleImageToSurface(const unsigned char *image,
154 const int width, const int height) {
155 // cairo's 8-bit type isn't BW, it's an alpha channel only, which would look a bit weird lol
156 cairo_surface_t *result = cairo_image_surface_create(CAIRO_FORMAT_RGB24, width, height);
157 uint32_t *resultData = (uint32_t *)cairo_image_surface_get_data(result);
158 // hopefully unnecessary
159 cairo_surface_flush(result);
160 for (long i = 0; i < width * height; i++) {
161 // equal r, g, and b components
162 resultData[i] = (image[i] << 16) + (image[i] << 8) + (image[i]);
163 }
164 cairo_surface_mark_dirty(result);
165 return result;
166}
167
175void SurfacePlot(std::string description,
176 cairo_surface_t *cairoSurface,
177 const Stars &stars,
178 const StarIdentifiers *starIds,
179 const Catalog *catalog,
180 const Attitude *attitude,
181 double red,
182 double green,
183 double blue,
184 double alpha,
185 // if true, don't use catalog name
186 bool rawStarIndexes = false) {
187 cairo_t *cairoCtx;
188 std::string metadata = description + " ";
189
190 cairoCtx = cairo_create(cairoSurface);
191 cairo_set_source_rgba(cairoCtx, red, green, blue, alpha);
192 cairo_set_line_width(cairoCtx, 1.0);
193 cairo_set_antialias(cairoCtx, CAIRO_ANTIALIAS_NONE);
194 cairo_font_options_t *cairoFontOptions = cairo_font_options_create();
195 cairo_font_options_set_antialias(cairoFontOptions, CAIRO_ANTIALIAS_NONE);
196 cairo_set_font_options(cairoCtx, cairoFontOptions);
197 cairo_text_extents_t cairoTextExtents;
198 cairo_text_extents(cairoCtx, "1234567890", &cairoTextExtents);
199 decimal textHeight = cairoTextExtents.height;
200
201 for (const Star &centroid : stars) {
202 // plot the box around the star
203 if (centroid.radiusX > DECIMAL(0.0)) {
204 decimal radiusX = centroid.radiusX;
205 decimal radiusY = centroid.radiusY > DECIMAL(0.0) ?
206 centroid.radiusY : radiusX;
207
208 // Rectangles should be entirely /outside/ the radius of the star, so the star is
209 // fully visible.
210 cairo_rectangle(cairoCtx,
211 (double) (centroid.position.x - radiusX),
212 (double) (centroid.position.y - radiusY),
213 (double) (radiusX * 2),
214 (double) (radiusY * 2));
215 cairo_stroke(cairoCtx);
216 } else {
217 cairo_rectangle(cairoCtx,
218 (double) DECIMAL_FLOOR(centroid.position.x),
219 (double) DECIMAL_FLOOR(centroid.position.y),
220 1, 1);
221 cairo_fill(cairoCtx);
222 }
223 }
224
225 metadata += std::to_string(stars.size()) + " centroids ";
226
227 if (starIds != NULL) {
228 assert(catalog != NULL);
229
230 for (const StarIdentifier &starId : *starIds) {
231 const Star &centroid = stars[starId.starIndex];
232 cairo_move_to(cairoCtx,
233
234 (double) (centroid.radiusX > DECIMAL(0.0)
235 ? centroid.position.x + centroid.radiusX + 3
236 : centroid.position.x + 8),
237
238 (double) (centroid.radiusY > DECIMAL(0.0)
239 ? centroid.position.y - centroid.radiusY + textHeight
240 : centroid.position.y + 10));
241
242 int plotName = rawStarIndexes ? starId.catalogIndex : (*catalog)[starId.catalogIndex].name;
243 cairo_show_text(cairoCtx, std::to_string(plotName).c_str());
244 }
245 metadata += std::to_string(starIds->size()) + " identified ";
246 }
247
248 if (attitude != NULL) {
249 EulerAngles spherical = attitude->ToSpherical();
250 metadata +=
251 "RA: " + std::to_string(RadToDeg(spherical.ra)) + " " +
252 "DE: " + std::to_string(RadToDeg(spherical.de)) + " " +
253 "Roll: " + std::to_string(RadToDeg(spherical.roll)) + " ";
254 }
255
256 // plot metadata
257 cairo_move_to(cairoCtx, 3, (double) (3 + textHeight));
258 cairo_show_text(cairoCtx, metadata.c_str());
259
260 cairo_font_options_destroy(cairoFontOptions);
261 cairo_destroy(cairoCtx);
262}
263
264// ALGORITHM PROMPTERS
265
269
271 MultiDatabaseDescriptor dbEntries;
272
273 SerializeContext catalogSer = serFromDbValues(values);
274 // TODO decide why we have this inclMagnitude and inclName and if we should change that
275 SerializeCatalog(&catalogSer, catalog, false, true);
276 dbEntries.emplace_back(kCatalogMagicValue, catalogSer.buffer);
277
278 if (values.kvector) {
279 decimal minDistance = DegToRad(values.kvectorMinDistance);
280 decimal maxDistance = DegToRad(values.kvectorMaxDistance);
281 long numBins = values.kvectorNumDistanceBins;
282 SerializeContext ser = serFromDbValues(values);
283 SerializePairDistanceKVector(&ser, catalog, minDistance, maxDistance, numBins);
284 dbEntries.emplace_back(PairDistanceKVectorDatabase::kMagicValue, ser.buffer);
285 }
286
287 if (values.tetra) {
288 decimal maxFovDeg = values.tetraMaxFov;
289
290 std::vector<uint16_t> catalogPatternStarInds =
291 TetraPreprocessCatalog(catalog, maxFovDeg, values.tetraPatternStarsPerFov);
292 std::cerr << "Number of pattern stars: " << catalogPatternStarInds.size() << std::endl;
293
294 SerializeContext ser = serFromDbValues(values);
296 &ser, catalog, maxFovDeg, catalogPatternStarInds, values.tetraEdgeRatioBins);
297 dbEntries.emplace_back(TetraDatabase::kMagicValue, ser.buffer);
298 }
299
300 if (dbEntries.size() <= 1) {
301 std::cerr << "No database builder selected -- no database generated." << std::endl;
302 exit(1);
303 }
304
305 return dbEntries;
306}
307
309std::ostream &operator<<(std::ostream &os, const Camera &camera) {
310 os << "camera_focal_length " << camera.FocalLength() << std::endl
311 << "camera_fov " << camera.Fov() << std::endl
312 << "camera_resolution_x " << camera.XResolution() << std::endl
313 << "camera_resolution_y " << camera.YResolution() << std::endl;
314 // TODO: principal point
315 return os;
316}
317
318// PIPELINE INPUT STUFF
319
324decimal FocalLengthFromOptions(const PipelineOptions &values, int xResolution) {
325 if ((values.pixelSize != -1) ^ (values.focalLength != 0)) {
326 std::cerr << "ERROR: Exactly one of --pixel-size or --focal-length were set." << std::endl;
327 exit(1);
328 }
329
330 // no surefire way to see if the fov was set on command line, so we just check if it was changed from default.
331 if (values.pixelSize != -1 && values.fov != 20) {
332 std::cerr << "ERROR: Both focal length and FOV were provided. We only need one of the two methods (pixel size + focal length, or fov) to determine fov, please only provide one." << std::endl;
333 exit(1);
334 }
335
336 if (values.pixelSize == -1) {
337 return FovToFocalLength(DegToRad(values.fov), xResolution);
338 } else {
339 return values.focalLength * 1000 / values.pixelSize;
340 }
341}
342
345cairo_surface_t *PipelineInput::InputImageSurface() const {
346 const Image *inputImage = InputImage();
347 return GrayscaleImageToSurface(inputImage->image, inputImage->width, inputImage->height);
348}
349
350// /**
351// * Pipeline input for an image that's already been identified using Astrometry.net.
352// * @todo Not implemented yet.
353// */
354// class AstrometryPipelineInput : public PipelineInput {
355// public:
356// explicit AstrometryPipelineInput(const std::string &path);
357
358// const Image *InputImage() const { return &image; };
359// const Attitude *InputAttitude() const { return &attitude; };
360// private:
361// Image image;
362// Attitude attitude;
363// };
364
371PngPipelineInput::PngPipelineInput(cairo_surface_t *cairoSurface, Camera camera, const Catalog &catalog)
372 : camera(camera), catalog(catalog) {
373
374 image.image = SurfaceToGrayscaleImage(cairoSurface);
375 image.width = cairo_image_surface_get_width(cairoSurface);
376 image.height = cairo_image_surface_get_height(cairoSurface);
377}
378
380 delete[] image.image;
381}
382
384static std::unique_ptr<PipelineInput> ReadPngPipelineInput(const std::string &pngPath, const PipelineOptions &values) {
385 cairo_surface_t *cairoSurface = cairo_image_surface_create_from_png(pngPath.c_str());
386 std::cerr << "PNG Read status: " << cairo_status_to_string(cairo_surface_status(cairoSurface)) << std::endl;
387 if (cairoSurface == NULL || cairo_surface_status(cairoSurface) != CAIRO_STATUS_SUCCESS) {
388 std::cerr << "ERROR: Can't read " << pngPath << " as a PNG image." << std::endl;
389 exit(1);
390 }
391
392 int xResolution = cairo_image_surface_get_width(cairoSurface);
393 int yResolution = cairo_image_surface_get_height(cairoSurface);
394 decimal focalLengthPixels = FocalLengthFromOptions(values, xResolution);
395 Camera cam = Camera(focalLengthPixels, xResolution, yResolution);
396
397 std::unique_ptr<PipelineInput> result(new PngPipelineInput(cairoSurface, cam, CatalogRead()));
398 cairo_surface_destroy(cairoSurface);
399 return result;
400}
401
403 PipelineInputList result;
404 for (const std::string &pngPath : values.png) {
405 result.push_back(ReadPngPipelineInput(pngPath, values));
406 }
407 return result;
408}
409
411static PipelineInputList GetImageDirPipelineInput(const PipelineOptions &values) {
412 DIR *dir = opendir(values.imageDir.c_str());
413 if (dir == NULL) {
414 std::cerr << "ERROR: Can't open directory " << values.imageDir << ": " << strerror(errno) << std::endl;
415 exit(1);
416 }
417 std::vector<std::string> names;
418 while (struct dirent *entry = readdir(dir)) {
419 std::string name = entry->d_name;
420 std::string extension = name.size() > 4 ? name.substr(name.size() - 4) : "";
421 std::transform(extension.begin(), extension.end(), extension.begin(), ::tolower);
422 if (extension != ".png") {
423 continue;
424 }
425 struct stat status;
426 if (stat((values.imageDir + "/" + name).c_str(), &status) != 0) {
427 // broken link or unreadable file: stop instead of skipping a frame
428 std::cerr << "ERROR: Can't read " << values.imageDir << "/" << name << ": " << strerror(errno) << std::endl;
429 exit(1);
430 }
431 // skip directories, pipes, etc. that happen to be named like images
432 if (S_ISREG(status.st_mode)) {
433 names.push_back(name);
434 }
435 }
436 closedir(dir);
437 if (names.empty()) {
438 std::cerr << "ERROR: No .png files in " << values.imageDir << std::endl;
439 exit(1);
440 }
441 std::sort(names.begin(), names.end());
442
443 PipelineInputList result;
444 for (const std::string &name : names) {
445 result.push_back(ReadPngPipelineInput(values.imageDir + "/" + name, values));
446 }
447 return result;
448}
449
450// AstrometryPipelineInput::AstrometryPipelineInput(const std::string &path) {
451// // create from path, TODO
452// }
453
454// PipelineInputList PromptAstrometryPipelineInput() {
455// // TODO: why does it let us do a reference to an ephemeral return value?
456// std::string path = Prompt<std::string>("Astrometry download directory");
457// PipelineInputList result;
458// result.push_back(std::unique_ptr<PipelineInput>(new AstrometryPipelineInput(path)));
459// return result;
460// }
461
463class GeneratedStar : public Star {
464public:
466 : Star(star), peakBrightness(peakBrightness), delta(motionBlurDelta) { };
467
470
473};
474
475// In the equations for pixel brightness both with motion blur enabled and disabled, we don't need
476// any constant scaling factor outside the integral because when d0=0, the brightness at the center
477// will be zero without any scaling. The scaling factor you usually see on a Normal distribution is
478// so that the Normal distribution integrates to one over the real line, making it a probability
479// distribution. But we want the /peak/ to be one, not the integral. motion blur enabled
480
491static decimal MotionBlurredPixelBrightness(const Vec2 &pixel, const GeneratedStar &generatedStar,
492 decimal t, decimal stddev) {
493 const Vec2 &p0 = generatedStar.position;
494 const Vec2 &delta = generatedStar.delta;
495 const Vec2 d0 = p0 - pixel;
496 return generatedStar.peakBrightness
497 * stddev*DECIMAL_SQRT(DECIMAL_M_PI) / (DECIMAL_SQRT(2)*delta.Magnitude())
498 * DECIMAL_EXP(DECIMAL_POW(d0.x*delta.x + d0.y*delta.y, 2) / (2*stddev*stddev*delta.MagnitudeSq())
499 - d0.MagnitudeSq() / (2*stddev*stddev))
500 * DECIMAL_ERF((t*delta.MagnitudeSq() + d0.x*delta.x + d0.y*delta.y) / (stddev*DECIMAL_SQRT(2)*delta.Magnitude()));
501}
502
504static decimal StaticPixelBrightness(const Vec2 &pixel, const GeneratedStar &generatedStar,
505 decimal t, decimal stddev) {
506 const Vec2 d0 = generatedStar.position - pixel;
507 return generatedStar.peakBrightness * t * DECIMAL_EXP(-d0.MagnitudeSq() / (2 * stddev * stddev));
508}
509
519static decimal CentroidImagingProbability(decimal mag, decimal cutoffMag) {
520 decimal brightness = MagToBrightness(mag);
521 decimal cutoffBrightness = MagToBrightness(cutoffMag);
522 decimal stddev = cutoffBrightness/DECIMAL(5.0);
523 // CDF of Normal distribution with given mean and stddev
524 return 1 - (DECIMAL(0.5) * (1 + DECIMAL_ERF((cutoffBrightness-brightness)/(stddev*DECIMAL_SQRT(2.0)))));
525}
526
527const int kMaxBrightness = 255;
528
534 Attitude attitude,
535 Camera camera,
536 std::default_random_engine *rng,
537
538 bool centroidsOnly,
539 decimal zeroMagTotalPhotons,
540 decimal starSpreadStdDev,
541 decimal saturationPhotons,
542 decimal darkCurrent,
543 decimal readNoiseStdDev,
544 Attitude motionBlurDirection, // applied on top of the attitude
545 decimal exposureTime,
546 decimal readoutTime, // zero for no rolling shutter
547 bool shotNoise,
548 int oversampling,
549 int numFalseStars,
550 decimal falseStarMinMagnitude,
551 decimal falseStarMaxMagnitude,
552 decimal cutoffMag,
553 decimal perturbationStddev)
554 : camera(camera), attitude(attitude), catalog(catalog), centroidsOnly(centroidsOnly) {
555
556 assert(falseStarMaxMagnitude <= falseStarMinMagnitude);
557 assert(perturbationStddev >= DECIMAL(0.0));
558
559 image.width = camera.XResolution();
560 image.height = camera.YResolution();
561 // number of true photons each pixel receives.
562
563 assert(oversampling >= 1);
564 int oversamplingPerAxis = DECIMAL_CEIL(DECIMAL_SQRT(oversampling));
565 if (oversamplingPerAxis*oversamplingPerAxis != oversampling) {
566 std::cerr << "WARNING: oversampling was not a perfect square. Rounding up to "
567 << oversamplingPerAxis*oversamplingPerAxis << "." << std::endl;
568 }
569 assert(exposureTime > 0);
570 bool motionBlurEnabled = abs(motionBlurDirection.GetQuaternion().Angle()) > DECIMAL(0.001);
571 Quaternion motionBlurDirectionQ = motionBlurDirection.GetQuaternion();
572 // attitude at the middle of exposure time
573 Quaternion currentAttitude = attitude.GetQuaternion();
574 // attitude 1 time unit after middle of exposure
575 Quaternion futureAttitude = motionBlurDirectionQ*currentAttitude;
576 std::vector<GeneratedStar> generatedStars;
577
578 // a star with 1 photon has peak density 1/(2pi sigma^2), because 2d gaussian formula. Then just
579 // multiply up proportionally!
580 decimal zeroMagPeakPhotonDensity = zeroMagTotalPhotons / (2*DECIMAL_M_PI * starSpreadStdDev*starSpreadStdDev);
581
582 Catalog catalogWithFalse = catalog;
583
584 std::uniform_real_distribution<decimal> uniformDistribution(DECIMAL(0.0), DECIMAL(1.0));
585 std::uniform_real_distribution<decimal> magnitudeDistribution(falseStarMaxMagnitude,
586 falseStarMinMagnitude);
587 for (int i = 0; i < numFalseStars; i++) {
588 decimal ra = uniformDistribution(*rng) * 2*DECIMAL_M_PI;
589 // to be uniform around sphere. Borel-Kolmogorov paradox is calling
590 decimal de = DECIMAL_ASIN(uniformDistribution(*rng)*2 - 1);
591 decimal magnitude = magnitudeDistribution(*rng);
592
593 catalogWithFalse.push_back(CatalogStar(ra, de, magnitude, -1));
594 }
595
596 for (int i = 0; i < (int)catalogWithFalse.size(); i++) {
597 bool isTrueStar = i < (int)catalog.size();
598
599 const CatalogStar &catalogStar = catalogWithFalse[i];
600 Vec3 rotated = attitude.Rotate(catalogWithFalse[i].spatial);
601 if (rotated.x <= 0) {
602 continue;
603 }
604 Vec2 camCoords = camera.SpatialToCamera(rotated);
605
606 if (camera.InSensor(camCoords)) {
607 Vec3 futureSpatial = futureAttitude.Rotate(catalogWithFalse[i].spatial);
608 Vec2 delta = camera.SpatialToCamera(futureSpatial) - camCoords;
609 if (!motionBlurEnabled) {
610 delta = {0, 0}; // avoid decimaling point funny business
611 }
612 // radiant intensity, in photons per time unit per pixel, at the center of the star.
613 decimal peakBrightnessPerTime = zeroMagPeakPhotonDensity * MagToBrightness(catalogStar.magnitude);
614 decimal interestingThreshold = DECIMAL(0.05); // we don't need to check pixels that are expected to
615 // receive this many photons or fewer.
616 // inverse of the function defining the Gaussian distribution: Find out how far from the
617 // mean we'll have to go until the number of photons is less than interestingThreshold
618 decimal radius = DECIMAL_CEIL(DECIMAL_SQRT(-DECIMAL_LOG(interestingThreshold/peakBrightnessPerTime/exposureTime)*2*DECIMAL_M_PI*starSpreadStdDev*starSpreadStdDev));
619 Star star = Star(camCoords.x, camCoords.y,
620 radius, radius,
621 // important to invert magnitude here, so that centroid magnitude becomes larger for brighter stars.
622 // It's possible to make it so that the magnitude is always positive too, but allowing weirder magnitudes helps keep star-id algos honest about their assumptions on magnitude.
623 // we don't use its magnitude anywhere else in generation; peakBrightness was already calculated.
624 -catalogStar.magnitude);
625 generatedStars.push_back(GeneratedStar(star, peakBrightnessPerTime, delta));
626
627 // Now add the star to the input and expected lists.
628 // We do actually want to add false stars as well, because:
629 // a) A centroider isn't any worse because it picks up a false star that looks exactly like a normal star, so why should we exclude them from compare-centroids?
630 // b) We want to feed false stars into star-ids to evaluate their false-star resilience without running centroiding.
631
632 // Add all stars to expected, cause that's how we roll
633 expectedStars.push_back(star);
634 // and provide expected identifications for all of them
635 if (isTrueStar) {
636 expectedStarIds.push_back(StarIdentifier(expectedStars.size()-1, i));
637 }
638
639 // for input, though, add perturbation and stuff.
640 Star inputStar = star;
641 if (perturbationStddev > DECIMAL(0.0)) {
642 std::normal_distribution<decimal> perturbation1DDistribution(DECIMAL(0.0), perturbationStddev);
643 // clamp to within 2 standard deviations for some reason:
644 inputStar.position.x += std::max(std::min(perturbation1DDistribution(*rng), 2*perturbationStddev), -2*perturbationStddev);
645 inputStar.position.y += std::max(std::min(perturbation1DDistribution(*rng), 2*perturbationStddev), -2*perturbationStddev);
646 }
647 // If it got perturbed outside of the sensor, don't add it.
648 if (camera.InSensor(inputStar.position)
649 // and also don't add it if it's too dim.
650 && (cutoffMag >= 100 // but always add the star if the cutoff is very high
651 || !isTrueStar // and always add the false stars
652 || std::bernoulli_distribution((double) CentroidImagingProbability(catalogStar.magnitude, cutoffMag))(*rng))) {
653 inputStars.push_back(inputStar);
654 if (isTrueStar) {
655 inputStarIds.push_back(StarIdentifier(inputStars.size()-1, i));
656 }
657 }
658 }
659 }
660
661 if (centroidsOnly) {
662 // we're outta here
663 return;
664 }
665
666 std::vector<decimal> photonsBuffer(image.width*image.height, 0);
667
668 for (const GeneratedStar &star : generatedStars) {
669 // delta will be exactly (0,0) when motion blur disabled
670 Vec2 earliestPosition = star.position - star.delta*(exposureTime/DECIMAL(2.0) + readoutTime/DECIMAL(2.0));
671 Vec2 latestPosition = star.position + star.delta*(exposureTime/DECIMAL(2.0) + readoutTime/DECIMAL(2.0));
672 int xMin = std::max(0, (int)std::min(earliestPosition.x - star.radiusX, latestPosition.x - star.radiusX));
673 int xMax = std::min(image.width-1, (int)std::max(earliestPosition.x + star.radiusX, latestPosition.x + star.radiusX));
674 int yMin = std::max(0, (int)std::min(earliestPosition.y - star.radiusX, latestPosition.y - star.radiusX));
675 int yMax = std::min(image.height-1, (int)std::max(earliestPosition.y + star.radiusX, latestPosition.y + star.radiusX));
676
677 // peak brightness is measured in photons per time unit per pixel, so if oversampling, we
678 // need to convert units to photons per time unit per sample
679 decimal oversamplingBrightnessFactor = oversamplingPerAxis*oversamplingPerAxis;
680
681 // the star.x and star.y refer to the pixel whose top left corner the star should appear at
682 // (and fractional amounts are relative to the corner). When we color a pixel, we ideally
683 // would integrate the intensity of the star over that pixel, but we can make do by sampling
684 // the intensity of the star at the /center/ of the pixel, ie, star.x+.5 and star.y+.5
685 for (int xPixel = xMin; xPixel <= xMax; xPixel++) {
686 for (int yPixel = yMin; yPixel <= yMax; yPixel++) {
687 // offset of beginning & end of readout compared to beginning & end of readout for
688 // center row
689 decimal readoutOffset = readoutTime * (yPixel - image.height/DECIMAL(2.0)) / image.height;
690 decimal tStart = -exposureTime/DECIMAL(2.0) + readoutOffset;
691 decimal tEnd = exposureTime/DECIMAL(2.0) + readoutOffset;
692
693 // loop through all samples in the current pixel
694 for (int xSample = 0; xSample < oversamplingPerAxis; xSample++) {
695 for (int ySample = 0; ySample < oversamplingPerAxis; ySample++) {
696 decimal x = xPixel + (xSample+DECIMAL(0.5))/oversamplingPerAxis;
697 decimal y = yPixel + (ySample+DECIMAL(0.5))/oversamplingPerAxis;
698
699 decimal curPhotons;
700 if (motionBlurEnabled) {
701 curPhotons =
702 (MotionBlurredPixelBrightness({x, y}, star, tEnd, starSpreadStdDev)
703 - MotionBlurredPixelBrightness({x, y}, star, tStart, starSpreadStdDev))
704 / oversamplingBrightnessFactor;
705 } else {
706 curPhotons = StaticPixelBrightness({x, y}, star, exposureTime, starSpreadStdDev)
707 / oversamplingBrightnessFactor;
708 }
709
710 assert(DECIMAL(0.0) <= curPhotons);
711
712 photonsBuffer[xPixel + yPixel*image.width] += curPhotons;
713 }
714 }
715 }
716 }
717 }
718
719 std::normal_distribution<decimal> standardNormalDist(DECIMAL(0.0), DECIMAL(1.0));
720
721 // convert from photon counts to observed pixel brightnesses, applying noise and such.
722 imageData = std::vector<unsigned char>(image.width*image.height);
723 image.image = imageData.data();
724 for (int i = 0; i < image.width * image.height; i++) {
725 decimal curBrightness = 0;
726
727 // dark current (Constant)
728 curBrightness += darkCurrent;
729
730 // read noise (Gaussian)
731 curBrightness += readNoiseStdDev * standardNormalDist(*rng);
732
733 // shot noise (Poisson), and quantize
734 long quantizedPhotons;
735 if (shotNoise) {
736 // with GNU libstdc++, it keeps sampling from the distribution until it's within the min-max
737 // range. This is problematic if the mean is far above the max long value, because then it
738 // might have to sample many many times (and furthermore, the results won't be useful
739 // anyway)
740 decimal photons = photonsBuffer[i];
741 if (photons > DECIMAL(LONG_MAX) - DECIMAL(3.0) * DECIMAL_SQRT(LONG_MAX)) {
742 std::cout << "ERROR: One of the pixels had too many photons. Generated image would not be physically accurate, exiting." << std::endl;
743 exit(1);
744 }
745 // std::poisson_distribution requires mean > 0
746 if (photons > DECIMAL(0.0)) {
747 std::poisson_distribution<long> shotNoiseDist((double) photons);
748 quantizedPhotons = shotNoiseDist(*rng);
749 } else {
750 quantizedPhotons = 0;
751 }
752 } else {
753 quantizedPhotons = round(photonsBuffer[i]);
754 }
755 curBrightness += quantizedPhotons / saturationPhotons;
756
757 // std::clamp not introduced until C++17, so we avoid it.
758 decimal clampedBrightness = std::max(std::min(curBrightness, DECIMAL(1.0)), DECIMAL(0.0));
759 imageData[i] = floor(clampedBrightness * kMaxBrightness); // TODO: off-by-one, 256?
760 }
761}
762
767static Attitude RandomAttitude(std::default_random_engine* pReng) {
768 std::uniform_real_distribution<decimal> randomAngleDistribution(0, 1);
769
770 // normally the ranges of the Ra and Dec are:
771 // Dec: [-90 deg, 90 deg] --> [-pi/2 rad, pi/2 rad], where negative means south
772 // of the celestial equator and positive means north
773 // Ra: [0 deg, 360 deg] --> [0 rad, 2pi rad ]
774 // Roll: [0 rad, 2 pi rad]
775
776 decimal randomRa = 2 * DECIMAL_M_PI * randomAngleDistribution(*pReng);
777 decimal randomDec = (DECIMAL_M_PI / 2) - acos(1 - 2 * randomAngleDistribution(*pReng)); //acos returns a decimal in range [0, pi]
778 decimal randomRoll = 2 * DECIMAL_M_PI * randomAngleDistribution(*pReng);
779
780 Attitude randAttitude = Attitude(SphericalToQuaternion(randomRa, randomDec, randomRoll));
781
782 return randAttitude;
783}
784
787 // TODO: prompt for attitude, imagewidth, etc and then construct a GeneratedPipelineInput
788
789 int seed;
790
791 // time based seed if option specified
792 if (values.timeSeed) {
793 seed = time(0);
794 } else {
795 seed = values.generateSeed;
796 }
797
798 std::default_random_engine attitudeRng(seed);
799 std::default_random_engine noiseRng(seed);
800
801 // TODO: allow random angle generation?
803 DegToRad(values.generateDe),
804 DegToRad(values.generateRoll)));
805
806 Attitude motionBlurDirection = Attitude(SphericalToQuaternion(DegToRad(values.generateBlurRa),
807 DegToRad(values.generateBlurDe),
808 DegToRad(values.generateBlurRoll)));
809 PipelineInputList result;
810
811 decimal focalLength = FocalLengthFromOptions(values, values.generateXRes);
812
813
814 for (int i = 0; i < values.generate; i++) {
815
816
817 Attitude inputAttitude;
818 if (values.generateRandomAttitudes) {
819 inputAttitude = RandomAttitude(&attitudeRng);
820 } else {
821 inputAttitude = attitude;
822 }
823
825 CatalogRead(),
826 inputAttitude,
827 Camera(focalLength, values.generateXRes, values.generateYRes),
828 &noiseRng,
829
834 values.generateDarkCurrent,
836 motionBlurDirection,
837 values.generateExposure,
838 values.generateReadoutTime,
839 values.generateShotNoise,
842 values.generateFalseMinMag,
843 values.generateFalseMaxMag,
844 values.generateCutoffMag,
846
847 result.push_back(std::unique_ptr<PipelineInput>(curr));
848
849
850 }
851
852
853
854 return result;
855}
856
859
860 if (!values.png.empty()) {
861 return GetPngPipelineInput(values);
862 } else if (values.imageDir != "") {
863 return GetImageDirPipelineInput(values);
864 } else {
865 return GetGeneratedPipelineInput(values);
866 }
867}
868
874 StarIdAlgorithm *starIdAlgorithm,
875 AttitudeEstimationAlgorithm *attitudeEstimationAlgorithm,
876 unsigned char *database)
877 : Pipeline() {
878 if (centroidAlgorithm) {
879 this->centroidAlgorithm = std::unique_ptr<CentroidAlgorithm>(centroidAlgorithm);
880 }
881 if (starIdAlgorithm) {
882 this->starIdAlgorithm = std::unique_ptr<StarIdAlgorithm>(starIdAlgorithm);
883 }
884 if (attitudeEstimationAlgorithm) {
885 this->attitudeEstimationAlgorithm = std::unique_ptr<AttitudeEstimationAlgorithm>(attitudeEstimationAlgorithm);
886 }
887 if (database) {
888 this->database = std::unique_ptr<unsigned char[]>(database);
889 }
890}
891
892
895 Pipeline result;
896
897 // TODO: more flexible or sth
898 // TODO: don't allow setting star-id until database is set, and perhaps limit the star-id
899 // choices to those compatible with the database?
900 //
901
902 // centroid algorithm stage
903 if (values.centroidAlgo == "dummy") {
904 result.centroidAlgorithm = std::unique_ptr<CentroidAlgorithm>(new DummyCentroidAlgorithm(values.centroidDummyNumStars));
905 } else if (values.centroidAlgo == "cog") {
906 result.centroidAlgorithm = std::unique_ptr<CentroidAlgorithm>(new CenterOfGravityAlgorithm());
907 } else if (values.centroidAlgo == "iwcog") {
908 result.centroidAlgorithm = std::unique_ptr<CentroidAlgorithm>(new IterativeWeightedCenterOfGravityAlgorithm());
909 } else if (values.centroidAlgo != "") {
910 std::cout << "Illegal centroid algorithm." << std::endl;
911 exit(1);
912 }
913
914 // centroid magnitude filter stage
915 if (values.centroidMagFilter > 0) result.centroidMinMagnitude = values.centroidMagFilter;
916 if (values.centroidFilterBrightest > 0) result.centroidMinStars = values.centroidFilterBrightest;
917
918 // database stage
919 if (values.databasePath != "") {
920 std::fstream fs;
921 fs.open(values.databasePath, std::fstream::in | std::fstream::binary);
922 fs.seekg(0, fs.end);
923 long length = fs.tellg();
924 fs.seekg(0, fs.beg);
925 if (fs.fail()) {
926 std::cerr << "Error reading database! " << strerror(errno) << std::endl;
927 exit(1);
928 }
929 std::cerr << "Reading " << length << " bytes of database" << std::endl;
930 result.database = std::unique_ptr<unsigned char[]>(new unsigned char[length]);
931 fs.read((char *)result.database.get(), length);
932 std::cerr << "Done" << std::endl;
933 }
934
935 if (values.idAlgo == "dummy") {
936 result.starIdAlgorithm = std::unique_ptr<StarIdAlgorithm>(new DummyStarIdAlgorithm());
937 } else if (values.idAlgo == "gv") {
938 result.starIdAlgorithm = std::unique_ptr<StarIdAlgorithm>(new GeometricVotingStarIdAlgorithm(DegToRad(values.angularTolerance)));
939 } else if (values.idAlgo == "py") {
940 result.starIdAlgorithm = std::unique_ptr<StarIdAlgorithm>(new PyramidStarIdAlgorithm(
942 values.maxMismatchProb, 1000));
943 } else if (values.idAlgo == "tetra") {
945 if (values.tetraPairingMode == "triad") {
947 } else if (values.tetraPairingMode == "centroid-radius") {
949 } else {
950 std::cerr << "Illegal tetra pairing mode: " << values.tetraPairingMode << std::endl;
951 exit(1);
952 }
953 result.starIdAlgorithm = std::unique_ptr<StarIdAlgorithm>(
955 } else if (values.idAlgo != "") {
956 std::cout << "Illegal id algorithm." << std::endl;
957 exit(1);
958 }
959
960 if (values.attitudeAlgo == "dqm") {
961 result.attitudeEstimationAlgorithm = std::unique_ptr<AttitudeEstimationAlgorithm>(new DavenportQAlgorithm());
962 } else if (values.attitudeAlgo == "triad") {
963 result.attitudeEstimationAlgorithm = std::unique_ptr<AttitudeEstimationAlgorithm>(new TriadAlgorithm());
964 } else if (values.attitudeAlgo == "quest") {
965 result.attitudeEstimationAlgorithm = std::unique_ptr<AttitudeEstimationAlgorithm>(new QuestAlgorithm());
966 } else if (values.attitudeAlgo != "") {
967 std::cout << "Illegal attitude algorithm." << std::endl;
968 exit(1);
969 }
970
971 return result;
972}
973
980 // Start executing the pipeline at the first stage that has both input and an algorithm. From
981 // there, execute each successive stage of the pipeline using the output of the last stage
982 // (human centipede) until there are no more stages set.
983 PipelineOutput result;
984
985 const Image *inputImage = input.InputImage();
986 const Stars *inputStars = input.InputStars();
987 const StarIdentifiers *inputStarIds = input.InputStarIds();
988
989 // if database is provided, that's where we get catalog from.
990 if (database) {
991 MultiDatabase multiDatabase(database.get());
992 const unsigned char *catalogBuffer = multiDatabase.SubDatabasePointer(kCatalogMagicValue);
993 if (catalogBuffer != NULL) {
994 DeserializeContext des(catalogBuffer);
995 result.catalog = DeserializeCatalog(&des, NULL, NULL);
996 } else {
997 std::cerr << "WARNING: That database does not include a catalog. Proceeding with the full catalog." << std::endl;
998 result.catalog = input.GetCatalog();
999 }
1000 } else {
1001 result.catalog = input.GetCatalog();
1002 }
1003
1004 if (centroidAlgorithm && inputImage) {
1005
1006 // run centroiding, keeping track of the time it takes
1007 std::chrono::time_point<std::chrono::steady_clock> start = std::chrono::steady_clock::now();
1008
1009 // TODO: we should probably modify Go to just take an image argument
1010 Stars unfilteredStars = centroidAlgorithm->Go(inputImage->image, inputImage->width, inputImage->height);
1011
1012 std::chrono::time_point<std::chrono::steady_clock> end = std::chrono::steady_clock::now();
1013 result.centroidingTimeNs = std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count();
1014
1015 // MAGNITUDE FILTERING
1016 decimal minMagnitude = centroidMinMagnitude;
1017 if (centroidMinStars > 0
1018 // don't need to filter if we don't even have that many stars
1019 && centroidMinStars < (int)unfilteredStars.size()) {
1020
1021 Stars magSortedStars = unfilteredStars;
1022 // sort descending
1023 std::sort(magSortedStars.begin(), magSortedStars.end(), [](const Star &a, const Star &b) { return a.magnitude > b.magnitude; });
1024 minMagnitude = std::max(minMagnitude, magSortedStars[centroidMinStars - 1].magnitude);
1025 }
1026 // determine the minimum magnitude according to sorted stars
1027 Stars *filteredStars = new std::vector<Star>();
1028 for (const Star &star : unfilteredStars) {
1029 assert(star.magnitude >= 0); // catalog stars can have negative magnitude, but by our
1030 // conventions, centroids shouldn't.
1031 if (star.magnitude >= minMagnitude) {
1032 filteredStars->push_back(star);
1033 }
1034 }
1035 result.stars = std::unique_ptr<Stars>(filteredStars);
1036 inputStars = filteredStars;
1037
1038 // any starid set up to this point needs to be discarded, because it's based on input
1039 // centroids instead of our new centroids.
1040 inputStarIds = NULL;
1041 result.starIds = NULL;
1042 } else if (centroidAlgorithm) {
1043 std::cerr << "ERROR: Centroid algorithm specified, but no input image to run it on." << std::endl;
1044 exit(1);
1045 }
1046
1047 if (starIdAlgorithm && database && inputStars && input.InputCamera()) {
1048 // TODO: don't copy the vector!
1049 std::chrono::time_point<std::chrono::steady_clock> start = std::chrono::steady_clock::now();
1050
1051 result.starIds = std::unique_ptr<StarIdentifiers>(new std::vector<StarIdentifier>(
1052 starIdAlgorithm->Go(database.get(), *inputStars, result.catalog, *input.InputCamera())));
1053
1054 std::chrono::time_point<std::chrono::steady_clock> end = std::chrono::steady_clock::now();
1055 result.starIdTimeNs = std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count();
1056
1057 inputStarIds = result.starIds.get();
1058 } else if (starIdAlgorithm) {
1059 std::cerr << "ERROR: Star ID algorithm specified but cannot run because database, centroids, or camera are missing." << std::endl;
1060 exit(1);
1061 }
1062
1063 if (attitudeEstimationAlgorithm && inputStarIds && input.InputCamera()) {
1064 assert(inputStars); // ensure that starIds doesn't exist without stars
1065 std::chrono::time_point<std::chrono::steady_clock> start = std::chrono::steady_clock::now();
1066
1067 result.attitude = std::unique_ptr<Attitude>(
1068 new Attitude(attitudeEstimationAlgorithm->Go(*input.InputCamera(), *inputStars, result.catalog, *inputStarIds)));
1069
1070 std::chrono::time_point<std::chrono::steady_clock> end = std::chrono::steady_clock::now();
1071 result.attitudeEstimationTimeNs = std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count();
1072 } else if (attitudeEstimationAlgorithm) {
1073 std::cerr << "ERROR: Attitude estimation algorithm set, but either star IDs or camera are missing. One reason this can happen: Setting a centroid algorithm and attitude algorithm, but no star-id algorithm -- that can't work because the input star-ids won't properly correspond to the output centroids!" << std::endl;
1074 exit(1);
1075 }
1076
1077 return result;
1078}
1079
1081std::vector<PipelineOutput> Pipeline::Go(const PipelineInputList &inputs) {
1082 std::vector<PipelineOutput> result;
1083
1084
1085 for (const std::unique_ptr<PipelineInput> &input : inputs) {
1086 result.push_back(Go(*input));
1087 }
1088
1089 return result;
1090}
1091
1093// COMPARISON //
1095
1101public:
1108
1113
1119
1120 // We no longer have a num missing because often generated stars have too low of a signal-to-noise ratio and the centroid algo won't pick them up.
1121};
1122
1127static std::multimap<int, int> FindClosestCentroids(decimal threshold,
1128 const Stars &one,
1129 const Stars &two) {
1130 std::multimap<int, int> result;
1131
1132 for (int i = 0; i < (int)one.size(); i++) {
1133 std::vector<std::pair<decimal, int>> closest;
1134 for (int k = 0; k < (int)two.size(); k++) {
1135 decimal currDistance = (one[i].position - two[k].position).Magnitude();
1136 if (currDistance <= threshold) {
1137 closest.emplace_back(currDistance, k);
1138 }
1139 }
1140 std::sort(closest.begin(), closest.end());
1141 for (const std::pair<decimal, int> &pair : closest) {
1142 result.emplace(i, pair.second);
1143 }
1144 }
1145
1146 return result;
1147}
1148
1155 const Stars &expected,
1156 const Stars &actual) {
1157
1158 // TODO: Somehow penalize when multiple centroids correspond to the same expected star (i.e.,
1159 // one star turned into multiple centroids). That should probably be considered an extra
1160 // centroid, but rn it isn't.
1161
1162 CentroidComparison result;
1163 // maps from indexes in each list to the closest centroid from other list
1164 std::multimap<int, int> actualToExpected = FindClosestCentroids(threshold, actual, expected);
1165
1166 for (int i = 0; i < (int)actualToExpected.size(); i++) {
1167 auto closest = actualToExpected.find(i);
1168 if (closest == actualToExpected.end()) {
1169 result.numExtraCentroids++;
1170 } else {
1171 result.meanError += (actual[i].position - expected[closest->second].position).Magnitude();
1172 result.numCorrectCentroids++;
1173 }
1174 }
1175 result.meanError /= result.numCorrectCentroids;
1176
1177 return result;
1178}
1179
1180CentroidComparison CentroidComparisonsCombine(std::vector<CentroidComparison> comparisons) {
1181 assert(comparisons.size() > 0);
1182
1183 CentroidComparison result;
1184
1185 for (const CentroidComparison &comparison : comparisons) {
1186 result.meanError += comparison.meanError;
1187 result.numCorrectCentroids += comparison.numCorrectCentroids;
1188 result.numExtraCentroids += comparison.numExtraCentroids;
1189 }
1190
1191 result.meanError /= comparisons.size();
1192 result.numExtraCentroids /= comparisons.size();
1193 result.numCorrectCentroids /= comparisons.size();
1194
1195 return result;
1196}
1197
1198// (documentation in hpp)
1200 // use these to map indices to names for the respective lists of StarIdentifiers
1201 const Catalog &expectedCatalog, const Catalog &actualCatalog,
1202 decimal centroidThreshold,
1203 const Stars &expectedStars, const Stars &inputStars) {
1204
1205 StarIdComparison result = {
1206 0, // correct
1207 0, // incorrect
1208 0, // total
1209 };
1210
1211 // EXPECTED STAR IDS
1212
1213 // map from expected star indices to expected catalog indices (basically flattening the expected star-ids)
1214 std::vector<int> expectedCatalogIndices(expectedStars.size(), -1);
1215 for (const StarIdentifier &starId : expected) {
1216 assert(0 <= starId.starIndex && starId.starIndex <= (int)expectedStars.size());
1217 assert(0 <= starId.catalogIndex && starId.catalogIndex <= (int)expectedCatalog.size());
1218 expectedCatalogIndices[starId.starIndex] = starId.catalogIndex;
1219 }
1220
1221 // FIND NEAREST CENTROIDS
1222
1223 std::multimap<int, int> inputToExpectedCentroids = FindClosestCentroids(centroidThreshold, inputStars, expectedStars);
1224 // std::multimap<int, int> expectedToInputCentroids = FindClosestCentroids(centroidThreshold, expectedStars, inputStars);
1225
1226 // COMPUTE TOTAL
1227 // Count the number of expected stars with at least one input star near them
1228 for (int i = 0; i < (int)inputStars.size(); i++) {
1229 // make sure there's at least one expected star near this input star which has an identification
1230 auto closestRange = inputToExpectedCentroids.equal_range(i);
1231 bool found = false;
1232 for (auto it = closestRange.first; it != closestRange.second; it++) {
1233 if (expectedCatalogIndices[it->second] != -1) {
1234 found = true;
1235 break;
1236 }
1237 }
1238 if (found) {
1239 result.numTotal++;
1240 }
1241 }
1242
1243 // COMPUTE CORRECT AND INCORRECT
1244
1245 std::vector<bool> identifiedInputCentroids(inputStars.size(), false);
1246 for (const StarIdentifier &starId : actual) {
1247 // as later, there shouldn't be duplicate starIndex. This indicates a bug in the star-id algorithm, not comparison code.
1248 assert(!identifiedInputCentroids[starId.starIndex]);
1249 identifiedInputCentroids[starId.starIndex] = true;
1250 assert(0 <= starId.starIndex && starId.starIndex <= (int)inputStars.size());
1251 assert(0 <= starId.catalogIndex && starId.catalogIndex <= (int)actualCatalog.size());
1252
1253 // Check that there's at least one expected centroid in range which agrees with your identification.
1254 auto expectedCentroidsInRange = inputToExpectedCentroids.equal_range(starId.starIndex);
1255 bool found = false;
1256 for (auto it = expectedCentroidsInRange.first; it != expectedCentroidsInRange.second; it++) {
1257 int expectedCatalogIndex = expectedCatalogIndices[it->second];
1258 if (expectedCatalogIndex != -1
1259 && expectedCatalog[expectedCatalogIndex].name == actualCatalog[starId.catalogIndex].name) {
1260
1261 result.numCorrect++;
1262 found = true;
1263 break;
1264 }
1265 }
1266
1267 // Either there's no expected centroid in range, or none of them agree with the identification.
1268 if (!found) {
1269 result.numIncorrect++;
1270 }
1271 }
1272
1273 return result;
1274}
1275
1277// PIPELINE OUTPUT //
1279
1280typedef void (*PipelineComparator)(std::ostream &os,
1281 const PipelineInputList &,
1282 const std::vector<PipelineOutput> &,
1283 const PipelineOptions &);
1284
1286static cairo_status_t OstreamPlotter(void *closure, const unsigned char *data, unsigned int length) {
1287 std::ostream *os = (std::ostream *)closure;
1288 os->write((const char *)data, length);
1289 return CAIRO_STATUS_SUCCESS;
1290}
1291
1293static void PipelineComparatorPlotRawInput(std::ostream &os,
1294 const PipelineInputList &expected,
1295 const std::vector<PipelineOutput> &,
1296 const PipelineOptions &) {
1297
1298 cairo_surface_t *cairoSurface = expected[0]->InputImageSurface();
1299 cairo_surface_write_to_png_stream(cairoSurface, OstreamPlotter, &os);
1300 cairo_surface_destroy(cairoSurface);
1301}
1302
1304// TODO: should probably use Expected methods, not Input methods, because future PipelineInputs could add noise to the result of the Input methods.
1305static void PipelineComparatorPlotInput(std::ostream &os,
1306 const PipelineInputList &expected,
1307 const std::vector<PipelineOutput> &,
1308 const PipelineOptions &) {
1309 cairo_surface_t *cairoSurface = expected[0]->InputImageSurface();
1310 assert(expected[0]->InputStars() != NULL);
1311 SurfacePlot("pipeline input",
1312 cairoSurface,
1313 *expected[0]->InputStars(),
1314 expected[0]->InputStarIds(),
1315 &expected[0]->GetCatalog(),
1316 expected[0]->InputAttitude(),
1317 // green
1318 0.0, 1.0, 0.0, 0.6);
1319 cairo_surface_write_to_png_stream(cairoSurface, OstreamPlotter, &os);
1320 cairo_surface_destroy(cairoSurface);
1321}
1322
1323static void PipelineComparatorPlotExpected(std::ostream &os,
1324 const PipelineInputList &expected,
1325 const std::vector<PipelineOutput> &,
1326 const PipelineOptions &) {
1327 cairo_surface_t *cairoSurface = expected[0]->InputImageSurface();
1328 assert(expected[0]->ExpectedStars() != NULL);
1329 SurfacePlot("expected output",
1330 cairoSurface,
1331 *expected[0]->ExpectedStars(),
1332 expected[0]->ExpectedStarIds(),
1333 &expected[0]->GetCatalog(),
1334 expected[0]->ExpectedAttitude(),
1335 // blu
1336 0.2, 0.5, 1.0, 0.7);
1337 cairo_surface_write_to_png_stream(cairoSurface, OstreamPlotter, &os);
1338 cairo_surface_destroy(cairoSurface);
1339}
1340
1342static void PipelineComparatorCentroids(std::ostream &os,
1343 const PipelineInputList &expected,
1344 const std::vector<PipelineOutput> &actual,
1345 const PipelineOptions &values) {
1346 int size = (int)expected.size();
1347
1348 decimal threshold = values.centroidCompareThreshold;
1349
1350 std::vector<CentroidComparison> comparisons;
1351 for (int i = 0; i < size; i++) {
1352 comparisons.push_back(CentroidsCompare(threshold,
1353 *(expected[i]->ExpectedStars()),
1354 *(actual[i].stars)));
1355 }
1356
1357 CentroidComparison result = CentroidComparisonsCombine(comparisons);
1358 os << "centroids_num_correct " << result.numCorrectCentroids << std::endl
1359 << "centroids_num_extra " << result.numExtraCentroids << std::endl
1360 << "centroids_mean_error " << result.meanError << std::endl;
1361}
1362
1363static void PrintCentroids(const std::string &prefix,
1364 std::ostream &os,
1365 const Catalog &catalog,
1366 const std::vector<Stars> &starses,
1367 // May be NULL. Should be the only the first starId, because we don't have any reasonable aggregative action to perform.
1368 const StarIdentifiers *starIds) {
1369 assert(starses.size() > 0);
1370 decimal avgNumStars = 0;
1371 for (const Stars &stars : starses) {
1372 avgNumStars += stars.size();
1373 }
1374 avgNumStars /= starses.size();
1375
1376 os << "num_" << prefix << "_centroids " << avgNumStars << std::endl;
1377 if (starses.size() == 1) {
1378 const Stars &stars = starses[0];
1379 for (int i = 0; i < (int)stars.size(); i++) {
1380 os << prefix << "_centroid_" << i << "_x " << stars[i].position.x << std::endl;
1381 os << prefix << "_centroid_" << i << "_y " << stars[i].position.y << std::endl;
1382 if (starIds) {
1383 for (const StarIdentifier &starId : *starIds) {
1384 if (starId.starIndex == i) {
1385 os << prefix << "_centroid_" << i << "_id " << catalog[starId.catalogIndex].name << std::endl;
1386 }
1387 }
1388 }
1389 }
1390 }
1391}
1392
1394static void PipelineComparatorPrintExpectedCentroids(std::ostream &os,
1395 const PipelineInputList &expected,
1396 const std::vector<PipelineOutput> &, // actual
1397 const PipelineOptions &) {
1398 assert(expected.size() > 0);
1399 assert(expected[0]->ExpectedStars());
1400
1401 std::vector<Stars> expectedStarses;
1402 for (const auto &input : expected) {
1403 expectedStarses.push_back(*input->ExpectedStars());
1404 }
1405 PrintCentroids("expected",
1406 os,
1407 expected[0]->GetCatalog(),
1408 expectedStarses,
1409 expected[0]->ExpectedStarIds());
1410}
1411
1412static void PipelineComparatorPrintInputCentroids(std::ostream &os,
1413 const PipelineInputList &expected,
1414 const std::vector<PipelineOutput> &, // actual
1415 const PipelineOptions &) {
1416 assert(expected.size() > 0);
1417 assert(expected[0]->InputStars());
1418
1419 std::vector<Stars> inputStarses;
1420 for (const auto &input : expected) {
1421 inputStarses.push_back(*input->InputStars());
1422 }
1423 PrintCentroids("input",
1424 os,
1425 expected[0]->GetCatalog(),
1426 inputStarses,
1427 expected[0]->InputStarIds());
1428}
1429
1430static void PipelineComparatorPrintActualCentroids(std::ostream &os,
1431 const PipelineInputList &expected, // expected
1432 const std::vector<PipelineOutput> &actual,
1433 const PipelineOptions &values) {
1434 assert(actual.size() > 0);
1435 assert(actual[0].stars);
1436
1437 std::vector<Stars> actualStarses;
1438 for (const auto &output : actual) {
1439 actualStarses.push_back(*output.stars);
1440 }
1441 PrintCentroids("actual",
1442 os,
1443 actual[0].catalog,
1444 actualStarses,
1445 actual[0].starIds.get());
1446
1447 if (expected.size() == 1 && expected[0]->ExpectedStars() && expected[0]->ExpectedStarIds()) {
1448 // also print expected ID of each one
1449 const Stars &actualStars = *actual[0].stars;
1450 const Stars &expectedStars = *expected[0]->ExpectedStars();
1451 std::multimap<int, int> actualToExpectedCentroids = FindClosestCentroids(values.centroidCompareThreshold, actualStars, expectedStars);
1452 for (int i = 0; i < (int)actualStars.size(); i++) {
1453 auto range = actualToExpectedCentroids.equal_range(i);
1454 auto it = range.first;
1455 auto end = range.second;
1456 for (int j = 0;
1457 it != end;
1458 j++, it++) {
1459
1460 int expectedCentroidIndex = it->second;
1461 bool foundIt = false; // just to be sure
1462 for (const StarIdentifier &starId : *expected[0]->ExpectedStarIds()) {
1463 if (starId.starIndex == expectedCentroidIndex) {
1464 assert(!foundIt);
1465 int expectedName = expected[0]->GetCatalog()[starId.catalogIndex].name;
1466 std::cout << "actual_centroid_" << i << "_expected_id_" << j << " " << expectedName << std::endl;
1467 foundIt = true;
1468 }
1469 }
1470 }
1471 }
1472 }
1473}
1474
1478 const PipelineInputList &expected,
1479 const std::vector<PipelineOutput> &actual,
1480 const PipelineOptions &) {
1481 const Stars &stars = actual[0].stars ? *actual[0].stars : *expected[0]->InputStars();
1482 StarIdentifiers identifiers;
1483 for (int i = 0; i < (int)stars.size(); i++) {
1484 identifiers.push_back(StarIdentifier(i, i));
1485 }
1486 cairo_surface_t *cairoSurface = expected[0]->InputImageSurface();
1487 SurfacePlot("centroid indices (input)",
1488 cairoSurface,
1489 stars,
1490 &identifiers,
1491 &actual[0].catalog,
1492 NULL,
1493 // orange
1494 1.0, 0.5, 0.0, 0.5,
1495 // don't resolve names
1496 true);
1497 cairo_surface_write_to_png_stream(cairoSurface, OstreamPlotter, &os);
1498 cairo_surface_destroy(cairoSurface);
1499}
1500
1502static void PipelineComparatorPlotOutput(std::ostream &os,
1503 const PipelineInputList &expected,
1504 const std::vector<PipelineOutput> &actual,
1505 const PipelineOptions &) {
1506 // don't need to worry about mutating the surface; InputImageSurface returns a fresh one
1507 cairo_surface_t *cairoSurface = expected[0]->InputImageSurface();
1508 SurfacePlot("pipeline output",
1509 cairoSurface,
1510 actual[0].stars ? *actual[0].stars : *expected[0]->InputStars(),
1511 actual[0].starIds.get(),
1512 &actual[0].catalog,
1513 actual[0].attitude.get(),
1514 // red
1515 1.0, 0.0, 0.0, 0.5);
1516 cairo_surface_write_to_png_stream(cairoSurface, OstreamPlotter, &os);
1517 cairo_surface_destroy(cairoSurface);
1518}
1519
1521static void PipelineComparatorStarIds(std::ostream &os,
1522 const PipelineInputList &expected,
1523 const std::vector<PipelineOutput> &actual,
1524 const PipelineOptions &values) {
1525 int numImagesCorrect = 0;
1526 int numImagesIncorrect = 0;
1527 int numImagesTotal = expected.size();
1528 for (int i = 0; i < numImagesTotal; i++) {
1529 // since the actual star IDs exist, it must have gotten input from somewhere!
1530 // TODO: overhaul: It seems that in these comparators there should be a more fundamental way to figure out the input that was actually sent to a stage.
1531 // I.e., instead of having expected and actual arguments, have some sort of PipelineRunSummary object, where the InputStars method looks at actual, then input.
1532 assert(actual[i].stars.get() || expected[i]->InputStars());
1533
1534 const Stars &inputStars = actual[i].stars.get()
1535 ? *actual[i].stars.get()
1536 : *expected[i]->InputStars();
1537 StarIdComparison comparison =
1538 StarIdsCompare(*expected[i]->ExpectedStarIds(), *actual[i].starIds,
1539 expected[i]->GetCatalog(), actual[i].catalog,
1540 values.centroidCompareThreshold, *expected[i]->ExpectedStars(), inputStars);
1541
1542 if (numImagesTotal == 1) {
1543 os << "starid_num_correct " << comparison.numCorrect << std::endl;
1544 os << "starid_num_incorrect " << comparison.numIncorrect << std::endl;
1545 os << "starid_num_total " << comparison.numTotal << std::endl;
1546 }
1547
1548 if (comparison.numCorrect > 0 && comparison.numIncorrect == 0) {
1549 numImagesCorrect++;
1550 }
1551 if (comparison.numIncorrect > 0) {
1552 numImagesIncorrect++;
1553 }
1554 }
1555
1556 // A "correct" image is one where at least two stars are correctly id'd and none are incorrectly id'd
1557 os << "starid_num_images_correct " << numImagesCorrect << std::endl;
1558 os << "starid_num_images_incorrect " << numImagesIncorrect << std::endl;
1559}
1560
1561static void PrintAttitude(std::ostream &os, const std::string &prefix, const Attitude &attitude) {
1562 if (attitude.IsKnown()) {
1563 os << prefix << "attitude_known 1" << std::endl;
1564
1565 EulerAngles spherical = attitude.ToSpherical();
1566 os << prefix << "attitude_ra " << RadToDeg(spherical.ra) << std::endl;
1567 os << prefix << "attitude_de " << RadToDeg(spherical.de) << std::endl;
1568 os << prefix << "attitude_roll " << RadToDeg(spherical.roll) << std::endl;
1569
1570 Quaternion q = attitude.GetQuaternion();
1571 os << prefix << "attitude_i " << q.i << std::endl;
1572 os << prefix << "attitude_j " << q.j << std::endl;
1573 os << prefix << "attitude_k " << q.k << std::endl;
1574 os << prefix << "attitude_real " << q.real << std::endl;
1575
1576 } else {
1577 os << prefix << "attitude_known 0" << std::endl;
1578 }
1579}
1580
1582static void PipelineComparatorPrintAttitude(std::ostream &os,
1583 const PipelineInputList &,
1584 const std::vector<PipelineOutput> &actual,
1585 const PipelineOptions &) {
1586 for (const PipelineOutput &output : actual) {
1587 assert(output.attitude);
1588 PrintAttitude(os, "", *output.attitude);
1589 }
1590}
1591
1592static void PipelineComparatorPrintExpectedAttitude(std::ostream &os,
1593 const PipelineInputList &expected,
1594 const std::vector<PipelineOutput> &,
1595 const PipelineOptions &) {
1596 assert(expected.size() == 1);
1597 assert(expected[0]->ExpectedAttitude());
1598 PrintAttitude(os, "expected_", *expected[0]->ExpectedAttitude());
1599}
1600
1602static void PipelineComparatorAttitude(std::ostream &os,
1603 const PipelineInputList &expected,
1604 const std::vector<PipelineOutput> &actual,
1605 const PipelineOptions &values) {
1606
1607 // TODO: use Wahba loss function (maybe average per star) instead of just angle. Also break
1608 // apart roll error from boresight error. This is just quick and dirty for testing
1609
1610 decimal angleThreshold = DegToRad(values.attitudeCompareThreshold);
1611
1612 decimal attitudeErrorSum = 0.0f;
1613 int numCorrect = 0;
1614 int numIncorrect = 0;
1615
1616 for (int i = 0; i < (int)expected.size(); i++) {
1617 if (actual[i].attitude->IsKnown()) {
1618 Quaternion expectedQuaternion = expected[i]->ExpectedAttitude()->GetQuaternion();
1619 Quaternion actualQuaternion = actual[i].attitude->GetQuaternion();
1620 decimal attitudeError = (expectedQuaternion * actualQuaternion.Conjugate()).SmallestAngle();
1621 assert(attitudeError >= 0);
1622
1623 if (attitudeError <= angleThreshold) {
1624 attitudeErrorSum += attitudeError;
1625 numCorrect++;
1626 } else {
1627 numIncorrect++;
1628 }
1629 }
1630 }
1631
1632 decimal attitudeErrorMean = DECIMAL(attitudeErrorSum) / numCorrect;
1633 decimal fractionCorrect = DECIMAL(numCorrect) / expected.size();
1634 decimal fractionIncorrect = DECIMAL(numIncorrect) / expected.size();
1635
1636 os << "attitude_error_mean " << attitudeErrorMean << std::endl;
1637 os << "attitude_availability " << fractionCorrect << std::endl;
1638 os << "attitude_error_rate " << fractionIncorrect << std::endl;
1639}
1640
1641static void PrintTimeStats(std::ostream &os, const std::string &prefix, const std::vector<long long> &times) {
1642 assert(times.size() > 0);
1643
1644 // print average, min, max, and 95% max
1645 long long sum = 0;
1646 long long min = LONG_MAX;
1647 long long max = 0;
1648 for (int i = 0; i < (int)times.size(); i++) {
1649 assert(times[i] > 0);
1650 sum += times[i];
1651 min = std::min(min, times[i]);
1652 max = std::max(max, times[i]);
1653 }
1654 long average = sum / times.size();
1655 std::vector<long long> sortedTimes = times;
1656 std::sort(sortedTimes.begin(), sortedTimes.end());
1657 // what really is the 95th percentile? Being conservative, we want to pick a value that at least
1658 // 95% of the times are less than. This means: (1) finding the number of times, (2) Finding
1659 // Math.ceil(0.95 * numTimes), and (3) subtracting 1 to get the index.
1660 int ninetyFiveIndex = (int)std::ceil(0.95 * times.size()) - 1;
1661 assert(ninetyFiveIndex >= 0);
1662 long long ninetyFifthPercentile = sortedTimes[ninetyFiveIndex];
1663
1664 os << prefix << "_average_ns " << average << std::endl;
1665 os << prefix << "_min_ns " << min << std::endl;
1666 os << prefix << "_max_ns " << max << std::endl;
1667 os << prefix << "_95%_ns " << ninetyFifthPercentile << std::endl;
1668}
1669
1671static void PipelineComparatorPrintSpeed(std::ostream &os,
1672 const PipelineInputList &,
1673 const std::vector<PipelineOutput> &actual,
1674 const PipelineOptions &) {
1675 std::vector<long long> centroidingTimes;
1676 std::vector<long long> starIdTimes;
1677 std::vector<long long> attitudeTimes;
1678 std::vector<long long> totalTimes;
1679 for (int i = 0; i < (int)actual.size(); i++) {
1680 long long totalTime = 0;
1681 if (actual[i].centroidingTimeNs > 0) {
1682 centroidingTimes.push_back(actual[i].centroidingTimeNs);
1683 totalTime += actual[i].centroidingTimeNs;
1684 }
1685 if (actual[i].starIdTimeNs > 0) {
1686 starIdTimes.push_back(actual[i].starIdTimeNs);
1687 totalTime += actual[i].starIdTimeNs;
1688 }
1689 if (actual[i].attitudeEstimationTimeNs > 0) {
1690 attitudeTimes.push_back(actual[i].attitudeEstimationTimeNs);
1691 totalTime += actual[i].attitudeEstimationTimeNs;
1692 }
1693 totalTimes.push_back(totalTime);
1694 }
1695 if (centroidingTimes.size() > 0) {
1696 PrintTimeStats(os, "centroiding", centroidingTimes);
1697 }
1698 if (starIdTimes.size() > 0) {
1699 PrintTimeStats(os, "starid", starIdTimes);
1700 }
1701 if (attitudeTimes.size() > 0) {
1702 PrintTimeStats(os, "attitude", attitudeTimes);
1703 }
1704 if (centroidingTimes.size() > 0 || starIdTimes.size() > 0 || attitudeTimes.size() > 0) {
1705 PrintTimeStats(os, "total", totalTimes);
1706 }
1707}
1708
1709// TODO: add these debug comparators back in!
1710// void PipelineComparatorPrintPairDistance(std::ostream &os,
1711// const PipelineInputList &expected,
1712// const std::vector<PipelineOutput> &actual) {
1713// int index1 = Prompt<int>("Index of first star");
1714// int index2 = Prompt<int>("Index of second star");
1715
1716// const Camera &camera = *expected[0]->InputCamera();
1717// const Stars &stars = *actual[0].stars;
1718
1719// assert(index1 >= 0 && index2 >= 0 && index1 < (int)stars.size() && index2 < (int)stars.size());
1720// os << "pair_distance " << Angle(camera.CameraToSpatial(stars[index1].position),
1721// camera.CameraToSpatial(stars[index2].position))
1722// << std::endl;
1723// }
1724
1725// void PipelineComparatorPrintPyramidDistances(std::ostream &os,
1726// const PipelineInputList &expected,
1727// const std::vector<PipelineOutput> &actual) {
1728// int index1 = Prompt<int>("Catalog name/index of first star");
1729// int index2 = Prompt<int>("Catalog name/index of second star");
1730// int index3 = Prompt<int>("Catalog name/index of third star");
1731// int index4 = Prompt<int>("Catalog name/index of four star");
1732
1733// const Camera &camera = *expected[0]->InputCamera();
1734// const Stars &stars = *actual[0].stars;
1735
1736// Vec3 spatial1 = camera.CameraToSpatial(stars[index1].position);
1737// Vec3 spatial2 = camera.CameraToSpatial(stars[index2].position);
1738// Vec3 spatial3 = camera.CameraToSpatial(stars[index3].position);
1739// Vec3 spatial4 = camera.CameraToSpatial(stars[index4].position);
1740
1741// std::cout << "pair_distance_12 " << Angle(spatial1, spatial2) << std::endl;
1742// std::cout << "pair_distance_13 " << Angle(spatial1, spatial3) << std::endl;
1743// std::cout << "pair_distance_14 " << Angle(spatial1, spatial4) << std::endl;
1744// std::cout << "pair_distance_23 " << Angle(spatial2, spatial3) << std::endl;
1745// std::cout << "pair_distance_24 " << Angle(spatial2, spatial4) << std::endl;
1746// std::cout << "pair_distance_34 " << Angle(spatial3, spatial4) << std::endl;
1747// }
1748
1749// void PipelineComparatorPrintTripleAngle(std::ostream &os,
1750// const PipelineInputList &expected,
1751// const std::vector<PipelineOutput> &actual) {
1752// int index1 = Prompt<int>("Index of first star");
1753// int index2 = Prompt<int>("Index of second star");
1754// int index3 = Prompt<int>("Index of third star");
1755
1756// const Camera &camera = *expected[0]->InputCamera();
1757// const Stars &stars = *actual[0].stars;
1758
1759// assert(index1 >= 0 && index1 < (int)stars.size());
1760// assert(index2 >= 0 && index2 < (int)stars.size());
1761// assert(index3 >= 0 && index3 < (int)stars.size());
1762
1763// // TODO, when merging with nondimensional branch
1764// }
1765
1771 const std::vector<PipelineOutput> &actual,
1772 const PipelineOptions &values) {
1773 if (actual.size() == 0) {
1774 std::cerr << "ERROR: No output! Did you specify any input images? Try --png or --generate." << std::endl;
1775 exit(1);
1776 }
1777
1778 assert(expected.size() == actual.size() && expected.size() > 0);
1779
1780 // TODO: Remove the asserts and print out more reasonable error messages.
1781
1782#define LOST_PIPELINE_COMPARE(precondition, errmsg, comparator, path, isBinary) do { \
1783 if (precondition) { \
1784 UserSpecifiedOutputStream pos(path, isBinary); \
1785 comparator(pos.Stream(), expected, actual, values); \
1786 } else { \
1787 std::cerr << "ERROR: Comparator not applicable: " << errmsg << std::endl; \
1788 exit(1); \
1789 } \
1790 } while (0)
1791
1792 if (values.plotRawInput != "") {
1793 LOST_PIPELINE_COMPARE(expected[0]->InputImage() && expected.size() == 1,
1794 "--plot-raw-input requires exactly 1 input image, but " + std::to_string(expected.size()) + " many were provided.",
1795 PipelineComparatorPlotRawInput, values.plotRawInput, true);
1796 }
1797
1798 if (values.plotInput != "") {
1799 LOST_PIPELINE_COMPARE(expected[0]->InputImage() && expected.size() == 1 && expected[0]->InputStars(),
1800 "--plot-input requires exactly 1 input image, and for centroids to be available on that input image. " + std::to_string(expected.size()) + " many input images were provided.",
1801 PipelineComparatorPlotInput, values.plotInput, true);
1802 }
1803 if (values.plotExpected != "") {
1804 LOST_PIPELINE_COMPARE(expected[0]->InputImage() && expected.size() == 1 && expected[0]->ExpectedStars(),
1805 "--plot-expected-input requires exactly 1 input image, and for expected centroids to be available on that input image. " + std::to_string(expected.size()) + " many input images were provided.",
1806 PipelineComparatorPlotExpected, values.plotExpected, true);
1807 }
1808 if (values.plotOutput != "") {
1809 LOST_PIPELINE_COMPARE(actual.size() == 1 && (actual[0].stars || actual[0].starIds),
1810 "--plot-output requires exactly 1 output image, and for either centroids or star IDs to be available on that output image. " + std::to_string(actual.size()) + " many output images were provided.",
1811 PipelineComparatorPlotOutput, values.plotOutput, true);
1812 }
1813 if (values.printExpectedCentroids != "") {
1814 LOST_PIPELINE_COMPARE(expected[0]->ExpectedStars(),
1815 "--print-expected-centroids requires at least 1 input with expected centroids. " + std::to_string(expected.size()) + " many input images were provided.",
1816 PipelineComparatorPrintExpectedCentroids, values.printExpectedCentroids, false);
1817 }
1818 if (values.printInputCentroids != "") {
1819 LOST_PIPELINE_COMPARE(expected[0]->InputStars(),
1820 "--print-input-centroids requires at least 1 input with centroids. " + std::to_string(expected.size()) + " many input images were provided.",
1821 PipelineComparatorPrintInputCentroids, values.printInputCentroids, false);
1822 }
1823 if (values.printActualCentroids != "") {
1824 LOST_PIPELINE_COMPARE(actual[0].stars,
1825 "--print-actual-centroids requires at least 1 output image, and for centroids to be available on the output images. " + std::to_string(actual.size()) + " many output images were provided.",
1826 PipelineComparatorPrintActualCentroids, values.printActualCentroids, false);
1827 }
1828 if (values.plotCentroidIndices != "") {
1829 LOST_PIPELINE_COMPARE(expected.size() == 1 && expected[0]->InputImage(),
1830 "--plot-centroid-indices requires exactly 1 input with image. " + std::to_string(expected.size()) + " many inputs were provided.",
1832 }
1833 if (values.compareCentroids != "") {
1834 LOST_PIPELINE_COMPARE(actual[0].stars && expected[0]->ExpectedStars() && values.centroidCompareThreshold,
1835 "--compare-centroids requires at least 1 output image, and for expected centroids to be available on the input image. " + std::to_string(actual.size()) + " many output images were provided.",
1836 PipelineComparatorCentroids, values.compareCentroids, false);
1837 }
1838 if (values.compareStarIds != "") {
1839 LOST_PIPELINE_COMPARE(expected[0]->ExpectedStarIds() && actual[0].starIds && expected[0]->ExpectedStars(),
1840 "--compare-star-ids requires at least 1 output image, and for expected star IDs and centroids to be available on the input image. " + std::to_string(actual.size()) + " many output images were provided.",
1841 PipelineComparatorStarIds, values.compareStarIds, false);
1842 }
1843 if (values.printAttitude != "") {
1844 LOST_PIPELINE_COMPARE(std::all_of(actual.begin(), actual.end(), [](const PipelineOutput &output) { return output.attitude != nullptr; }),
1845 "--print-attitude requires attitude to be available on every output image. " + std::to_string(actual.size()) + " many output images were provided.",
1846 PipelineComparatorPrintAttitude, values.printAttitude, false);
1847 }
1848 if (values.printExpectedAttitude != "") {
1849 LOST_PIPELINE_COMPARE(expected[0]->ExpectedAttitude() && expected.size() == 1,
1850 "--print-expected-attitude requires exactly 1 input image, and for expected attitude to be available on that input image. " + std::to_string(expected.size()) + " many input images were provided.",
1851 PipelineComparatorPrintExpectedAttitude, values.printExpectedAttitude, false);
1852 }
1853 if (values.compareAttitudes != "") {
1854 LOST_PIPELINE_COMPARE(actual[0].attitude && expected[0]->ExpectedAttitude() && values.attitudeCompareThreshold,
1855 "--compare-attitudes requires at least 1 output image, and for expected attitude to be available on the input image. " + std::to_string(actual.size()) + " many output images were provided.",
1856 PipelineComparatorAttitude, values.compareAttitudes, false);
1857 }
1858 if (values.printSpeed != "") {
1859 LOST_PIPELINE_COMPARE(actual.size() > 0,
1860 // I don't think this should ever actually happen??
1861 "--print-speed requires at least 1 output image. " + std::to_string(actual.size()) + " many output images were provided.",
1862 PipelineComparatorPrintSpeed, values.printSpeed, false);
1863 }
1864
1865#undef LOST_PIPELINE_COMPARE
1866}
1867
1868// TODO: Add CLI options for all the inspectors!
1869
1870// typedef void (*CatalogInspector)(const Catalog &);
1871
1872// static std::vector<const CatalogStar *> PromptCatalogStars(const Catalog &catalog, int howMany) {
1873// std::vector<const CatalogStar *> result;
1874// for (int i = 0; i < howMany; i++) {
1875// int name = Prompt<int>("Catalog name of " + std::to_string(i) + "-th star");
1876// const CatalogStar *star = findNamedStar(catalog, name);
1877// if (star == NULL) {
1878// std::cerr << "Star not found!" << std::endl;
1879// exit(1);
1880// }
1881// result.push_back(star);
1882// }
1883// return result;
1884// }
1885
1886// void InspectPairDistance(const Catalog &catalog) {
1887// auto stars = PromptCatalogStars(catalog, 2);
1888
1889// // TODO: not cout, prompt for an ostream in inspect and pass argument
1890// std::cout << Angle(stars[0]->spatial, stars[1]->spatial) << std::endl;
1891// }
1892
1893// void InspectPyramidDistances(const Catalog &catalog) {
1894// auto stars = PromptCatalogStars(catalog, 4);
1895
1896// std::cout << "pair_distance_01 " << Angle(stars[0]->spatial, stars[1]->spatial) << std::endl;
1897// std::cout << "pair_distance_02 " << Angle(stars[0]->spatial, stars[2]->spatial) << std::endl;
1898// std::cout << "pair_distance_03 " << Angle(stars[0]->spatial, stars[3]->spatial) << std::endl;
1899// std::cout << "pair_distance_12 " << Angle(stars[1]->spatial, stars[2]->spatial) << std::endl;
1900// std::cout << "pair_distance_13 " << Angle(stars[1]->spatial, stars[3]->spatial) << std::endl;
1901// std::cout << "pair_distance_23 " << Angle(stars[2]->spatial, stars[3]->spatial) << std::endl;
1902// }
1903
1904// void InspectTripleAngle(const Catalog &catalog) {
1905// auto stars = PromptCatalogStars(catalog, 3);
1906
1907// // TODO
1908// }
1909
1910// void InspectFindStar(const Catalog &catalog) {
1911// std::string raStr = PromptLine("Right Ascension");
1912
1913// decimal raRadians;
1914
1915// int raHours, raMinutes;
1916// decimal raSeconds;
1917// int raFormatTime = sscanf(raStr.c_str(), "%dh %dm %fs", &raHours, &raMinutes, &raSeconds);
1918
1919// decimal raDeg;
1920// int raFormatDeg = sscanf(raStr.c_str(), "%f", &raDeg);
1921
1922// if (raFormatTime == 3) {
1923// raRadians = (raHours * 2*DECIMAL_M_PI/24) + (raMinutes * 2*DECIMAL_M_PI/24/60) + (raSeconds * 2*DECIMAL_M_PI/24/60/60);
1924// } else if (raFormatDeg == 1) {
1925// raRadians = DegToRad(raFormatDeg);
1926// } else {
1927// std::cerr << "Invalid right ascension format. Do \"09h 38m 29.8754s\" or a number of degrees." << std::endl;
1928// exit(1);
1929// }
1930
1931// std::string deStr = PromptLine("Declination");
1932
1933// decimal deRadians;
1934
1935// int deDegPart, deMinPart;
1936// decimal deSecPart;
1937// char dummy[8];
1938// int deFormatParts = sscanf(deStr.c_str(), "%d%s %d%s %f%s", &deDegPart, dummy, &deMinPart, dummy, &deSecPart, dummy);
1939
1940// decimal deDeg;
1941// int deFormatDeg = sscanf(deStr.c_str(), "%f", &deDeg);
1942
1943// if (deFormatParts == 6) {
1944// deRadians = DegToRad(deDegPart + (decimal)deMinPart/60 + (decimal)deSecPart/60/60);
1945// } else if (deFormatDeg == 1) {
1946// deRadians = DegToRad(deFormatDeg);
1947// } else {
1948// std::cerr << "Invalid declination format." << std::endl;
1949// exit(1);
1950// }
1951
1952// // find the star
1953
1954// decimal tolerance = 0.001;
1955// Vec3 userSpatial = SphericalToSpatial(raRadians, deRadians);
1956// int i = 0;
1957// for (const CatalogStar &curStar : catalog) {
1958// if ((curStar.spatial - userSpatial).Magnitude() < tolerance) {
1959// std::cout << "found_star_" << i << " " << curStar.name << std::endl;
1960// std::cout << "fonud_star_magnitude_" << i << " " << curStar.magnitude << std::endl;
1961// i++;
1962// }
1963// }
1964// if (i == 0) {
1965// std::cerr << "No stars found" << std::endl;
1966// }
1967// }
1968
1969// void InspectPrintStar(const Catalog &catalog) {
1970// auto stars = PromptCatalogStars(catalog, 1);
1971// decimal ra, de;
1972// SpatialToSpherical(stars[0]->spatial, &ra, &de);
1973
1974// std::cout << "star_ra " << RadToDeg(ra) << std::endl;
1975// std::cout << "star_de " << RadToDeg(de) << std::endl;
1976// }
1977
1978// void InspectCatalog() {
1979// InteractiveChoice<CatalogInspector> inspectorChoice;
1980// inspectorChoice.Register("pair_distance", "pair distance angle", InspectPairDistance);
1981// inspectorChoice.Register("pyramid_distances", "all pair distances in pyramid", InspectPyramidDistances);
1982// inspectorChoice.Register("triple_angle", "inner angle of a triangle", InspectTripleAngle);
1983// inspectorChoice.Register("find_star", "find a star name based on ra/de", InspectFindStar);
1984// inspectorChoice.Register("print_star", "print coordinates of a star", InspectPrintStar);
1985// (*inspectorChoice.Prompt("Inspect the catalog"))(CatalogRead());
1986// }
1987
1988} // namespace lost
An attitude estimation algorithm estimates the orientation of the camera based on identified stars.
The attitude (orientation) of a spacecraft.
EulerAngles ToSpherical() const
Get the euler angles from the attitude, converting from whatever format is stored.
Quaternion GetQuaternion() const
Get the quaternion representing the attitude, converting from whatever format is stored.
A full description of a camera. Enough information to reconstruct the camera matrix and then some.
Definition camera.hpp:9
int XResolution() const
Width of the sensor in pixels.
Definition camera.hpp:38
int YResolution() const
Height of the sensor in pixels.
Definition camera.hpp:40
decimal Fov() const
Horizontal field of view in radians.
Definition camera.cpp:66
decimal FocalLength() const
Focal length in pixels.
Definition camera.hpp:42
A star from the Bright Star Catalog.
decimal magnitude
The apparent magnitude of the star (e.g., Sirius = -1.46, Polaris = 1.98).
A simple, fast, and pretty decent centroid algorithm.
An algorithm that detects the (x,y) coordinates of bright points in an image, called "centroids".
The result of comparing actual and expected centroids Used for debugging and benchmarking.
Definition io.cpp:1100
decimal numExtraCentroids
Stars in actual but not expected.
Definition io.cpp:1118
decimal numCorrectCentroids
Number of actual stars within the centroiding threshold of an expected star.
Definition io.cpp:1112
decimal meanError
Average distance from actual to expected centroids (in pixels) Only correct centroids are considered ...
Definition io.cpp:1107
Command line options when using the database command.
Definition io.hpp:346
int tetraPatternStarsPerFov
Definition io.hpp:360
long kvectorNumDistanceBins
Definition io.hpp:354
bool swapDecimalEndianness
Definition io.hpp:356
decimal kvectorMaxDistance
Definition io.hpp:353
decimal kvectorMinDistance
Definition io.hpp:352
decimal tetraMaxFov
Definition io.hpp:358
bool swapIntegerEndianness
Definition io.hpp:355
A slow but reliable attitude estimation algorithm.
A centroid algorithm for debugging that returns random centroids.
A star-id algorithm that returns random results. For debugging.
Definition star-id.hpp:57
A "human-readable" way to represent a 3d rotation or orientation.
decimal roll
How far we roll counterclockwise. Roll is performed last (after yaw and pitch).
decimal de
Declination. How far we pitch up (or down if negative). Pitch is performed second,...
decimal ra
Right ascension. How far we yaw left. Yaw is performed first.
A pipeline input which is generated (fake image).
Definition io.hpp:183
GeneratedPipelineInput(const Catalog &, Attitude, Camera, std::default_random_engine *, bool centroidsOnly, decimal observedReferenceBrightness, decimal starSpreadStdDev, decimal sensitivity, decimal darkCurrent, decimal readNoiseStdDev, Attitude motionBlurDirection, decimal exposureTime, decimal readoutTime, bool shotNoise, int oversampling, int numFalseStars, decimal falseMinMagnitude, decimal falseMaxMagnitude, decimal cutoffMag, decimal perturbationStddev)
Create a generated pipeline input.
Definition io.cpp:533
A star used in simulated image generation. Contains extra data about how to simulate the star.
Definition io.cpp:463
decimal peakBrightness
the brightness density per time unit at the center of the star. 0.0 is black, 1.0 is white.
Definition io.cpp:469
GeneratedStar(Star star, decimal peakBrightness, Vec2 motionBlurDelta)
Definition io.cpp:465
Vec2 delta
(only meaningful with motion blur) Where the star will appear one time unit in the future.
Definition io.cpp:472
A star-id algorithm based on assigning votes for each centroid-catalog pair then choosing the highest...
Definition star-id.hpp:66
An 8-bit grayscale 2d image.
Definition io.hpp:57
unsigned char * image
The raw pixel data in the image.
Definition io.hpp:63
int height
Definition io.hpp:66
int width
Definition io.hpp:65
A more complicated centroid algorithm which doesn't perform much better than CenterOfGravityAlgorithm...
const unsigned char * SubDatabasePointer(int32_t magicValue) const
MultiDatabase memory layout:
static const int32_t kMagicValue
Magic value to use when storing inside a MultiDatabase.
Definition databases.hpp:72
Represents the input and expected outputs of a pipeline run.
Definition io.hpp:152
virtual const Image * InputImage() const
Definition io.hpp:156
virtual const Catalog & GetCatalog() const =0
The catalog to which catalog indexes returned from other methods refer.
virtual const StarIdentifiers * InputStarIds() const
The centroid indices in the StarIdentifiers returned from InputStarIds should be indices into InputSt...
Definition io.hpp:162
virtual const Stars * InputStars() const
Definition io.hpp:159
cairo_surface_t * InputImageSurface() const
Convert the InputImage() output into a cairo surface.
Definition io.cpp:345
virtual const Camera * InputCamera() const
Definition io.hpp:165
The command line options passed when running a pipeline.
Definition io.hpp:75
decimal generateDe
Definition io.hpp:129
std::string compareStarIds
Definition io.hpp:114
decimal generateExposure
Definition io.hpp:135
std::string compareCentroids
Definition io.hpp:113
bool generateCentroidsOnly
Definition io.hpp:121
std::string compareAttitudes
Definition io.hpp:115
int generateNumFalseStars
Definition io.hpp:138
std::string plotRawInput
Definition io.hpp:102
std::string attitudeAlgo
Definition io.hpp:94
bool generateRandomAttitudes
Definition io.hpp:131
std::string printSpeed
Definition io.hpp:112
decimal attitudeCompareThreshold
Definition io.hpp:101
decimal generateFalseMaxMag
Definition io.hpp:140
decimal generateSpreadStdDev
Definition io.hpp:124
int centroidDummyNumStars
Definition io.hpp:86
decimal generatePerturbationStddev
Definition io.hpp:141
decimal generateSaturationPhotons
Definition io.hpp:123
decimal focalLength
Definition io.hpp:80
std::string printActualCentroids
Definition io.hpp:109
decimal centroidMagFilter
Definition io.hpp:87
std::string plotInput
Definition io.hpp:103
decimal generateCutoffMag
Definition io.hpp:142
std::string imageDir
Definition io.hpp:79
int centroidFilterBrightest
Definition io.hpp:88
std::string printExpectedAttitude
Definition io.hpp:111
decimal centroidCompareThreshold
Definition io.hpp:100
std::string printAttitude
Definition io.hpp:110
decimal generateBlurRoll
Definition io.hpp:134
decimal angularTolerance
Definition io.hpp:91
decimal tetraPatternSearchRange
Definition io.hpp:96
std::string databasePath
Definition io.hpp:89
decimal maxMismatchProb
Definition io.hpp:93
std::string plotCentroidIndices
Definition io.hpp:105
decimal generateBlurRa
Definition io.hpp:132
std::vector< std::string > png
Definition io.hpp:78
std::string plotExpected
Definition io.hpp:104
std::string printExpectedCentroids
Definition io.hpp:107
decimal generateFalseMinMag
Definition io.hpp:139
decimal generateRoll
Definition io.hpp:130
decimal pixelSize
Definition io.hpp:81
std::string tetraPairingMode
Definition io.hpp:95
std::string printInputCentroids
Definition io.hpp:108
decimal generateBlurDe
Definition io.hpp:133
int estimatedNumFalseStars
Definition io.hpp:92
decimal generateReadoutTime
Definition io.hpp:136
decimal tetraPatternMatchTolerance
Definition io.hpp:97
decimal generateDarkCurrent
Definition io.hpp:126
decimal generateZeroMagPhotons
Definition io.hpp:122
std::string idAlgo
Definition io.hpp:90
std::string centroidAlgo
Definition io.hpp:85
decimal generateReadNoiseStdDev
Definition io.hpp:127
decimal generateRa
Definition io.hpp:128
std::string plotOutput
Definition io.hpp:106
Pipeline()=default
PipelineOutput Go(const PipelineInput &)
Run all stages of a pipeline.
Definition io.cpp:979
PngPipelineInput(cairo_surface_t *, Camera, const Catalog &)
Pipeline input for an image that's already been identified using Astrometry.net.
Definition io.cpp:371
The "de facto" star-id algorithm used in many real-world missions.
Definition star-id.hpp:83
A quaternion is a common way to represent a 3d rotation.
decimal Angle() const
How many radians the rotation represented by this quaternion has.
Vec3 Rotate(const Vec3 &) const
Rotate a 3d vector according to the rotation represented by the quaternion.
decimal SmallestAngle() const
Returns the smallest angle that can be used to represent the rotation represented by the quaternion.
A faster and just as accurate attitude estimator as the Davenport Q algorithm.
std::vector< unsigned char > buffer
A star idenification algorithm.
Definition star-id.hpp:14
Records that a certain Star (detected in the image) corresponds to a certain CatalogStar.
A "centroid" detected in an image.
Star(decimal x, decimal y, decimal radiusX, decimal radiusY, decimal magnitude)
decimal radiusY
Approximate vertical radius of the bright area in pixels.
Vec2 position
The (x,y) pixel coordinates in the image (top left is 0,0).
decimal radiusX
Approximate horizontal radius of the bright area in pixels.
static const int32_t kMagicValue
Magic value to use when storing inside a MultiDatabase.
Tetra star identification algorithm based on the one originally proposed by Brown & Stubis Creates pa...
Definition star-id.hpp:29
A fast attitude estimator which only takes into account information from two stars.
UserSpecifiedOutputStream(std::string filePath, bool isBinary)
Create a PromptedOutputStream which will output to the given file.
Definition io.cpp:36
Three dimensional vector with decimaling point components.
double decimal
Definition decimal.hpp:8
#define DECIMAL_ASIN(x)
Definition decimal.hpp:52
#define DECIMAL_LOG(x)
Definition decimal.hpp:38
#define DECIMAL(x)
Definition decimal.hpp:18
#define DECIMAL_POW(base, power)
Definition decimal.hpp:36
#define DECIMAL_M_PI
Definition decimal.hpp:26
#define DECIMAL_CEIL(x)
Definition decimal.hpp:44
#define DECIMAL_SQRT(x)
Definition decimal.hpp:37
#define DECIMAL_ERF(x)
Definition decimal.hpp:40
#define DECIMAL_EXP(x)
Definition decimal.hpp:39
#define DECIMAL_FLOOR(x)
Definition decimal.hpp:45
#define DEFAULT_BSC_PATH
Definition io.cpp:92
#define LOST_PIPELINE_COMPARE(precondition, errmsg, comparator, path, isBinary)
LOST starting point.
decimal FovToFocalLength(decimal xFov, decimal xResolution)
Definition camera.cpp:58
CentroidComparison CentroidComparisonsCombine(std::vector< CentroidComparison > comparisons)
Definition io.cpp:1180
unsigned char * SurfaceToGrayscaleImage(cairo_surface_t *cairoSurface)
Convert a colored Cairo image surface into a row-major array of grayscale pixels.
Definition io.cpp:124
decimal FocalLengthFromOptions(const PipelineOptions &values, int xResolution)
Calculate the focal length, in pixels, based on the given command line options.
Definition io.cpp:324
const int32_t kCatalogMagicValue
Definition databases.hpp:15
std::vector< StarIdentifier > StarIdentifiers
void SerializeCatalog(SerializeContext *ser, const Catalog &catalog, bool inclMagnitude, bool inclName)
Serialize the catalog to buffer.
Catalog DeserializeCatalog(DeserializeContext *des, bool *inclMagnitudeReturn, bool *inclNameReturn)
Deserialize a catalog.
const Catalog & CatalogRead()
Read and parse the full catalog from disk. If called multiple times, will re-use the first result.
Definition io.cpp:96
std::vector< Star > Stars
decimal DegToRad(decimal deg)
Quaternion SphericalToQuaternion(decimal ra, decimal dec, decimal roll)
Return a quaternion that will reorient the coordinate axes so that the x-axis points at the given rig...
std::vector< MultiDatabaseEntry > MultiDatabaseDescriptor
decimal RadToDeg(decimal rad)
void PipelineComparatorPlotCentroidIndices(std::ostream &os, const PipelineInputList &expected, const std::vector< PipelineOutput > &actual, const PipelineOptions &)
Plot an annotated image where centroids are annotated with their centroid index.
Definition io.cpp:1477
void SerializeTetraDatabase(SerializeContext *ser, const Catalog &catalog, decimal maxFovDeg, const std::vector< uint16_t > &catalogPatternStarInds, int numEdgeRatioBins)
PipelineInputList GetPngPipelineInput(const PipelineOptions &values)
Definition io.cpp:402
std::vector< CatalogStar > BscParse(std::string tsvPath)
Parse the bright star catalog from the TSV file on disk.
Definition io.cpp:60
void SurfacePlot(std::string description, cairo_surface_t *cairoSurface, const Stars &stars, const StarIdentifiers *starIds, const Catalog *catalog, const Attitude *attitude, double red, double green, double blue, double alpha, bool rawStarIndexes=false)
Plot information about an image onto the image using Cairo.
Definition io.cpp:175
StarIdComparison StarIdsCompare(const StarIdentifiers &expected, const StarIdentifiers &actual, const Catalog &expectedCatalog, const Catalog &actualCatalog, decimal centroidThreshold, const Stars &expectedStars, const Stars &inputStars)
Compare expected and actual star identifications.
Definition io.cpp:1199
void SerializePairDistanceKVector(SerializeContext *ser, const Catalog &catalog, decimal minDistance, decimal maxDistance, long numBins)
Serialize a pair-distance KVector into buffer.
const int kMaxBrightness
Definition io.cpp:527
std::vector< uint16_t > TetraPreprocessCatalog(const Catalog &catalog, const decimal maxFovDeg, int numPatternStarsPerFov)
void(* PipelineComparator)(std::ostream &os, const PipelineInputList &, const std::vector< PipelineOutput > &, const PipelineOptions &)
Definition io.cpp:1280
MultiDatabaseDescriptor GenerateDatabases(const Catalog &catalog, const DatabaseOptions &values)
Appropriately create descriptors for all requested databases according to command-line options.
Definition io.cpp:270
SerializeContext serFromDbValues(const DatabaseOptions &values)
Definition io.cpp:266
std::vector< std::unique_ptr< PipelineInput > > PipelineInputList
Definition io.hpp:222
PipelineInputList GetPipelineInput(const PipelineOptions &values)
Come up with a list of pipeline inputs based on command line options.
Definition io.cpp:858
void PipelineComparison(const PipelineInputList &expected, const std::vector< PipelineOutput > &actual, const PipelineOptions &values)
Print or otherwise analyze the results of (perhaps multiple) runs of a star tracking pipeline.
Definition io.cpp:1770
Pipeline SetPipeline(const PipelineOptions &values)
Create a pipeline from command line options.
Definition io.cpp:894
CentroidComparison CentroidsCompare(decimal threshold, const Stars &expected, const Stars &actual)
Compare expected and actual centroids.
Definition io.cpp:1154
std::ostream & operator<<(std::ostream &output, const Vec2 &vec)
PipelineInputList GetGeneratedPipelineInput(const PipelineOptions &values)
Create a GeneratedPipelineInput based on the command line options in values.
Definition io.cpp:786
std::vector< CatalogStar > Catalog
cairo_surface_t * GrayscaleImageToSurface(const unsigned char *image, const int width, const int height)
Definition io.cpp:153
decimal MagToBrightness(decimal mag)
returns some relative brightness measure, which is proportional to the total number of photons receiv...
The result of running a pipeline.
Definition io.hpp:250
Catalog catalog
The catalog that the indices in starIds refer to.
Definition io.hpp:265
long long centroidingTimeNs
How many nanoseconds the centroiding stage of the pipeline took.
Definition io.hpp:257
std::unique_ptr< Stars > stars
Definition io.hpp:251
long long starIdTimeNs
Definition io.hpp:258
long long attitudeEstimationTimeNs
Definition io.hpp:259
std::unique_ptr< Attitude > attitude
Definition io.hpp:253
std::unique_ptr< StarIdentifiers > starIds
Definition io.hpp:252
The result of comparing an actual star identification with the true star idenification,...
Definition io.hpp:269
int numCorrect
The number of centroids in the image which are close to an expected centroid that had an expected ide...
Definition io.hpp:272
int numTotal
The number of centroids sufficiently close to a true expected star.
Definition io.hpp:280
int numIncorrect
The number of centroids which were either:
Definition io.hpp:277
A two dimensional vector with decimaling point components.
decimal MagnitudeSq() const
The square of the magnitude.
decimal Magnitude() const