Files
star-map/tools/etl/fetchDeepSky.ts
T
Claude 3a859360ba Add the deep-sky backdrop, the last unbuilt piece of the plan
The design doc scopes deep-sky objects as a galaxy-view backdrop and lists
fetchDeepSky.ts, deepsky.json and deepsky.model.ts, but none of it existed —
it was the only part of the plan with no implementation behind it.

ETL: fetchDeepSky.ts pulls the OpenNGC catalog, classifies each object as a
galaxy/nebula/cluster, and keeps the ~460 worth drawing (everything Messier,
everything with a common name, and anything brighter than magnitude 9) out of
~12,000 mostly-anonymous rows. build.ts runs it and validates the output.

Distances are the hard part: OpenNGC has no distance column, and both fallbacks
fail for the best-known objects. M31, M33 and M42 are Local Group members whose
redshift is negative or absent, and a galaxy's catalog parallax comes from a
cross-matched foreground star — 6 mas for M31 would put a 780 kpc galaxy at
167 pc. So records store a unit direction on the celestial sphere rather than a
position (the line of sight is always known precisely, and the objects are drawn
on a fixed backdrop shell where true distance is unusable anyway), and distance
is optional metadata carrying its own provenance. Parallax is trusted only for
galactic objects, redshift only above z=0.003 where expansion outweighs peculiar
velocity. 330 of 463 get a distance; the rest honestly report none.

Rendering: DeepSkyRenderer paints the objects as soft additive billboards on a
2500 pc shell — clear of the 50 pc star field, beyond the camera's 2000 pc orbit
limit, and inside its 5000 pc far plane. Size comes from real angular extent, so
Andromeda is six times wider than the full Moon, clamped at both ends. Sprites
rather than points because the WebGPU backend caps point primitives at one pixel;
materials are shared per kind and brightness band, so 460 objects cost nine of
them. The brightest dozen get permanent labels, which needed the label overlay to
accept string ids alongside numeric star ids. The backdrop is decorative, so a
failure to load its dataset is logged and the star field comes up regardless.

Also documents the app in the README, which until now covered only the plugin
marketplace.

Tests: 112 passing, up from 54. Build, both typechecks and the Playwright suite
are green.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WaySiNst4HhDXBHnMy8p5G
2026-08-03 15:19:39 +00:00

148 lines
5.2 KiB
TypeScript

import { writeFileSync } from 'node:fs';
import { parseSexagesimal, raDecToUnitVector } from '../../src/app/shared/astro/coordinates';
import { classifyOpenNgcType, estimateDeepSkyDistancePc, isNotableDeepSkyObject } from '../../src/app/shared/astro/deep-sky';
import { DeepSkyRecord } from '../../src/app/shared/models/deepsky.model';
import { parseCsvObjects } from './lib/csv';
import { fetchTextCached } from './lib/http';
import { dataPath, ensureDataDir } from './lib/paths';
const OPENNGC_CSV_URL = 'https://raw.githubusercontent.com/mattiaverga/OpenNGC/master/database_files/NGC.csv';
/** OpenNGC publishes semicolon-separated files, not comma-separated. */
const OPENNGC_DELIMITER = ';';
const ARCMIN_PER_DEGREE = 60;
/**
* Reads a numeric catalog column. Empty strings mean "not measured" and must become `null`
* rather than `0`: `Number('')` is `0`, which would silently turn every unphotometered object
* into a magnitude-0 blaze brighter than Sirius.
*/
function numericField(value: string | undefined): number | null {
if (value === undefined || value.trim() === '') {
return null;
}
const parsed = Number(value);
return Number.isFinite(parsed) ? parsed : null;
}
function textField(value: string | undefined): string | null {
const trimmed = value?.trim();
return trimmed ? trimmed : null;
}
/** OpenNGC stores Messier numbers zero-padded ("031"); render them as "M31". */
function messierDesignation(value: string | undefined): string | null {
const raw = textField(value);
if (!raw) {
return null;
}
const number = Number(raw);
return Number.isFinite(number) ? `M${number}` : `M${raw}`;
}
/** OpenNGC's `Common names` column is comma-separated; the first entry is the best known. */
function primaryCommonName(value: string | undefined): string | null {
const raw = textField(value);
return raw ? (textField(raw.split(',')[0]) ?? null) : null;
}
/**
* Display name, most recognisable first: a common name ("Andromeda Galaxy") beats a Messier
* number ("M31"), which beats the raw catalog designation ("NGC0224").
*/
function resolveName(commonName: string | null, messier: string | null, designation: string): string {
return commonName ?? messier ?? designation;
}
/**
* Downloads the OpenNGC catalog, keeps the objects notable enough to be worth drawing, and
* writes `deepsky.json` — each entry a unit direction on the celestial sphere plus its kind,
* apparent size, magnitude and (where derivable) distance.
*
* See `DeepSkyRecord` for why these are stored as directions rather than positions.
*/
export async function fetchDeepSky(): Promise<DeepSkyRecord[]> {
console.log('Fetching OpenNGC deep-sky catalog...');
const csv = await fetchTextCached(OPENNGC_CSV_URL, 'openngc.csv');
const rows = parseCsvObjects(csv, OPENNGC_DELIMITER);
const records: DeepSkyRecord[] = [];
let skippedUnclassified = 0;
let skippedNotNotable = 0;
let skippedUnpositioned = 0;
for (const row of rows) {
const kind = classifyOpenNgcType(row['Type']);
if (!kind) {
skippedUnclassified++;
continue;
}
const magnitude = numericField(row['V-Mag']) ?? numericField(row['B-Mag']);
const messier = messierDesignation(row['M']);
const commonName = primaryCommonName(row['Common names']);
if (!isNotableDeepSkyObject({ messier, commonName, magnitude })) {
skippedNotNotable++;
continue;
}
const raHours = parseSexagesimal(row['RA']);
const decDeg = parseSexagesimal(row['Dec']);
if (raHours === null || decDeg === null) {
skippedUnpositioned++;
continue;
}
const designation = textField(row['Name']) ?? '';
if (!designation) {
skippedUnpositioned++;
continue;
}
const { x, y, z } = raDecToUnitVector(raHours, decDeg);
const distance = estimateDeepSkyDistancePc({
kind,
redshift: numericField(row['Redshift']),
parallaxMas: numericField(row['Pax'])
});
records.push({
id: designation,
name: resolveName(commonName, messier, designation),
kind,
x,
y,
z,
angularSizeDeg: (numericField(row['MajAx']) ?? 0) / ARCMIN_PER_DEGREE,
magnitude,
distancePc: distance?.distancePc ?? null,
distanceMethod: distance?.method ?? null,
constellation: textField(row['Const']) ?? 'Unknown',
messier
});
}
// Brightest first, so a consumer taking a prefix gets the most prominent objects. Objects
// with no measured magnitude sort last rather than being treated as infinitely bright.
records.sort((a, b) => (a.magnitude ?? Infinity) - (b.magnitude ?? Infinity) || a.id.localeCompare(b.id));
ensureDataDir();
writeFileSync(dataPath('deepsky.json'), JSON.stringify(records));
const withDistance = records.filter((record) => record.distancePc !== null).length;
console.log(` kept ${records.length} deep-sky objects (of ${rows.length} catalog rows).`);
console.log(` skipped: ${skippedUnclassified} not deep-sky, ${skippedNotNotable} too faint, ${skippedUnpositioned} unusable coordinates.`);
console.log(` ${withDistance}/${records.length} have a derivable distance.`);
return records;
}
if (require.main === module) {
fetchDeepSky().catch((error) => {
console.error(error);
process.exitCode = 1;
});
}