@motionstudies/data 0.1.0-alpha.3 → 0.1.0-alpha.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +43 -0
- package/air-endpoints.d.mts +5 -0
- package/air-endpoints.mjs +146 -0
- package/package.json +6 -2
package/README.md
CHANGED
|
@@ -25,8 +25,51 @@ Build release candidates with `npm run build:packages`. Distribution manifests a
|
|
|
25
25
|
|
|
26
26
|
Source workspace manifests always stay private. `npm run check:release` builds public candidates, tests their packed consumer and records the tested tarball hashes; `npm run release:dry-run` inspects the publication without writing to npm. The manual main-branch `release.yml` workflow publishes those same tarballs with public access and provenance. See [release instructions](https://github.com/emmettl/motionstudies/blob/main/docs/RELEASING.md) for bootstrap-token and trusted-publisher setup. All four shared packages are MIT-licensed; each distribution includes `LICENSE`.
|
|
27
27
|
|
|
28
|
+
## Selection labels
|
|
29
|
+
|
|
30
|
+
`NationalNetworkScene` gives the selected station first label priority, followed by the selected route's terminal stops (including branches), then intermediate stops. Selected services use their own endpoints. Priority precedes retained labels and ordinary rank/tier admission; clearing selection restores edition ranking. This is built in for every consumer, including geographic and diagram layouts. Supply complete enabled infrastructure as `referenceSnapshot` to preserve endpoints through timetable gaps; its stop indexes need not match the active snapshot. See the [edition behaviour contract](https://github.com/emmettl/motionstudies/blob/main/docs/EDITIONS.md#selection-and-station-labels).
|
|
31
|
+
|
|
28
32
|
## Button help
|
|
29
33
|
|
|
30
34
|
`mountMotionStudy` installs one shared tooltip surface. Independent consumers such as the lab can render `ButtonTooltips` from `@motionstudies/web/components/ButtonTooltips` once instead. Put concise, action-oriented help in each button’s `data-tooltip`; icon buttons fall back to their `aria-label`. An empty `data-tooltip` opts out. Avoid native `title` attributes on these buttons, which can also appear during touch interaction.
|
|
31
35
|
|
|
32
36
|
Help appears after a short mouse hover or on keyboard focus when the primary pointer is fine and supports hover. Touch input suppresses it, including on hybrid devices. Escape, activation, scrolling and blur dismiss it. The tooltip stays inside the viewport, can itself be hovered, and temporarily extends `aria-describedby` without replacing existing descriptions. Copy and translations stay in the edition; rendering and input handling stay in this package. The Controls specimen and packed-consumer tests exercise this contract.
|
|
37
|
+
|
|
38
|
+
## Airport heroes and split-flap boards
|
|
39
|
+
|
|
40
|
+
`AirportHeroCard` provides an airport identity header and switchable departure/arrival boards. `SplitFlapBoard` is the underlying transport-neutral widget, also suitable for rail stations. Both use scoped package styles, semantic tables, full accessible cell values, keyboard-operable selection, contained horizontal scrolling and reduced-motion support. Only changed characters remount for the flap animation.
|
|
41
|
+
|
|
42
|
+
```tsx
|
|
43
|
+
import { AirportHeroCard } from '@motionstudies/web/components/AirportHeroCard'
|
|
44
|
+
import '@motionstudies/web/airport-hero-card.css'
|
|
45
|
+
|
|
46
|
+
<AirportHeroCard
|
|
47
|
+
key={airport.id}
|
|
48
|
+
airport={airport}
|
|
49
|
+
departures={departures}
|
|
50
|
+
arrivals={arrivals}
|
|
51
|
+
study={{ time, windowStart: metadata.windowStart, windowEnd: metadata.windowEnd }}
|
|
52
|
+
dateLabel={metadata.serviceDate}
|
|
53
|
+
note="Observed study · inferred directions; times are observations."
|
|
54
|
+
onSelectFlight={selectAirTrack}
|
|
55
|
+
selectedFlightId={selectedAirTrackId}
|
|
56
|
+
/>
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
Entries have a stable `id`, a `service` label, and optional numeric `time`, `place`, `stand`, `status` and `tone` (`neutral`, `accent` or `warning`). Movement times and `study.time`, `windowStart`, and `windowEnd` must use the same study-relative seconds and service date. Do not parse display strings or normalize numeric times at midnight: an event after 24:00 retains its value above 86,400. `formatTime` optionally controls display formatting; the default uses the study's `formatServiceTime` helper. The header clock is derived directly from `study.time`, with no independent wall clock.
|
|
60
|
+
|
|
61
|
+
The card sorts movements chronologically and shows up to eight rows per direction inside the intersection of the study bounds and a rolling window: ten minutes behind the playback clock and sixty minutes ahead, with inclusive endpoints. Override this with `horizon={{ lookBehindSeconds: 600, lookAheadSeconds: 3600 }}` and `maxRows`. Playback, backward seeking, changed study bounds and updated movement times all recalculate the rows. An out-of-study or invalid clock shows no movements; rows with missing or non-finite times are excluded because they cannot be placed in the window. Other unknown fields render as a dash. Labels include `studyTime`, `boardWindow` and `outsideWindow` for localization. Filtering does not infer operational statuses or clear the consumer's map selection when a row leaves the window.
|
|
62
|
+
|
|
63
|
+
Consumers still own time coordinates, source interpretation and data loading. Supply movements for the displayed horizon, not just aircraft active at the current second, and use the selected study's bounds rather than an individual progressive chunk's bounds. Do not turn an approach-envelope association into a confirmed departure/arrival: unclassified tracks should remain outside these direction lists. Current `AirTrack` data does not supply scheduled times, routes or gates; leave those fields absent, use observation times only when clearly labelled, and explain any inference in the required `note`.
|
|
64
|
+
|
|
65
|
+
Pass `labels` for edition translations, `loading`, or a localized `error` and `onRetry` for data states. The selected direction is local to each card; key the card by airport ID to reset it on selection changes. The Airports lab specimen exercises synthetic timetables, playback, scrubbing, study-window changes, incomplete observations, French labels, long destinations, updates and recovery. Edition adoption happens through their independently pinned package releases; adding this export does not update deployed studies.
|
|
66
|
+
|
|
67
|
+
For a custom rail or transport board, import `SplitFlapBoard` from `@motionstudies/web/components/SplitFlapBoard` and `@motionstudies/web/split-flap-board.css`. Supply `columns` (`key`, `label`, `characters`) and `rows` (`id`, `cells`, optional `tone`). Cell text longer than its flap count is visually ellipsized, with the full value retained for assistive technology and hover. `onSelectRow`, `selectedRowId` and `selectionColumn` optionally make one cell per row selectable.
|
|
68
|
+
|
|
69
|
+
The shared board also accepts `loading`, a localized `loadingMessage`, and `loadingRows` (default five). While loading, its decorative rows cycle through staggered letters and digits; they are hidden from assistive technology and cannot be selected. A single status message announces loading. When data arrives, characters flip through a short sequence and settle into their actual values; later changes animate only the changed characters. These CSS animations have no JavaScript timers and stop looping when loading ends or the board is removed. Reduced-motion users get static blank loading flaps and immediate final text. `AirportHeroCard` uses this shared loading treatment automatically. Use **Reload board** in the Airports lab to preview the complete loading-to-ready transition.
|
|
70
|
+
|
|
71
|
+
Empty messages also appear on the flaps, in the widest column (the destination/origin column in airport cards), with the other columns blank. Longer localized messages wrap across display rows instead of being truncated. They settle with the same animation as flight details, and one hidden status announces the complete message to assistive technology. This also applies when the study clock moves into a window with no movements.
|
|
72
|
+
|
|
73
|
+
Rail and other transport consumers can share the same time filtering through `movementBoardWindow(study, horizon)` and `movementsForBoard(entries, window, maxRows)` from `@motionstudies/core/domain/movement-board`. Format the returned numeric times when mapping them into `SplitFlapBoard` cells. The lab's rail board follows the same study clock and horizon as its airport card.
|
|
74
|
+
|
|
75
|
+
`@motionstudies/data/air-endpoints` provides offline `enrichAirEndpoints` for existing air manifests, chunks and opening snapshots. Supply cached same-date global ADSB.lol heatmaps, an OurAirports CSV and the service date's local UTC offset. It associates only unambiguous low-altitude endpoints near a reference airport; cruise-only traces and uncertain routes stay unknown. Optional `AirEndpoint` origin/destination fields carry airport identity, observed boundary time and `observed-endpoint` evidence. `airportBoardMovements` maps full manifest entries to board rows without confusing playback chunk boundaries with flight endpoints. Input hashes and source/licence attribution are recorded in fixture metadata. These fields describe inferred observations, never flight schedules, gates or live status.
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { AirEndpoint, AirSample } from '@motionstudies/core/domain/air'
|
|
2
|
+
export interface EndpointAirport { icao: string; iata: string; name: string; city: string; longitude: number; latitude: number; elevation: number }
|
|
3
|
+
export function parseAirports(csv: string): EndpointAirport[]
|
|
4
|
+
export function inferAirEndpoints(samples: readonly AirSample[], airports: readonly EndpointAirport[]): { origin?: AirEndpoint; destination?: AirEndpoint }
|
|
5
|
+
export function enrichAirEndpoints(options: { manifestPath: string; snapshotPaths?: string[]; heatmapDirectory: string; airportCsvPath: string; utcOffsetHours: number }): Promise<{ tracks: number; origins: number; destinations: number }>
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
import { readFile, readdir, writeFile } from 'node:fs/promises'
|
|
2
|
+
import { dirname, join } from 'node:path'
|
|
3
|
+
import { gunzipSync } from 'node:zlib'
|
|
4
|
+
import { createHash } from 'node:crypto'
|
|
5
|
+
import { parseCsvLine } from './gtfs.mjs'
|
|
6
|
+
|
|
7
|
+
export function parseAirports(csv) {
|
|
8
|
+
const [header, ...lines] = csv.trim().split(/\r?\n/)
|
|
9
|
+
const keys = parseCsvLine(header)
|
|
10
|
+
return lines.map(line => Object.fromEntries(parseCsvLine(line).map((value, index) => [keys[index], value])))
|
|
11
|
+
.filter(row => ['large_airport', 'medium_airport'].includes(row.type) && row.ident && row.elevation_ft)
|
|
12
|
+
.map(row => ({ icao: row.ident, iata: row.iata_code, name: row.name, city: row.municipality,
|
|
13
|
+
longitude: Number(row.longitude_deg), latitude: Number(row.latitude_deg), elevation: Number(row.elevation_ft) }))
|
|
14
|
+
.filter(row => [row.longitude, row.latitude, row.elevation].every(Number.isFinite))
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function distance(sample, airport) {
|
|
18
|
+
const longitude = ((sample[1] - airport.longitude + 540) % 360) - 180
|
|
19
|
+
return Math.hypot(longitude * 111.32 * Math.cos((sample[2] + airport.latitude) * Math.PI / 360), (sample[2] - airport.latitude) * 111.32)
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function atAirport(sample, airport) {
|
|
23
|
+
return sample[3] >= airport.elevation - 500 && sample[3] <= airport.elevation + 1500 && sample[4] <= 250 && distance(sample, airport) <= 6
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Conservative endpoint association; cruise-only traces and ambiguous neighbouring airports stay unknown. */
|
|
27
|
+
export function inferAirEndpoints(samples, airports) {
|
|
28
|
+
if (samples.length < 4) return {}
|
|
29
|
+
const maximumAltitude = Math.max(...samples.map(sample => sample[3]))
|
|
30
|
+
const endpoint = (arrival) => {
|
|
31
|
+
const ordered = arrival ? [...samples].reverse() : samples
|
|
32
|
+
const candidates = airports.filter(airport => atAirport(ordered[0], airport) && maximumAltitude >= airport.elevation + 3000)
|
|
33
|
+
if (candidates.length !== 1) return undefined
|
|
34
|
+
const airport = candidates[0]
|
|
35
|
+
let boundary = ordered[0]
|
|
36
|
+
for (const sample of ordered.slice(1)) {
|
|
37
|
+
if (!atAirport(sample, airport)) break
|
|
38
|
+
boundary = sample
|
|
39
|
+
}
|
|
40
|
+
return { icao: airport.icao, iata: airport.iata, name: airport.name, city: airport.city, time: boundary[0], evidence: 'observed-endpoint' }
|
|
41
|
+
}
|
|
42
|
+
const origin = endpoint(false), destination = endpoint(true)
|
|
43
|
+
if (origin && destination && (origin.icao === destination.icao || origin.time >= destination.time)) return {}
|
|
44
|
+
return { ...(origin ? { origin } : {}), ...(destination ? { destination } : {}) }
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function segmentsFor(samples) {
|
|
48
|
+
const segments = []
|
|
49
|
+
let current = []
|
|
50
|
+
for (const sample of samples.sort((a, b) => a[0] - b[0])) {
|
|
51
|
+
const previous = current.at(-1)
|
|
52
|
+
if (previous && previous[0] === sample[0]) continue
|
|
53
|
+
if (previous && (sample[0] - previous[0] > 1800 || sample[5] !== previous[5])) {
|
|
54
|
+
segments.push(current)
|
|
55
|
+
current = []
|
|
56
|
+
}
|
|
57
|
+
current.push(sample)
|
|
58
|
+
}
|
|
59
|
+
if (current.length) segments.push(current)
|
|
60
|
+
return segments
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Enrich an existing study and its chunks using cached, same-date global heatmaps. No network requests. */
|
|
64
|
+
export async function enrichAirEndpoints({ manifestPath, snapshotPaths = [], heatmapDirectory, airportCsvPath, utcOffsetHours }) {
|
|
65
|
+
const readJson = async path => JSON.parse(await readFile(path, 'utf8'))
|
|
66
|
+
const manifest = await readJson(manifestPath)
|
|
67
|
+
const snapshots = await Promise.all(snapshotPaths.map(readJson))
|
|
68
|
+
const date = manifest.metadata.serviceDate
|
|
69
|
+
if (!/^\d{4}-\d{2}-\d{2}$/.test(date) || !Number.isFinite(utcOffsetHours)) throw new Error('A service date and UTC offset are required')
|
|
70
|
+
if (snapshots.some(snapshot => snapshot.metadata.serviceDate !== date)) throw new Error('Air snapshots must share the manifest service date')
|
|
71
|
+
const tracks = [...manifest.aircraft, ...snapshots.flatMap(snapshot => snapshot.tracks)]
|
|
72
|
+
const wanted = new Set(tracks.map(track => parseInt(track.icaoAddress ?? track.id.split('-')[0], 16)))
|
|
73
|
+
const records = new Map()
|
|
74
|
+
const dayStart = Date.parse(`${date}T00:00:00Z`) - utcOffsetHours * 3600000
|
|
75
|
+
const files = (await readdir(heatmapDirectory)).filter(file => file.endsWith('.bin.ttf')).sort()
|
|
76
|
+
if (!files.length) throw new Error('No cached heatmap slices found')
|
|
77
|
+
const sources = []
|
|
78
|
+
for (const file of files) {
|
|
79
|
+
const raw = await readFile(join(heatmapDirectory, file))
|
|
80
|
+
const buffer = gunzipSync(raw)
|
|
81
|
+
let time
|
|
82
|
+
const callsigns = new Map()
|
|
83
|
+
let used = false
|
|
84
|
+
for (let offset = 0; offset + 16 <= buffer.length; offset += 16) {
|
|
85
|
+
const address = buffer.readUInt32LE(offset), latitude = buffer.readInt32LE(offset + 4)
|
|
86
|
+
if (address === 0x0e7f7c9d) {
|
|
87
|
+
time = Math.round((Number((BigInt(latitude) << 32n) | BigInt(buffer.readUInt32LE(offset + 8))) - dayStart) / 1000)
|
|
88
|
+
continue
|
|
89
|
+
}
|
|
90
|
+
const id = address & 0xffffff
|
|
91
|
+
if (!wanted.has(id) || (address & 0x01000000)) continue
|
|
92
|
+
if (latitude >= 0 && (latitude & 0x40000000) !== 0) {
|
|
93
|
+
callsigns.set(id, buffer.subarray(offset + 8, offset + 16).toString('ascii').replaceAll('\0', '').trim().toUpperCase())
|
|
94
|
+
continue
|
|
95
|
+
}
|
|
96
|
+
if (time === undefined || time < 0 || time > 86400) continue
|
|
97
|
+
const altitude = buffer.readInt16LE(offset + 12), speed = buffer.readInt16LE(offset + 14)
|
|
98
|
+
if (altitude < 0 || speed < 0) continue
|
|
99
|
+
const samples = records.get(id) ?? []
|
|
100
|
+
samples.push([time, buffer.readInt32LE(offset + 8) / 1e6, latitude / 1e6, altitude * 25, speed / 10, callsigns.get(id) ?? samples.at(-1)?.[5] ?? ''])
|
|
101
|
+
records.set(id, samples)
|
|
102
|
+
used = true
|
|
103
|
+
}
|
|
104
|
+
if (used) sources.push({ file, sha256: createHash('sha256').update(raw).digest('hex') })
|
|
105
|
+
}
|
|
106
|
+
const csv = await readFile(airportCsvPath, 'utf8')
|
|
107
|
+
if (!sources.length) throw new Error('No same-date observations matched the study aircraft')
|
|
108
|
+
const airports = parseAirports(csv)
|
|
109
|
+
if (!airports.length) throw new Error('No usable airports in the reference CSV')
|
|
110
|
+
const segments = new Map([...records].map(([id, samples]) => [id, segmentsFor(samples).map(samples => ({
|
|
111
|
+
start: samples[0][0], end: samples.at(-1)[0], callsign: samples[0][5], ...inferAirEndpoints(samples, airports),
|
|
112
|
+
}))]))
|
|
113
|
+
const enrich = (track) => {
|
|
114
|
+
const candidates = (segments.get(parseInt(track.icaoAddress ?? track.id.split('-')[0], 16)) ?? [])
|
|
115
|
+
.filter(segment => segment.callsign && segment.callsign === track.callsign && segment.start <= track.start + 30 && segment.end >= track.end - 30)
|
|
116
|
+
const { origin: _origin, destination: _destination, ...rest } = track
|
|
117
|
+
if (candidates.length !== 1) return rest
|
|
118
|
+
const { origin, destination } = candidates[0]
|
|
119
|
+
return { ...rest, ...(origin ? { origin } : {}), ...(destination ? { destination } : {}) }
|
|
120
|
+
}
|
|
121
|
+
const metadata = {
|
|
122
|
+
serviceDate: date, method: 'observed-endpoint', note: 'Origin/destination inferred from full-trace endpoints within 6 km and 1500 ft above an airport; observed times, not schedules or confirmed flight plans.',
|
|
123
|
+
airportSource: 'https://ourairports.com/data/', airportLicense: 'Public Domain', airportSha256: createHash('sha256').update(csv).digest('hex'),
|
|
124
|
+
traceSource: manifest.metadata.sourceUrl, traceLicense: 'ODbL 1.0', utcOffsetHours, sourceFiles: sources,
|
|
125
|
+
}
|
|
126
|
+
const aircraft = manifest.aircraft.map(enrich)
|
|
127
|
+
const byId = new Map(aircraft.map(track => [track.id, track]))
|
|
128
|
+
const writes = []
|
|
129
|
+
for (const descriptor of manifest.chunks) {
|
|
130
|
+
const path = join(dirname(manifestPath), descriptor.path)
|
|
131
|
+
const chunk = await readJson(path)
|
|
132
|
+
chunk.tracks = chunk.tracks.map(track => {
|
|
133
|
+
const { origin: _origin, destination: _destination, ...rest } = track
|
|
134
|
+
const full = byId.get(track.id)
|
|
135
|
+
return { ...rest, ...(full?.origin ? { origin: full.origin } : {}), ...(full?.destination ? { destination: full.destination } : {}) }
|
|
136
|
+
})
|
|
137
|
+
const bytes = Buffer.from(`${JSON.stringify(chunk)}\n`)
|
|
138
|
+
if ('bytes' in descriptor) descriptor.bytes = bytes.length
|
|
139
|
+
if ('sha256' in descriptor) descriptor.sha256 = createHash('sha256').update(bytes).digest('hex')
|
|
140
|
+
writes.push([path, chunk])
|
|
141
|
+
}
|
|
142
|
+
writes.push([manifestPath, { ...manifest, metadata: { ...manifest.metadata, routeEnrichment: metadata }, aircraft }])
|
|
143
|
+
snapshots.forEach((snapshot, index) => writes.push([snapshotPaths[index], { ...snapshot, metadata: { ...snapshot.metadata, routeEnrichment: metadata }, tracks: snapshot.tracks.map(enrich) }]))
|
|
144
|
+
for (const [path, value] of writes) await writeFile(path, `${JSON.stringify(value)}\n`)
|
|
145
|
+
return { tracks: aircraft.length, origins: aircraft.filter(track => track.origin).length, destinations: aircraft.filter(track => track.destination).length }
|
|
146
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@motionstudies/data",
|
|
3
|
-
"version": "0.1.0-alpha.
|
|
3
|
+
"version": "0.1.0-alpha.5",
|
|
4
4
|
"private": false,
|
|
5
5
|
"type": "module",
|
|
6
6
|
"description": "Offline data preparation primitives for Motion Studies.",
|
|
@@ -23,6 +23,10 @@
|
|
|
23
23
|
"node": ">=24.0.0"
|
|
24
24
|
},
|
|
25
25
|
"exports": {
|
|
26
|
+
"./air-endpoints": {
|
|
27
|
+
"types": "./air-endpoints.d.mts",
|
|
28
|
+
"import": "./air-endpoints.mjs"
|
|
29
|
+
},
|
|
26
30
|
"./gtfs": {
|
|
27
31
|
"types": "./gtfs.d.mts",
|
|
28
32
|
"import": "./gtfs.mjs"
|
|
@@ -51,6 +55,6 @@
|
|
|
51
55
|
],
|
|
52
56
|
"sideEffects": false,
|
|
53
57
|
"dependencies": {
|
|
54
|
-
"@motionstudies/core": "0.1.0-alpha.
|
|
58
|
+
"@motionstudies/core": "0.1.0-alpha.5"
|
|
55
59
|
}
|
|
56
60
|
}
|