SPB Git

Repository Public

CosmosExport.md 9.8 KB 146 lines markdown

1<!--2ORIX Cosmos3File: Documentation/modules/CosmosExport.md4Description: Export module: the scientific context model, CSV/JSON formats and number policy, PNG metadata, charts, PDF report, video, reproducibility bundle, what the tests verify and known limitations.5Author: Simon-Pierre Boucher6Contact: contact@spboucher.ai7-->8# CosmosExport910Writers for CSV, JSON, PNG, PDF, video and reproducibility bundles. Depends on `CosmosCore` and Apple11frameworks only (Foundation, CoreGraphics, CoreText, ImageIO, AVFoundation, CryptoKit). Every writer takes an12`ExportContext` and embeds it or writes it beside the data. Every file writer goes through a temporary sibling13file and an atomic rename: a failed or cancelled export leaves nothing at the destination and never damages a14file that was already there.1516## 1. Scientific context (`ExportContext`, schema version 1)1718Filled by the caller: `title`, `description`, `createdUTC`, `instants` (each with the TDB `Instant` and the UTC19string computed by CosmosTime at the call site — this module does not convert time scales; a missing UTC is20printed as "not provided"), `frame` (`ReferenceFrame`) and `center`, `observer`, `provenance` (`[Provenance]`),21`statuses` (`[ScientificStatus]`), `units`, `packs` (id, version, manifest SHA-256 from22`InstalledPack.manifestSHA256`), `engines`, `application` (name, version, build), free-form `parameters`.23`jsonData()` is deterministic (sorted keys). `textLines(_:)` gives the plain-text form used by the CSV24preamble; `footerLines(_:)` three short lines for an image footer.2526**Language.** All labels come from an `ExportStrings` value supplied by the caller; `ExportStrings.english`27and `.french` are complete presets. The module never reads the system language.2829## 2. Tables: CSV and JSON3031Model: `ExportTable` (name, `ExportColumn`s with `unit`, `kind`, `description`, optional per-column `format`;32rows of `ExportValue`: `number`, `integer`, `text`, `boolean`, `missing`). `ExportSeries.table()` converts a33sampled series (with optional errors).3435**Numbers** (`NumberFormat`): `.roundTrip` — the shortest decimal that reads back to the same Double — or36`.significant(n)` (1…17 digits, `%g` style). Both use `.` as the decimal separator and no grouping whatever37the locale (checked on a fr_CA system; `String(format:)` without locale ignores `Locale.current` and `setlocale`).38The format in use is stated in the file.3940**Non-finite and missing values — never 0:**4142| | CSV | JSON | PDF table |43|---|---|---|---|44| 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 |45| missing | empty unquoted field | `null` | `—` |4647**CSV** (`CSVExporter`, `CSVStreamWriter`, `CSVReader`): UTF-8 without BOM, CRLF by default (RFC 4180; LF48optional), fields quoted when they contain a comma, a quote, CR or LF (quotes doubled), and also when an49unquoted text would be read back as something else (empty string, a number, `true`/`false`, a non-finite50token, leading/trailing blank, leading `#`). Header: `name [unit]` (default), a second row of units, or names51only. A preamble of `# ` lines carries the context, the number format, the non-finite and missing-value52policies and the column descriptions; `CSVOptions.includePreamble = false` removes it for strict consumers.5354**JSON** (`JSONExporter`, `JSONTableStreamWriter`): one document with keys always in this order —55`schemaVersion`, `kind` (`orix-cosmos.table`), `name`, `context`, `numberFormat`, `nonFinite`, `columns`,56`rows` — context keys sorted, one row per line. Integers are written as integers (64-bit values survive).5758Streaming writers hold at most 64 KiB in memory; `finish()` commits, `cancel()` (or releasing the writer)59discards.6061## 3. PNG (`PNGExporter`)6263Input: a `CGImage`, or a `RasterImage` (RGBA rows top-down, 8 or 16 bits per channel — little-endian UInt16 —64tagged `sRGB` or `displayP3`, opaque/premultiplied/straight alpha). Without footer the pixels, depth and colour65space pass through to ImageIO unchanged. Metadata: the full context as compact JSON in the XMP property66`cosmos:context` (namespace `https://www.orixlab.dev/ns/cosmos/1.0/`, stored by ImageIO in an iTXt chunk),67plus the PNG text fields Title, Description, Software, Source, Copyright (credits) and Comment (the text68lines) for generic viewers. `PNGExporter.readContext` reads it back. Optional `PNGFooter`: a dark band under69the image with caller-supplied lines (CoreText, long lines truncated with an ellipsis), rendered at the depth70and in the colour space of the image.7172## 4. Charts (`Chart`, `ChartRenderer`)7374Line, scatter and line-with-markers series on one x axis and one y axis (no dual axes): linear or logarithmic75scale, optional fixed range, inverted direction (HR diagrams), axis titles with units, symmetric or asymmetric76error bars on x and y, legend when there are two series or more, optional note line. Output: vector PDF77(`pdfData`), bitmap (`image`), or any `CGContext` (`draw`, used by the report). Colours are a fixed78eight-slot categorical palette checked for colour-vision deficiency (worst adjacent pair ΔE 9.1 protan);79three slots have less than 3:1 contrast on the light surface, so identity is also carried by marker shape and80the legend, and the data itself is exported as a table. `ChartRenderReport` counts what was not drawn:81non-finite points, non-positive values on a logarithmic axis, clipped error bars, series beyond the palette.8283## 5. PDF report (`ReportDocument`, `PDFReportRenderer`)8485CoreGraphics PDF context + CoreText, A4 or Letter, vector text (extractable). Flow: title block (title,86description, application and date, instants in UTC and TDB, frame, observer, statuses) → summary → caller87blocks (`heading`, `paragraph`, `table`, `image`, `chart`, `pageBreak`) → **Data sources** (always present:88source, version, licence, retrieval date, URL, method, citation — or an explicit "no external data source89recorded") → **Methodology and status legend** (caller notes, a definition of each status present, units,90pack and engine versions, parameters). Footer on every page: title and "Page i of N" (two rendering passes).91Tables continue across pages with the header repeated; `maximumRows` bounds a table and the report then states92"n / total rows shown".9394## 6. Video (`VideoExporter`)9596`AVAssetWriter`, H.264 or HEVC, `.mov` or `.mp4`. Frames (`VideoFrame`: premultiplied BGRA 8-bit) are pulled97one at a time from a `VideoFrameSource` (async); the loop waits on `isReadyForMoreMediaData` rather than98queueing frames; task cancellation stops the export and removes the temporary file; progress reports frames99written. Metadata: title, description, software, source (credits), creation date as common items; in100QuickTime movies also a comment (text lines) and the full context JSON (`quickTimeMetadataInformation`).101MP4 cannot hold the full context: it is written to `<file>.context.json` beside the movie, before the movie102is moved into place. `readContext(from:)` handles both.103104## 7. Reproducibility bundle (`ReproducibilityBundle`)105106A directory, built in a temporary sibling and renamed into place:107108```109<name>/bundle.json          schemaVersion, kind, createdUTC, configurationType, application, engines,110                            packs (id, version, manifest SHA-256), files [{path, size, sha256}]111       configuration.json   the caller's Codable payload (opaque to this module, sorted keys)112       context.json         the ExportContext113       files/…              the exported files (attachments)114```115116`load(from:)` verifies before returning anything: every listed file present, regular, same size and SHA-256;117no unlisted file; `context.json` and `configuration.json` covered; manifest paths safe (no `..`, no absolute118path). `problems(in:)` lists the discrepancies without throwing.119120## 8. What the tests verify (`swift test --filter CosmosExportTests`)121122CSV and JSON golden files (`Tests/Fixtures/table_golden.*`), quoting and round trips with hostile strings,123the non-finite policy, 2000 random doubles through both number formats, streaming output byte-identical to124in-memory output on 30 000 rows, no temporary file after cancellation or error; PNG read back through ImageIO125(context, text fields, 8/16 bits, sRGB/P3 profile, corner pixels, footer band); chart PDFs with extractable126axis titles and legends, skip/clip counts; a 150-row report with the expected page count, per-page127"Page i of N", repeated table headers, the sources and methodology sections, in English and in French128(PDFKit); H.264/HEVC movies read back (12 frames, 64×48, 2.0 s, codec, metadata, context), cancellation and129failing sources leaving no file; bundle round trip and nine kinds of tampering.130131## 9. Limitations132133* UTC strings are the caller's responsibility (CosmosTime is not a dependency of this module).134* The bundle is a directory, not a single archive.135* PDF tables truncate over-long cells with an ellipsis; the complete data belongs in the CSV/JSON export.136  Right-to-left text and hyphenation are whatever CoreText does by default. Fonts: Helvetica with CoreText fallback.137* Charts: line and scatter only (no bars, histograms, colour maps); at most eight coloured series; tick labels138  use six significant digits; no dark theme.139* PNG: 16-bit float and HDR are not handled; the footer is rendered in the image's own colour space (sRGB when140  that space is not an RGB output space).141* Video: no audio track, constant frame rate, SDR 8-bit input, even dimensions required; encoder availability142  is the system's (hardware HEVC assumed on Apple Silicon); MP4 context is a sidecar file.143* CSV: no protection against spreadsheet formula interpretation (`=…` is written as text, quoted only when144  RFC 4180 or type disambiguation requires it).145* The visual quality of the report and charts was checked by eye on sample renders, not by automated image comparison.146
Files main
Menu

Theme