SPB Git

Repository Public

CosmosExport.md 9.8 KB

# CosmosExport

Writers for CSV, JSON, PNG, PDF, video and reproducibility bundles. Depends on CosmosCore and Apple frameworks only (Foundation, CoreGraphics, CoreText, ImageIO, AVFoundation, CryptoKit). Every writer takes an ExportContext and embeds it or writes it beside the data. Every file writer goes through a temporary sibling file and an atomic rename: a failed or cancelled export leaves nothing at the destination and never damages a file that was already there.

# 1. Scientific context (ExportContext, schema version 1)

Filled by the caller: title, description, createdUTC, instants (each with the TDB Instant and the UTC string computed by CosmosTime at the call site — this module does not convert time scales; a missing UTC is printed as "not provided"), frame (ReferenceFrame) and center, observer, provenance ([Provenance]), statuses ([ScientificStatus]), units, packs (id, version, manifest SHA-256 from InstalledPack.manifestSHA256), engines, application (name, version, build), free-form parameters. jsonData() is deterministic (sorted keys). textLines(_:) gives the plain-text form used by the CSV preamble; footerLines(_:) three short lines for an image footer.

Language. All labels come from an ExportStrings value supplied by the caller; ExportStrings.english and .french are complete presets. The module never reads the system language.

# 2. Tables: CSV and JSON

Model: ExportTable (name, ExportColumns with unit, kind, description, optional per-column format; rows of ExportValue: number, integer, text, boolean, missing). ExportSeries.table() converts a sampled series (with optional errors).

Numbers (NumberFormat): .roundTrip — the shortest decimal that reads back to the same Double — or .significant(n) (1…17 digits, %g style). Both use . as the decimal separator and no grouping whatever the locale (checked on a fr_CA system; String(format:) without locale ignores Locale.current and setlocale). The format in use is stated in the file.

Non-finite and missing values — never 0:

CSV JSON PDF table
NaN, ±∞ NaN, Infinity, -Infinity (default) or refusal (.fail → ExportError.nonFiniteValue) the strings "NaN", "Infinity", "-Infinity" in number columns, declared by "nonFinite": "string-tokens"; or refusal the same tokens
missing empty unquoted field null —

