@motionstudies/data 0.1.0-alpha.0

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Motion Studies contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,26 @@
1
+ # Motion Studies packages
2
+
3
+ Shared packages for the Motion Studies transport instrument. The source workspace and compiled distributions expose the same explicit, extensionless module subpaths. The initial release is `0.1.0-alpha.0` under npm’s `next` tag.
4
+
5
+ - `@motionstudies/core`: transport contracts, indexing, interpolation and visual theme contracts; no browser or Node dependencies.
6
+ - `@motionstudies/three`: `NationalNetworkScene`, `HubPulseScene`, `StationFlowScene`, camera framing and label-mode contracts. React, React Three Fiber and Three.js are peers; rendering internals are not public subpaths.
7
+ - `@motionstudies/web`: picker, theme application, mounting, progressive loaders, observed operations and recording. Import `tokens.css` and `mobile-picker.css` for isolated widgets. `shell.css` is an optional full-page study shell scoped to `.motion-study`; `mountMotionStudy` applies that class. Fonts and edition layouts belong to consumers.
8
+ - `@motionstudies/data`: Node-only GTFS readers, network chunking, merging and station ranking. ZIP reading requires `unzip` on the host. Source selection, provenance overrides and compilation commands belong to each edition.
9
+
10
+ ```tsx
11
+ import { MobilePicker } from '@motionstudies/web/components/MobilePicker'
12
+ import { createDataUrlResolver } from '@motionstudies/web/data-url'
13
+ import { useProgressiveNetworkDay } from '@motionstudies/web/use-progressive-network-day'
14
+ import '@motionstudies/web/tokens.css'
15
+ import '@motionstudies/web/mobile-picker.css'
16
+
17
+ const resolveData = createDataUrlResolver('/my-edition/data/')
18
+ // Inside a React component:
19
+ // const day = useProgressiveNetworkDay('day.json', enabled, time, resolveData)
20
+ ```
21
+
22
+ Keep the resolver stable across renders. Manifest paths and their chunk paths are relative to the supplied asset root. Changing the resolved manifest URL resets the loader; disabling cancels requests, and re-enabling retries failures. Optional road manifests distinguish a 404 from an error. Observations poll serially; changing their endpoint drops the previous source's state, and disabling/unmounting cancels the request and timer.
23
+
24
+ Build release candidates with `npm run build:packages`. Distribution manifests and compiled ESM/declarations are written to `.package-dist/`; workspace manifests continue to point at source for fast local iteration. `npm run check:packed` packs and installs those distributions into a separate consumer, builds the lab and validates the public exports. No source aliases or workspace links are used in that consumer.
25
+
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`.
package/gtfs.d.mts ADDED
@@ -0,0 +1,11 @@
1
+ export type GtfsRow = Record<string, string>
2
+ export type TransportMode = 'tram' | 'metro' | 'rail' | 'bus' | 'ferry' | 'cableway' | 'funicular'
3
+ export interface SourceStop { name: string; latitude: number; longitude: number; platformCode: string }
4
+ export function parseCsvLine(line: string): string[]
5
+ export function parseGtfsTime(value: string): number
6
+ export function weekdayField(date: string): string
7
+ export function transportModeForRouteType(value: string | number): TransportMode | undefined
8
+ /** Streams a ZIP entry using the host's unzip executable. */
9
+ export function rowsFromArchive(archive: string, fileName: string): AsyncGenerator<GtfsRow>
10
+ export function activeServices(archive: string, serviceDate: string): Promise<Set<string>>
11
+ export function stopsById(archive: string): Promise<Map<string, SourceStop>>
package/gtfs.mjs ADDED
@@ -0,0 +1,148 @@
1
+ import { spawn } from 'node:child_process'
2
+ import { createInterface } from 'node:readline'
3
+
4
+ export function parseCsvLine(line) {
5
+ const values = []
6
+ let value = ''
7
+ let quoted = false
8
+
9
+ for (let index = 0; index < line.length; index += 1) {
10
+ const character = line[index]
11
+ if (character === '"') {
12
+ if (quoted && line[index + 1] === '"') {
13
+ value += '"'
14
+ index += 1
15
+ } else {
16
+ quoted = !quoted
17
+ }
18
+ } else if (character === ',' && !quoted) {
19
+ values.push(value)
20
+ value = ''
21
+ } else {
22
+ value += character
23
+ }
24
+ }
25
+
26
+ values.push(value)
27
+ return values
28
+ }
29
+
30
+ export function parseGtfsTime(value) {
31
+ const [hours, minutes, seconds] = value.split(':').map(Number)
32
+ return hours * 3600 + minutes * 60 + seconds
33
+ }
34
+
35
+ function compactDate(value) {
36
+ return value.replaceAll('-', '')
37
+ }
38
+
39
+ export function weekdayField(date) {
40
+ return [
41
+ 'sunday',
42
+ 'monday',
43
+ 'tuesday',
44
+ 'wednesday',
45
+ 'thursday',
46
+ 'friday',
47
+ 'saturday',
48
+ ][new Date(`${date}T12:00:00Z`).getUTCDay()]
49
+ }
50
+
51
+ export function transportModeForRouteType(value) {
52
+ const routeType = Number(value)
53
+ if (routeType === 0 || (routeType >= 900 && routeType < 1000)) return 'tram'
54
+ if (routeType === 1 || (routeType >= 400 && routeType < 500)) return 'metro'
55
+ if (routeType === 2 || (routeType >= 100 && routeType < 200)) return 'rail'
56
+ if (
57
+ routeType === 3 ||
58
+ routeType === 11 ||
59
+ (routeType >= 200 && routeType < 300) ||
60
+ (routeType >= 700 && routeType < 800)
61
+ ) return 'bus'
62
+ if (routeType === 4 || (routeType >= 1000 && routeType < 1100)) return 'ferry'
63
+ if (routeType === 6 || (routeType >= 1300 && routeType < 1400)) {
64
+ return 'cableway'
65
+ }
66
+ if (routeType === 7 || (routeType >= 1400 && routeType < 1500)) {
67
+ return 'funicular'
68
+ }
69
+ return undefined
70
+ }
71
+
72
+ export async function* rowsFromArchive(archive, fileName) {
73
+ const child = spawn('unzip', ['-p', archive, fileName], {
74
+ stdio: ['ignore', 'pipe', 'pipe'],
75
+ })
76
+ let standardError = ''
77
+ child.stderr.setEncoding('utf8')
78
+ child.stderr.on('data', (chunk) => {
79
+ standardError += chunk
80
+ })
81
+ const completed = new Promise((resolvePromise, rejectPromise) => {
82
+ child.once('error', rejectPromise)
83
+ child.once('close', (code) => {
84
+ if (code === 0) resolvePromise()
85
+ else rejectPromise(new Error(`unzip ${fileName} failed: ${standardError.trim()}`))
86
+ })
87
+ })
88
+
89
+ // Observe rejection immediately; the generator may still be consuming stdout.
90
+ void completed.catch(() => {})
91
+ const lines = createInterface({ input: child.stdout, crlfDelay: Infinity })
92
+ try {
93
+ let headers
94
+ for await (const line of lines) {
95
+ if (!headers) {
96
+ headers = parseCsvLine(line.replace(/^\uFEFF/, ''))
97
+ continue
98
+ }
99
+ const values = parseCsvLine(line)
100
+ const row = Object.create(null)
101
+ for (let index = 0; index < headers.length; index += 1) {
102
+ row[headers[index]] = values[index] ?? ''
103
+ }
104
+ yield row
105
+ }
106
+ await completed
107
+ } finally {
108
+ lines.close()
109
+ if (child.exitCode === null) child.kill()
110
+ await completed.catch(() => {})
111
+ }
112
+ }
113
+
114
+ export async function activeServices(archive, serviceDate) {
115
+ const date = compactDate(serviceDate)
116
+ const weekday = weekdayField(serviceDate)
117
+ const services = new Set()
118
+
119
+ for await (const row of rowsFromArchive(archive, 'calendar.txt')) {
120
+ if (row.start_date <= date && row.end_date >= date && row[weekday] === '1') {
121
+ services.add(row.service_id)
122
+ }
123
+ }
124
+
125
+ for await (const row of rowsFromArchive(archive, 'calendar_dates.txt')) {
126
+ if (row.date !== date) continue
127
+ if (row.exception_type === '1') services.add(row.service_id)
128
+ if (row.exception_type === '2') services.delete(row.service_id)
129
+ }
130
+
131
+ return services
132
+ }
133
+
134
+ export async function stopsById(archive) {
135
+ const stops = new Map()
136
+ for await (const row of rowsFromArchive(archive, 'stops.txt')) {
137
+ const latitude = Number(row.stop_lat)
138
+ const longitude = Number(row.stop_lon)
139
+ if (!Number.isFinite(latitude) || !Number.isFinite(longitude)) continue
140
+ stops.set(row.stop_id, {
141
+ name: row.stop_name,
142
+ latitude,
143
+ longitude,
144
+ platformCode: row.platform_code,
145
+ })
146
+ }
147
+ return stops
148
+ }
@@ -0,0 +1,8 @@
1
+ import type { NetworkSnapshot } from '@motionstudies/core/domain/network'
2
+ export interface MergeOptions {
3
+ retrievedAt?: string
4
+ note?: string
5
+ metadata?: Partial<NetworkSnapshot['metadata']>
6
+ geometryMetadata?: Partial<NonNullable<NetworkSnapshot['metadata']['geometry']>>
7
+ }
8
+ export function mergeNetworkSnapshots(snapshots: readonly NetworkSnapshot[], options?: MergeOptions): NetworkSnapshot
@@ -0,0 +1,118 @@
1
+ import { createHash } from 'node:crypto'
2
+
3
+ function boundsFor(stops) {
4
+ return stops.reduce((bounds, [longitude, latitude]) => ({
5
+ minLongitude: Math.min(bounds.minLongitude, longitude),
6
+ minLatitude: Math.min(bounds.minLatitude, latitude),
7
+ maxLongitude: Math.max(bounds.maxLongitude, longitude),
8
+ maxLatitude: Math.max(bounds.maxLatitude, latitude),
9
+ }), {
10
+ minLongitude: Number.POSITIVE_INFINITY,
11
+ minLatitude: Number.POSITIVE_INFINITY,
12
+ maxLongitude: Number.NEGATIVE_INFINITY,
13
+ maxLatitude: Number.NEGATIVE_INFINITY,
14
+ })
15
+ }
16
+
17
+ function sha256(value) {
18
+ return createHash('sha256').update(JSON.stringify(value)).digest('hex')
19
+ }
20
+
21
+ export function mergeNetworkSnapshots(snapshots, {
22
+ retrievedAt = new Date().toISOString(),
23
+ note,
24
+ metadata = {},
25
+ geometryMetadata = {},
26
+ } = {}) {
27
+ if (!snapshots.length) throw new Error('At least one network snapshot is required')
28
+ const first = snapshots[0]
29
+ for (const snapshot of snapshots.slice(1)) {
30
+ if (snapshot.metadata.serviceDate !== first.metadata.serviceDate ||
31
+ snapshot.metadata.windowStart !== first.metadata.windowStart ||
32
+ snapshot.metadata.windowEnd !== first.metadata.windowEnd) {
33
+ throw new Error('Network snapshots must share a service date and study window')
34
+ }
35
+ }
36
+
37
+ const stops = []
38
+ const stopIndexBySourceId = new Map()
39
+ const paths = []
40
+ const pathIndexByCoordinates = new Map()
41
+ const edges = []
42
+ const edgePaths = []
43
+ const trains = []
44
+
45
+ for (const snapshot of snapshots) {
46
+ const stopRemap = snapshot.stops.map((stop) => {
47
+ const sourceId = stop[4] ?? `${stop[0]}:${stop[1]}:${stop[2]}`
48
+ const existing = stopIndexBySourceId.get(sourceId)
49
+ if (existing !== undefined) return existing
50
+ const index = stops.length
51
+ stops.push(stop)
52
+ stopIndexBySourceId.set(sourceId, index)
53
+ return index
54
+ })
55
+ const pathRemap = (snapshot.paths ?? []).map((path) => {
56
+ const key = JSON.stringify(path)
57
+ const existing = pathIndexByCoordinates.get(key)
58
+ if (existing !== undefined) return existing
59
+ const index = paths.length
60
+ paths.push(path)
61
+ pathIndexByCoordinates.set(key, index)
62
+ return index
63
+ })
64
+ snapshot.edges.forEach(([from, to], index) => {
65
+ edges.push([stopRemap[from], stopRemap[to]])
66
+ const sourcePath = snapshot.edgePaths ? snapshot.edgePaths[index] : index
67
+ edgePaths.push(sourcePath == null ? null : pathRemap[sourcePath] ?? null)
68
+ })
69
+ trains.push(...snapshot.trains.map((train) => ({
70
+ ...train,
71
+ stops: train.stops.map(([stopIndex, arrival, departure]) => [stopRemap[stopIndex], arrival, departure]),
72
+ pathSegments: train.pathSegments?.map((pathIndex) => pathIndex === null ? null : pathRemap[pathIndex] ?? null),
73
+ })))
74
+ }
75
+
76
+ const sources = snapshots.map(({ metadata }) => ({
77
+ modes: metadata.modes,
78
+ sourceUrl: metadata.sourceUrl,
79
+ sourceSha256: metadata.sourceSha256,
80
+ geometrySourceUrl: metadata.geometry?.sourceUrl,
81
+ geometrySourceSha256: metadata.geometry?.sourceSha256,
82
+ model: metadata.model,
83
+ note: metadata.note,
84
+ }))
85
+ const modes = [...new Set(snapshots.flatMap(({ metadata }) => metadata.modes ?? []))]
86
+ return {
87
+ metadata: {
88
+ ...first.metadata,
89
+ ...metadata,
90
+ serviceDate: first.metadata.serviceDate,
91
+ windowStart: first.metadata.windowStart,
92
+ windowEnd: first.metadata.windowEnd,
93
+ focusTime: first.metadata.focusTime,
94
+ sourceSha256: sha256(sources),
95
+ retrievedAt,
96
+ note: note ?? `${snapshots.length} studies merged into one network.`,
97
+ modes,
98
+ sources,
99
+ geometry: {
100
+ publisher: first.metadata.publisher,
101
+ feedVersion: first.metadata.feedVersion,
102
+ sourceUrl: first.metadata.sourceUrl,
103
+ model: 'Deduplicated paths from component networks',
104
+ ...first.metadata.geometry,
105
+ ...geometryMetadata,
106
+ sourceSha256: sha256(sources.map(({ geometrySourceSha256 }) => geometrySourceSha256)),
107
+ matchedSegments: paths.length,
108
+ totalSegments: paths.length,
109
+ },
110
+ },
111
+ bounds: boundsFor(stops),
112
+ stops,
113
+ edges,
114
+ paths,
115
+ edgePaths,
116
+ trains,
117
+ }
118
+ }
@@ -0,0 +1,6 @@
1
+ import type { NetworkSnapshot, NetworkDayManifest, NetworkDayChunkDescriptor, NetworkDayChunk } from '@motionstudies/core/domain/network'
2
+ export function extractNetworkWindow(snapshot: NetworkSnapshot, windowStart: number, windowEnd: number, focusTime: number): NetworkSnapshot
3
+ export function chunkNetworkSnapshot(snapshot: NetworkSnapshot, chunkSeconds: number, chunkDirectoryName: string): {
4
+ manifest: NetworkDayManifest
5
+ chunks: { descriptor: NetworkDayChunkDescriptor; payload: NetworkDayChunk }[]
6
+ }
@@ -0,0 +1,71 @@
1
+ import { createHash } from 'node:crypto'
2
+
3
+ export function extractNetworkWindow(snapshot, windowStart, windowEnd, focusTime) {
4
+ if (windowStart >= windowEnd) throw new Error('Network window must have positive duration')
5
+ return {
6
+ ...snapshot,
7
+ metadata: {
8
+ ...snapshot.metadata,
9
+ windowStart,
10
+ windowEnd,
11
+ focusTime,
12
+ },
13
+ trains: snapshot.trains.filter(
14
+ (train) => train.start <= windowEnd && train.end >= windowStart,
15
+ ),
16
+ }
17
+ }
18
+
19
+ export function chunkNetworkSnapshot(snapshot, chunkSeconds, chunkDirectoryName) {
20
+ if (!Number.isSafeInteger(chunkSeconds) || chunkSeconds <= 0) {
21
+ throw new Error('Chunk duration must be a positive whole number of seconds')
22
+ }
23
+ if (!Number.isSafeInteger(snapshot.metadata.windowStart) || !Number.isSafeInteger(snapshot.metadata.windowEnd) || snapshot.metadata.windowEnd <= snapshot.metadata.windowStart) {
24
+ throw new Error('Network window must have positive duration in whole seconds')
25
+ }
26
+ const clockId = (time) => `${String(Math.floor(time / 3600)).padStart(2, '0')}h${String(Math.floor(time / 60) % 60).padStart(2, '0')}m${String(time % 60).padStart(2, '0')}s`
27
+ const chunks = []
28
+ for (
29
+ let windowStart = snapshot.metadata.windowStart;
30
+ windowStart < snapshot.metadata.windowEnd;
31
+ windowStart += chunkSeconds
32
+ ) {
33
+ const windowEnd = Math.min(snapshot.metadata.windowEnd, windowStart + chunkSeconds)
34
+ const startHour = String(Math.floor(windowStart / 3600)).padStart(2, '0')
35
+ const endHour = String(Math.ceil(windowEnd / 3600)).padStart(2, '0')
36
+ const id = windowStart % 3600 === 0 && windowEnd % 3600 === 0
37
+ ? `${startHour}-${endHour}`
38
+ : `${clockId(windowStart)}-${clockId(windowEnd)}`
39
+ const trains = snapshot.trains.filter(
40
+ (train) => train.start <= windowEnd && train.end >= windowStart,
41
+ )
42
+ const payload = { windowStart, windowEnd, trains }
43
+ const encoded = JSON.stringify(payload)
44
+ chunks.push({
45
+ descriptor: {
46
+ id,
47
+ windowStart,
48
+ windowEnd,
49
+ path: `${chunkDirectoryName}/${id}.json`,
50
+ tripCount: trains.length,
51
+ bytes: Buffer.byteLength(encoded),
52
+ sha256: createHash('sha256').update(encoded).digest('hex'),
53
+ },
54
+ payload,
55
+ })
56
+ }
57
+
58
+ return {
59
+ manifest: {
60
+ metadata: snapshot.metadata,
61
+ bounds: snapshot.bounds,
62
+ stops: snapshot.stops,
63
+ edges: snapshot.edges,
64
+ ...(snapshot.paths ? { paths: snapshot.paths } : {}),
65
+ ...(snapshot.edgePaths ? { edgePaths: snapshot.edgePaths } : {}),
66
+ tripCount: snapshot.trains.length,
67
+ chunks: chunks.map(({ descriptor }) => descriptor),
68
+ },
69
+ chunks,
70
+ }
71
+ }
package/package.json ADDED
@@ -0,0 +1,56 @@
1
+ {
2
+ "name": "@motionstudies/data",
3
+ "version": "0.1.0-alpha.0",
4
+ "private": false,
5
+ "type": "module",
6
+ "description": "Offline data preparation primitives for Motion Studies.",
7
+ "license": "MIT",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/emmettl/motionstudies.git",
11
+ "directory": "packages/data"
12
+ },
13
+ "homepage": "https://github.com/emmettl/motionstudies#readme",
14
+ "bugs": {
15
+ "url": "https://github.com/emmettl/motionstudies/issues"
16
+ },
17
+ "publishConfig": {
18
+ "access": "public",
19
+ "registry": "https://registry.npmjs.org/",
20
+ "tag": "next"
21
+ },
22
+ "engines": {
23
+ "node": ">=20"
24
+ },
25
+ "exports": {
26
+ "./gtfs": {
27
+ "types": "./gtfs.d.mts",
28
+ "import": "./gtfs.mjs"
29
+ },
30
+ "./network-chunks": {
31
+ "types": "./network-chunks.d.mts",
32
+ "import": "./network-chunks.mjs"
33
+ },
34
+ "./station-ranking": {
35
+ "types": "./station-ranking.d.mts",
36
+ "import": "./station-ranking.mjs"
37
+ },
38
+ "./merge-network": {
39
+ "types": "./merge-network.d.mts",
40
+ "import": "./merge-network.mjs"
41
+ }
42
+ },
43
+ "files": [
44
+ "**/*.js",
45
+ "**/*.mjs",
46
+ "**/*.d.ts",
47
+ "**/*.d.mts",
48
+ "**/*.css",
49
+ "README.md",
50
+ "LICENSE"
51
+ ],
52
+ "sideEffects": false,
53
+ "dependencies": {
54
+ "@motionstudies/core": "0.1.0-alpha.0"
55
+ }
56
+ }
@@ -0,0 +1,19 @@
1
+ import type { NetworkSnapshot } from '@motionstudies/core/domain/network'
2
+ export interface StationRank {
3
+ name: string
4
+ labelRank: number
5
+ modeCount: number
6
+ routeCount: number
7
+ movementCount: number
8
+ neighbourCount: number
9
+ score: number
10
+ }
11
+ export interface RankingOptions {
12
+ catalogue?: { lines?: readonly {
13
+ mode: string
14
+ name: string
15
+ directions?: readonly { branches: readonly { stopIds?: readonly string[] }[] }[]
16
+ }[] }
17
+ }
18
+ export function rankNetworkStations(snapshot: NetworkSnapshot, options?: RankingOptions): StationRank[]
19
+ export function applyStationLabelRanks(snapshot: NetworkSnapshot, options?: RankingOptions): NetworkSnapshot
@@ -0,0 +1,101 @@
1
+
2
+
3
+ export function rankNetworkStations(snapshot, { catalogue } = {}) {
4
+ const records = new Map()
5
+ const nameByStopIndex = snapshot.stops.map((stop, stopIndex) => {
6
+ const name = stop[2]
7
+ const record = records.get(name) ?? {
8
+ name,
9
+ stopIndexes: [],
10
+ trainIds: new Set(),
11
+ routes: new Set(),
12
+ modes: new Set(),
13
+ neighbours: new Set(),
14
+ }
15
+ record.stopIndexes.push(stopIndex)
16
+ records.set(name, record)
17
+ return name
18
+ })
19
+
20
+ for (const train of snapshot.trains) {
21
+ const visited = new Set()
22
+ for (const [stopIndex] of train.stops) {
23
+ const name = nameByStopIndex[stopIndex]
24
+ if (!name || visited.has(name)) continue
25
+ visited.add(name)
26
+ const record = records.get(name)
27
+ record.trainIds.add(train.id)
28
+ record.routes.add(`${train.mode ?? train.category}:${train.route}`)
29
+ record.modes.add(train.mode ?? train.category)
30
+ }
31
+ }
32
+
33
+ if (catalogue) {
34
+ const nameBySourceId = new Map(snapshot.stops.map((stop) => [stop[4], stop[2]]))
35
+ for (const line of catalogue.lines ?? []) {
36
+ const visitedNames = new Set()
37
+ for (const branch of line.directions?.flatMap(({ branches }) => branches) ?? []) {
38
+ for (const sourceId of branch.stopIds ?? []) {
39
+ const name = nameBySourceId.get(sourceId)
40
+ if (!name || visitedNames.has(name)) continue
41
+ visitedNames.add(name)
42
+ const record = records.get(name)
43
+ record.routes.add(`${line.mode}:${line.name}`)
44
+ record.modes.add(line.mode)
45
+ }
46
+ }
47
+ }
48
+ }
49
+
50
+ for (const [fromIndex, toIndex] of snapshot.edges) {
51
+ const from = nameByStopIndex[fromIndex]
52
+ const to = nameByStopIndex[toIndex]
53
+ if (!from || !to || from === to) continue
54
+ records.get(from).neighbours.add(to)
55
+ records.get(to).neighbours.add(from)
56
+ }
57
+
58
+ const scored = [...records.values()].map((record) => ({
59
+ ...record,
60
+ score:
61
+ record.modes.size * 40 +
62
+ record.routes.size * 12 +
63
+ Math.log2(record.trainIds.size + 1) * 3 +
64
+ Math.min(record.neighbours.size, 10),
65
+ }))
66
+ return scored
67
+ .sort((first, second) =>
68
+ second.score - first.score ||
69
+ second.modes.size - first.modes.size ||
70
+ second.routes.size - first.routes.size ||
71
+ second.trainIds.size - first.trainIds.size ||
72
+ second.neighbours.size - first.neighbours.size ||
73
+ first.name.localeCompare(second.name, 'en-GB'))
74
+ .map((record, labelRank) => ({
75
+ name: record.name,
76
+ labelRank,
77
+ modeCount: record.modes.size,
78
+ routeCount: record.routes.size,
79
+ movementCount: record.trainIds.size,
80
+ neighbourCount: record.neighbours.size,
81
+ score: Number(record.score.toFixed(3)),
82
+ }))
83
+ }
84
+
85
+ export function applyStationLabelRanks(snapshot, options) {
86
+ const ranking = rankNetworkStations(snapshot, options)
87
+ const rankByName = new Map(ranking.map(({ name, labelRank }) => [name, labelRank]))
88
+ return {
89
+ ...snapshot,
90
+ metadata: {
91
+ ...snapshot.metadata,
92
+ labelHierarchy: {
93
+ model: `Stable station-name rank by mode interchange, distinct routes, scheduled calls and graph degree${options?.catalogue ? ', enriched by advertised topology' : ''}`,
94
+ stationCount: ranking.length,
95
+ },
96
+ },
97
+ stops: snapshot.stops.map((stop) => [
98
+ stop[0], stop[1], stop[2], stop[3], stop[4], rankByName.get(stop[2]),
99
+ ]),
100
+ }
101
+ }