Commit f41d28ad5b
Unsigned
Layout: unified · split
App/Sources/LogScreen.swift +7
| @@ -79,6 +79,7 @@ let observingLog = ObservingLog(folder: URL.documentsDirectory.appending(path: " | |||
| 79 | struct LogScreen: View { | 79 | struct LogScreen: View { |
| 80 | @ObservedObject private var store = observingLogStore | 80 | @ObservedObject private var store = observingLogStore |
| 81 | @State private var editing: Observation? | 81 | @State private var editing: Observation? |
| 82 | @State private var exporting = false | ||
| 82 | var newEntry: () -> Observation | 83 | var newEntry: () -> Observation |
| 83 | @Environment(\.dismiss) private var dismiss | 84 | @Environment(\.dismiss) private var dismiss |
| 84 | 85 | ||
| @@ -108,6 +109,10 @@ struct LogScreen: View { | |||
| 108 | .navigationBarTitleDisplayMode(.inline) | 109 | .navigationBarTitleDisplayMode(.inline) |
| 109 | .toolbar { | 110 | .toolbar { |
| 110 | ToolbarItem(placement: .cancellationAction) { Button("Done") { dismiss() } } | 111 | ToolbarItem(placement: .cancellationAction) { Button("Done") { dismiss() } } |
| 112 | ToolbarItem(placement: .primaryAction) { | ||
| 113 | Button { exporting = true } label: { Image(systemName: "square.and.arrow.up") } | ||
| 114 | .accessibilityLabel("Export reports") | ||
| 115 | } | ||
| 111 | ToolbarItem(placement: .primaryAction) { | 116 | ToolbarItem(placement: .primaryAction) { |
| 112 | NavigationLink { EquipmentScreen() } label: { Image(systemName: "binoculars") } | 117 | NavigationLink { EquipmentScreen() } label: { Image(systemName: "binoculars") } |
| 113 | .accessibilityLabel("Equipment") | 118 | .accessibilityLabel("Equipment") |
| @@ -124,6 +129,7 @@ struct LogScreen: View { | |||
| 124 | .sheet(item: $editing) { o in | 129 | .sheet(item: $editing) { o in |
| 125 | ObservationEditor(observation: o) | 130 | ObservationEditor(observation: o) |
| 126 | } | 131 | } |
| 132 | .sheet(isPresented: $exporting) { ReportExportSheet(log: entries) } | ||
| 127 | } | 133 | } |
| 128 | .onAppear { store.reload() } | 134 | .onAppear { store.reload() } |
| 129 | } | 135 | } |
| @@ -162,6 +168,7 @@ struct ObservationEditor: View { | |||
| 162 | Section("Notes") { | 168 | Section("Notes") { |
| 163 | TextEditor(text: $observation.notes).frame(minHeight: 140) | 169 | TextEditor(text: $observation.notes).frame(minHeight: 140) |
| 164 | } | 170 | } |
| 171 | ReportFields(observation: $observation) | ||
| 165 | if let error { Text(error).foregroundStyle(.red).font(.footnote) } | 172 | if let error { Text(error).foregroundStyle(.red).font(.footnote) } |
| 166 | } | 173 | } |
| 167 | .navigationTitle(observation.object.isEmpty ? "New observation" : observation.object) | 174 | .navigationTitle(observation.object.isEmpty ? "New observation" : observation.object) |
App/Sources/ProgramsScreen.swift +10
| @@ -51,6 +51,7 @@ struct ProgramDetail: View { | |||
| 51 | @ObservedObject private var store = observingLogStore | 51 | @ObservedObject private var store = observingLogStore |
| 52 | @State private var upTonight: [Candidate]? | 52 | @State private var upTonight: [Candidate]? |
| 53 | @State private var editing: Observation? | 53 | @State private var editing: Observation? |
| 54 | @State private var pdf: URL? | ||
| 54 | 55 | ||
| 55 | private var progress: ProgramProgress? { store.progress[program.id] } | 56 | private var progress: ProgramProgress? { store.progress[program.id] } |
| 56 | 57 | ||
| @@ -81,11 +82,20 @@ struct ProgramDetail: View { | |||
| 81 | } | 82 | } |
| 82 | .navigationTitle(program.title) | 83 | .navigationTitle(program.title) |
| 83 | .navigationBarTitleDisplayMode(.inline) | 84 | .navigationBarTitleDisplayMode(.inline) |
| 85 | .toolbar { | ||
| 86 | ToolbarItem(placement: .primaryAction) { | ||
| 87 | if let pdf { | ||
| 88 | ShareLink(item: pdf) { Image(systemName: "square.and.arrow.up") } | ||
| 89 | .accessibilityLabel("Share log as PDF") | ||
| 90 | } | ||
| 91 | } | ||
| 92 | } | ||
| 84 | .sheet(item: $editing) { o in | 93 | .sheet(item: $editing) { o in |
| 85 | ObservationEditor(observation: o) | 94 | ObservationEditor(observation: o) |
| 86 | } | 95 | } |
| 87 | .onAppear { store.reload() } | 96 | .onAppear { store.reload() } |
| 88 | .task { await findUpTonight() } | 97 | .task { await findUpTonight() } |
| 98 | .task(id: progress?.count) { pdf = ProgramLogPDF.write(program, progress: progress) } | ||
| 89 | } | 99 | } |
| 90 | 100 | ||
| 91 | /// Opens the first entry for a logged object, else a new entry for it. | 101 | /// Opens the first entry for a logged object, else a new entry for it. |
App/Sources/ReportViews.swift added +172
| @@ -0,0 +1,172 @@ | |||
| 1 | import ObservingLog | ||
| 2 | import SwiftUI | ||
| 3 | |||
| 4 | /// Fields for an IMO, COBS or AAVSO report, stored as Org properties on the entry. | ||
| 5 | struct ReportFields: View { | ||
| 6 | @Binding var observation: Observation | ||
| 7 | |||
| 8 | private func field(_ label: String, _ key: String, prompt: String = "", keyboard: UIKeyboardType = .default) -> some View { | ||
| 9 | TextField(label, text: Binding { observation[property: key] } set: { observation[property: key] = $0 }, prompt: Text(prompt)) | ||
| 10 | .keyboardType(keyboard) | ||
| 11 | .textInputAutocapitalization(.characters) | ||
| 12 | .autocorrectionDisabled() | ||
| 13 | } | ||
| 14 | |||
| 15 | var body: some View { | ||
| 16 | Section { | ||
| 17 | Picker("Report", selection: $observation.report) { | ||
| 18 | Text("None").tag(ReportKind?.none) | ||
| 19 | Text("Variable star (AAVSO)").tag(ReportKind?.some(.variable)) | ||
| 20 | Text("Comet (COBS)").tag(ReportKind?.some(.comet)) | ||
| 21 | Text("Meteor count (IMO)").tag(ReportKind?.some(.meteors)) | ||
| 22 | } | ||
| 23 | switch observation.report { | ||
| 24 | case .variable: | ||
| 25 | field("Star", ":DESIGNATION:", prompt: observation.object) | ||
| 26 | field("Magnitude", ":MAGNITUDE:", prompt: "10.9, or <11.1 if fainter") | ||
| 27 | field("Comparison stars", ":COMPARISON:", prompt: "110 113") | ||
| 28 | field("Chart", ":CHART:", prompt: "X12345ABC") | ||
| 29 | field("Comment code", ":COMMENT_CODE:", prompt: "Optional, e.g. B") | ||
| 30 | case .comet: | ||
| 31 | field("Comet", ":DESIGNATION:", prompt: "C/2023 A3 or 12P") | ||
| 32 | field("Magnitude", ":MAGNITUDE:", prompt: "7.8; 7.8: if unsure; [12.0 not seen") | ||
| 33 | field("Method", ":METHOD:", prompt: "S, M, B or I") | ||
| 34 | field("Reference", ":REFERENCE:", prompt: "Comparison catalogue, e.g. TK") | ||
| 35 | field("Aperture, cm", ":APERTURE:", keyboard: .decimalPad) | ||
| 36 | field("Instrument", ":INSTRUMENT:", prompt: "B, L, R, T or E") | ||
| 37 | field("Focal ratio", ":FOCAL_RATIO:", keyboard: .decimalPad) | ||
| 38 | field("Magnification", ":POWER:", keyboard: .numberPad) | ||
| 39 | field("Coma, arcmin", ":COMA:", keyboard: .decimalPad) | ||
| 40 | field("DC", ":DC:", prompt: "0–9") | ||
| 41 | field("Tail, degrees", ":TAIL:", keyboard: .decimalPad) | ||
| 42 | field("Tail PA, degrees", ":PA:", keyboard: .numberPad) | ||
| 43 | case .meteors: | ||
| 44 | field("Minutes watched", ":MINUTES:", keyboard: .numberPad) | ||
| 45 | field("Limiting magnitude", ":LIMITING_MAG:", keyboard: .decimalPad) | ||
| 46 | field("Cloud, % of field", ":CLOUD:", keyboard: .numberPad) | ||
| 47 | field("Counts", ":COUNTS:", prompt: "ORI 12 SPO 4") | ||
| 48 | field("Elevation, m", ":ELEVATION:", keyboard: .numberPad) | ||
| 49 | field("Country", ":COUNTRY:", prompt: Locale.current.region.flatMap { Locale.current.localizedString(forRegionCode: $0.identifier) } ?? "") | ||
| 50 | case nil: | ||
| 51 | EmptyView() | ||
| 52 | } | ||
| 53 | } header: { | ||
| 54 | Text("Report") | ||
| 55 | } footer: { | ||
| 56 | switch observation.report { | ||
| 57 | case .variable: Text("Comparison stars are the labels on the AAVSO chart, magnitude × 10.") | ||
| 58 | case .comet: Text("ICQ codes, as COBS uses them. S: Sidgwick, M: Morris, B: Bobrovnikoff, I: in-out. B: binoculars, L: reflector, R: refractor, T: Schmidt-Cassegrain, E: naked eye.") | ||
| 59 | case .meteors: Text("The time above is when counting started. Counts are IAU shower codes and numbers; SPO for sporadics.") | ||
| 60 | case nil: Text("Adds the fields an IMO, COBS or AAVSO report needs.") | ||
| 61 | } | ||
| 62 | } | ||
| 63 | } | ||
| 64 | } | ||
| 65 | |||
| 66 | /// Writes the AAVSO, COBS and IMO files for the entries marked with a report. | ||
| 67 | struct ReportExportSheet: View { | ||
| 68 | var log: [Observation] | ||
| 69 | @AppStorage("aavsoCode") private var aavsoCode = "" | ||
| 70 | @AppStorage("icqCode") private var icqCode = "" | ||
| 71 | @AppStorage("imoName") private var imoName = "" | ||
| 72 | @Environment(\.dismiss) private var dismiss | ||
| 73 | |||
| 74 | private var software: String { "Moonrise \(Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "")" } | ||
| 75 | |||
| 76 | private func count(_ k: ReportKind) -> Int { log.filter { $0.report == k }.count } | ||
| 77 | |||
| 78 | private func write(_ name: String, _ text: String) -> URL { | ||
| 79 | let url = FileManager.default.temporaryDirectory.appending(path: name) | ||
| 80 | try? text.write(to: url, atomically: true, encoding: .utf8) | ||
| 81 | return url | ||
| 82 | } | ||
| 83 | |||
| 84 | var body: some View { | ||
| 85 | NavigationStack { | ||
| 86 | Form { | ||
| 87 | Section { | ||
| 88 | TextField("Observer code", text: $aavsoCode).textInputAutocapitalization(.characters).autocorrectionDisabled() | ||
| 89 | if !aavsoCode.isEmpty { | ||
| 90 | ShareLink(item: write("aavso-visual.txt", AAVSOVisual.file(log, observerCode: aavsoCode, software: software))) { | ||
| 91 | Label("AAVSO visual file", systemImage: "doc.text") | ||
| 92 | } | ||
| 93 | } | ||
| 94 | } header: { | ||
| 95 | Text("Variable stars, \(count(.variable))") | ||
| 96 | } footer: { | ||
| 97 | Text("Upload with WebObs › Upload a file at aavso.org.") | ||
| 98 | } | ||
| 99 | Section { | ||
| 100 | TextField("ICQ observer code", text: $icqCode).textInputAutocapitalization(.characters).autocorrectionDisabled() | ||
| 101 | if !icqCode.isEmpty { | ||
| 102 | ShareLink(item: write("cobs-icq.txt", ICQ.file(log, observerCode: icqCode))) { | ||
| 103 | Label("ICQ file for COBS", systemImage: "doc.text") | ||
| 104 | } | ||
| 105 | } | ||
| 106 | } header: { | ||
| 107 | Text("Comets, \(count(.comet))") | ||
| 108 | } footer: { | ||
| 109 | Text("For import on cobs.si as ICQ format. COBS issues ICQ observer codes.") | ||
| 110 | } | ||
| 111 | Section { | ||
| 112 | TextField("Observer name", text: $imoName) | ||
| 113 | if !imoName.isEmpty { | ||
| 114 | let region = Locale.current.region.flatMap { Locale(identifier: "en_US").localizedString(forRegionCode: $0.identifier) } ?? "" | ||
| 115 | let files = IMOReport.files(log, observerName: imoName, defaultCountry: region) | ||
| 116 | ShareLink(items: [write("imo-sessions.csv", files.sessions), write("imo-rates.csv", files.rates)]) { | ||
| 117 | Label("IMO session and rate files", systemImage: "doc.text") | ||
| 118 | } | ||
| 119 | } | ||
| 120 | } header: { | ||
| 121 | Text("Meteor counts, \(count(.meteors))") | ||
| 122 | } footer: { | ||
| 123 | Text("Semicolon-separated CSV in the IMO Visual Meteor Database's columns. Times are UTC.") | ||
| 124 | } | ||
| 125 | } | ||
| 126 | .navigationTitle("Export reports") | ||
| 127 | .navigationBarTitleDisplayMode(.inline) | ||
| 128 | .toolbar { ToolbarItem(placement: .confirmationAction) { Button("Done") { dismiss() } } } | ||
| 129 | } | ||
| 130 | } | ||
| 131 | } | ||
| 132 | |||
| 133 | /// A program's log as a US Letter PDF: each object with the date, place and equipment of its first observation. | ||
| 134 | enum ProgramLogPDF { | ||
| 135 | static func write(_ program: ObservingProgram, progress: ProgramProgress?) -> URL { | ||
| 136 | let page = CGRect(x: 0, y: 0, width: 612, height: 792), margin: CGFloat = 54 | ||
| 137 | let width = page.width - 2 * margin | ||
| 138 | let title: [NSAttributedString.Key: Any] = [.font: UIFont.systemFont(ofSize: 20, weight: .semibold)] | ||
| 139 | let body: [NSAttributedString.Key: Any] = [.font: UIFont.systemFont(ofSize: 10)] | ||
| 140 | let bold: [NSAttributedString.Key: Any] = [.font: UIFont.systemFont(ofSize: 10, weight: .semibold)] | ||
| 141 | let small: [NSAttributedString.Key: Any] = [.font: UIFont.systemFont(ofSize: 8), .foregroundColor: UIColor.darkGray] | ||
| 142 | let url = FileManager.default.temporaryDirectory.appending(path: "\(program.title).pdf") | ||
| 143 | let data = UIGraphicsPDFRenderer(bounds: page).pdfData { ctx in | ||
| 144 | var y = page.height | ||
| 145 | func draw(_ s: String, _ a: [NSAttributedString.Key: Any], x: CGFloat = margin, w: CGFloat = width) -> CGFloat { | ||
| 146 | let text = NSAttributedString(string: s, attributes: a) | ||
| 147 | let h = ceil(text.boundingRect(with: CGSize(width: w, height: .greatestFiniteMagnitude), options: .usesLineFragmentOrigin, context: nil).height) | ||
| 148 | text.draw(with: CGRect(x: x, y: y, width: w, height: h), options: .usesLineFragmentOrigin, context: nil) | ||
| 149 | return h | ||
| 150 | } | ||
| 151 | func room(_ h: CGFloat) { | ||
| 152 | if y + h > page.height - margin { ctx.beginPage(); y = margin } | ||
| 153 | } | ||
| 154 | room(page.height) | ||
| 155 | y += draw(program.title, title) + 4 | ||
| 156 | y += draw("\(progress?.count ?? 0) of \(program.objects.count) logged · \(Date.now.formatted(date: .long, time: .omitted))", small) + 14 | ||
| 157 | for o in program.objects { | ||
| 158 | let logged = progress?.first[o.id] | ||
| 159 | let detail = logged.map { [$0.date.formatted(date: .abbreviated, time: .shortened), $0.place, $0.equipment].filter { !$0.isEmpty }.joined(separator: " · ") } ?? "" | ||
| 160 | room(30) | ||
| 161 | let mark = draw(logged == nil ? "☐" : "☑", body, w: 14) | ||
| 162 | let name = draw(o.name, bold, x: margin + 18, w: width * 0.4 - 18) | ||
| 163 | let right = draw(detail, body, x: margin + width * 0.4, w: width * 0.6) | ||
| 164 | y += max(mark, name, right) | ||
| 165 | if !o.detail.isEmpty { y += draw(o.detail, small, x: margin + 18, w: width * 0.4 - 18) } | ||
| 166 | y += 6 | ||
| 167 | } | ||
| 168 | } | ||
| 169 | try? data.write(to: url) | ||
| 170 | return url | ||
| 171 | } | ||
| 172 | } | ||
PLAN.org +4 −1
| @@ -586,7 +586,10 @@ Worker; DSN Now freshness; NASA/ESA image licences; 26 LoC plates bundled. | |||
| 586 | - Meteor radiant altitude (radiant coordinates for the major showers). | 586 | - Meteor radiant altitude (radiant coordinates for the major showers). |
| 587 | Done: IMO radiants; each peak in Events gives when the radiant is highest | 587 | Done: IMO radiants; each peak in Events gives when the radiant is highest |
| 588 | in the dark window, how high, and ZHR × sin(altitude). | 588 | in the dark window, how high, and ZHR × sin(altitude). |
| 589 | - IMO, COBS and AAVSO exports; a program log PDF. | 589 | - IMO, COBS and AAVSO exports; a program log PDF. Done: a Report section |
| 590 | on each entry (fields kept as Org properties); Export on the log writes | ||
| 591 | the AAVSO visual file, an ICQ file for COBS and IMO VMDB session and rate | ||
| 592 | CSVs; Share on a program writes its PDF. | ||
| 590 | - Astronomical League lists (Herschel 400, Double Star, Lunar, Binocular | 593 | - Astronomical League lists (Herschel 400, Double Star, Lunar, Binocular |
| 591 | Messier) and Lunar 100 (Charles Wood, Sky & Telescope), with permission; | 594 | Messier) and Lunar 100 (Charles Wood, Sky & Telescope), with permission; |
| 592 | user program files cover them meanwhile. | 595 | user program files cover them meanwhile. |
Packages/MoonriseKit/Sources/ObservingLog/Reports.swift added +182
| @@ -0,0 +1,182 @@ | |||
| 1 | import Foundation | ||
| 2 | |||
| 3 | /// Report fields kept as Org properties, so the files stay readable in Emacs and orgstar. | ||
| 4 | public enum ReportKind: String, Sendable, CaseIterable { | ||
| 5 | case variable, comet, meteors | ||
| 6 | } | ||
| 7 | |||
| 8 | extension Observation { | ||
| 9 | public static let reportKey = ":REPORT:" | ||
| 10 | |||
| 11 | /// The value of a property the app does not otherwise use; setting "" removes it. | ||
| 12 | public subscript(property key: String) -> String { | ||
| 13 | get { otherProperties.first { $0.key == key }?.value ?? "" } | ||
| 14 | set { | ||
| 15 | let value = newValue.trimmingCharacters(in: .whitespacesAndNewlines) | ||
| 16 | if let i = otherProperties.firstIndex(where: { $0.key == key }) { | ||
| 17 | if value.isEmpty { otherProperties.remove(at: i) } else { otherProperties[i].value = value } | ||
| 18 | } else if !value.isEmpty { | ||
| 19 | otherProperties.append(OrgProperty(key: key, value: value)) | ||
| 20 | } | ||
| 21 | } | ||
| 22 | } | ||
| 23 | |||
| 24 | public var report: ReportKind? { | ||
| 25 | get { ReportKind(rawValue: self[property: Self.reportKey]) } | ||
| 26 | set { self[property: Self.reportKey] = newValue?.rawValue ?? "" } | ||
| 27 | } | ||
| 28 | |||
| 29 | /// :DESIGNATION: if set, else the object name. | ||
| 30 | var designation: String { | ||
| 31 | let d = self[property: ":DESIGNATION:"] | ||
| 32 | return d.isEmpty ? object : d | ||
| 33 | } | ||
| 34 | } | ||
| 35 | |||
| 36 | /// Julian date (UT) of `date`. | ||
| 37 | func julianDate(_ date: Date) -> Double { date.timeIntervalSince1970 / 86_400 + 2_440_587.5 } | ||
| 38 | |||
| 39 | private let utc: Calendar = { | ||
| 40 | var c = Calendar(identifier: .gregorian) | ||
| 41 | c.timeZone = TimeZone(identifier: "UTC")! | ||
| 42 | return c | ||
| 43 | }() | ||
| 44 | |||
| 45 | /// AAVSO Visual File Format (AAVSO Manual for Visual Observing of Variable Stars, chapter 7): one line per estimate, | ||
| 46 | /// NAME,DATE,MAG,COMMENTCODE,COMP1,COMP2,CHART,NOTES with JD dates and "na" for missing fields. | ||
| 47 | /// Properties: :MAGNITUDE: ("10.9", or "<11.1" fainter than), :COMPARISON: (one or two comparison star labels), | ||
| 48 | /// :CHART:, :COMMENT_CODE:. | ||
| 49 | public enum AAVSOVisual { | ||
| 50 | public static func file(_ log: [Observation], observerCode: String, software: String) -> String { | ||
| 51 | var lines = ["#TYPE=VISUAL", "#OBSCODE=\(observerCode.uppercased())", "#SOFTWARE=\(software)", "#DELIM=,", "#DATE=JD", "#OBSTYPE=Visual", | ||
| 52 | "#NAME,DATE,MAG,COMMENTCODE,COMP1,COMP2,CHART,NOTES"] | ||
| 53 | for o in log.filter({ $0.report == .variable }).sorted(by: { $0.date < $1.date }) { | ||
| 54 | let mag = o[property: ":MAGNITUDE:"] | ||
| 55 | guard !mag.isEmpty else { continue } | ||
| 56 | let comps = o[property: ":COMPARISON:"].split(separator: " ").map(String.init) | ||
| 57 | lines.append([ | ||
| 58 | clean(o.designation.uppercased()), | ||
| 59 | String(format: "%.4f", julianDate(o.date)), | ||
| 60 | clean(mag), | ||
| 61 | field(o[property: ":COMMENT_CODE:"]), | ||
| 62 | field(comps.first ?? ""), | ||
| 63 | field(comps.dropFirst().first ?? ""), | ||
| 64 | field(o[property: ":CHART:"]), | ||
| 65 | field(String(o.notes.prefix(100))), | ||
| 66 | ].joined(separator: ",")) | ||
| 67 | } | ||
| 68 | return lines.joined(separator: "\n") + "\n" | ||
| 69 | } | ||
| 70 | |||
| 71 | private static func clean(_ s: String) -> String { | ||
| 72 | s.replacingOccurrences(of: ",", with: ";").replacingOccurrences(of: "#", with: "").components(separatedBy: .newlines).joined(separator: " ") | ||
| 73 | } | ||
| 74 | |||
| 75 | private static func field(_ s: String) -> String { | ||
| 76 | let c = clean(s).trimmingCharacters(in: .whitespaces) | ||
| 77 | return c.isEmpty ? "na" : c | ||
| 78 | } | ||
| 79 | } | ||
| 80 | |||
| 81 | /// ICQ 80-column visual format, as COBS imports it (cobs.si/help/icq_format). Properties: :DESIGNATION: ("C/2023 A3", | ||
| 82 | /// "12P"), :METHOD: (S, M, B, I), :MAGNITUDE: ("7.8", "7.8:" uncertain, "[12.0" not seen), :REFERENCE: (e.g. TK), | ||
| 83 | /// :APERTURE: cm, :INSTRUMENT: (B binoculars, L reflector, R refractor, T Schmidt-Cassegrain, E eye), :FOCAL_RATIO:, | ||
| 84 | /// :POWER:, :COMA: arcmin, :DC: (0–9, "5/" for 5–6), :TAIL: degrees, :PA: degrees. | ||
| 85 | public enum ICQ { | ||
| 86 | public static func file(_ log: [Observation], observerCode: String) -> String { | ||
| 87 | log.filter { $0.report == .comet }.sorted { $0.date < $1.date }.compactMap { line($0, observerCode: observerCode) }.map { $0 + "\n" }.joined() | ||
| 88 | } | ||
| 89 | |||
| 90 | public static func line(_ o: Observation, observerCode: String) -> String? { | ||
| 91 | guard let id = designation(o.designation), let mag = magnitude(o[property: ":MAGNITUDE:"]) else { return nil } | ||
| 92 | var row = Array(repeating: Character(" "), count: 80) | ||
| 93 | func put(_ s: String, _ from: Int, _ to: Int, right: Bool = false) { | ||
| 94 | let width = to - from + 1 | ||
| 95 | let text = String(s.prefix(width)) | ||
| 96 | let padded = right ? String(repeating: " ", count: width - text.count) + text : text + String(repeating: " ", count: width - text.count) | ||
| 97 | for (i, c) in padded.enumerated() { row[from - 1 + i] = c } | ||
| 98 | } | ||
| 99 | put(id, 1, 11) | ||
| 100 | let d = utc.dateComponents([.year, .month, .day, .hour, .minute, .second], from: o.date) | ||
| 101 | let day = Double(d.day!) + (Double(d.hour!) * 3600 + Double(d.minute!) * 60 + Double(d.second!)) / 86_400 | ||
| 102 | put(String(format: "%04d %02d %05.2f", d.year!, d.month!, (day * 100).rounded(.down) / 100), 12, 24) | ||
| 103 | put(o[property: ":METHOD:"].uppercased(), 27, 27) | ||
| 104 | put(mag, 28, 33) | ||
| 105 | put(o[property: ":REFERENCE:"].uppercased(), 34, 35) | ||
| 106 | if let a = Double(o[property: ":APERTURE:"]) { put(String(format: "%.1f", a), 36, 40, right: true) } | ||
| 107 | put(o[property: ":INSTRUMENT:"].uppercased(), 41, 41) | ||
| 108 | if let f = Double(o[property: ":FOCAL_RATIO:"]) { put(String(Int((f / 2).rounded()) * 2), 42, 43, right: true) } | ||
| 109 | if let p = Int(o[property: ":POWER:"]) { put(String(p), 44, 47, right: true) } | ||
| 110 | if let c = Double(o[property: ":COMA:"]) { put(String(format: "%4.1f", c), 50, 53) } | ||
| 111 | put(o[property: ":DC:"], 56, 57) | ||
| 112 | // Degrees with the decimal point in column 61; from 10° the whole number reaches into column 59. | ||
| 113 | if let t = Double(o[property: ":TAIL:"]) { t < 10 ? put(String(format: "%.2f", t), 60, 63) : put(String(format: "%.0f.", t), 58, 61, right: true) } | ||
| 114 | if let pa = Double(o[property: ":PA:"]) { put(String(Int((pa / 2).rounded()) * 2 % 360), 65, 67, right: true) } | ||
| 115 | put("ICQ XX", 69, 74) | ||
| 116 | put(observerCode.uppercased(), 76, 80) | ||
| 117 | return String(row).replacing(/\s+$/, with: "") | ||
| 118 | } | ||
| 119 | |||
| 120 | /// Columns 1–11: "12P" → " 12", "C/2023 A3" → " 2023A3", "P/2010 H2" → " P2010H2". | ||
| 121 | static func designation(_ s: String) -> String? { | ||
| 122 | let t = s.uppercased().replacingOccurrences(of: " ", with: "") | ||
| 123 | if let m = t.wholeMatch(of: /(\d{1,3})P(?:\/.*)?/) { | ||
| 124 | return String(repeating: " ", count: 3 - m.1.count) + m.1 | ||
| 125 | } | ||
| 126 | if let m = t.wholeMatch(of: /([CP])\/(\d{4})([A-Z])(\d{1,2})(?:-([A-Z]))?/) { | ||
| 127 | return " " + (m.1 == "P" ? "P" : " ") + m.2 + m.3 + m.4 + String(repeating: " ", count: 2 - m.4.count) + (m.5.map { String($0).lowercased() } ?? "") | ||
| 128 | } | ||
| 129 | return nil | ||
| 130 | } | ||
| 131 | |||
| 132 | /// Columns 28–33, decimal point in column 31. | ||
| 133 | static func magnitude(_ s: String) -> String? { | ||
| 134 | guard let m = s.trimmingCharacters(in: .whitespaces).wholeMatch(of: /(\[)?\s*(-?\d{1,2}(?:\.\d)?)\s*(:)?/), let v = Double(m.2) else { return nil } | ||
| 135 | let number = String(format: "%.1f", v) | ||
| 136 | return (m.1 == nil ? " " : "[") + String(repeating: " ", count: max(0, 4 - number.count)) + number + (m.3 == nil ? " " : ":") | ||
| 137 | } | ||
| 138 | } | ||
| 139 | |||
| 140 | /// IMO Visual Meteor Database CSV, semicolon-separated: a sessions file and a rates file (column names as | ||
| 141 | /// imo-vmdb reads them). One observation is one session with one counting period. Properties: :MINUTES: (effective | ||
| 142 | /// observing time), :LIMITING_MAG:, :CLOUD: (percent of the field obstructed), :COUNTS: ("ORI 12 SPO 4", IAU codes), | ||
| 143 | /// :ELEVATION: metres, :COUNTRY:. | ||
| 144 | public enum IMOReport { | ||
| 145 | public static func files(_ log: [Observation], observerName: String, defaultCountry: String) -> (sessions: String, rates: String) { | ||
| 146 | var sessions = ["session_id;observer_name;latitude;longitude;elevation;country;location_name"] | ||
| 147 | var rates = ["rate_id;session_id;shower;period_start;period_end;freq;lim_magn;t_eff;f"] | ||
| 148 | var rate = 0 | ||
| 149 | for (n, o) in log.filter({ $0.report == .meteors }).sorted(by: { $0.date < $1.date }).enumerated() { | ||
| 150 | guard let lat = o.latitude, let lon = o.longitude, let minutes = Double(o[property: ":MINUTES:"]), minutes > 0, | ||
| 151 | let lm = Double(o[property: ":LIMITING_MAG:"]) else { continue } | ||
| 152 | let session = n + 1 | ||
| 153 | let country = o[property: ":COUNTRY:"].isEmpty ? defaultCountry : o[property: ":COUNTRY:"] | ||
| 154 | let km = (Double(o[property: ":ELEVATION:"]) ?? 0) / 1000 | ||
| 155 | sessions.append([String(session), clean(observerName), String(format: "%.4f", lat), String(format: "%.4f", lon), String(format: "%.3f", km), | ||
| 156 | clean(country), clean(o.place)].joined(separator: ";")) | ||
| 157 | let cloud = min(Double(o[property: ":CLOUD:"]) ?? 0, 90) | ||
| 158 | let end = o.date.addingTimeInterval(minutes * 60) | ||
| 159 | for (shower, count) in counts(o[property: ":COUNTS:"]) { | ||
| 160 | rate += 1 | ||
| 161 | rates.append([String(rate), String(session), shower, stamp(o.date), stamp(end), String(count), String(format: "%.2f", lm), | ||
| 162 | String(format: "%.3f", minutes / 60), String(format: "%.2f", 1 / (1 - cloud / 100))].joined(separator: ";")) | ||
| 163 | } | ||
| 164 | } | ||
| 165 | return (sessions.joined(separator: "\n") + "\n", rates.joined(separator: "\n") + "\n") | ||
| 166 | } | ||
| 167 | |||
| 168 | /// "ORI 12 SPO 4" → [("ORI", 12), ("SPO", 4)]. | ||
| 169 | static func counts(_ s: String) -> [(String, Int)] { | ||
| 170 | let parts = s.uppercased().split(whereSeparator: { $0 == " " || $0 == "," }) | ||
| 171 | return stride(from: 0, to: parts.count - 1, by: 2).compactMap { i in | ||
| 172 | Int(parts[i + 1]).map { (String(parts[i]), $0) } | ||
| 173 | } | ||
| 174 | } | ||
| 175 | |||
| 176 | static func stamp(_ d: Date) -> String { | ||
| 177 | d.formatted(Date.VerbatimFormatStyle(format: "\(year: .defaultDigits)-\(month: .twoDigits)-\(day: .twoDigits) \(hour: .twoDigits(clock: .twentyFourHour, hourCycle: .zeroBased)):\(minute: .twoDigits):\(second: .twoDigits)", | ||
| 178 | locale: Locale(identifier: "en_US_POSIX"), timeZone: .gmt, calendar: utc)) | ||
| 179 | } | ||
| 180 | |||
| 181 | private static func clean(_ s: String) -> String { s.replacingOccurrences(of: ";", with: ",").components(separatedBy: .newlines).joined(separator: " ") } | ||
| 182 | } | ||
Packages/MoonriseKit/Tests/ObservingLogTests/ReportsTests.swift added +58
| @@ -0,0 +1,58 @@ | |||
| 1 | import Foundation | ||
| 2 | import Testing | ||
| 3 | @testable import ObservingLog | ||
| 4 | |||
| 5 | private let utc = TimeZone(identifier: "UTC")! | ||
| 6 | |||
| 7 | private func entry(_ object: String, _ iso: String, _ props: [String: String], notes: String = "") throws -> Observation { | ||
| 8 | var o = Observation(object: object, date: try Date(iso, strategy: .iso8601), place: "Peak Crossing", latitude: -27.78, longitude: 152.73, notes: notes) | ||
| 9 | for (k, v) in props { o[property: k] = v } | ||
| 10 | return o | ||
| 11 | } | ||
| 12 | |||
| 13 | @Test func propertiesSetAndClear() throws { | ||
| 14 | var o = try entry("SS Cyg", "2026-10-20T03:00:00Z", [":REPORT:": "variable", ":MAGNITUDE:": " 10.9 "]) | ||
| 15 | #expect(o.report == .variable) | ||
| 16 | #expect(o[property: ":MAGNITUDE:"] == "10.9") | ||
| 17 | o[property: ":MAGNITUDE:"] = "" | ||
| 18 | #expect(o.otherProperties == [OrgProperty(key: ":REPORT:", value: "variable")]) | ||
| 19 | #expect(Observation(org: o.org)?.report == .variable) | ||
| 20 | } | ||
| 21 | |||
| 22 | /// COBS observation by DRE01 on 2024-10-03, rebuilt from its fields (extinction note and tail modifier left out). | ||
| 23 | @Test func icqLineMatchesCOBSColumns() throws { | ||
| 24 | let o = try entry("Tsuchinshan–ATLAS", "2024-10-03T18:43:12Z", [ | ||
| 25 | ":REPORT:": "comet", ":DESIGNATION:": "C/2023 A3", ":METHOD:": "M", ":MAGNITUDE:": "1.5:", ":REFERENCE:": "TT", | ||
| 26 | ":APERTURE:": "5", ":INSTRUMENT:": "B", ":POWER:": "12", ":COMA:": "2.5", ":DC:": "7/", ":TAIL:": "3.9", ":PA:": "258", | ||
| 27 | ]) | ||
| 28 | #expect(ICQ.line(o, observerCode: "DRE01") == " 2023A3 2024 10 03.78 M 1.5:TT 5.0B 12 2.5 7/ 3.90 258 ICQ XX DRE01") | ||
| 29 | #expect(ICQ.designation("12P") == " 12") | ||
| 30 | #expect(ICQ.designation("12P/Pons-Brooks") == " 12") | ||
| 31 | #expect(ICQ.designation("P/2010 H2") == " P2010H2 ") | ||
| 32 | #expect(ICQ.magnitude("[12") == "[12.0 ") | ||
| 33 | #expect(ICQ.magnitude("bright") == nil) | ||
| 34 | } | ||
| 35 | |||
| 36 | @Test func aavsoFileFollowsTheManualExample() throws { | ||
| 37 | let a = try entry("SS Cyg", "2008-08-24T14:57:41Z", [":REPORT:": "variable", ":MAGNITUDE:": "<11.1", ":COMMENT_CODE:": "U", ":COMPARISON:": "110 113", ":CHART:": "070613"], notes: "Partly cloudy, low") | ||
| 38 | let b = try entry("SS Cyg", "2008-08-25T14:57:41Z", [":REPORT:": "variable", ":MAGNITUDE:": "10.9", ":COMPARISON:": "110"]) | ||
| 39 | let skipped = try entry("M31", "2008-08-25T15:00:00Z", [:]) | ||
| 40 | let lines = AAVSOVisual.file([b, skipped, a], observerCode: "tst01", software: "Moonrise 5.6.0").split(separator: "\n") | ||
| 41 | #expect(lines.prefix(6) == ["#TYPE=VISUAL", "#OBSCODE=TST01", "#SOFTWARE=Moonrise 5.6.0", "#DELIM=,", "#DATE=JD", "#OBSTYPE=Visual"]) | ||
| 42 | #expect(lines[7] == "SS CYG,2454703.1234,<11.1,U,110,113,070613,Partly cloudy; low") | ||
| 43 | #expect(lines[8] == "SS CYG,2454704.1234,10.9,na,110,na,na,na") | ||
| 44 | #expect(lines.count == 9) | ||
| 45 | } | ||
| 46 | |||
| 47 | @Test func imoSessionAndRates() throws { | ||
| 48 | let o = try entry("Orionids", "2026-10-21T09:00:00Z", [ | ||
| 49 | ":REPORT:": "meteors", ":MINUTES:": "90", ":LIMITING_MAG:": "6.2", ":CLOUD:": "20", ":COUNTS:": "ori 14, SPO 5", ":ELEVATION:": "120", | ||
| 50 | ]) | ||
| 51 | let (sessions, rates) = IMOReport.files([o], observerName: "A. Observer", defaultCountry: "Australia") | ||
| 52 | #expect(sessions == "session_id;observer_name;latitude;longitude;elevation;country;location_name\n1;A. Observer;-27.7800;152.7300;0.120;Australia;Peak Crossing\n") | ||
| 53 | #expect(rates.split(separator: "\n") == [ | ||
| 54 | "rate_id;session_id;shower;period_start;period_end;freq;lim_magn;t_eff;f", | ||
| 55 | "1;1;ORI;2026-10-21 09:00:00;2026-10-21 10:30:00;14;6.20;1.500;1.25", | ||
| 56 | "2;1;SPO;2026-10-21 09:00:00;2026-10-21 10:30:00;5;6.20;1.500;1.25", | ||
| 57 | ]) | ||
| 58 | } | ||