Commit 7bf5734d1f
Unsigned
Layout: unified · split
App/Sources/SunForecastViews.swift added +94
| @@ -0,0 +1,94 @@ | ||
| 1 | import Charts | |
| 2 | import Feeds | |
| 3 | import SwiftUI | |
| 4 | ||
| 5 | /// CCOR-2's view of the corona over the last day: the latest frame, and a loop of one frame an hour on request. | |
| 6 | struct CoronagraphLoop: View { | |
| 7 | var frames: [SunForecast.Frame] | |
| 8 | var ink: Color | |
| 9 | var accent: Color | |
| 10 | @State private var loop: [(date: Date, image: UIImage)] = [] | |
| 11 | @State private var loading = false | |
| 12 | ||
| 13 | var body: some View { | |
| 14 | VStack(alignment: .leading, spacing: 8) { | |
| 15 | if loop.isEmpty { | |
| 16 | RemoteImage(url: frames.last?.url, points: 600) { Color.black } | |
| 17 | .aspectRatio(1024 / 960, contentMode: .fit) | |
| 18 | Button(loading ? "Loading \(frames.count) frames" : "Play the last 24 hours") { Task { await play() } } | |
| 19 | .disabled(loading).tint(accent).font(.footnote) | |
| 20 | } else { | |
| 21 | TimelineView(.periodic(from: .now, by: 0.25)) { context in | |
| 22 | let i = Int(context.date.timeIntervalSinceReferenceDate * 4) % loop.count | |
| 23 | VStack(alignment: .leading, spacing: 4) { | |
| 24 | Image(uiImage: loop[i].image).resizable().aspectRatio(1024 / 960, contentMode: .fit) | |
| 25 | Text(loop[i].date.formatted(date: .abbreviated, time: .shortened)).font(.caption2.monospacedDigit()).dimmed(0.6) | |
| 26 | } | |
| 27 | } | |
| 28 | } | |
| 29 | } | |
| 30 | .accessibilityLabel("Coronagraph images of the Sun's outer corona") | |
| 31 | } | |
| 32 | ||
| 33 | private func play() async { | |
| 34 | loading = true | |
| 35 | var out: [(Date, UIImage)] = [] | |
| 36 | for f in frames { | |
| 37 | if let image = try? await ImageLoader.load(f.url, maxPixels: 600) { out.append((f.t, image)) } | |
| 38 | } | |
| 39 | loop = out | |
| 40 | loading = false | |
| 41 | } | |
| 42 | } | |
| 43 | ||
| 44 | /// WSA-Enlil's forecast of the solar wind speed at Earth, with CME arrivals shaded. | |
| 45 | struct EnlilChart: View { | |
| 46 | var points: [SunForecast.EnlilPoint] | |
| 47 | var ink: Color | |
| 48 | var accent: Color | |
| 49 | ||
| 50 | var body: some View { | |
| 51 | Chart { | |
| 52 | ForEach(points.filter(\.cloud)) { p in | |
| 53 | RectangleMark(xStart: .value("", p.t), xEnd: .value("", p.t.addingTimeInterval(3600))).foregroundStyle(accent.opacity(0.25)) | |
| 54 | } | |
| 55 | ForEach(points) { p in LineMark(x: .value("Time", p.t), y: .value("Speed", p.speed)).foregroundStyle(ink) } | |
| 56 | RuleMark(x: .value("Now", Date.now)).foregroundStyle(ink.opacity(0.5)).lineStyle(StrokeStyle(lineWidth: 0.5, dash: [3, 3])) | |
| 57 | } | |
| 58 | .chartYAxis { AxisMarks(values: [300, 500, 700, 900]) { _ in AxisGridLine().foregroundStyle(ink.opacity(0.12)); AxisValueLabel().foregroundStyle(ink.opacity(0.6)) } } | |
| 59 | .chartXAxis { AxisMarks(values: .stride(by: .day)) { _ in AxisGridLine().foregroundStyle(ink.opacity(0.12)); AxisValueLabel(format: .dateTime.weekday(.abbreviated)).foregroundStyle(ink.opacity(0.6)) } } | |
| 60 | .frame(height: 130) | |
| 61 | .accessibilityLabel("Forecast solar wind speed at Earth in kilometres per second") | |
| 62 | } | |
| 63 | } | |
| 64 | ||
| 65 | /// Monthly sunspot numbers through cycle 25 and NOAA's prediction with its range. | |
| 66 | struct CycleChart: View { | |
| 67 | var cycle: SunForecast.Cycle | |
| 68 | var ink: Color | |
| 69 | var accent: Color | |
| 70 | ||
| 71 | var body: some View { | |
| 72 | Chart { | |
| 73 | ForEach(cycle.predicted) { p in | |
| 74 | if let d = p.date { | |
| 75 | AreaMark(x: .value("Month", d), yStart: .value("Low", p.low), yEnd: .value("High", p.high)).foregroundStyle(ink.opacity(0.15)) | |
| 76 | LineMark(x: .value("Month", d), y: .value("Predicted", p.ssn), series: .value("", "predicted")) | |
| 77 | .foregroundStyle(ink.opacity(0.5)).lineStyle(StrokeStyle(lineWidth: 1, dash: [3, 3])) | |
| 78 | } | |
| 79 | } | |
| 80 | ForEach(cycle.observed) { m in | |
| 81 | if let d = m.date, let s = m.ssn { | |
| 82 | BarMark(x: .value("Month", d, unit: .month), y: .value("Sunspots", s)).foregroundStyle(ink.opacity(0.35)) | |
| 83 | } | |
| 84 | if let d = m.date, let s = m.smoothed { | |
| 85 | LineMark(x: .value("Month", d), y: .value("Smoothed", s), series: .value("", "smoothed")).foregroundStyle(accent) | |
| 86 | } | |
| 87 | } | |
| 88 | } | |
| 89 | .chartXAxis { AxisMarks(values: .stride(by: .year, count: 2)) { _ in AxisGridLine().foregroundStyle(ink.opacity(0.12)); AxisValueLabel(format: .dateTime.year()).foregroundStyle(ink.opacity(0.6)) } } | |
| 90 | .chartYAxis { AxisMarks { _ in AxisGridLine().foregroundStyle(ink.opacity(0.12)); AxisValueLabel().foregroundStyle(ink.opacity(0.6)) } } | |
| 91 | .frame(height: 140) | |
| 92 | .accessibilityLabel("Monthly sunspot numbers in solar cycle 25") | |
| 93 | } | |
| 94 | } | |
App/Sources/SunScreen.swift +11
| @@ -14,6 +14,7 @@ struct SunScreen: View { | ||
| 14 | 14 | @State private var imageFailed = false |
| 15 | 15 | @State private var solarWind: SolarWind? |
| 16 | 16 | @State private var regions: [SolarRegion] = [] |
| 17 | @State private var forecast: SunForecast? | |
| 17 | 18 | @AppStorage("sunRegionLabels") private var regionLabels = true |
| 18 | 19 | @Environment(\.dynamicTypeSize) private var typeSize |
| 19 | 20 | |
| @@ -61,10 +62,19 @@ struct SunScreen: View { | ||
| 61 | 62 | if let solarWind { |
| 62 | 63 | section("Solar wind", note: "Measured 1.5 million km sunward of Earth, 30 to 60 minutes before it arrives. When Bz, the north–south part of its magnetic field, turns strongly negative (south), aurora often follows.") { solarWindPanel(solarWind) } |
| 63 | 64 | } |
| 65 | if let f = forecast, !f.enlil.isEmpty { | |
| 66 | section("Solar wind forecast", note: "NOAA's WSA-Enlil model of the solar wind speed at Earth, in km/s, for the coming days. Shaded: a coronal mass ejection arriving, which can bring a storm.") { EnlilChart(points: f.enlil, ink: ink, accent: accent) } | |
| 67 | } | |
| 68 | if let f = forecast, !f.ccor2.isEmpty { | |
| 69 | section("Coronagraph", note: "The Sun's outer corona from NOAA's CCOR-2 on SOLAR-1, with the bright disk blocked. Coronal mass ejections show as expanding clouds.") { CoronagraphLoop(frames: f.ccor2, ink: ink, accent: accent) } | |
| 70 | } | |
| 64 | 71 | section("Solar flares, last 24 h", note: "X-rays from the Sun, measured by NOAA's GOES satellites. Spikes are flares: M and X class can disrupt radio and GPS, and the biggest can bring a storm a day or two later.") { |
| 65 | 72 | flares |
| 66 | 73 | if let p = data?.probabilities { probabilityTable(p) } |
| 67 | 74 | } |
| 75 | if let c = forecast?.cycle { | |
| 76 | section("Solar cycle 25", note: "Monthly sunspot numbers since the cycle began in December 2019 (bars), smoothed (red), and NOAA's prediction with its range.") { CycleChart(cycle: c, ink: ink, accent: accent) } | |
| 77 | } | |
| 68 | 78 | section("Geomagnetic activity (Kp)", note: "How disturbed Earth's magnetic field is, from 0 (quiet) to 9. At 5 or more it is a storm and the aurora reaches lower latitudes.") { kpChart } |
| 69 | 79 | |
| 70 | 80 | Text("The Sun as NASA's Solar Dynamics Observatory sees it now, and the space weather it sends our way: flares, magnetic storms and the aurora.") |
| @@ -85,6 +95,7 @@ struct SunScreen: View { | ||
| 85 | 95 | if data == nil { await show(SunFeeds.lastSaved()) } |
| 86 | 96 | if let apiBase { solarWind = (try? await SolarWind.fetch(base: apiBase)) ?? solarWind } |
| 87 | 97 | regions = (try? await SolarRegion.fetch()) ?? regions |
| 98 | if let apiBase { forecast = (try? await SunForecast.fetch(base: apiBase)) ?? forecast } | |
| 88 | 99 | if force { imageID = .now } |
| 89 | 100 | let result = await SunFeeds.load(force: force) |
| 90 | 101 | await show(result?.snapshot) |
PLAN.org +3 −1
| @@ -524,7 +524,9 @@ Worker; DSN Now freshness; NASA/ESA image licences; 26 LoC plates bundled. | ||
| 524 | 524 | - Sun path, golden and blue hour, day length. Done: =SunDay= (SkyEngine) and a Sun tab |
| 525 | 525 | section with the altitude curve, rise, set, noon, day length against |
| 526 | 526 | yesterday, golden (−4° to +6°) and blue (−6° to −4°) hours. |
| 527 | - CCOR-2 coronagraph loop, WSA-Enlil forecast line, solar cycle progress. | |
| 527 | - CCOR-2 coronagraph loop, WSA-Enlil forecast line, solar cycle progress. Done: =/v1/sun= | |
| 528 | (hourly Enlil at Earth with CME hours, CCOR-2 frames one an hour for a day, | |
| 529 | cycle 25 monthly); Sun tab charts and a loop played on request. | |
| 528 | 530 | |
| 529 | 531 | ** v5.2: Sky |
| 530 | 532 | - Milky Way from ESA's "Gaia's sky in colour" (CC BY-SA), clipped before |
Packages/MoonriseKit/Sources/Feeds/SunForecast.swift added +77
| @@ -0,0 +1,77 @@ | ||
| 1 | import Foundation | |
| 2 | ||
| 3 | /// The backend's /v1/sun: WSA-Enlil solar wind forecast at Earth (hourly), CCOR-2 coronagraph frames (hourly over a | |
| 4 | /// day) and solar cycle 25 sunspot numbers (monthly), all from NOAA SWPC. | |
| 5 | public struct SunForecast: Sendable, Decodable { | |
| 6 | public struct EnlilPoint: Sendable, Decodable, Identifiable { | |
| 7 | public var t: Date | |
| 8 | public var speed: Double | |
| 9 | public var density: Double | |
| 10 | /// In a coronal mass ejection's cloud. | |
| 11 | public var cloud: Bool | |
| 12 | public var id: Date { t } | |
| 13 | } | |
| 14 | ||
| 15 | public struct Frame: Sendable, Decodable, Identifiable { | |
| 16 | public var t: Date | |
| 17 | public var url: URL | |
| 18 | public var id: Date { t } | |
| 19 | } | |
| 20 | ||
| 21 | public struct Month: Sendable, Decodable, Identifiable { | |
| 22 | public var month: String | |
| 23 | public var ssn: Double? | |
| 24 | public var smoothed: Double? | |
| 25 | public var id: String { month } | |
| 26 | } | |
| 27 | ||
| 28 | public struct Predicted: Sendable, Decodable, Identifiable { | |
| 29 | public var month: String | |
| 30 | public var ssn: Double | |
| 31 | public var high: Double | |
| 32 | public var low: Double | |
| 33 | public var id: String { month } | |
| 34 | } | |
| 35 | ||
| 36 | public struct Cycle: Sendable, Decodable { | |
| 37 | public var observed: [Month] | |
| 38 | public var predicted: [Predicted] | |
| 39 | } | |
| 40 | ||
| 41 | public var enlil: [EnlilPoint] | |
| 42 | public var ccor2: [Frame] | |
| 43 | public var cycle: Cycle? | |
| 44 | ||
| 45 | private struct Raw: Decodable { | |
| 46 | struct Part<T: Decodable>: Decodable { var points: T?; var frames: T?; var months: T? } | |
| 47 | var enlil: Part<[EnlilPoint]> | |
| 48 | var ccor2: Part<[Frame]> | |
| 49 | var cycle: Part<Cycle> | |
| 50 | } | |
| 51 | ||
| 52 | static func decode(_ data: Data) throws -> SunForecast { | |
| 53 | let d = JSONDecoder() | |
| 54 | d.dateDecodingStrategy = .custom { decoder in | |
| 55 | let s = try decoder.singleValueContainer().decode(String.self) | |
| 56 | guard let date = try? Date(s, strategy: Date.ISO8601FormatStyle(includingFractionalSeconds: true)) else { | |
| 57 | throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: "bad date \(s)")) | |
| 58 | } | |
| 59 | return date | |
| 60 | } | |
| 61 | let r = try d.decode(Raw.self, from: data) | |
| 62 | return SunForecast(enlil: r.enlil.points ?? [], ccor2: r.ccor2.frames ?? [], cycle: r.cycle.months) | |
| 63 | } | |
| 64 | ||
| 65 | public static func fetch(base: URL, session: URLSession = .shared) async throws -> SunForecast { | |
| 66 | try decode(await session.data(from: base.appending(path: "v1/sun")).0) | |
| 67 | } | |
| 68 | } | |
| 69 | ||
| 70 | extension SunForecast.Month { | |
| 71 | /// The first of the month, UTC. | |
| 72 | public var date: Date? { try? Date(month + "-01T00:00:00Z", strategy: .iso8601) } | |
| 73 | } | |
| 74 | ||
| 75 | extension SunForecast.Predicted { | |
| 76 | public var date: Date? { try? Date(month + "-01T00:00:00Z", strategy: .iso8601) } | |
| 77 | } | |
Packages/MoonriseKit/Tests/FeedsTests/SpaceWeatherTests.swift +8
| @@ -44,3 +44,11 @@ let forecast = Data(""" | ||
| 44 | 44 | #expect(w.density == 5.8) |
| 45 | 45 | #expect(try SolarWind.decodeToday(Data(#"{"spaceWeather":null}"#.utf8)) == nil) |
| 46 | 46 | } |
| 47 | ||
| 48 | @Test func decodesBackendSun() throws { | |
| 49 | let data = Data(#"{"enlil":{"fetchedAt":"x","points":[{"t":"2026-10-22T00:00:00.000Z","speed":410,"density":5,"cloud":false}]},"ccor2":{"fetchedAt":"x","frames":[{"t":"2026-10-22T03:30:00.000Z","url":"https://services.swpc.noaa.gov/images/animations/ccor2/20261022_0330_ccor2_1024by960.jpg"}]},"cycle":{"fetchedAt":null,"months":null}}"#.utf8) | |
| 50 | let s = try SunForecast.decode(data) | |
| 51 | #expect(s.enlil.first?.speed == 410) | |
| 52 | #expect(s.ccor2.count == 1) | |
| 53 | #expect(s.cycle == nil) | |
| 54 | } | |
server/src/index.ts +33 −3
| @@ -6,6 +6,7 @@ import { activeEvent, fetchTrajectory, STEP_MINUTES } from "./live"; | ||
| 6 | 6 | import { fetchLaunch, fetchLaunches, PREVIOUS_URL, throttleSeconds, Throttled, UPCOMING_URL, type Launch } from "./ll2"; |
| 7 | 7 | import { digestPayload, dueOffsets, fetchLatest, localDate, pickHeadlines, type Article } from "./news"; |
| 8 | 8 | import { fetchSolarWind, STORM_KP, stormLikely, type SolarWind } from "./solarwind"; |
| 9 | import { fetchCcor2, fetchCycle, fetchEnlil } from "./sun"; | |
| 9 | 10 | import { fetchSpaceWeather, next24h, type SpaceWeather } from "./swpc"; |
| 10 | 11 | |
| 11 | 12 | interface Env { |
| @@ -49,7 +50,7 @@ const json = (body: unknown, status = 200, maxAge?: number) => | ||
| 49 | 50 | const PRIVACY_URL = "https://krz.sh/privacy/moonrise/"; |
| 50 | 51 | |
| 51 | 52 | /** Read-only endpoints whose responses are the same for everyone. */ |
| 52 | const API = new Set(["/v1/today", "/v1/launches", "/v1/live", "/v1/satellites", "/v1/news"]); | |
| 53 | const API = new Set(["/v1/today", "/v1/launches", "/v1/live", "/v1/satellites", "/v1/news", "/v1/sun"]); | |
| 53 | 54 | |
| 54 | 55 | function api(url: URL, env: Env, now: Date): Promise<Response> { |
| 55 | 56 | switch (url.pathname) { |
| @@ -57,10 +58,20 @@ function api(url: URL, env: Env, now: Date): Promise<Response> { | ||
| 57 | 58 | case "/v1/launches": return launches(env, url, now); |
| 58 | 59 | case "/v1/live": return live(env, url, now); |
| 59 | 60 | case "/v1/news": return news(env); |
| 61 | case "/v1/sun": return sun(env); | |
| 60 | 62 | default: return satellites(env); |
| 61 | 63 | } |
| 62 | 64 | } |
| 63 | 65 | |
| 66 | /** WSA-Enlil at Earth, CCOR-2 frames and solar cycle 25, each with the time it was fetched. */ | |
| 67 | async function sun(env: Env): Promise<Response> { | |
| 68 | const rows = await env.DB.prepare("SELECT feed, fetched_at, body FROM feed_snapshots WHERE feed IN ('sun:enlil', 'sun:ccor2', 'sun:cycle') AND ok = 1") | |
| 69 | .all<{ feed: string; fetched_at: string; body: string }>(); | |
| 70 | const get = (f: string) => rows.results.find((r) => r.feed === f); | |
| 71 | const part = (f: string, key: string) => ({ fetchedAt: get(f)?.fetched_at ?? null, [key]: get(f) ? JSON.parse(get(f)!.body) : null }); | |
| 72 | return json({ enlil: part("sun:enlil", "points"), ccor2: part("sun:ccor2", "frames"), cycle: part("sun:cycle", "months") }, 200, MAX_AGE.sun); | |
| 73 | } | |
| 74 | ||
| 64 | 75 | /** Spaceflight News API articles in its own field names, so clients do not call The Space Devs directly. */ |
| 65 | 76 | async function news(env: Env): Promise<Response> { |
| 66 | 77 | const row = await env.DB.prepare("SELECT fetched_at, body FROM feed_snapshots WHERE feed = 'news' AND ok = 1").first<{ fetched_at: string; body: string }>(); |
| @@ -90,7 +101,7 @@ async function cached(request: Request, ctx: ExecutionContext | undefined, respo | ||
| 90 | 101 | } |
| 91 | 102 | |
| 92 | 103 | /** How long clients may reuse each GET response, matched to how often its source is polled. */ |
| 93 | export const MAX_AGE = { today: 60, launches: 300, satellites: 3600, live: 300, news: 600 } as const; | |
| 104 | export const MAX_AGE = { today: 60, launches: 300, satellites: 3600, live: 300, news: 600, sun: 1800 } as const; | |
| 94 | 105 | |
| 95 | 106 | function validDevice(d: Partial<DeviceRequest>): d is DeviceRequest { |
| 96 | 107 | return ( |
| @@ -155,7 +166,7 @@ export default { | ||
| 155 | 166 | if (now.getUTCHours() === 0 && now.getUTCMinutes() === 0) ctx.waitUntil(prune(env, now)); |
| 156 | 167 | } else if (controller.cron === SATELLITE_CRON) ctx.waitUntil(pollSatellites(env, now)); |
| 157 | 168 | else if (controller.cron === FOCUS_CRON) ctx.waitUntil(focusTick(env, now)); |
| 158 | else ctx.waitUntil(Promise.all([pollSpaceWeather(env, now), launchTick(env, now), retrySatellites(env, now)])); | |
| 169 | else ctx.waitUntil(Promise.all([pollSpaceWeather(env, now), launchTick(env, now), retrySatellites(env, now), pollSun(env, now)])); | |
| 159 | 170 | }, |
| 160 | 171 | } satisfies ExportedHandler<Env>; |
| 161 | 172 | |
| @@ -490,6 +501,25 @@ async function pollSolarWind(env: Env, now: Date): Promise<SolarWind | null> { | ||
| 490 | 501 | } |
| 491 | 502 | } |
| 492 | 503 | |
| 504 | /** | |
| 505 | * Hourly at minute 20: WSA-Enlil (runs every few hours) and the CCOR-2 listing; solar cycle numbers once a day | |
| 506 | * (monthly data), or whenever none are stored. Each kept until a fetch succeeds. | |
| 507 | */ | |
| 508 | async function pollSun(env: Env, now: Date): Promise<void> { | |
| 509 | if (now.getUTCMinutes() !== 20) return; | |
| 510 | const save = env.DB.prepare("INSERT INTO feed_snapshots (feed, fetched_at, ok, body) VALUES (?1, ?2, 1, ?3) ON CONFLICT (feed) DO UPDATE SET fetched_at = ?2, ok = 1, body = ?3"); | |
| 511 | const jobs: [string, () => Promise<unknown>][] = [["sun:enlil", () => fetchEnlil(now)], ["sun:ccor2", () => fetchCcor2(now)]]; | |
| 512 | const cycle = await env.DB.prepare("SELECT 1 FROM feed_snapshots WHERE feed = 'sun:cycle' AND ok = 1").first(); | |
| 513 | if (now.getUTCHours() === 0 || !cycle) jobs.push(["sun:cycle", () => fetchCycle()]); | |
| 514 | for (const [feed, job] of jobs) { | |
| 515 | try { | |
| 516 | await save.bind(feed, now.toISOString(), JSON.stringify(await job())).run(); | |
| 517 | } catch (e) { | |
| 518 | console.error(feed, String(e)); | |
| 519 | } | |
| 520 | } | |
| 521 | } | |
| 522 | ||
| 493 | 523 | async function sendAuroraAlerts(env: Env, w: SpaceWeather, wind: SolarWind | null, now: Date): Promise<void> { |
| 494 | 524 | const forecastKp = actionableKp(w.kpNow, w.forecast, now); |
| 495 | 525 | const early = stormLikely(wind, now) && forecastKp < STORM_KP; |
server/src/sun.ts added +76
| @@ -0,0 +1,76 @@ | ||
| 1 | // Sun tab extras from SWPC, reduced for the app: the WSA-Enlil forecast at Earth (hourly), CCOR-2 coronagraph | |
| 2 | // frames (one an hour for a day) and solar cycle 25 sunspot numbers (monthly). | |
| 3 | import { USER_AGENT } from "./agent.ts"; | |
| 4 | ||
| 5 | const BASE = "https://services.swpc.noaa.gov"; | |
| 6 | const headers = { "user-agent": USER_AGENT }; | |
| 7 | ||
| 8 | export interface EnlilPoint { t: string; speed: number; density: number; cloud: boolean } | |
| 9 | export interface Frame { t: string; url: string } | |
| 10 | export interface CycleMonth { month: string; ssn: number | null; smoothed: number | null } | |
| 11 | export interface CyclePrediction { month: string; ssn: number; high: number; low: number } | |
| 12 | export interface Cycle { observed: CycleMonth[]; predicted: CyclePrediction[] } | |
| 13 | ||
| 14 | async function get(path: string): Promise<Response> { | |
| 15 | const res = await fetch(BASE + path, { headers }); | |
| 16 | if (!res.ok) throw new Error(`SWPC ${res.status} for ${path}`); | |
| 17 | return res; | |
| 18 | } | |
| 19 | ||
| 20 | interface EnlilRow { time_tag: string; earth_particles_per_cm3: number; v_r: number; cloud: number | null } | |
| 21 | ||
| 22 | /** Hourly means from `from` on; an hour counts as in a CME cloud if any sample in it is. */ | |
| 23 | export function reduceEnlil(rows: EnlilRow[], from: Date): EnlilPoint[] { | |
| 24 | const hours = new Map<number, { v: number[]; n: number[]; cloud: boolean }>(); | |
| 25 | for (const r of rows) { | |
| 26 | const t = Date.parse(r.time_tag + "Z"); | |
| 27 | if (!(t >= from.getTime()) || !Number.isFinite(r.v_r)) continue; | |
| 28 | const k = Math.floor(t / 3600_000) * 3600_000; | |
| 29 | const h = hours.get(k) ?? { v: [], n: [], cloud: false }; | |
| 30 | h.v.push(r.v_r); | |
| 31 | h.n.push(r.earth_particles_per_cm3); | |
| 32 | h.cloud ||= r.cloud != null && r.cloud > 0; | |
| 33 | hours.set(k, h); | |
| 34 | } | |
| 35 | const avg = (xs: number[]) => Math.round(xs.reduce((a, b) => a + b, 0) / xs.length * 10) / 10; | |
| 36 | return [...hours.entries()].sort((a, b) => a[0] - b[0]) | |
| 37 | .map(([k, h]) => ({ t: new Date(k).toISOString(), speed: avg(h.v), density: avg(h.n), cloud: h.cloud })); | |
| 38 | } | |
| 39 | ||
| 40 | /** The last frame of each hour over the last day, from SWPC's directory listing. */ | |
| 41 | export function ccor2Frames(listing: string, now: Date): Frame[] { | |
| 42 | const byHour = new Map<string, Frame>(); | |
| 43 | for (const m of listing.matchAll(/href="((\d{4})(\d{2})(\d{2})_(\d{2})(\d{2})_ccor2_1024by960\.jpg)"/g)) { | |
| 44 | const t = new Date(`${m[2]}-${m[3]}-${m[4]}T${m[5]}:${m[6]}:00Z`); | |
| 45 | if (now.getTime() - t.getTime() > 24 * 3600_000 || t > now) continue; | |
| 46 | byHour.set(t.toISOString().slice(0, 13), { t: t.toISOString(), url: `${BASE}/images/animations/ccor2/${m[1]}` }); | |
| 47 | } | |
| 48 | return [...byHour.values()].sort((a, b) => a.t.localeCompare(b.t)); | |
| 49 | } | |
| 50 | ||
| 51 | interface ObservedRow { "time-tag": string; ssn: number; smoothed_ssn: number } | |
| 52 | interface PredictedRow { "time-tag": string; predicted_ssn: number; high_ssn: number; low_ssn: number } | |
| 53 | ||
| 54 | /** Cycle 25 began in December 2019. SWPC marks missing smoothed values −1. */ | |
| 55 | export function reduceCycle(observed: ObservedRow[], predicted: PredictedRow[]): Cycle { | |
| 56 | return { | |
| 57 | observed: observed.filter((r) => r["time-tag"] >= "2019-12").map((r) => ({ | |
| 58 | month: r["time-tag"], ssn: r.ssn >= 0 ? r.ssn : null, smoothed: r.smoothed_ssn >= 0 ? r.smoothed_ssn : null, | |
| 59 | })), | |
| 60 | predicted: predicted.map((r) => ({ month: r["time-tag"], ssn: r.predicted_ssn, high: r.high_ssn, low: r.low_ssn })), | |
| 61 | }; | |
| 62 | } | |
| 63 | ||
| 64 | export async function fetchEnlil(now: Date): Promise<EnlilPoint[]> { | |
| 65 | return reduceEnlil(await (await get("/json/enlil_time_series.json")).json() as EnlilRow[], new Date(now.getTime() - 24 * 3600_000)); | |
| 66 | } | |
| 67 | ||
| 68 | export async function fetchCcor2(now: Date): Promise<Frame[]> { | |
| 69 | return ccor2Frames(await (await get("/images/animations/ccor2/")).text(), now); | |
| 70 | } | |
| 71 | ||
| 72 | export async function fetchCycle(): Promise<Cycle> { | |
| 73 | const observed = await (await get("/json/solar-cycle/observed-solar-cycle-indices.json")).json() as ObservedRow[]; | |
| 74 | const predicted = await (await get("/json/solar-cycle/predicted-solar-cycle.json")).json() as PredictedRow[]; | |
| 75 | return reduceCycle(observed, predicted); | |
| 76 | } | |
server/test/sun.test.ts added +33
| @@ -0,0 +1,33 @@ | ||
| 1 | import assert from "node:assert/strict"; | |
| 2 | import { test } from "node:test"; | |
| 3 | import { ccor2Frames, reduceCycle, reduceEnlil } from "../src/sun.ts"; | |
| 4 | ||
| 5 | test("Enlil: hourly means from the start time, CME hours flagged", () => { | |
| 6 | const rows = [ | |
| 7 | { time_tag: "2026-10-22T00:10:00", earth_particles_per_cm3: 4, v_r: 400, cloud: null }, | |
| 8 | { time_tag: "2026-10-22T00:50:00", earth_particles_per_cm3: 6, v_r: 420, cloud: null }, | |
| 9 | { time_tag: "2026-10-22T01:10:00", earth_particles_per_cm3: 20, v_r: 700, cloud: 1 }, | |
| 10 | { time_tag: "2026-10-21T22:00:00", earth_particles_per_cm3: 5, v_r: 380, cloud: null }, | |
| 11 | ]; | |
| 12 | assert.deepEqual(reduceEnlil(rows, new Date("2026-10-22T00:00:00Z")), [ | |
| 13 | { t: "2026-10-22T00:00:00.000Z", speed: 410, density: 5, cloud: false }, | |
| 14 | { t: "2026-10-22T01:00:00.000Z", speed: 700, density: 20, cloud: true }, | |
| 15 | ]); | |
| 16 | }); | |
| 17 | ||
| 18 | test("CCOR-2: the last frame of each hour in the last day", () => { | |
| 19 | const listing = ["20261021_0300", "20261022_0315", "20261022_0330", "20261022_0400", "20261021_0245"] | |
| 20 | .map((s) => `<a href="${s}_ccor2_1024by960.jpg">x</a>`).join("") + `<a href="latest.jpg">l</a>`; | |
| 21 | const frames = ccor2Frames(listing, new Date("2026-10-22T04:10:00Z")); | |
| 22 | assert.deepEqual(frames.map((f) => f.t), ["2026-10-22T03:30:00.000Z", "2026-10-22T04:00:00.000Z"]); | |
| 23 | assert.equal(frames[0].url, "https://services.swpc.noaa.gov/images/animations/ccor2/20261022_0330_ccor2_1024by960.jpg"); | |
| 24 | }); | |
| 25 | ||
| 26 | test("Cycle 25 from December 2019, missing values as null", () => { | |
| 27 | const c = reduceCycle( | |
| 28 | [{ "time-tag": "2019-11", ssn: 1, smoothed_ssn: 2 }, { "time-tag": "2019-12", ssn: 1.5, smoothed_ssn: 1.8 }, { "time-tag": "2026-09", ssn: 60.3, smoothed_ssn: -1 }], | |
| 29 | [{ "time-tag": "2026-10", predicted_ssn: 90, high_ssn: 100, low_ssn: 80 }], | |
| 30 | ); | |
| 31 | assert.deepEqual(c.observed, [{ month: "2019-12", ssn: 1.5, smoothed: 1.8 }, { month: "2026-09", ssn: 60.3, smoothed: null }]); | |
| 32 | assert.deepEqual(c.predicted, [{ month: "2026-10", ssn: 90, high: 100, low: 80 }]); | |
| 33 | }); | |