krz/moonrise

Night-sky companion for iPhone, Apple Watch and Vision Pro: what's up tonight, the Moon, planets, launches and missions, and a Library of the solar system. SwiftUI app with a Cloudflare Workers backend. astronomy cloudflare-workers ios night-sky space swiftui visionos watchos

Commit f783dd307a

f783dd307aac86127fad610a52fcdd28eac94d27

parent: aeab22a293

Unsigned

cmc <hello@cleberg.net> · 2026-10-21 07:13 UTC

Sun tab: X-ray chart from 5-minute maxima, place and night from SkyModel (!77)

- X-ray chart draws `XRay.maxima` (highest sample per 5 minutes, 288 marks instead of 1,440). Peaks keep their flux and time; `chartXScale` keeps the full day. Test `xrayMaximaKeepPeaks`.
- `SunScreen.observer` reads `SkyModel.shared.observer` instead of creating a `CLLocationManager` twice per body.
- `SunFeeds.summary` is async and uses `SkyModel.tonight`; it computes a `Tonight` on the `Astronomer` actor only when none exists or it has ended. `SkyScreen` now uses `SkyModel.shared`.
- Behaviour change: the summary and the aurora-map marker use the Sky tab's place, so a city chosen in Settings, rather than the device's last fix.

## Measurements

iPhone 18 Pro simulator (iOS 27), Release build, M2 Pro. Driver: a UI test (launch, open Sun, scroll, back to Sky, reopen Sun). Frame intervals come from a temporary CADisplayLink probe, which is not committed. Each window runs from the tab tap to 1.5 s after. Load average (12 cores) was 2.2–4.0 at the start of every run.

Sun tab first open, 6 runs without the profiler on each side:

| | before | after |
|---|---:|---:|
| Longest frame, ms (range) | 188–376 | 95–326 |
| Longest frame, median | 236 | 134 |
| Frames over 100 ms per open | 2–3 (every run) | 0–2 (1 in 4 runs) |
| ms lost to frames over 25 ms, median | 552 | 375 |
| Longest frame with a saved snapshot (4 runs) | 188–376 | 95–135 |
| Longest frame on a fresh install, no saved snapshot (2 runs) | 221, 282 | 233, 326 |

Time Profiler, first open (1 run each):
- Charts on the main thread: 283 → 122 ms.
- All main-thread time in the step: 700 → 510 ms.
- `CLLocationManager`, `SunFeeds.summary` and `Tonight` on main: 11 → 0 ms.

The longest remaining frame (410 ms under the profiler) is mostly the tab's first presentation. Its main-thread time was 218 ms:
- SwiftUI and UIKit: 91 ms
- Swift conformance lookups: 67 ms (much larger in the simulator)
- Charts: 51 ms (both charts, first use)
- SDO image decode in `loadImage`: about 17 ms (left as is)

Chart render, macOS release benchmark, the app's full chart at 353×160 pt @3x through `ImageRenderer`, median:
- 1,440 marks: 13.6 ms
- 288 marks: 4.3 ms
- Axes and rules alone: 2.1 ms
- `XRay.maxima` alone: 0.012 ms

The line marks therefore went from 11.5 to 2.2 ms.

Appearance:
- On a live NOAA day (1,436 samples, peak C2.9), 0.5% of the chart's pixels differ by more than 24/255 between before and after, and the peak is the same.
- On the benchmark's synthetic fixture (random per-minute noise) 13.5% of pixels differ, because the min–max band of the noise turns into its upper envelope.
- In-app screenshots before and after show the same chart.

## Tests

- `swift test` (MoonriseKit): pass.
- `npm test` (server): 55 pass.
- `xcodebuild test` on the iPhone 18 Pro: pass. The accessibility audit finds 64 issues before and after, with the same counts per screen: Sky 4, Settings 2, System 7, Sun 3, News & launches 21, Library 14, Library page 13.

## Not verified

- Not tested on a device.
- Frames over 100 ms still occur on first open in 5 of 6 runs. On a fresh install the change did not help.
- The whole chart renders in 4.3 ms, which misses the 3 ms target. The axes and rules alone take 2.1 ms.
- VoiceOver's audio graph now reads 288 points instead of 1,440. Not listened to.

Layout: unified · split