CSV (CSVExporter, CSVStreamWriter, CSVReader): UTF-8 without BOM, CRLF by default (RFC 4180; LF optional), fields quoted when they contain a comma, a quote, CR or LF (quotes doubled), and also when an unquoted text would be read back as something else (empty string, a number, true/false, a non-finite token, leading/trailing blank, leading #). Header: name [unit] (default), a second row of units, or names only. A preamble of # lines carries the context, the number format, the non-finite and missing-value policies and the column descriptions; CSVOptions.includePreamble = false removes it for strict consumers.

JSON (JSONExporter, JSONTableStreamWriter): one document with keys always in this order — schemaVersion, kind (orix-cosmos.table), name, context, numberFormat, nonFinite, columns, rows — context keys sorted, one row per line. Integers are written as integers (64-bit values survive).

Streaming writers hold at most 64 KiB in memory; finish() commits, cancel() (or releasing the writer) discards.

# 3. PNG (PNGExporter)

Input: a CGImage, or a RasterImage (RGBA rows top-down, 8 or 16 bits per channel — little-endian UInt16 — tagged sRGB or displayP3, opaque/premultiplied/straight alpha). Without footer the pixels, depth and colour space pass through to ImageIO unchanged. Metadata: the full context as compact JSON in the XMP property cosmos:context (namespace https://www.orixlab.dev/ns/cosmos/1.0/, stored by ImageIO in an iTXt chunk), plus the PNG text fields Title, Description, Software, Source, Copyright (credits) and Comment (the text lines) for generic viewers. PNGExporter.readContext reads it back. Optional PNGFooter: a dark band under the image with caller-supplied lines (CoreText, long lines truncated with an ellipsis), rendered at the depth and in the colour space of the image.

# 4. Charts (Chart, ChartRenderer)

Line, scatter and line-with-markers series on one x axis and one y axis (no dual axes): linear or logarithmic scale, optional fixed range, inverted direction (HR diagrams), axis titles with units, symmetric or asymmetric error bars on x and y, legend when there are two series or more, optional note line. Output: vector PDF (pdfData), bitmap (image), or any CGContext (draw, used by the report). Colours are a fixed eight-slot categorical palette checked for colour-vision deficiency (worst adjacent pair ΔE 9.1 protan); three slots have less than 3:1 contrast on the light surface, so identity is also carried by marker shape and the legend, and the data itself is exported as a table. ChartRenderReport counts what was not drawn: non-finite points, non-positive values on a logarithmic axis, clipped error bars, series beyond the palette.

# 5. PDF report (ReportDocument, PDFReportRenderer)

CoreGraphics PDF context + CoreText, A4 or Letter, vector text (extractable). Flow: title block (title, description, application and date, instants in UTC and TDB, frame, observer, statuses) → summary → caller blocks (heading, paragraph, table, image, chart, pageBreak) → Data sources (always present: source, version, licence, retrieval date, URL, method, citation — or an explicit "no external data source recorded") → Methodology and status legend (caller notes, a definition of each status present, units, pack and engine versions, parameters). Footer on every page: title and "Page i of N" (two rendering passes). Tables continue across pages with the header repeated; maximumRows bounds a table and the report then states "n / total rows shown".

# 6. Video (VideoExporter)

AVAssetWriter, H.264 or HEVC, .mov or .mp4. Frames (VideoFrame: premultiplied BGRA 8-bit) are pulled one at a time from a VideoFrameSource (async); the loop waits on isReadyForMoreMediaData rather than queueing frames; task cancellation stops the export and removes the temporary file; progress reports frames written. Metadata: title, description, software, source (credits), creation date as common items; in QuickTime movies also a comment (text lines) and the full context JSON (quickTimeMetadataInformation). MP4 cannot hold the full context: it is written to <file>.context.json beside the movie, before the movie is moved into place. readContext(from:) handles both.

# 7. Reproducibility bundle (ReproducibilityBundle)

A directory, built in a temporary sibling and renamed into place:

text
<name>/bundle.json          schemaVersion, kind, createdUTC, configurationType, application, engines,
                            packs (id, version, manifest SHA-256), files [{path, size, sha256}]
       configuration.json   the caller's Codable payload (opaque to this module, sorted keys)
       context.json         the ExportContext
       files/…              the exported files (attachments)

load(from:) verifies before returning anything: every listed file present, regular, same size and SHA-256; no unlisted file; context.json and configuration.json covered; manifest paths safe (no .., no absolute path). problems(in:) lists the discrepancies without throwing.

# 8. What the tests verify (swift test --filter CosmosExportTests)

CSV and JSON golden files (Tests/Fixtures/table_golden.*), quoting and round trips with hostile strings, the non-finite policy, 2000 random doubles through both number formats, streaming output byte-identical to in-memory output on 30 000 rows, no temporary file after cancellation or error; PNG read back through ImageIO (context, text fields, 8/16 bits, sRGB/P3 profile, corner pixels, footer band); chart PDFs with extractable axis titles and legends, skip/clip counts; a 150-row report with the expected page count, per-page "Page i of N", repeated table headers, the sources and methodology sections, in English and in French (PDFKit); H.264/HEVC movies read back (12 frames, 64×48, 2.0 s, codec, metadata, context), cancellation and failing sources leaving no file; bundle round trip and nine kinds of tampering.

# 9. Limitations

  • UTC strings are the caller's responsibility (CosmosTime is not a dependency of this module).
  • The bundle is a directory, not a single archive.
  • PDF tables truncate over-long cells with an ellipsis; the complete data belongs in the CSV/JSON export. Right-to-left text and hyphenation are whatever CoreText does by default. Fonts: Helvetica with CoreText fallback.
  • Charts: line and scatter only (no bars, histograms, colour maps); at most eight coloured series; tick labels use six significant digits; no dark theme.
  • PNG: 16-bit float and HDR are not handled; the footer is rendered in the image's own colour space (sRGB when that space is not an RGB output space).
  • Video: no audio track, constant frame rate, SDR 8-bit input, even dimensions required; encoder availability is the system's (hardware HEVC assumed on Apple Silicon); MP4 context is a sidecar file.
  • CSV: no protection against spreadsheet formula interpretation (=… is written as text, quoted only when RFC 4180 or type disambiguation requires it).
  • The visual quality of the report and charts was checked by eye on sample renders, not by automated image comparison.
Files main
Menu

Theme