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 {
4040@MainActor
4141@Observable
4242final 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()
4345 /// Used until a location fix arrives or when location is denied.
4446 static let fallback = Observer(latitude: 41.8781, longitude: -87.6298)
4547
App/Sources/SkyScreen.swift +1 −1
@@ -5,7 +5,7 @@ import SkyRenderer
55import SwiftUI
66
77struct SkyScreen: View {
8 @State private var model = SkyModel()
8 @State private var model = SkyModel.shared
99 @State private var pointer = MotionPointer()
1010 @State private var azimuth = 180.0
1111 @State private var altitude = 45.0
App/Sources/SolarSystem3D.swift +1 −1
@@ -919,7 +919,7 @@ struct SolarSystem3DView: View {
919919 if let s {
920920 let recent = s.snapshot.xray.filter { $0.time > .now.addingTimeInterval(-3 * 3600) }
921921 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)))" }
923923 }
924924 #if DEBUG
925925 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 @@
11import Charts
2import CoreLocation
32import Feeds
43import SkyEngine
54import SkyRenderer
@@ -73,17 +72,17 @@ struct SunScreen: View {
7372 }
7473
7574 private func load(force: Bool) async {
76 if data == nil { show(await SunFeeds.lastSaved()) }
75 if data == nil { await show(SunFeeds.lastSaved()) }
7776 if force { imageID = .now }
7877 let result = await SunFeeds.load(force: force)
79 show(result?.snapshot)
78 await show(result?.snapshot)
8079 failed = !(result?.complete ?? false)
8180 }
8281
83 private func show(_ snapshot: SunSnapshot?) {
82 private func show(_ snapshot: SunSnapshot?) async {
8483 guard let snapshot else { return }
8584 data = snapshot
86 summary = SunFeeds.summary(snapshot)
85 summary = await SunFeeds.summary(snapshot)
8786 }
8887
8988 /// An SDO image, with the time it was saved when it comes from the cache.
@@ -205,10 +204,10 @@ struct SunScreen: View {
205204 .padding(.top, 24)
206205 }
207206
208 /// Last known location, or Chicago.
207 /// The Sky tab's place.
209208 private var observer: (lat: Double, lon: Double) {
210 let c = CLLocationManager().location?.coordinate
211 return (c?.latitude ?? 41.8781, c?.longitude ?? -87.6298)
209 let o = SkyModel.shared.observer
210 return (o.latitude, o.longitude)
212211 }
213212
214213 @ViewBuilder
@@ -241,7 +240,7 @@ struct SunScreen: View {
241240 stat("Peak at", peak.time.formatted(date: .omitted, time: .shortened))
242241 }
243242 Chart {
244 ForEach(xray) { s in
243 ForEach(XRay.maxima(xray)) { s in
245244 LineMark(x: .value("Time", s.time), y: .value("Flux", s.flux))
246245 .foregroundStyle(ink)
247246 .lineStyle(StrokeStyle(lineWidth: 1))
@@ -256,6 +255,8 @@ struct SunScreen: View {
256255 }
257256 }
258257 .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)
259260 .chartYAxis(.hidden)
260261 .chartXAxis {
261262 AxisMarks(values: .stride(by: .hour, count: 6)) { _ in
@@ -353,10 +354,12 @@ enum SunFeeds {
353354 return saved
354355 }
355356
356 /// Summary for the last known location, or Chicago.
357 static func summary(_ s: SunSnapshot, at date: Date = .now) -> String? {
358 let observer = CLLocationManager().location.map { Observer(latitude: $0.coordinate.latitude, longitude: $0.coordinate.longitude) } ?? SkyModel.fallback
359 let night = (try? Tonight(at: date, from: observer)).map { DateInterval(start: $0.start, end: $0.end) } ?? DateInterval(start: date, duration: 0)
357 /// Summary for the Sky tab's place and night. A night that has ended is worked out again on the `Astronomer` actor.
358 static func summary(_ s: SunSnapshot, at date: Date = .now) async -> String? {
359 let sky = SkyModel.shared, observer = sky.observer
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)
360363 return SunSummary.text(
361364 scales: s.scales, kp: s.kp, probabilities: s.probabilities, xray: s.xray,
362365 geomagneticLatitude: Geomagnetic.latitude(observer), night: night, at: date
Packages/MoonriseKit/Sources/Feeds/Sun.swift +17
@@ -85,6 +85,23 @@ public enum XRay {
8585 try decode(await session.data(from: dayURL).0)
8686 }
8787
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
88105 /// Flare class for a flux, e.g. 1.5e-6 → "C1.5".
89106 public static func flareClass(_ flux: Double) -> String {
90107 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
2121 #expect(samples[0].flux == 6.5876e-07)
2222}
2323
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
2439@Test func kpBarsMarkPredicted() throws {
2540 let bars = try SpaceWeather.decodeKpBars(forecast)
2641 #expect(bars.count == 4)