App/Sources/SkyModel.swift +2
@@ -40,6 +40,8 @@ struct BodyDetails: Sendable {
40@MainActor 40@MainActor
41@Observable 41@Observable
42final class SkyModel: NSObject, CLLocationManagerDelegate { 42final class SkyModel: NSObject, CLLocationManagerDelegate {
43 /// The Sky tab's model. The Sun tab reads its place and night from here.
44 static let shared = SkyModel()
43 /// Used until a location fix arrives or when location is denied. 45 /// Used until a location fix arrives or when location is denied.
44 static let fallback = Observer(latitude: 41.8781, longitude: -87.6298) 46 static let fallback = Observer(latitude: 41.8781, longitude: -87.6298)
45 47
App/Sources/SkyScreen.swift +1 −1
@@ -5,7 +5,7 @@ import SkyRenderer
5import SwiftUI 5import SwiftUI
6 6
7struct SkyScreen: View { 7struct SkyScreen: View {
8 @State private var model = SkyModel() 8 @State private var model = SkyModel.shared
9 @State private var pointer = MotionPointer() 9 @State private var pointer = MotionPointer()
10 @State private var azimuth = 180.0 10 @State private var azimuth = 180.0
11 @State private var altitude = 45.0 11 @State private var altitude = 45.0
App/Sources/SolarSystem3D.swift +1 −1
@@ -919,7 +919,7 @@ struct SolarSystem3DView: View {
919 if let s { 919 if let s {
920 let recent = s.snapshot.xray.filter { $0.time > .now.addingTimeInterval(-3 * 3600) } 920 let recent = s.snapshot.xray.filter { $0.time > .now.addingTimeInterval(-3 * 3600) }
921 if let peak = recent.max(by: { $0.flux < $1.flux }) { w.flare = (peak.flux, peak.time) } 921 if let peak = recent.max(by: { $0.flux < $1.flux }) { w.flare = (peak.flux, peak.time) }
922 w.summary = SunFeeds.summary(s.snapshot).map { s.complete ? $0 : "\($0) (\(SunFeeds.source(s.snapshot)))" } 922 w.summary = await SunFeeds.summary(s.snapshot).map { s.complete ? $0 : "\($0) (\(SunFeeds.source(s.snapshot)))" }
923 } 923 }
924 #if DEBUG 924 #if DEBUG
925 if UserDefaults.standard.bool(forKey: "debugSolarEvents") { w.kp = 6.3; w.flare = (2.4e-5, .now) } 925 if UserDefaults.standard.bool(forKey: "debugSolarEvents") { w.kp = 6.3; w.flare = (2.4e-5, .now) }
App/Sources/SunScreen.swift +16 −13
@@ -1,5 +1,4 @@
1import Charts 1import Charts
2import CoreLocation
3import Feeds 2import Feeds
4import SkyEngine 3import SkyEngine
5import SkyRenderer 4import SkyRenderer
@@ -73,17 +72,17 @@ struct SunScreen: View {
73 } 72 }
74 73
75 private func load(force: Bool) async { 74 private func load(force: Bool) async {
76 if data == nil { show(await SunFeeds.lastSaved()) } 75 if data == nil { await show(SunFeeds.lastSaved()) }
77 if force { imageID = .now } 76 if force { imageID = .now }
78 let result = await SunFeeds.load(force: force) 77 let result = await SunFeeds.load(force: force)
79 show(result?.snapshot) 78 await show(result?.snapshot)
80 failed = !(result?.complete ?? false) 79 failed = !(result?.complete ?? false)
81 } 80 }
82 81
83 private func show(_ snapshot: SunSnapshot?) { 82 private func show(_ snapshot: SunSnapshot?) async {
84 guard let snapshot else { return } 83 guard let snapshot else { return }
85 data = snapshot 84 data = snapshot
86 summary = SunFeeds.summary(snapshot) 85 summary = await SunFeeds.summary(snapshot)
87 } 86 }
88 87
89 /// An SDO image, with the time it was saved when it comes from the cache. 88 /// An SDO image, with the time it was saved when it comes from the cache.
@@ -205,10 +204,10 @@ struct SunScreen: View {
205 .padding(.top, 24) 204 .padding(.top, 24)
206 } 205 }
207 206
208 /// Last known location, or Chicago. 207 /// The Sky tab's place.
209 private var observer: (lat: Double, lon: Double) { 208 private var observer: (lat: Double, lon: Double) {
210 let c = CLLocationManager().location?.coordinate 209 let o = SkyModel.shared.observer
211 return (c?.latitude ?? 41.8781, c?.longitude ?? -87.6298) 210 return (o.latitude, o.longitude)
212 } 211 }
213 212
214 @ViewBuilder 213 @ViewBuilder
@@ -241,7 +240,7 @@ struct SunScreen: View {
241 stat("Peak at", peak.time.formatted(date: .omitted, time: .shortened)) 240 stat("Peak at", peak.time.formatted(date: .omitted, time: .shortened))
242 } 241 }
243 Chart { 242 Chart {
244 ForEach(xray) { s in 243 ForEach(XRay.maxima(xray)) { s in
245 LineMark(x: .value("Time", s.time), y: .value("Flux", s.flux)) 244 LineMark(x: .value("Time", s.time), y: .value("Flux", s.flux))
246 .foregroundStyle(ink) 245 .foregroundStyle(ink)
247 .lineStyle(StrokeStyle(lineWidth: 1)) 246 .lineStyle(StrokeStyle(lineWidth: 1))
@@ -256,6 +255,8 @@ struct SunScreen: View {
256 } 255 }
257 } 256 }
258 .chartYScale(domain: 1e-8...1e-3, type: .log) 257 .chartYScale(domain: 1e-8...1e-3, type: .log)
258 // The whole day, not just the first and last 5-minute maxima.
259 .chartXScale(domain: xray[0].time...last.time)
259 .chartYAxis(.hidden) 260 .chartYAxis(.hidden)
260 .chartXAxis { 261 .chartXAxis {
261 AxisMarks(values: .stride(by: .hour, count: 6)) { _ in 262 AxisMarks(values: .stride(by: .hour, count: 6)) { _ in
@@ -353,10 +354,12 @@ enum SunFeeds {
353 return saved 354 return saved
354 } 355 }
355 356
356 /// Summary for the last known location, or Chicago. 357 /// Summary for the Sky tab's place and night. A night that has ended is worked out again on the `Astronomer` actor.
357 static func summary(_ s: SunSnapshot, at date: Date = .now) -> String? { 358 static func summary(_ s: SunSnapshot, at date: Date = .now) async -> String? {
358 let observer = CLLocationManager().location.map { Observer(latitude: $0.coordinate.latitude, longitude: $0.coordinate.longitude) } ?? SkyModel.fallback 359 let sky = SkyModel.shared, observer = sky.observer
359 let night = (try? Tonight(at: date, from: observer)).map { DateInterval(start: $0.start, end: $0.end) } ?? DateInterval(start: date, duration: 0) 360 var tonight = sky.tonight
361 if tonight.map({ $0.end <= date }) ?? true { tonight = try? await sky.astronomer.tonight(at: date, from: observer) }
362 let night = tonight.map { DateInterval(start: $0.start, end: $0.end) } ?? DateInterval(start: date, duration: 0)
360 return SunSummary.text( 363 return SunSummary.text(
361 scales: s.scales, kp: s.kp, probabilities: s.probabilities, xray: s.xray, 364 scales: s.scales, kp: s.kp, probabilities: s.probabilities, xray: s.xray,
362 geomagneticLatitude: Geomagnetic.latitude(observer), night: night, at: date 365 geomagneticLatitude: Geomagnetic.latitude(observer), night: night, at: date
Packages/MoonriseKit/Sources/Feeds/Sun.swift +17
@@ -85,6 +85,23 @@ public enum XRay {
85 try decode(await session.data(from: dayURL).0) 85 try decode(await session.data(from: dayURL).0)
86 } 86 }
87 87
88 /// The highest sample in each `interval` of time-ordered samples, for charting: a day of minutes becomes
89 /// 288 points and every flare peak keeps its flux and time.
90 public static func maxima(_ samples: [XRaySample], every interval: TimeInterval = 300) -> [XRaySample] {
91 var out: [XRaySample] = []
92 var bin = -Double.infinity
93 for s in samples {
94 let b = (s.time.timeIntervalSince1970 / interval).rounded(.down)
95 if b != bin {
96 out.append(s)
97 bin = b
98 } else if s.flux > out[out.count - 1].flux {
99 out[out.count - 1] = s
100 }
101 }
102 return out
103 }
104
88 /// Flare class for a flux, e.g. 1.5e-6 → "C1.5". 105 /// Flare class for a flux, e.g. 1.5e-6 → "C1.5".
89 public static func flareClass(_ flux: Double) -> String { 106 public static func flareClass(_ flux: Double) -> String {
90 let classes: [(String, Double)] = [("X", 1e-4), ("M", 1e-5), ("C", 1e-6), ("B", 1e-7), ("A", 1e-8)] 107 let classes: [(String, Double)] = [("X", 1e-4), ("M", 1e-5), ("C", 1e-6), ("B", 1e-7), ("A", 1e-8)]
Packages/MoonriseKit/Tests/FeedsTests/SunTests.swift +15
@@ -21,6 +21,21 @@ import Testing
21 #expect(samples[0].flux == 6.5876e-07) 21 #expect(samples[0].flux == 6.5876e-07)
22} 22}
23 23
24@Test func xrayMaximaKeepPeaks() throws {
25 let start = try Date("2026-10-17T00:00:00Z", strategy: .iso8601)
26 var samples = (0..<1440).map { XRaySample(time: start.addingTimeInterval(Double($0) * 60), flux: 1e-7 * (1 + Double($0 % 7) / 10)) }
27 samples[733].flux = 2.4e-5 // one-minute M2.4 at 12:13
28 samples[1001].flux = 3.1e-6 // C3.1 at 16:41
29 let m = XRay.maxima(samples)
30 #expect(m.count == 288)
31 #expect(m.contains(samples[733]))
32 #expect(m.contains(samples[1001]))
33 #expect(m.max { $0.flux < $1.flux } == samples[733])
34 for (i, s) in m.enumerated() {
35 #expect(s.flux == samples[i * 5..<i * 5 + 5].map(\.flux).max())
36 }
37}
38
24@Test func kpBarsMarkPredicted() throws { 39@Test func kpBarsMarkPredicted() throws {
25 let bars = try SpaceWeather.decodeKpBars(forecast) 40 let bars = try SpaceWeather.decodeKpBars(forecast)
26 #expect(bars.count == 4) 41 #expect(bars.count == 4)